{"text": "(* Universidade de Bras\u00edlia\n    Instituto de Ci\u00eancias Exatas \n    Departamento de Ci\u00eancia da Computa\u00e7\u00e3o\n    L\u00f3gica Computacional 1 - turma B - 2020/2 \n    Professor: Fl\u00e1vio L. C. de Moura\n    Estagi\u00e1rio de doc\u00eancia: Gabriel Ferreira Silva *)\n\nRequire Import Arith List Recdef.\nRequire Import Coq.Program.Wf.\n\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\nDefinition le_all x l := forall y, In y l -> x <= y.\nInfix \"<=*\" := le_all (at level 70, no associativity).\n\n\nLemma tail_sorted: forall l a, sorted (a :: l) -> sorted l.\nProof.\n  intro l.\n  case l.\n  - intros a H.  \n    apply nil_sorted.  \n  - intros n l' a H.  \n    inversion H; subst.\n    assumption.  \nQed.  \n\n\n(** *** Quest\u00e3o 1: \ud83d\ude0e\ufe0f**) \n(** A primeira quest\u00e3o consiste em provar que se [a] \u00e9 menor ou igual a todo elemento de [l], e [l] \u00e9 uma lista ordenada ent\u00e3o a lista (a :: l) tamb\u00e9m est\u00e1 ordenada: *)\n\nLemma le_all_sorted: forall l a, a <=* l -> sorted l -> sorted (a :: l).\nProof.\n  intro l.\n  case l.\n  - intros a menor ordenado_nulo.\n    apply one_sorted.\n  - intros n l0 a menor ordenado.\n    apply all_sorted.\n    + assumption.\n    + unfold le_all in menor.\n      apply menor.\n      apply in_eq. (** pesquisamos a estrutura do In**)\nQed.\n\n(** O lema a seguir \u00e9 bem parecido com o lema [tail_sorted] visto anteriormente, mas ao inv\u00e9s 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\u00f3s esta remo\u00e7\u00e3o a lista resultante ainda est\u00e1 ordenada. Veja que a prova \u00e9 por an\u00e1lise 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\u00e3o 2 \ud83d\ude0f\ufe0f*)\n(** A segunda quest\u00e3o consiste em provar que, se a lista [(a :: l)] est\u00e1 ordenada ent\u00e3o [a] \u00e9 menor ou igual a todo elemento de [l]. A dica \u00e9 fazer indu\u00e7\u00e3o 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 ordenada n ta_dentro.\n    (*caso seja dif\u00edcil explicar o destruct, usar contradiction.*)\n    destruct ta_dentro.\n  - intros num ordenada. (** refatorar esta prova **)\n    unfold le_all.\n    intros y H0.\n    inversion ordenada.\n    subst.\n    inversion H0.\n    subst.\n    assumption.\n    apply IHl in H2.  \n    unfold le_all in H2.\n    specialize(H2 y H). (** aplica a hip\u00f3tese e substitui o resultado **)\n    apply Nat.le_trans with (m := a); assumption.\n\nQed.\n\n(** ** Segunda parte: *)\n(** Agora definiremos a no\u00e7\u00e3o de permuta\u00e7\u00e3o e apresentaremos \nalguns lemas relacionados. A no\u00e7\u00e3o de permuta\u00e7\u00e3o que ser\u00e1 utilizada \nneste projeto \u00e9 baseada no n\u00famero de ocorr\u00eancias de um elemento.\n A fun\u00e7\u00e3o recursiva [num_oc n l] retorna o n\u00famero de ocorr\u00eancias do \nnatural [n] na lista [l]. A palavra reservada [Fixpoint] \u00e9 usada para \ndefinir fun\u00e7\u00f5es recursivas, enquanto que [Definition] \u00e9 usada para fun\u00e7\u00f5es\n n\u00e3o-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\u00e3o que duas listas [l] e [l'] s\u00e3o permuta\u00e7\u00f5es uma da outra\n se qualquer natural [n] possui o mesmo n\u00famero de ocorr\u00eancias em ambas as \nlistas. *)\n\nDefinition perm l l' := forall n:nat, num_oc n l = num_oc n l'.\n\n(** A reflexividade \u00e9 uma propriedade que pode ser obtida a partir \ndesta defini\u00e7\u00e3o: uma lista \u00e9 sempre permuta\u00e7\u00e3o 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 \u00e9 um resultado t\u00e9cnico, \nmas que pode ser utilizado em provas futuras. \nEle diz que o n\u00famero de ocorr\u00eancias de um natural [n] \nno append das listas [l1] e [l2] (nota\u00e7\u00e3o [l1 ++ l2]) \u00e9 igual\n \u00e0 soma das ocorr\u00eancias de [n] em [l1] com as ocorr\u00eancias 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).\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\n(** *** Terceira parte: *)\n(** Nesta parte definiremos o algoritmo mergesort. \nIniciaremos pela fun\u00e7\u00e3o [merge] que faz a etapa de combina\u00e7\u00e3o \ndescrita anteriormente. A fun\u00e7\u00e3o [merge] recebe como argumento \num par de listas de naturais ordenadas e gera uma nova lista ordenada\n contendo exatamente os elementos das duas listas recebidas como argumento.\n Iniciamos ent\u00e3o com a defini\u00e7\u00e3o do predicado [sorted_pair_lst] que recebe \num par de listas e retorna a conjun\u00e7\u00e3o expressando o fato de que cada lista \nque comp\u00f5e o par est\u00e1 ordenada: *)\n\nDefinition sorted_pair_lst (p: list nat * list nat) :=\nsorted (fst p) /\\ sorted (snd p).\n\n(** Agora necessitamos de uma m\u00e9trica para definirmos a fun\u00e7\u00e3o [merge]. \nEsta m\u00e9trica consiste no tamanho do par que cont\u00e9m duas listas e \u00e9 \ndefinido 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\u00e7\u00e3o recursiva [merge]. \nDado um par [p] de listas de naturais, se alguma das listas\n que comp\u00f5em este par \u00e9 a lista vazia ent\u00e3o a fun\u00e7\u00e3o simplesmente\n retorna o outro elemento do par. Quando ambas as listas que comp\u00f5em o\n par s\u00e3o n\u00e3o-vazias ent\u00e3o os primeiros elementos de cada lista s\u00e3o \ncomparados e o menor deles ser\u00e1 o colocado na lista final, e o processo\n se repete recursivamente para o par sem este menor elemento. Para\n garantirmos que esta fun\u00e7\u00e3o est\u00e1 bem definida, precisamos que as \nchamadas recursivas se aproximem do ponto de parada (chamadas sem recurs\u00e3o)\n que ocorre quando alguma das listas do par \u00e9 a lista vazia. Esta garantia \n\u00e9 dada pelo medida (ou m\u00e9trica) definida anteriormente: o comprimento do par \nque [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] \u00e9 utilizada para definir fun\u00e7\u00f5es \nrecursivas mais sofisticadas, ou seja, para fun\u00e7\u00f5es recursivas cuja \nboa defini\u00e7\u00e3o n\u00e3o pode ser inferida automaticamente pelo Coq. Neste caso,\n 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\u00e1 bastante \u00fatil em provas futuras. \nEle estabelece que se [y] \u00e9 um elemento da lista [merge p] ent\u00e3o [y] \nest\u00e1 em alguma das listas que comp\u00f5em 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\u00e3o 3 *)\n(** Esta quest\u00e3o \u00e9 a mais importante do projeto.\ud83e\udd23\ufe0f Ela estabelece que se as\n listas que comp\u00f5em o par [p] est\u00e3o ordenadas ent\u00e3o [merge p] tamb\u00e9m est\u00e1 \nordenada. Como [merge] \u00e9 uma fun\u00e7\u00e3o recursiva mais sofisticada, as \npropriedades envolvendo esta fun\u00e7\u00e3o tamb\u00e9m ter\u00e3o provas mais complexas. \nComo voc\u00ea pode ver, esta prova \u00e9 composta de quatro casos, dos quais dois \nest\u00e3o provados, e dois fazem parte do exerc\u00edcio. Cada caso deixado como \nexerc\u00edcio \u00e9 semelhante ao caso anterior, ent\u00e3o use estas subprovas que est\u00e3o\n feitas como ideias para completar a prova deste teorema. Os lemas anteriores\n tamb\u00e9m podem ser \u00fateis! *)\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    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.\n    apply le_all_sorted.\n    + unfold le_all.\n      intro. intro.\n      apply merge_in in H0.\n      destruct H0 as [H1 | H2].\n      apply leb_complete_conv in e0.\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 snd in H3.\n        Search(In _ (_ :: _)).\n        apply in_inv in H1.\n        destruct H1.\n        -- subst.\n           Search(_ < _ -> _ <= _).\n           apply Nat.lt_le_incl.\n           assumption.\n        --  apply H2 in H.\n            Search(le_trans).\n            apply Nat.le_trans with (m := hd1).\n            *** apply Nat.lt_le_incl.\n                assumption.\n            *** assumption.\n     * apply leb_complete_conv in e0.\n       simpl snd in H2. unfold sorted_pair_lst in H. destruct H as [H22 H33].\n       simpl snd in H33. apply sorted_le_all in H33. unfold le_all in H33.\n       apply H33 in H2.\n       assumption.\n   + destruct H.\n     simpl snd in H0.\n     apply tail_sorted in H0.\n     apply IHl.\n     simpl fst in H.\n     unfold sorted_pair_lst.\n     simpl fst.\n     simpl snd.\n     split.\n     * assumption.\n     * assumption.\nQed.\n\n(** Agora vamos definir a fun\u00e7\u00e3o [mergesort] que recebe uma lista [l] como \nargumento. Se esta lista for vazia ou unit\u00e1ria, o algoritmo n\u00e3o faz nada. \nCaso contr\u00e1rio, a lista \u00e9 dividida ao meio, cada sublista \u00e9 ordenada \nrecursivamente, e no final as sublistas ordenadas s\u00e3o fundidas com a fun\u00e7\u00e3o\n [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 \u00e0 defini\u00e7\u00e3o da fun\u00e7\u00e3o [merge], precisamos \nprovar que [mergesort] est\u00e1 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\u00e3o 4 *)\n(** Agora prove que a fun\u00e7\u00e3o [mergesort] realmente ordena a lista recebida \ncomo argumento. *)\n\nTheorem mergesort_sorts: forall l, sorted (mergesort l).\nProof.\n  intros.\n  functional induction (mergesort l).\n  - apply nil_sorted.\n  - apply one_sorted.\n  - destruct IHl0.\n    * apply merge_sorts.\n      unfold sorted_pair_lst.\n      simpl.\n      split.\n      ** apply nil_sorted.\n      ** assumption.\n    * apply merge_sorts.\n      unfold sorted_pair_lst.\n      simpl.\n      split.\n      ** apply one_sorted.\n      ** assumption.\n    * apply merge_sorts.\n      unfold sorted_pair_lst.\n      simpl.\n      split.\n      ** apply all_sorted; assumption.\n      ** assumption.\nQed.\n\n\n\n(** O lema a seguir \u00e9 um lema t\u00e9cnico que pode ser usado nas quest\u00f5es \nseguintes. Este lema estabelece que o n\u00famero de ocorr\u00eancias de um elemento \n[n] no par de listas [p] \u00e9 igual \u00e0 soma das ocorr\u00eancias de [n] em cada lista \ndo 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\u00e3o 5 *)\n(** Prove que [mergesort] gera uma permuta\u00e7\u00e3o da lista recebida como argumento. *)\n\n(**\nintro.\n  functional induction (mergesort l).\n  - apply perm_refl.\n  - apply perm_refl.\n  - intros n.\n    unfold merge.\n    destruct mergesort.\n    destruct merge_terminate.\n    rewrite merge_num_oc.\n**)\n\nTheorem mergesort_is_perm: forall l, perm l (mergesort l).\nProof.\n  intro.\n  functional induction (mergesort l).\n  - apply perm_refl.\n  - apply perm_refl.\n  - unfold perm. intros n.\n    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.\n      Search firstn.\n      rewrite firstn_skipn.\n      reflexivity.\n    + destruct mergesort.\n      * unfold perm in IHl1.\n        rewrite -> IHl1.\n        reflexivity.\n      * unfold perm in IHl1.\n        rewrite -> IHl1.\n        reflexivity.\n    + unfold perm in IHl0.\n      rewrite -> IHl0.\n      reflexivity.\nQed.\n\n(** *** Quest\u00e3o 6 *)\n(** Por fim, prove que [mergesort] \u00e9 correto. *)\n\nTheorem mergesort_is_correct: forall l, perm l (mergesort l) /\\ sorted (mergesort l).\nProof.\n  intros.\n  split.\n  - apply mergesort_is_perm.\n  - apply mergesort_sorts.\nQed.\n\n(** ESSE TRABALHO VALE 10 HEIN? \ud83d\ude0f\ufe0f\ud83d\ude08\ufe0f\ud83d\udd25\ufe0f\ud83d\udd25\ufe0f\ud83d\udd25\ufe0f\ud83d\udd25\ufe0f\ud83d\udd25\ufe0f\ud83d\ude0e\ufe0f*)\n\n(** ** Extra\u00e7\u00e3o de c\u00f3digo *)\n(** Uma das vantagens de formalizar um algoritmo \u00e9 que voc\u00ea pode extrair o c\u00f3digo certificado do algoritmo. O algoritmo de extra\u00e7\u00e3o garante que o c\u00f3digo extra\u00eddo satisfaz todas as propriedades provadas. Vamos extrair automaticamente o c\u00f3digo do algoritmo mergesort? *)\n\nRequire Extraction.\n\n(** As op\u00e7\u00f5es de linguagens fornecidas pelo Coq s\u00e3o: OCaml, Haskell, Scheme e JSON. *)\n\nExtraction Language OCaml.\n\n(** Extra\u00e7\u00e3o apenas da fun\u00e7\u00e3o [mergesort]: *)\n\nExtraction mergesort.\n\n(** Extra\u00e7\u00e3o do programa inteiro: *)\n\nRecursive Extraction mergesort.\n\n(** Extra\u00e7\u00e3o para um arquivo: *)\n\nExtraction \"mergesort\" mergesort.", "meta": {"author": "gutorsantos", "repo": "coq", "sha": "0561be1c033564cf12b9c4e451eb213083a7c512", "save_path": "github-repos/coq/gutorsantos-coq", "path": "github-repos/coq/gutorsantos-coq/coq-0561be1c033564cf12b9c4e451eb213083a7c512/mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.9219218348550491, "lm_q1q2_score": 0.8499398735379685}}
{"text": "Inductive Nat : Type :=\n  | O : Nat\n  | S : Nat -> Nat.\n\nInductive BinaryTree : Type :=\n| Leaf (n : Nat)\n| Node (l r : BinaryTree).\n\nFixpoint plus (n m : Nat) : Nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nNotation \"x + y\" := (plus x y)\n  (at level 50, left associativity).\n\n\nFixpoint sum1 (t : BinaryTree) : Nat :=\nmatch t with\n| Leaf n => n\n| Node l r => sum1 l + sum1 r\nend.\n\nFixpoint sum2 (t : BinaryTree) : Nat :=\nmatch t with\n| Leaf n => n\n| Node l r => sum2 r + sum2 l\nend.\n\nLemma rightid (x : Nat) : x + O = x.\nProof.\n  induction x.\n  - simpl. reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_r_S : forall (a b : Nat), a + S b = S (a + b).\nProof.\n  intros.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite IHa. reflexivity.\nQed.\n\nLemma plus_comm (x y : Nat) : x + y = y + x.\nProof.\n  induction x.\n  - simpl. rewrite (rightid). reflexivity.\n  - simpl. rewrite (plus_r_S). rewrite IHx. reflexivity.\nQed.\n\nLemma sum1_2_eq : forall t : BinaryTree, sum1 t = sum2 t.\nProof.\n  intros.\n  induction t.\n  - simpl.  reflexivity.\n  - simpl. rewrite <- (IHt2). rewrite (IHt1). rewrite (plus_comm). reflexivity.\nQed. \n\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Arith.PeanoNat.\n\nCheck nat.\n\n(* Innent\u0139\u0091l kezdve haszn\u0102\u0104ljuk az STDLB NAT-j\u0102\u0104t *)\n(* Aritmetikai nyelv formaliz\u0102\u0104l\u0102\u0104sa, BNF: *)\n(*a ::= n | a1 + a2 | a1 - a2*)\n(*a ::= alit(n) | plus(a1,a2) | sub(a1,a2)*)\nInductive AExp : Type :=\n | ALit (n : nat)\n | APlus (n m : AExp)\n | ASub ( n m : AExp)\n.\n\n(* Checkek *)\n\n(* Hogyan tudunk ki\u0102\u0160rt\u0102\u0160kelni aritmetikai kifejez\u0102\u0160seket --> denot\u0102\u0104ci\u0102\u0142s szemantika *)\nFixpoint aeval (a : AExp) : nat :=\n  match a with\n  | ALit n => n\n  | APlus n m => (aeval n) + (aeval m)\n  | ASub n m => (aeval n) - (aeval m)\n  end.\n\nFixpoint leaves_count (a : AExp) : nat := \n  match a with\n  | ALit _ => 1\n  | APlus n m => (leaves_count n) + (leaves_count m)\n  | ASub n m => (leaves_count n) + (leaves_count m)\n  end.\n\nDefinition myA1 := (APlus (ALit 1) (ALit 2)).\nDefinition myA2 := (ASub (APlus (ALit 5) (ALit 7)) (ALit 42)).\n\nEval compute in leaves_count(myA1).\nEval compute in leaves_count(myA2).\n\n\n\nLemma leaf_l_r: forall (a1 a2 : AExp), leaves_count (APlus a1 a2) = leaves_count (APlus a2 a1).\nProof.\n intros.\n simpl.\n Search Nat.\n rewrite (Nat.add_comm).\n reflexivity.\nQed.\n\nLemma leaf_l_r_ind: forall (a1 a2 : AExp), leaves_count (APlus a1 a2) = leaves_count (APlus a2 a1).\nProof.\n  intros.\n  induction a1.\n  - simpl. Search \"+\" S. rewrite (Nat.add_1_r). reflexivity.\n  - simpl. rewrite (Nat.add_comm). reflexivity.\n  - simpl. rewrite (Nat.add_comm). reflexivity.\nQed. \n\n\n\n", "meta": {"author": "Kokan", "repo": "elte_msc", "sha": "2092ccd8f65bf33473eab54e9d7f5facb7eda6e1", "save_path": "github-repos/coq/Kokan-elte_msc", "path": "github-repos/coq/Kokan-elte_msc/elte_msc-2092ccd8f65bf33473eab54e9d7f5facb7eda6e1/formalsemantics/gy03pre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474168650673, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.849917078354392}}
{"text": "Module NatPlayground.\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\nPrint nat.\nEval compute in O.\nEval compute in (S O).\nEval compute in S(S O).\n\nFixpoint add (a b : nat) : nat := \n  match a with \n  | O => b\n  | S n => S (add n b)\n  end.   \n\nTheorem add_assoc : forall (a b c : nat),\n  (add a( add b c)) = (add (add a b) c).\nProof.\nintros a b c.\ninduction a. simpl. reflexivity.\nsimpl. rewrite -> IHa. reflexivity.\nQed.\n\nPrint add_assoc.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nDefinition succ (n : nat) : nat := \n  match n with \n  | O => (S O)\n  | s => (S s)\nend.\n\nCheck (S (S (S (S O)))).\n\nFixpoint plus (n : nat) (m : nat) := \n  match n with \n  | O => m\n  | S n' => plus n' (succ m)\nend.\nCompute plus (S (S (S O))) (S (S O)).\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\nEnd NatPlayground.\n\nCompute (NatPlayground.succ NatPlayground.O).\nCheck (S (S (S (S O)))).\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\nCompute (minustwo 4).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\nend.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nCompute (oddb 4).\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\nCompute (plus 3 2).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minux (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | S _, O => n\n  | S n', S m' => minus n' m'\nend.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S p => mult base (exp base p)\nend.\n\n(* Exercise: 1 star (factorial) *)\nFixpoint factorial (n:nat) : nat :=\n  match n with \n  | O   => S O\n  | S p => mult n (factorial p)\nend.\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\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 beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\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  match (beq_nat n m) with\n  | true => false\n  | false => leb n m\nend.\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_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. simpl. reflexivity. Qed.\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\n(* Proof by Rewriting *)\nTheorem plus_id_example : forall n m:nat,\n  n = m -> n + n = m + m.\n\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite <- H.\n  reflexivity. Qed.\n\n\n(* Exercise: 1 star (plus_id_exercise) *)\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 Hnm.\n  rewrite <- Hnm.\n  intros Hno.\n  rewrite Hno.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite plus_O_n.\n  reflexivity. \nQed.\n  \n(*Exercise: 2 stars (mult_S_1) *)\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n intros m n.\n simpl.\n intros H.\n rewrite <- H.\n reflexivity. \nQed.\n\n(*----------------------------------------------------------*)\n(* Proof by Case Analysis *)\n\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(*Lemma induction_test : forall n:nat, n = n -> n <= n.*)\n\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity. Qed.\n\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\nQed.\n\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b.\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\n\n(*Exercise: 2 stars (andb_true_elim2) *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n      + simpl. reflexivity.\n      + simpl.  intros J. rewrite J. reflexivity.\n  - destruct c.\n      + simpl. intros T. reflexivity.\n      + simpl. intros T. rewrite T. reflexivity.\nQed.\n\n(* Exercise: 1 star (zero_nbeq_plus_1) *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof. \n  intros n. destruct n as [ | n'].\n    - simpl. reflexivity.\n    - simpl. reflexivity.\nQed.\n\n(* More on Notation (Optional) *)\n\n\n(* More Exercises *)\n(* Exercise: 2 stars (boolean_functions) *)\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f. destruct b.\n  - rewrite H. rewrite H. reflexivity. \n  - rewrite H. rewrite H. reflexivity.\nQed.\n    \n\n(* FILL IN HERE *)\n(* The Import statement on the next line tells Coq to use the\n   standard library String module.  We'll use strings more in later\n   chapters, but for the moment we just need syntax for literal\n   strings for the grader comments. *)\nFrom Coq Require Export String.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (prod 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. destruct b.\n    - rewrite H. rewrite H. simpl. reflexivity.\n    - rewrite H. rewrite H. simpl. reflexivity.\nQed.\n    \n\n(* Exercise: 3 stars, optional (andb_eq_orb) *)\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->  b = c.\nProof.\n  intros c. destruct c. \n    -intros b. simpl. intros H. rewrite H. reflexivity. \n    - intros b. simpl. intros H. rewrite <- H. reflexivity.\nQed.\n\n\n(* Exercise: 3 stars (binary) *)\n(* \nhttp://staff.ustc.edu.cn/~bjhua/courses/theory/2014/slides/lec1notes.html\nhttp://kyledef.org/inzamam/2015/07/07/a-binary-number-system-in-coq/\nhttps://www.cs.cmu.edu/~emc/15414-s14/assignment/hw2/Basics_w_ans.v\n*)\n\nInductive bin : Type :=\n           | Z  : bin\n           | T  : bin -> bin\n           | T' : bin -> bin.\n\n   \nFixpoint inc (n : bin) : bin :=\n  match n with\n    | Z => T' Z\n    | T t => T' t\n    | T' n' => T (inc n')\n  end.\n\nFixpoint bin_to_nat (n : bin) : nat :=\n  match n with\n  | Z => 0\n  | T t => 2 *(bin_to_nat t)\n  | T' t => 2 *(bin_to_nat t) + 1\n  end.\n\nCompute bin_to_nat (inc (inc Z)).\n\nExample test_bin_incr1: bin_to_nat (inc (inc (inc Z))) = 3.\nProof. simpl. reflexivity. Qed.\n(*\nFixpoint Simple_Collatz (b : bin) : bin :=\n  match b with\n    | Z => Z\n    | T b' => Simple_Collatz b'\n    | T' b' =>\n      match b' with\n        | Z => b\n        | T b'' => Simple_Collatz (inc(b))\n        | T' b'' => Simple_Collatz(inc(b))\n      end\n  end.\n*)\n\n", "meta": {"author": "mymoocs", "repo": "sf", "sha": "e448a4ae87e770bbe6e92b6c9f2360cccee3e39d", "save_path": "github-repos/coq/mymoocs-sf", "path": "github-repos/coq/mymoocs-sf/sf-e448a4ae87e770bbe6e92b6c9f2360cccee3e39d/LF/Basics/nats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.9173026652376182, "lm_q1q2_score": 0.8497008768857595}}
{"text": "(*Require Import untypedLC.*)\n\nSection type_booleen.\n\n\nVariable T : Set.\nVariable N: Set. \n\n(* Declaration de cbool *)\nDefinition cbool:= T -> T -> T.\n\nDefinition ctr: cbool := fun x y => x. (* true (church) *)\nDefinition cfa: cbool := fun x y => y. (* false (church) *)\n\nDefinition cif: cbool->T->T->T := fun b u v => b u v. (* IF b THEN u ELSE v *)\n\nVariable E:T.\nVariable F:T.\nDefinition TestConditionnelle0:= cif ctr E F. (* IF ctr THEN E ELSE F *)\nCompute  TestConditionnelle0. (* = E *)\nDefinition TestConditionnelle1:= cif cfa E F. (* IF cfa THEN E ELSE F *)\nCompute  TestConditionnelle1.  (* = F *)\n\n(* si b est cfa sortie ctr, si ctr sortie cfa *)\nDefinition neg: cbool->cbool := fun b => fun x y =>b y x . \nDefinition testNeg:= neg ctr.  (* not true==false*)\nCompute testNeg. (* => x0 *)\n\n(* AND *)\nDefinition cand: cbool->cbool->cbool := fun a b => fun x y=> a( b x y) y. \nDefinition testCand:= cand ctr cfa. (* true and  false== false*)\nCompute testCand. (* => x0 *)\n\n(* or *)\nDefinition cor:cbool->cbool->cbool:= fun a b => fun x y => a x (b x y).\nDefinition testCor:= cor cfa cfa. (* false or  false== false*)\nCompute testCor.  (* => x0 *)\n\n(* 1.2.2 *)\n\n(* declaration de type cnat *)\nDefinition cnat:= (T->T)->(T->T).\n(* codage des 5 premiers entiers de churche *)\nDefinition c0:cnat :=fun f x =>x .\nDefinition c1:cnat:=fun f x=>f x.\nDefinition c2:cnat:=fun f x => f(f x).\nDefinition c3:cnat:=fun f x => f(f(f x)).\nDefinition c4:cnat:=fun f x => f(f(f(f x))).\n\n(* fonction successeur *)\n(* n avec une fois de ++ *)\nDefinition csucc:cnat->cnat := fun n => fun f x => f(n f x).\nDefinition TestCsucc:= csucc c1.\nCompute  TestCsucc. (* 1++ ==2*)\n\n(* fonction addition *)\n(* m avec n fois de ++ *)\nDefinition cplus:cnat->cnat->cnat := fun n m => fun f x => n f (m f x).\nDefinition TestCplus:= cplus c2 c3.\nCompute  TestCplus. (* 2+3==5*)\n\n(* fonction multiplication *)\n(*m avec n fois de +m *)\nDefinition cmul:cnat->cnat->cnat := fun n m=> fun f => n (m f).\nDefinition TestCmul := cmul c2 c3.\nCompute  TestCmul. (*2*3==6*)\n\n(* fonction egale 0 *)\n(* utilise n pour choisir x ou y sur (\\z~y)x *)\nDefinition ceq0:cnat->cbool :=fun n => fun x y => n( fun z=> y) x.\nDefinition TestCeq0tr := ceq0 c0.\nCompute  TestCeq0tr.  (* 0==0 -> ctr*)\nDefinition TestCeq0fa := ceq0 c1.\nCompute  TestCeq0fa. (* 1!=0 -> cfa*)", "meta": {"author": "wen9xin", "repo": "Lambde_Calcul_Projet", "sha": "fb73b80a4210d55d5af303e42858478f0af649e7", "save_path": "github-repos/coq/wen9xin-Lambde_Calcul_Projet", "path": "github-repos/coq/wen9xin-Lambde_Calcul_Projet/Lambde_Calcul_Projet-fb73b80a4210d55d5af303e42858478f0af649e7/partie_1,2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947171284515, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8496649503001303}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(** Dans cet exercice, nous \u00e9tudions la question de l'\u00e9galit\u00e9 dans les\n    mono\u00efdes. En math\u00e9matique (et donc en informatique), un mono\u00efde\n    est un ensemble [M] muni d'un \u00e9l\u00e9ment unit\u00e9 [unit : M] et d'une\n    op\u00e9ration de s\u00e9quence [seq : M -> M -> M] v\u00e9rifiant les \u00e9quations\n    suivantes:\n\n    [[\n       (unit\u00e9 \u00e0 gauche:) \n           forall m: M, seq unit m = m\n\n       (unit\u00e9 \u00e0 droite:) \n           forall m: M, seq m unit = m\n\n       (associativit\u00e9:) \n           forall m n o: M,\n               seq m (seq n o) = seq (seq m n) o \n    ]]\n\n    Par exemple, les entiers naturels [nat] forment un mono\u00efde\n    (commutatif, de surcro\u00eet) pour l'unit\u00e9 [0 : nat] et l'addition \n    [+ : nat -> nat -> nat]. *)\n\nLemma nat_left_unit: forall n: nat, 0 + n = n.\nProof. trivial. Qed.\n\nLemma nat_right_unit: forall n: nat, n + 0 = n.\nProof. now induction n. Qed.\n\nLemma nat_assoc: forall m n o: nat, m + (n + o) = (m + n) + o.\nProof. now induction m; auto; simpl; intros; rewrite IHm. Qed.\n\n(** QUESTION [difficult\u00e9 [*] / longueur [*]]\n\n    Montrer que les listes forment \u00e9galement un mono\u00efde (non\n    commutatif) pour l'unit\u00e9 [nil : list A] et la concat\u00e9nation\n    [++ : list A -> list A -> list A]. *)\n\n\n\nLemma list_left_unit {A}: forall l: list A, [] ++ l = l.\nProof. \n  intro.\n  induction l; simpl; auto.\nQed.\n\nLemma list_right_unit {A}: forall l: list A, l ++ [] = l.\nProof. \n  apply app_nil_r.\nQed.\n\nLemma list_assoc {A}: forall (l m n: list A), (l ++ m) ++ n = l ++ (m ++ n).\nProof. \n  apply app_assoc_reverse. \nQed.\n\n(** Dans ce sujet, on s'int\u00e9resse \u00e0 la question de savoir si deux\n    expressions [e1] et [e2] de type [M] sont \u00e9gales. *)\n\n(** QUESTION  [difficult\u00e9 [*] / longueur [***]]\n\n    Prouver que les deux expressions suivantes, \u00e9crites\n    dans le mono\u00efde des listes, sont \u00e9gales: *)\nSearchAbout \"++\".\n\nExample list_eq {A}: forall (x y z: list A),\n    (x ++ (y ++ [])) ++ (z ++ [])\n        = \n    (x ++ []) ++ ([] ++ y) ++ z.\nProof.\n  intros.\n  induction x.\n   + simpl.\n     induction y.\n     * simpl. apply list_right_unit.\n     * simpl. rewrite IHy. reflexivity.\n   + simpl. rewrite IHx. simpl. reflexivity.\n\nQed.\n\n(** Plut\u00f4t que de faire une telle preuve \u00e0 chaque probl\u00e8me, nous\n    allons construire une _proc\u00e9dure de d\u00e9cision_ r\u00e9solvant le\n    probl\u00e8me de l'\u00e9galit\u00e9 pour n'importe quelle \u00e9quation et sur\n    n'importe quel mono\u00efde. *)\n\n(** * Expressions *)\n\n(** Pour cela, la premi\u00e8re \u00e9tape consiste \u00e0 d\u00e9crire, dans Coq, la\n    syntaxe de telles \u00e9quations. Pour repr\u00e9senter les variables de ces\n    \u00e9quations, nous utilisons des identifiants : *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id x1 x2 :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** Par exemple, on d\u00e9fini (arbitrairement) les variables [U] \u00e0 [Z] de\n    la fa\u00e7on suivante: *)\n\nDefinition U : id := Id 0.\nDefinition V : id := Id 1.\nDefinition W : id := Id 2.\nDefinition X : id := Id 3.\nDefinition Y : id := Id 4.\nDefinition Z : id := Id 5.\n\n(** On peut associer des valeurs Coq \u00e0 des identifiants par le moyen\n    d'un _environnement_ : *)\n\nDefinition env (A: Type) := id -> A.\n\nDefinition update {A}(e: env A)(x: id)(v: A): env A := \n  fun y => if beq_id x y then v else e y.\n\nNotation \"m [ x |-> v ]\" := (update m x v) \n                              (at level 10, x, v at next level).\n\n(** Une expression dans un mono\u00efde correspond alors \u00e0 une variable\n    [AId], \u00e0 l'unit\u00e9 [Unit] du mono\u00efde ou \u00e0 la s\u00e9quence [Seq] du\n    mono\u00efde. *)\n\nInductive exp: Type :=\n| AId: id -> exp\n| Unit: exp\n| Seq: exp -> exp -> exp.\n\n(** On note [e1 # e2] la s\u00e9quence [Seq e1 e2] et [`X] le terme [AId X]. *)\n\nInfix \"#\" := Seq \n               (right associativity, at level 60, only parsing).\nNotation \"` X\" := (AId X) \n               (at level 5, only parsing).\n\nReserved Notation \"e1 '~' e2\" (at level 65).\n\n(** Deux expressions [e1] et [e2] sont \u00e9gales, suivant les \u00e9quations\ndu mono\u00efde, si et seulement ils satisfont la relation d'\u00e9quivalence\nsuivante, ie. si l'on peut construire une preuve de [e1 ~ e2]: *)\n\nInductive eq: exp -> exp -> Prop :=\n| mon_left_id: forall e, Unit # e ~ e\n| mon_right_id: forall e, e # Unit ~ e\n| mon_assoc: forall e f g, (e # f) # g ~ e # (f # g)\n\n| mon_refl: forall e, e ~ e\n| mon_sym: forall e f, e ~ f -> f ~ e\n| mon_trans: forall e f g, e ~ f -> f ~ g -> e ~ g\n| mon_congr: forall e f g h, e ~ g -> f ~ h -> e # f ~ g # h\n\nwhere \"e1 '~' e2\" := (eq e1 e2).\n\n(** QUESTION  [difficult\u00e9 [*] / longueur [***]]\n\n    Prouver l'\u00e9quivalence suivante: *)\n\nExample mon_exp_eq:\n    (`X # (`Y # Unit)) # (`Z # Unit)\n        ~ \n    (`X # Unit) # (Unit # `Y) # `Z.\nProof.\n  assert (((`X # (`Y # Unit)) # (`Z # Unit)) ~\n  (`X # ((`Y # Unit) # (`Z # Unit)))).    \n  - apply mon_assoc.\n  - admit.  \nQed.\n\n(** Le type [exp] nous permet ainsi de repr\u00e9senter une expression\n    quelconque d'un mono\u00efde tandis que [~] capture pr\u00e9cisement les\n    \u00e9quations que v\u00e9rifie ce mono\u00efde. La preuve [mon_exp_eq] ci-dessus\n    s'applique ainsi \u00e0 _tous_ les mono\u00efdes concevables: il s'agit\n    d'une preuve \"g\u00e9n\u00e9rique\".  *)\n\n(** Cependant, la preuve en elle-m\u00eame consiste \u00e0 cr\u00e9er un t\u00e9moin de\n    l'\u00e9quivalence par le truchement des constructeurs du type [~]:\n    pour des preuves non-triviales, cela n\u00e9cessitera de construire des\n    t\u00e9moins de preuves en m\u00e9moire, ralentissant voir rendant\n    impossible l'effort de preuve. *)\n\n(** * Normalisation par \u00e9valuation *)\n\n(** Nous allons remplacer la construction manuelle de ces t\u00e9moins de\n    preuves par un _programme_ calculant ces t\u00e9moins. En prouvant la\n    correction de ce programme, on obtient alors la correction de\n    notre proc\u00e9dure de d\u00e9cision. *)\n\n(** On remarque que nos expressions s'interpr\u00e8tent naturellement dans\n    le mono\u00efde des fonctions de domaine [exp] et de co-domaine [exp],\n    o\u00f9 l'unit\u00e9 correspond \u00e0 la fonction identit\u00e9 et o\u00f9 la s\u00e9quence\n    correspond \u00e0 la composition de fonctions: *)\n\nDefinition sem_exp := exp -> exp.\n\nNotation sem_exp_unit := (fun x => x) \n                           (only parsing).\nNotation sem_exp_seq e1 e2 := (fun x => e1 (e2 x))\n                           (only parsing).\n\nFixpoint eval (c: exp): sem_exp :=\n  match c with\n  | Unit => sem_exp_unit\n  | Seq e1 e2 => sem_exp_seq (eval e1) (eval e2)\n  | AId i => fun e => `i # e\n  end.\n\n\n(** \u00c9tant donn\u00e9 un [sem_exp], on obtient une expression [exp] par\n    application \u00e0 l'unit\u00e9. Par composition de l'\u00e9valuation et de la\n    r\u00e9ification, on obtient une proc\u00e9dure de normalisation des\n    expressions. *)\n\nDefinition reify (f: sem_exp): exp := f Unit.\n\nDefinition norm (e: exp): exp := reify (eval e).\n\n(** Il s'agit de prouver que les termes ainsi obtenus sont\n    effectivement des formes normales. Formellement, il s'agit de\n    prouver la correction de notre proc\u00e9dure, ie. si deux expressions\n    sont identifi\u00e9es par [norm] alors elles sont \u00e9quivalentes par\n    l'\u00e9quivalence [~]:\n\n    [[\n    Lemma soundness:\n          forall e1 e2, norm e1 = norm e2 -> e1 ~ e2.\n    ]] \n\n    et, inversement, il s'agit aussi de prouver la compl\u00e9tude de notre\n    proc\u00e9dure, ie. si deux expressions sont \u00e9quivalentes par [~] alors\n    elles sont identifi\u00e9es par [norm]: \n\n    [[\n    Lemma completeness:\n          forall e1 e2, e1 ~ e2 -> norm e1 = norm e2.\n    ]]\n    *)\n\n(** QUESTION  [difficult\u00e9 [**] / longueur [**]]\n\n    \u00c0 cette fin, prouvez les trois lemmes techniques suivants: *)\n\nPrint eq.\n\nLemma yoneda: \n  forall e e', e # e' ~ eval e e'.\nProof.\n  intros.\n  induction e.\n  + simpl. apply mon_refl.\n  + simpl. apply mon_left_id.\n  + simpl.  \n    inversion IHe1.\n    - simpl. replace (Seq (Seq Unit e2) e') with (Seq e2 e').\n      assumption.\n      admit.\n    - admit.\n    - admit.\n    - admit.\n    - admit.\n    - admit.\n    - admit.\nQed.\n\nLemma pre_soundness: \n  forall e, e ~ norm e.\nProof.\n  intro e.\n  eapply mon_trans.\n  eapply mon_sym. eapply mon_right_id.\n  unfold norm, reify.\n  apply yoneda.\nQed.\n\nLemma pre_completeness: \n  forall e1 e2, e1 ~ e2 -> forall e', eval e1 e' = eval e2 e'.\nProof.\n  intros e1 e2 H e'.\n  induction H; try easy.\n  rewrite IHeq1. rewrite IHeq2.\n  reflexivity. simpl.\n  SearchPattern ( _ = _).\n  rewrite IHeq2.\n  (* f_equal. *)\n  admit.\nQed.\n\n(** QUESTION [difficult\u00e9 [***] / longueur [*]]\n\n    \u00c0 partir des r\u00e9sultats techniques ci-dessus, compl\u00e9tez\n    les th\u00e9or\u00e8mes suivants: *)\n\nTheorem soundness:\n  forall e1 e2, norm e1 = norm e2 -> e1 ~ e2.\nProof.\n  intros.\n  unfold norm, reify in H.\n  (** AAAAAAAAAAAAHHHHH **)\n  (* apply pre_completeness in H.*)\n  \n (* induction e1.\n  - simpl in H. apply mon_sym. *)\n    admit.\nQed.\n\nTheorem completeness: \n  forall e1 e2, e1 ~ e2 -> norm e1 = norm e2.\nProof.\n  intros. apply pre_completeness. assumption.\nQed.\n\n\n(** QUESTION [difficult\u00e9 [***] / longueur [*]]\n\n    Ces r\u00e9sultats ne servent pas seulement \u00e0 s'assurer de la validit\u00e9\n    de notre programme, ils nous permettent de donner une preuve\n    triviale \u00e0 des probl\u00e8mes d'\u00e9galit\u00e9. Par exemple, prouvez le lemme\n    suivant de fa\u00e7on concise: *)\n\nExample non_trivial_equality:\n  Seq (`U # Unit) \n       (Seq (Unit # `V)\n            (`W # \n                 (Seq (`X # `Y)\n                      (`Z # Unit))))\n    ~\n  (Seq (AId U) \n       (Seq (Seq (Seq (AId V) Unit)\n                 (Seq (AId W) Unit)) \n            (Seq (AId X) (Seq (AId Y) (AId Z))))).\nProof.\n  apply soundness.\n  unfold norm, reify. simpl. reflexivity.\nQed.\n\n(** * Preuve par r\u00e9flection *)\n\nVariable A : Type.\n\n(** Dans la section pr\u00e9c\u00e9dente, nous avons d\u00e9velopp\u00e9 une proc\u00e9dure de\n    d\u00e9cision v\u00e9rifi\u00e9e pour d\u00e9cider l'\u00e9galit\u00e9 d'expressions sur un\n    mono\u00efde quelconque. Nous allons d\u00e9sormais exploiter cet outil pour\n    d\u00e9cider de l'\u00e9galit\u00e9 dans le cas particulier du mono\u00efde des\n    listes. *)\n\n(** \u00c0 cette fin, nous donnons une interpr\u00e9tation des expressions vers\n    les listes, o\u00f9 l'unit\u00e9 est traduite vers [nil], la s\u00e9quence est\n    traduite vers la concat\u00e9nation [++] et l'interpr\u00e9tation des\n    variables est donn\u00e9e par l'environnement. *)\n\nFixpoint interp (m: env (list A))(e: exp): list A :=\n  match e with\n  | Unit => []\n  | Seq a b => interp m a ++ interp m b\n  | AId x => m x\n  end.\n\n(** Cette fonction d'interpr\u00e9tation nous permet de remplacer (de fa\u00e7on\n    calculatoirement transparente) des expressions Coq portant sur le\n    mono\u00efde des listes vers des expressions [exp] portant sur un\n    mono\u00efde quelconque. *)\n\nDefinition empty: env (list A) := fun _ => [].\n\nRemark trivial_eq: forall (x y z: list A),\n    let m := empty [ X |-> x ][ Y |-> y ][ Z |-> z ] in\n\n    (x ++ (y ++ [])) ++ (z ++ [])\n       = \n    interp m ((`X # (`Y # Unit)) # (`Z # Unit)).\n\nProof. reflexivity. Qed.\n\n\n(** QUESTION [difficult\u00e9 [**] / longueur [**]]\n\n    L'interpr\u00e9tation [interp] est _correcte_ si elle respecte les\n    \u00e9galit\u00e9s des mono\u00efdes. Prouvez que c'est effectivement le cas. *)\n\nLemma interp_proper: forall m e e', e ~ e' -> interp m e = interp m e'.\nProof.\n  intros.\n  induction H; try auto.\n  - simpl. SearchAbout \"app_\". apply app_nil_r.\n  - simpl. apply app_assoc_reverse.\n  - simpl. rewrite IHeq1. rewrite IHeq2. auto.\n  - simpl. rewrite IHeq1. rewrite IHeq2. auto.\nQed.\n\n(** QUESTION [difficult\u00e9 [***] / longueur [**]]\n\n    En exploitant le lemme [interp_proper] et la correction de la\n    proc\u00e9dure de d\u00e9cision, donnez des preuves concises des \u00e9galit\u00e9s\n    suivantes. *)\n\nExample list_eq2: forall (x y z: list A),\n    (x ++ (y ++ [])) ++ (z ++ [])\n        = \n    (x ++ []) ++ ([] ++ y) ++ z.\nProof.\n  intros.\n  set (m := empty [ X |-> x ][ Y |-> y ][ Z |-> z]).\n  change ((x ++ (y ++ [])) ++ (z ++ [])) \n  with (interp m ((`X # (`Y # Unit)) # (`Z # Unit))).\n  change ((x ++ []) ++ ([] ++ y) ++ z)\n  with (interp m ((`X # Unit) # (Unit # `Y) # `Z)).\n  apply interp_proper.\n  apply soundness. compute. reflexivity.  \nQed.\n\nExample list_eq3 : forall (u: list A) v w x y z, \n    u ++ ([] ++ v ++ []) ++ w ++ x ++ (y ++ []) ++ z\n      = \n    u ++ ((v ++ [] ++ w) ++ x ++ y) ++ (z ++ []) ++ [].\nProof.\n  intros.\n  set (m := empty [ U |-> u ][ V |-> v ][ W |-> w] [X |-> x ][ Y |-> y ][ Z |-> z]).\n  change (u ++ ([] ++ v ++ []) ++ w ++ x ++ (y ++ []) ++ z) \n  with (interp m (`U # (Unit # (AId V)# Unit) # (AId W) # (AId X) #\n                   ((AId Y) # Unit) # (AId Z))).\n  change (u ++ ((v ++ [] ++ w) ++ x ++ y) ++ (z ++ []) ++ [])\n  with (interp m (`U # (((AId V) # Unit # (AId W)) # (AId X) # (AId Y))\n                   # ((AId Z) # Unit) # Unit)).\n  apply interp_proper.\n  apply soundness. reflexivity.\nQed.", "meta": {"author": "infou012", "repo": "Verification", "sha": "14ddcb52ab106d6b5b50c2b76b64f6908491dac3", "save_path": "github-repos/coq/infou012-Verification", "path": "github-repos/coq/infou012-Verification/Verification-14ddcb52ab106d6b5b50c2b76b64f6908491dac3/dm_1_monoidstudent_issa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850066369693, "lm_q2_score": 0.9073122219871936, "lm_q1q2_score": 0.849502829785083}}
{"text": "Require Import ZArith List.\nOpen Scope Z_scope.\n\n(* Define a datatype of binary trees where non-atomic nodes have only two\n  components which are binary trees, and only atomic nodes carry an integer\n  value.  Include a case for empty trees. *)\n\nInductive bt : Type :=  E | L (x : Z) | N (t1 t2 : bt).\n\n(* Define a function that takes a list as input and constructs a balanced\n  binary tree carrying the same values.  The trick is to interchange the\n  the two components of each node after inserting an integer into the first\n  node -- beware that you have to define two recursive functions for this\n  question. *)\n\nFixpoint insert_bt (x : Z) (t : bt) : bt :=\n  match t with\n    E => L x\n  | L y => N (L x) (L y)\n  | N t1 t2 =>  N t2 (insert_bt x t1)\n  end.\n\nDefinition bt_of_l : list Z -> bt := fold_right insert_bt E.\n\n(* Define a function with three arguments: a natural number and two\n  lists, which builds a new list by always taking the least element\n  of the heads of the two lists.  The length of the resulting list should\n  be the natural number given as first input (if the two lists are long enough).\n\n  This is a merge function as in the \"merge sort\" algorithm, except that the\n  natural number argument should be the sum of the lengths of the two input\n  lists.\n*)\n\nFixpoint merge' (n:nat)(l1 l2 : list Z) : list Z :=\n  match n with\n    O => nil\n  | S p => \n    match l1, l2 with\n      (a::l1), (b::l2) =>\n         if Zle_bool a b then\n            a::merge' p l1 (b::l2)\n         else\n            b::merge' p (a::l1) l2\n    | (a::l1), nil => a::merge' p l1 nil\n    | nil, (b::l2) => b::merge' p nil l2\n    | nil, nil => nil\n    end\n  end.\n\n(* Define a function that merges two lists bu first computing the sum of their\n  lengths and then calling the previous function. *)\n\nDefinition merge (l1 l2 : list Z) : list Z :=\n  merge' (length l1 + length l2) l1 l2.\n\n(* Define a recursive function on binary trees which returns a sorted list:\n  - on empty trees it returns the empty list\n  - on leaf treeas carrying one value, it returns a singleton list\n  - on binary nodes, it returns the merge of the two sorted lists obtained\n    from the sub-components. *)\n\nFixpoint sl_of_bt (t : bt) : list Z :=\n  match t with\n    E => nil\n  | L x => x::nil\n  | N t1 t2 => merge (sl_of_bt t1) (sl_of_bt t2)\n  end.\n\n(* Define a function that sorts a list by first constructing a balanced binary\n  tree and then by calling the function above. *)\n\nDefinition merge_sort (l:list Z) := sl_of_bt (bt_of_l l).\n\n(* Define a function that takes three integers a, b, and n and constructs the\n  list a^n mod b, a^(n-1) mod b, ....  a mod b -- use the iter function\n  as in the previous class.  Use this function to generate large lists of\n  pseudo-random numbers.  Test your sorting function on these inputs. *)\n\nDefinition pseudo_rand a b n :=\n  let (_, l) := iter n (Z*list Z) (fun p => \n                     let (v,l) := p in\n                     let v' := Zmod (a * v) b in\n                          (v', v'::l)) (1, nil) in\n  l.\n\nDefinition l1 := Eval vm_compute in pseudo_rand 1789 100003 500.\n\nEval vm_compute in length l1.\nTime Eval vm_compute in (merge_sort l1).\n\n\nFixpoint sorted_bool (l:list Z) : bool :=\n match l with nil => true\n            | a::nil => true\n            | a::((b::l) as l1)  => if Zle_bool a b \n                                    then sorted_bool l1 \n                                    else false\n end.\n\nEval compute in sorted_bool (merge_sort l1).\nEval vm_compute in sorted_bool l1.\n\n\n\n", "meta": {"author": "magret2canard", "repo": "master1", "sha": "a993e9cbd38ee045af2900f9486ee9438d5e3274", "save_path": "github-repos/coq/magret2canard-master1", "path": "github-repos/coq/magret2canard-master1/master1-a993e9cbd38ee045af2900f9486ee9438d5e3274/LOGIQUE/TD2/TD2_solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024820841433, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8494892988019183}}
{"text": "Require Export Arith List.\n\nSection DivConq.\n\nVariable A : Type.\nImplicit Type l : list A.\n\n\n(* (Ordering) lengthOrder ls1 ls2 :=\n * length ls1 < length ls2\n *)\n\nDefinition lengthOrder (ls1 ls2 : list A) := length ls1 < length ls2.\n\nLemma lengthOrder_wf' : forall len, forall ls, \n  length ls <= len -> Acc lengthOrder ls.\nProof.\nunfold lengthOrder; induction len.\n- intros; rewrite Nat.le_0_r,length_zero_iff_nil in H; rewrite H; constructor;\n  intros; inversion H0.\n- destruct ls; constructor; simpl; intros.\n  + inversion H0.\n  + simpl in H; apply le_S_n in H; apply lt_n_Sm_le in H0; apply IHlen; \n    eapply Nat.le_trans; eassumption.\nDefined.\n\n\n(* lengthOrder_wf: \n * states that the ordering, lengthOrder, is well founded.\n *)\n\nLemma lengthOrder_wf : well_founded lengthOrder.\nProof.\nred; intro; eapply lengthOrder_wf'; eauto.\nDefined.\n\n\n(* div_conq: \n * Suppose for some arbitrary split function, splitF, with the condition that\n * for any list l, if the length of l is at least 2, then both the sublists\n * generated have length less than the input list. To prove some proposition P\n * holds for all lists ls, one needs to prove the following:\n * 1. P holds for empty list, nil.\n * 2. P holds for one-element list, (a :: nil).\n * 3. If P hold fst(splitF ls) and snd(splitF ls), then P must also hold for ls.\n *)\n\nLemma div_conq : \n  forall (P : list A -> Type) \n  (splitF : list A -> list A * list A)\n  (splitF_wf1 : forall ls, 2 <= length ls -> lengthOrder (fst (splitF ls)) ls)\n  (splitF_wf2 : forall ls, 2 <= length ls -> lengthOrder (snd (splitF ls)) ls),\n    P nil -> (forall a, P (a :: nil))\n    -> (forall ls, (P (fst (splitF ls)) -> P (snd (splitF ls)) -> P ls))\n    -> forall ls, P ls.\nProof.\nintros; apply (well_founded_induction_type lengthOrder_wf); intros.\ndestruct (le_lt_dec 2 (length x)).\n- apply X1; apply X2.\n  + apply splitF_wf1; auto.\n  + apply splitF_wf2; auto.\n- destruct x; auto. simpl in l; \n  apply le_S_n, le_S_n, Nat.le_0_r,length_zero_iff_nil  in l; rewrite l; auto.\nDefined.\n\n\n(* split:= \n * split an input list ls into two sublists where the first sublist contains all\n * the odd indexed element/s and the second sublist contains all the even\n * indexed element/s. \n *)\n\nFixpoint split (ls : list A) : list A * list A :=\n  match ls with\n  | nil => (nil, nil)\n  | h :: nil => (h :: nil, nil)\n  | h1 :: h2 :: ls' =>\n      let (ls1, ls2) := split ls' in\n        (h1 :: ls1, h2 :: ls2)\n  end.\n\n\n(* split_wf: \n * states that for any list ls of length at least 2, each of the two sublists\n * generated has length less than its original list's.\n *)\n\nLemma split_wf : forall len ls, 2 <= length ls <= len\n  -> let (ls1, ls2) := split ls in lengthOrder ls1 ls /\\ lengthOrder ls2 ls.\nProof.\nunfold lengthOrder; induction len; intros.\n- inversion H; inversion H1; rewrite H1 in H0; inversion H0.\n- destruct ls; inversion H.\n  + inversion H0.\n  + destruct ls; simpl; auto. \n    destruct (le_lt_dec 2 (length ls)).\n    * specialize (IHlen ls); destruct (split ls); destruct IHlen; simpl.\n      simpl in H1; apply le_S_n in H1; split; auto. apply le_Sn_le; auto. \n      split; rewrite <- Nat.succ_lt_mono; auto.\n    * inversion l. \n      -- destruct ls; inversion H3; apply length_zero_iff_nil in H4; rewrite H4;\n         simpl; auto.\n      -- apply le_S_n in H3. inversion H3. \n         apply length_zero_iff_nil in H5; rewrite H5; simpl; auto.\nDefined.\n\nLtac split_wf := intros ls ?; intros; generalize (@split_wf (length ls) ls);\n  destruct (split ls); destruct 1; auto.\n\nLemma split_wf1 : forall ls, 2 <= length ls -> lengthOrder (fst (split ls)) ls.\nProof.\nsplit_wf.\nDefined.\n\nLemma split_wf2 : forall ls, 2 <= length ls -> lengthOrder (snd (split ls)) ls.\nProof.\nsplit_wf.\nDefined.\n\n\n(* div_conq_split: \n * - an instance of div_conq where the arbitrary splitF function\n *   is replaced by the split function defined above.\n * - To prove some proposition P holds for all lists ls, one needs to prove the\n     following:\n *   1. P holds for empty list, nil.\n *   2. P holds for one-element list, (a :: nil).\n *   3. If P hold fst(split ls) and snd(split ls), then P must also hold for ls.\n *)\n\nDefinition div_conq_split P := div_conq P split split_wf1 split_wf2.\n\nEnd DivConq.\n\nLtac div_conq_split := eapply div_conq_split.", "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/ct04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.9149009555730611, "lm_q1q2_score": 0.8494021024151598}}
{"text": "(********** Exercice 1 **********)\n(* Question 1 *)\nFixpoint myplus (a b:nat) :=\nmatch b with\n| 0 => a\n| S n => S (myplus a n)\nend.\n\n(* Question 2 *)\nRequire Import Arith.\nLemma myplus_assoc : forall a b c : nat,\nmyplus (myplus a b) c = myplus a (myplus b c).\nProof.\nintros.\ninduction c.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHc.\nreflexivity.\nQed.\n\n(* Question 3 *)\nLemma myplus_Sn_m : forall n m : nat,\nmyplus (S n) m = S (myplus n m).\nProof.\nintros.\ninduction m.\nsimpl.\nreflexivity.\nsimpl.\nrewrite <- IHm.\nreflexivity.\nQed.\n\nLemma myplus_0_m : forall m : nat,\nmyplus 0 m = m.\nProof.\nintros.\ninduction m.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHm.\nreflexivity.\nQed.\n\n(* Question 4 *)\nLemma myplus_comm : forall a b :nat,\nmyplus a b = myplus b a.\nProof.\nintros.\ninduction a.\nsimpl.\nrewrite myplus_0_m.\nreflexivity.\nsimpl.\nrewrite myplus_Sn_m.\nrewrite IHa.\nreflexivity.\nQed.\n\n(* Question 5 *)\nFixpoint sommation (f:nat->nat) (n:nat) :=\nmatch n with\n| 0 => f n\n| S m => f (S m) + sommation f m\nend.\n\nEval compute in sommation (fun x => x) 100.\n\n(* Question 6 *)\nRequire Export ArithRing.\nLemma sommation_f_Sn : forall (f: nat->nat) (n:nat),\nsommation f (S n) = f (S n) + sommation f n.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nLemma q6 : forall n : nat,\n2 * sommation (plus 0) n = n*(n+1).\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nrewrite plus_Sn_m.\nrewrite sommation_f_Sn.\nrewrite plus_O_n.\nrewrite Nat.mul_add_distr_l.\nrewrite IHn.\nring.\nQed.\n\n(********** Exercice 2 **********)\n(* Question 7 *)\n(* \n  m correspond, \u00e0 .\n  i et j correspondent respectivement au nombre de pi\u00e8ces 5 et 3 euros.\n*)\n(* Question 8&9 *)\n(*\n  Avec le principe d'induction suivant, on pourra ais\u00e9ment d\u00e9montrer le th\u00e9or\u00e8me.\n  forall P : nat->Prop,\n  P 0 -> P 1 -> P 2 -> (forall n : nat, P n -> P(n+3)) -> forall n : nat, P n.\n*)\nLemma induc_by_3 : forall P : nat->Prop,\nP 0 -> P 1 -> P 2 -> (forall n : nat, P n -> P(S (S (S n)))) -> forall n : nat, P n.\nProof.\nintros.\nassert (Hx : P n /\\ P (S n) /\\ P (S (S n))).\ninduction n.\nsplit.\nassumption.\nsplit;assumption.\nsplit.\ndestruct IHn.\ndestruct H4.\nassumption.\nsplit.\ndestruct IHn.\ndestruct H4.\nassumption.\napply H2.\ndestruct IHn.\nassumption.\ndestruct Hx.\nassumption.\nQed.\n\nLemma pieces : forall m : nat, exists i : nat, exists j : nat,\n8+m=5*i+3*j.\nProof.\nintros.\ninduction m.\nexists 1.\nexists 1.\nreflexivity.\ndestruct IHm as [x [y H]].\nrewrite <- plus_n_Sm, H.\ndestruct x.\n(* x=0 *)\n  (* y=0 *)\n  destruct y.\n  discriminate.\n    (* y => Sy *)\n    destruct y.\n    discriminate.\n    destruct y.  \n    discriminate.\n    exists 2,y.\n    ring.\n(* x>0 *)\nexists x, (y+2).\nring.\nQed.\n\t\nLemma pieces_avec_mon_lemmme : forall m : nat, exists i : nat, exists j : nat,\n8+m=5*i+3*j.\nProof.\nQed.\n\n", "meta": {"author": "Neo-Purpinc", "repo": "Preuves-Assistees-par-Ordinateur", "sha": "f285b2efa87283e3940121095a67a98b1b488357", "save_path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur", "path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur/Preuves-Assistees-par-Ordinateur-f285b2efa87283e3940121095a67a98b1b488357/TP3/TP3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8492973517629385}}
{"text": "(* Exercise coq_tree_05 *)\n\nRequire Import Arith.\n\n(* Let us start with the definitions from the previous \n   exercises *)\n\nInductive nat_tree : Set :=\n  | leaf : nat_tree\n  | node : nat_tree -> nat -> nat_tree -> nat_tree.\n\nFixpoint In (n : nat) (T : nat_tree) {struct T} : Prop :=\n  match T with\n  | leaf => False\n  | node l v r => In n l \\/ v = n \\/ In n r\n  end.\n\nFixpoint mirror (T : nat_tree) : nat_tree :=\n  match T with\n  | leaf => leaf\n  | node l v r => node (mirror r) v (mirror l)\n  end. \n\nFixpoint tree_sum(T: nat_tree): nat := \n  match T with\n  | leaf => 0\n  | node l v r => (tree_sum l) + v + (tree_sum r)\n  end.\n\nSearch (?n + O).\n\nLemma tree_sum_ex : forall a b c d,\n  tree_sum (node (node leaf a leaf) b (node (node leaf c leaf) d leaf)) =\n  a + b + c + d.\n  \nProof.\nintros.\nsimpl.\nrepeat rewrite Nat.add_0_r.\nrewrite Nat.add_assoc.\nreflexivity.\nQed.\n\nPrint Nat.add_comm.\n(* Now let us prove that the sum of the elements in the\n   mirrored tree is the same as in the original one *)\n   \nLemma mirror_tree_sum : forall T, tree_sum T = tree_sum (mirror T).\n\nProof.\n  intros.\n  induction T.\n* simpl; reflexivity.\n* simpl.\n  rewrite IHT1.\n  rewrite IHT2.\n  rewrite Nat.add_comm.\n  rewrite Nat.add_comm with (m := n).\n  rewrite Nat.add_assoc.\n  reflexivity.\nQed.", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_tree_05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.847930075679043}}
{"text": "(* The next couple of commands are from bool.v but their\nneeded to make sense of the first part of this file *)\n\nInductive bool : Type :=\n\t| true : bool\n\t| false: bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n    | true => b2\n    | false => false\n   end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n    | true => true\n    | false => b2\n  end.\n\n\nModule NatPlayground.\n\nInductive nat : Type :=\n  | O : nat (* O is a natural number (note that this is the letter \"O,\" not the numeral \"0\")*)\n  | S : nat -> nat. (* S can be put in front of a natural number to yield another one \\u2014 if n is a natural number, then S n is too *)\n\n(* The following is the predecessor function, returns the nat before the nat given *)\nDefinition pred (n:nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n' (* \"if n has the form S n' for some n', then return n'.\" *)\n  end.\n\nEnd NatPlayground.\n\nCheck (S (S (S (S O)))).\n\nDefinition minustwo (n:nat) : nat :=\n  match n with \n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\n\nCompute (minustwo 4).\n\nCheck S.\n\nCheck pred.\n\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).\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatPlayground2.\n\nFixpoint plus (n:nat) (m:nat) : nat :=\n  match n with \n  | O => m\n  | S n'=> S (plus n' m)\n  end.\n\nCompute (plus 3 2).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m: nat) : nat :=\n  match (n, m) with\n  | (O, _) => O\n  | (S _, O) => n\n  | (S n', S m') => minus n' m'\n  end.\nEnd NatPlayground2.\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 3.\n\n(* Exercise *)\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y) (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).\nCompute ((0 + 1) + 1).\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\n(* tests whether its first argument is less \nthan or equal to its second argument, yielding a boolean. *)\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' => match m with\n            | O => false\n            | S m' => leb n' m'\n            end\n  end.\n\nExample test_leb1: (leb 2 2) = true.\nProof. simpl. reflexivity. Qed.\nExample test_leb2: (leb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_leb3: (leb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* exercise blt_nat *)\n\n\n\n\n\n\n\n\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": "dschneck", "repo": "coq-code", "sha": "3f8455c41488d95b7295b03b078d8499c6dc0034", "save_path": "github-repos/coq/dschneck-coq-code", "path": "github-repos/coq/dschneck-coq-code/coq-code-3f8455c41488d95b7295b03b078d8499c6dc0034/chapters/functional-programming-in-coq/Data_and_Functions/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.9230391590112402, "lm_q1q2_score": 0.847793240252314}}
{"text": "Inductive AExp : Type :=\n| ALit (n : nat)\n| APlus (a1 a2 : AExp)\n| ASub (a1 a2 : AExp).\n\nDefinition exTree : AExp := \n(APlus \n    (ASub \n        (ALit 1)\n        (APlus\n            (ALit 2)\n            (ALit 3)\n        )\n     )\n    (ALit 0)\n).\n\nFixpoint leaves (a : AExp) : nat := match a with\n  | ALit n => 1\n  | APlus a1 a2 => leaves a1 + leaves a2\n  | ASub a1 a2 => leaves a1 + leaves a2\n  end.\n\nFixpoint height (a : AExp) : nat := match a with\n  | ALit n => 0\n  | APlus a1 a2 => 1 + max (height a1) (height a2)\n  | ASub a1 a2 => 1 + max (height a1) (height a2)\n  end.\n\nExample exExp : AExp := (APlus (ALit 1) (ALit 2)).\n\nLemma exExpProp : height exExp = 1.\nProof.\n  simpl.\n  reflexivity.\nQed.\n(*\nTactic reminder:\n\n           INTRODUCTION     ELIMINATION\nTrue       split\nFalse                       destruct\n/\\         split            destruct\n\\/         left, right      destruct\nforall     intro            apply\nexists     exists           destruct\n->         intro            apply\n\nothers:\nassert\ndiscriminate\nsimpl\n*)\n\n\n(*\nAbstract representation levesl: \nABT  not possible to represent \"\\x.(x+y\" (\\x read as lambda x) due to scope\nWTT  not possible to represent \"true+1\" due to not possible to evaluate\nAlg\nHOAS\n*)\n\nExample expWithProperty : exists (a : AExp), leaves a = 3 /\\ height a = 2.\nProof.\n  exists (ASub (ALit 10) (ASub (ALit 1) (ALit 2))).\n  simpl.\n  split.\n  all: reflexivity.\nQed.\n\nExample notPoss : not (exists (a : AExp), leaves a = 2 /\\ height a = 0).\nProof.\n  unfold not.\n  intros.\n  destruct H.\n  destruct H.\n  destruct x.\n  { unfold leaves in H. discriminate. }\n  all: simpl in H0.\n  all: discriminate H0.\nQed.\n\n\n(* Denotational semantics *)\nFixpoint aeval (a : AExp) : nat :=\n  match a with\n  | ALit n      => n\n  | APlus a1 a2 => aeval a1 + aeval a2\n  | ASub  a1 a2 => aeval a1 - aeval a2\n  end.\n\nCompute aeval exTree.\nCompute exExp.\nCompute aeval exExp.\n\nLemma eval_exExp : aeval exExp = 3.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nCheck ex_proj1.\n\n\nFixpoint optim (a : AExp) : AExp :=\n  match a with\n  | ALit n => ALit n\n  | APlus e1 (ALit 0) => optim e1\n  | APlus e1 e2 => APlus (optim e1) (optim e2)\n  | ASub  e1 e2 => ASub  (optim e1) (optim e2)\n  end.\n\nCompute optim exExp.\nCompute aeval exExp.\nCompute aeval (APlus (ALit 1) (ALit 2)).\n\nRequire Import Coq.Arith.Plus.\n\nCheck plus_0_r.\n\n\nLemma optim_sound (a : AExp) :\n  aeval (optim a) = aeval a.\nProof.\n  induction a.\n  { simpl. reflexivity. }\n  { simpl.\n    destruct a2.\n    destruct n.\n    { rewrite IHa1. simpl. rewrite (plus_0_r). reflexivity. }\n    { simpl. rewrite IHa1. reflexivity. }\n    { simpl. simpl in IHa2. rewrite IHa2. rewrite IHa1. reflexivity. }\n    { simpl. simpl in IHa2. rewrite IHa2. rewrite IHa1. reflexivity. }\n  }\n  { simpl. rewrite -> IHa1. rewrite -> IHa2. reflexivity. }\nQed.\n\n\n\nLemma optim_sound2 (a : AExp) :\n  aeval (optim a) = aeval a.\nProof.\n  induction a.\n  all: try ( info_auto ).\n  all: try ( simpl; rewrite -> IHa1; rewrite -> IHa2; reflexivity ).\n  simpl.\n  destruct a2.\n  destruct n.\n  all: try ( simpl; simpl in IHa2; rewrite IHa2; rewrite IHa1; info_auto ).\n  all: try ( simpl; rewrite IHa1; reflexivity ).\n  rewrite IHa1. simpl.  rewrite (plus_0_r). reflexivity.\nQed.\n\n(* try, ; *)\n\n\nFixpoint optimoptim (a : AExp) : AExp := ALit (aeval a).\n\nLemma optimoptim_sound (a : AExp ) : aeval (optimoptim a) = aeval a.\nProof.\n  induction a.\n  all: simpl.\n  all: reflexivity.\nQed.\n\n\nFixpoint optim' (a : AExp) : AExp :=\n  match a with\n  | ALit n => ALit n\n  | APlus (ALit x) (ALit y) => ALit (x + y)\n  | APlus e1 e2 => APlus (optim' e1) (optim' e2)\n  | ASub  e1 e2 => ASub  (optim' e1) (optim' e2)\n  end.\n\nLemma optim'_sound (a : AExp) : aeval (optim' a) = aeval a.\nProof.\n  induction a.\n  all: try ( simpl; reflexivity ).\n  all: try ( simpl; rewrite IHa1; rewrite IHa2; reflexivity ).\n  destruct a1.\n  destruct a2.\n  destruct n.\n  all: try ( simpl; reflexivity ).\n  all: try ( simpl in IHa2; simpl; rewrite IHa2; reflexivity ).\n  all: try ( simpl in IHa1; simpl; rewrite IHa1; rewrite IHa2; reflexivity ).\nQed.\n\n(* exercise: create more optimisations and prove them sound! *)\n\t\t\t\t\t\t   \nRequire Import Nat.\nRequire Import Arith.\n\n(* standard library documentation *)\n\n(* See Arith.Le *)\n\nCheck Nat.le_refl.\nCheck Nat.le_trans.\nCheck Nat.le_max_l.\nCheck Nat.le_max_r.\nCheck Nat.pow_le_mono.\nCheck Nat.add_le_mono.\n\nLemma leaves_height (a : AExp) : leaves a <= 2 ^ height a.", "meta": {"author": "Kokan", "repo": "elte_msc", "sha": "2092ccd8f65bf33473eab54e9d7f5facb7eda6e1", "save_path": "github-repos/coq/Kokan-elte_msc", "path": "github-repos/coq/Kokan-elte_msc/elte_msc-2092ccd8f65bf33473eab54e9d7f5facb7eda6e1/formalsemantics/gy04pre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.9230391563648733, "lm_q1q2_score": 0.8477932357619834}}
{"text": "Require Import Arith fib_ind.\n\n\n(* A geralisation of the fibonacci sequence, parameterized by\n   its two first items *)\n\nFixpoint general_fib (a0 a1 n:nat) {struct n} : nat :=\n  match n with\n  | O => a0\n  | S p => general_fib a1 (a0 + a1) p\n  end.\n\nDefinition fib_tail (n:nat) := general_fib 1 1 n.\n\n\n(** Test : should return 89\n\nCompute fib_tail 10.\n\n*)\n\n\nLemma general_fib_1 : forall a b:nat, general_fib a b 1 = b.\nProof. reflexivity. Qed.\n\n\nLemma general_fib_S :\n forall a b n:nat, general_fib a b (S n) = general_fib b (a + b) n.\nProof. reflexivity. Qed. \n\n\nLemma general_fib_2 :\n forall a b n:nat,\n   general_fib a b (S (S n)) = general_fib a b n + general_fib a b (S n).\nProof.\n intros a b n; generalize a b; induction n as [ | n IHn].\n - reflexivity.\n - clear a b; intros a b.\n   rewrite (general_fib_S _ _ (S (S n))), IHn.\n   now rewrite (general_fib_S _ _  (S n)).\nQed.\n\nLemma linear_fibo_equiv : forall n:nat, fib_tail n = fib n.\nProof.\n intro n; induction n as [| | n IHn IHSn] using fib_ind.\n - reflexivity.  \n - reflexivity.  \n -  unfold fib_tail in *; rewrite general_fib_2.\n    rewrite IHn, IHSn; reflexivity.  \nQed.\n\n\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch9_function_specification/SRC/fib_tail.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8476756886528614}}
{"text": "Require Import ZArith.\nRequire Import List.\nRequire Extraction.\n\nSet Implicit Arguments.\n\n(* ================================================================================== *)\n(* ====================================EXERC\u00cdCIO 1=================================== *)\n(* ================================================================================== *)\n\n(*1. Apresente uma especifica\u00e7\u00e3o forte adequada a cada uma das fun\u00e7\u00f5es abaixo indicadas.\n     Fa\u00e7a a prova desses teoremas (especifica\u00e7\u00e3o) e, por fim, proceda \u00e0 extra\u00e7\u00e3o do respectivo programa Haskell.*)\n\n  (*a) Uma fun\u00e7\u00e3o que, dado um n\u00famero natural n e um valor x, constroi uma lista de tamanho n cujos elementos s\u00e3o todos iguais a x.*)\n  Inductive CreateNList (A: Type) : nat -> A -> (list A) -> Prop :=\n    | CNLzero : forall (x : A), CreateNList 0%nat x nil\n    | CNLsucc : forall (n: nat) (x: A) (l: list A), CreateNList n x l -> CreateNList (S n) x (x::l).\n\n  Theorem ex1a : forall (A: Type) (n: nat) (x: A), { l: list A | CreateNList n x l }.\n  Proof.\n    intros.\n    induction n.\n    - exists nil. apply CNLzero.\n    - elim IHn. intros. exists (x::x0). apply CNLsucc. apply p.\n  Qed.\n\n  Extraction Language Haskell.\n  Recursive Extraction ex1a.\n  Extraction Inline nat_rect.\n  Extraction Inline sig_rect.\n  Recursive Extraction ex1a.\n\n  Extraction \"ex1a\" ex1a.\n\n  (*b) Uma fun\u00e7\u00e3o que recebe uma lista de pares de n\u00fameros naturais, e produz a lista com as somas das partes constituintes de cada par da lista.*)\n  Inductive PairList : (list (nat*nat)) -> (list nat) -> Prop :=\n    | PLnil  : PairList nil nil\n    | PLcons : forall (p: (nat*nat)) (l1: list (nat*nat)) (l2: list nat), PairList l1 l2 -> PairList (p::l1) ((fst p + snd p)::l2).\n\n  Theorem ex1b : forall (l1: list (nat*nat)), { l2: list nat | PairList l1 l2 }.\n  Proof.\n    intros.\n    induction l1.\n    - exists nil. apply PLnil.\n    - elim IHl1. intros. exists ((fst a+snd a)::x). apply PLcons. apply p.\n  Qed.\n\n  Extraction Language Haskell.\n  Recursive Extraction ex1b.\n  Extraction Inline list_rect.\n  Extraction Inline list_rec.\n  Extraction Inline sig_rec.\n  Recursive Extraction ex1b.\n\n  Extraction \"ex1b\" ex1b.\n\n(* ================================================================================== *)\n(* ====================================EXERC\u00cdCIO 2=================================== *)\n(* ================================================================================== *)\n\n(*2. Recorde a fun\u00e7\u00e3o count que conta o n\u00famero de ocorr\u00eancias de um inteiro numa lista de inteiros.*)\nFixpoint count (z: Z) (l: list Z) {struct l} : nat :=\n  match l with\n    | nil => 0%nat\n    | (z' :: l') => if (Z.eq_dec z z')\n                    then S (count z l')\n                    else count z l'\n  end.\n\n  (*a) Prove a seguinte propriedade*)\n  Theorem ex2a : forall (x: Z) (a: Z) (l: list Z), x <> a -> count x (a :: l) = count x l.\n  Proof.\n    intros.\n    simpl.\n    elim (Z.eq_dec x a).\n      - easy.\n      - intros. reflexivity.\n  Qed.\n\n  (*b) Defina uma rela\u00e7\u00e3o indutiva que descreva a rela\u00e7\u00e3o entre o input e o output para a fun\u00e7\u00e3o count, ou seja, a sua especifica\u00e7\u00e3o.*)\n  Inductive CountRelation : Z -> (list Z) -> nat -> Prop :=\n    | CRnil     : forall (x: Z), CountRelation x nil 0%nat\n    | CRheadEq  : forall (x: Z) (l: list Z) (n: nat), CountRelation x l n -> CountRelation x (x::l) (S n)\n    | CRheadDif : forall (x y: Z) (l: list Z) (n: nat), (x <> y /\\ CountRelation x l n) -> CountRelation x (y::l) n.\n\n\n  (*c) Prove que a fun\u00e7\u00e3o dada acima satisfaz a especiifica\u00e7\u00e3o apresentada na al\u00ednea anterior.*)\n  Theorem ex2c : forall (x: Z) (l: list Z), CountRelation x l (count x l).\n  Proof.\n    intros.\n    induction l.\n    - simpl. apply CRnil.\n    - simpl. elim (Z.eq_dec x a).\n      + intros. replace a with x. apply CRheadEq. apply IHl.\n      + intros. apply CRheadDif. split.\n        * apply b.\n        * apply IHl.\n  Qed.", "meta": {"author": "GoncaloEsteves", "repo": "Formal-Verification", "sha": "e865fa4dbf3b50bb4823cc3963fdc43c0e3c25df", "save_path": "github-repos/coq/GoncaloEsteves-Formal-Verification", "path": "github-repos/coq/GoncaloEsteves-Formal-Verification/Formal-Verification-e865fa4dbf3b50bb4823cc3963fdc43c0e3c25df/Exercises/08_Coq(3)/questoesCoq3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.9161096170250075, "lm_q1q2_score": 0.8476120578741482}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\n(*\n    You are only allowed to use these tactics:\n\n    simpl, reflexivity, intros, rewrite, destruct, induction, apply, assert\n\n    You are not allowed to use theorems outside this file *unless*\n    explicitly recommended.\n*)\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nShow that 5 equals 5.\n\n *)\nTheorem ex1: 5 = 5.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\nShow that equality for natural numbers is reflexive.\n\n *)\nTheorem ex2: forall (x:nat), x = x.\nProof.\n  intros x.\n  reflexivity.\nQed.\n\n(**\n\nShow that [1 + n] equals the successor of [n].\n\n *)\nTheorem ex3: forall n, 1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\n\nQed.\n\n(**\n\nShow that if [x = y], then [y = x].\n\n *)\nTheorem ex4: forall x (y:nat), x = y -> y = x.\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n(**\n\nShow that if the result of the conjunction and the disjunction equal,\nthen both boolean values are equal.\n\n\n *)\nTheorem ex5: forall (b c : bool), (andb b c = orb b c) -> b = c.\nProof.\n  intros.\n  induction b.\n  -assert (Th: forall (b:bool), orb true b = true). { reflexivity. }\n   rewrite Th in H.\n   rewrite <- H.\n   reflexivity.\n  -assert (th: forall (b : bool), andb false b = false). { reflexivity. }\n   rewrite th in H.\n   rewrite -> H.\n   reflexivity.\nQed.\n\n(**\n\nIn an addition, we can move the successor of the left-hand side to\nthe outer most.\n\n\n *)\nTheorem ex6: forall n m, n + S m = S (n + m).\nProof.\n  intros.\n  induction n.\n  -simpl.\n   reflexivity.\n  -simpl.\n   rewrite <- IHn.\n   reflexivity.\nQed.\n\n\n(**\n\nIf two additions are equal, and the numbers to the left of each addition\nare equal, then the numbers to the right of each addition must be equal.\nTo complete this exercise you will need to use the auxiliary\ntheorem: eq_add_S\n\n\n *)\nTheorem ex7: forall x y n, n + x = n + y -> x = y.\nProof.\nintros.\n  induction n.\n  - simpl in H.\n    rewrite <- H.\n    reflexivity.\n  - simpl in H.\n    apply eq_add_S in H.\n    apply IHn.\n    rewrite -> H.\n    reflexivity.\n\nQed.\n\n(**\n\nShow that addition is commutative.\nHint: You might need to prove `x + 0 = x` and `S (y + x) = y + S x`\nseparately.\n\n\n *)\n\nTheorem eqn1 x: x + 0 = x.\nProof.\n  induction x.\n  -reflexivity.\n  -simpl.\n   rewrite -> IHx.\n   reflexivity.\nQed.\n\nTheorem eqn2 x y: x + S y = S(x + y).\nProof.\n  intros.\n  induction x.\n  -simpl.\n   reflexivity.\n -simpl.\n  rewrite IHx.\n  reflexivity.\nQed.\n\nTheorem ex8: forall x y, x + y = y + x.\nProof.\n  intros.\n  induction x.\n  -rewrite eqn1.\n   simpl.\n   reflexivity.\n  -simpl.\n   rewrite IHx.\n   rewrite eqn2.\n   reflexivity.\nQed.\n\n(**\n\nIf two additions are equal, and the numbers to the right of each addition\nare equal, then the numbers to the left of each addition must be equal.\n\nHint: Do not try to prove this theorem directly. You should be using\nauxiliary results. You can use Admitted theorems.\n\n\n *)\nTheorem ex9: forall x y n, x + n = y + n -> x = y.\nProof.\n  intros x y n eqn.\n  assert (equ: forall x n, x + n = n + x). { apply ex8. } \n  rewrite equ in eqn.\n  assert (eqy: forall y n, y + n = n + y). { apply ex8. }\n  symmetry in eqn.\n  rewrite eqy in eqn.\n  symmetry in eqn.\n  apply ex7 in eqn.\n  rewrite -> eqn.\n  reflexivity.\nQed.\n\n\n\n", "meta": {"author": "Kenilpatel057", "repo": "Intro-to-Theory-of-computation", "sha": "27a998cbda0ba0286056d8f61fe037d5c26c6381", "save_path": "github-repos/coq/Kenilpatel057-Intro-to-Theory-of-computation", "path": "github-repos/coq/Kenilpatel057-Intro-to-Theory-of-computation/Intro-to-Theory-of-computation-27a998cbda0ba0286056d8f61fe037d5c26c6381/hw1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.9161096147346158, "lm_q1q2_score": 0.8476120557550091}}
{"text": "Require Import nat.\nRequire Import le.\n\nDefinition relation (a:Type) : Type := a -> a -> Prop.\n\nInductive clos (a:Type) (r:relation a) : relation a :=\n| rt_step : forall x y, r x y -> clos a r x y\n| rt_refl : forall x, clos a r x x\n| rt_trans: forall x y z, clos a r x y -> clos a r y z -> clos a r x z\n.\n\nArguments clos {a} _ _ _.\n\nInductive next : relation nat := nextS : forall n, next n (S n).\n\n(* '<=' is the reflexive-transitive closure of 'next' *)\n\nLemma le_is_clos_next : forall (n m:nat), n <= m <-> clos next n m.\nProof.\n    intros n m . split.\n    - intros H. induction H as [n|n m H IH].\n        + apply rt_refl.\n        + apply rt_trans with (y:=m).\n            { exact IH. }\n            { apply rt_step, nextS. }\n    - intros H. induction H as [n m H|n|n m p H1 IH1 H2 IH2].\n        + inversion H. apply le_S, le_n.\n        + apply le_n.\n        + apply le_trans with (m:=m).\n            { exact IH1. }\n            { exact IH2. }\nQed.\n\n(*  The definition of refl-trans closure not very convenient\n    for doing proofs, due to the 'non-determinism' of the \n    transitive rule. We are now trying a more useful definition. \n*)\n\n\nInductive clos' (a:Type) (r:relation a) (x:a) : a -> Prop :=\n| rt'_refl : clos' a r x x\n| rt'_mix  : forall (y z:a), r x y -> clos' a r y z -> clos' a r x z\n.\n\nArguments clos' {a} _ _ _.\n\n(* are these two definitions equivalent *)\n\nLemma rt'_step : forall (a:Type) (r:relation a) (x y:a), \n    r x y -> clos' r x y.\nProof.\n    intros a r x y H. apply rt'_mix with (y:=y). \n    - exact H.\n    - apply rt'_refl.\nQed.\n\nLemma rt'_trans : forall (a:Type) (r:relation a) (x y z:a),\n    clos' r x y -> clos' r y z -> clos' r x z.\nProof.\n    intros a r x y z H. revert z. induction H as [|x y z Hxy H IH].\n    - intros z H. exact H.\n    - intros z' H'. apply rt'_mix with (y:=y).\n        + exact Hxy.\n        + apply IH. exact H'.\nQed.\n\nLemma clos_iff_clos' : forall (a:Type) (r: relation a) (x y:a),\n    clos r x y <-> clos' r x y.\nProof.\n    intros a r x y. split.\n    - intros H. induction H as [x y H|x|x y z H1 IH1 H2 IH2].\n        + apply rt'_step. exact H.\n        + apply rt'_refl.\n        + apply rt'_trans with (y:=y).\n            { exact IH1. }\n            { exact IH2. }\n    - intros H. induction H as [x|x y z H H' IH'].\n        + apply rt_refl.\n        + apply rt_trans with (y:=y).\n            { apply rt_step. exact H. }\n            { exact IH'. }\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/closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.897695283896349, "lm_q1q2_score": 0.8475831133675253}}
{"text": "Module Playground1.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n    | O => true\n    | S O => false\n    | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nDefinition admit {T: Type} : T.  Admitted.\n(* Haskell: undefined *)\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) {struct n} : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with \n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n    | O   , _    => O\n    | _   , O    => n          (* make this non-overlapping *)\n    | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  intro n.\n  simpl.\n  reflexivity.\nQed.\n\n(* End of seminar 1. *)\n\n(* ************************************************************ *)\n\n(* Looking up info *)\n\n(* Require Import Arith. *)\nSearch nat.\nSearchAbout nat.\n(* SearchPattern (_ -> nat).    (* Doesn't work in older coq versions *) *)\nSearchRewrite (0 + _).\n\n\n(* More tactics. *)\n\nTheorem plus_id_example : forall n m,\n                            n = m -> n + n = m + m.\nProof.\n  intros k l.\n  intros H.\n  rewrite <- H.                    (* show directions *)\n  reflexivity.\nQed.\n\nTheorem mult_O_plus : forall n m : nat,\n                        (0 + n) * m = n * m.\nProof.\n  intros.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n, m with\n    | O, O => true\n    | S n', S m' => beq_nat n' m'\n    | _, _ => false\n  end.\n\nPrint beq_nat.\n\nTheorem plus_1_neq_0_b : forall n : nat,\n                           beq_nat (n+1) 0 = false.\nProof.\n  intros.\n  (* destruct n; reflexivity. *)\n  destruct n.\n    reflexivity.\n\n    reflexivity.\nQed.\n\nAxiom convenient : forall n, n+1 = S n.\n\nTheorem plus_1_neq_0 : forall n : nat, n + 1 <> 0.\nProof.\n  intros.\n  (* rewrite convenient. *)\n  (* discriminate. *)\n  destruct n.\n    discriminate.\n\n    simpl.\n    discriminate.\nQed.\n\nTheorem eq_beq_nat : forall n m : nat,\n    n = m <-> beq_nat n m = true.\nProof.\n  intros.\n  split.\n    intro.\n    rewrite H.\n(* Finish from here. Hard. Good HW! :) *)\nAdmitted.\n\n\nTheorem plus_0_r : forall n, n + 0 = n.\nProof.\n  intros.\n  induction n.\n    reflexivity.\n\n    simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat, n - n = 0.\nProof.\n  intros.\n  induction n.\n    reflexivity.\n\n    simpl.\n    assumption.\nQed.\n\nTheorem plus_comm : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n    simpl.\n    rewrite plus_0_r.\n    reflexivity.\n\n    simpl.\n    rewrite IHn.\n    assert (forall k l, k + S l = S (k + l)).\n      clear IHn n m.\n      intros.\n      induction k.\n        reflexivity.\n\n        simpl.\n        rewrite IHk.\n        reflexivity.\n\n    rewrite H.\n    reflexivity.\nQed.\n(* HW: do without assert, but with induction within induction. *)\n\n(* Induction more closely *)\n\nFixpoint double n : nat :=\n  match n with\n    | O => O\n    | S n' => S (S (double n'))\n  end.\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n.\n  induction n.\n    intros.\n    simpl in H.\n    destruct m.\n      reflexivity.\n\n      simpl in H.\n      discriminate H.\n\n   (* induction side *)\n   intros.\n   destruct m.\n     discriminate H.\n\n     (* apply a hypothesis to the goal *)\n     f_equal.                   (* remove the same constructor *)\n     apply IHn.\n     simpl in H.\n     (* TODO(klao): look up how to introduce S-es to the goal. *)\n     (* union of 'discriminate' and 'f_equal in hypothesis' *)\n     inversion H.\n     reflexivity.\nQed.\n(* TODO(klao): look into: printing readable proofs. *)\n\n(* End of Seminar 2. *)\n\n(* ********************************************************************** *)\n(* Seminar 3 starts here. *)\n\n(* revert, generalize dependent, and induction in |- *)\n\n\n\nTheorem plus_rearrange : forall n m p q,\n    (n + m) + (p + q) = (m + n) + (q + p).\nProof.\n  intros.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  Check plus_comm.\n\n  rewrite (plus_comm n m).\n  (* rewrite (plus_comm p q). *)\n  (* reflexivity. *)\n  replace (p + q) with (q + p).\n  reflexivity.\n  apply plus_comm.\nQed.\n\n(* ************* *)\n(* 'Apply' and other tactic examples *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* intros. *)\n  (* apply H. *)\n  (* exact H0. *)\n\n  intro H.\n  (* apply H. *)\n  exact (H 3).\nQed.\n\nTheorem silly3 : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n\n  symmetry.\n  (* simpl. *) (* Actually, this [simpl] is unnecessary, since \n            [apply] will do a [simpl] step first. *)  \n  apply H.\nQed.\n\n(* Reasoning in assumptions, aka forward reasoning. *)\nTheorem silly3' : forall (n : nat),\n  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n     true = beq_nat n 5  ->\n     true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  remember H as H1.\n  clear HeqH1.\n  symmetry in H. apply eq in H. symmetry in H. \n  apply H.\nQed.\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n    (* Hint: use the plus_n_Sm lemma *)\n    intros. destruct m as [| m']. reflexivity.\n    simpl in H. discriminate H.\n\n    intros. destruct m as [| m']. discriminate H.\n    simpl in H. rewrite <- !plus_n_Sm in H.  (* rewrite modifiers *)\n    inversion H. apply IHn' in H1. rewrite H1. reflexivity.\nQed.\n\n\n(* Remember and destruct expression. *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n  | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n  assert (x = v) as H by reflexivity;\n  clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n    set (x := name); move_to_top x\n  | assert_eq x name; move_to_top x\n  | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  intros f b.\n  destruct b.\n  Case \"b = true\".\n  remember (f true) as ftrue.\n    destruct ftrue.\n    SCase \"f true = true\".\n      rewrite <- Heqftrue.\n      symmetry.\n      apply Heqftrue.\n    SCase \"f true = false\".\n      remember (f false) as ffalse.\n      destruct ffalse.\n      SSCase \"f false = true\".\n        symmetry.\n        apply Heqftrue.\n      SSCase \"f false = false\".\n        symmetry.\n        apply Heqffalse.\n  remember (f false) as ffalse.\n    destruct ffalse.\n    SCase \"f false = true\".\n      remember (f true) as ftrue.\n      destruct ftrue.\n      SSCase \"f true = true\".\n        symmetry.\n        apply Heqftrue.\n      SSCase \"f true = false\".\n        symmetry.\n        apply Heqffalse.\n    SCase \"f false = false\".\n      rewrite <- Heqffalse.\n      symmetry.\n      apply Heqffalse.\nQed.\n\n(* HW *)\nTheorem bool_funcs : forall (f : bool -> bool),\n  (forall b, f (f b) = f b) \\/ (forall b, f b = negb b).\nAdmitted.\n\nTheorem bool_fn_applied_thrice' : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  intro f.\n  destruct (bool_funcs f).\n    intro.\n    rewrite H.\n    rewrite H.\n    reflexivity.\n\n    intro.\n    rewrite !H.\n    (* SearchAbout negb. *)\n    rewrite Bool.negb_involutive.\n    reflexivity.\nQed.\n\n(* Seminar 3 ended here. *)\n(* ********************************************************** *)\n(* Seminar 4 starts here. *)\n\n\nModule ExampleList1.\n\nInductive list (T : Type) : Type :=\n  | nil\n  | cons : T -> list T -> list T.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nCheck (cons _ 2 (cons _ 1 (nil _))).\n\nCheck cons.\nCheck nil.\n\nEnd ExampleList1.\n\nModule ExampleList2.\n\nSet Implicit Arguments.\n\nInductive list (T : Type) : Type :=\n  | nil\n  | cons : T -> list T -> list T.\n\nCheck (cons 2 (cons 1 (nil _))).\n\nImplicit Arguments nil [[T]].\n(* Deprecated, use: Arguments nil [T]. *)\n\nCheck (cons 2 (cons 1 nil)).\n\nUnset Implicit Arguments.\n\nFixpoint length {X:Type} (l:list X) : nat := \n  match l with\n  | nil      => 0\n  | cons h t => S (length t)\n  end.\n\nEval compute in length (cons 2 (cons 1 nil)).\n\nCheck @length.\n\nNotation \"x :: y\" := (cons x y) \n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\n\n(* Define app! *)\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n    | [] => l2\n    | h :: t => h :: app t l2\n  end.\n\nNotation \"x ++ y\" := (app x y) \n                     (at level 60, right associativity).\n\n\nEval compute in [1,2,3] ++ 4::5::[].\n\nFixpoint repeat {X : Type} (x : X) (count : nat) : list X := \n  match count with\n    | O => nil\n    | S c' => x :: repeat x c'\n  end.\n\nEval compute in repeat true 3.\n\nTheorem repeat_length : forall n X (x : X), length (repeat x n) = n.\nAdmitted.\n\n(* Induction priciple for induction definition. *)\n\nCheck nat_ind.\nCheck list_ind.\n\nTheorem app_assoc : forall X (l1 l2 l3 : list X), l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\nAdmitted.\n\n(* HW: trivial *)\nTheorem app_length : forall X (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.\nAdmitted.\n\n(* HW: involved. What should the induction go on? *)\nTheorem app_length2 : forall X (l1 l2 : list X) n1 n2,\n     length l1 = n1 -> length l2 = n2 -> length (l1 ++ l2) = n1 + n2.\nAdmitted.\n\n\nInductive vector (T : Type) : nat -> Type :=\n  | nilv : vector T 0\n  | consv n : T -> vector T n -> vector T (S n).\n\nImplicit Arguments nilv [[T]].\nImplicit Arguments consv [[T] [n]].\n\nCheck consv 1 (consv 2 nilv).\n\nFixpoint lengthv {T : Type} {n : nat} (v : vector T n) : nat := admit.\n\nFixpoint repeatv {X : Type} (x : X) (n : nat) : vector X n :=\n  match n with\n    | 0 => nilv\n    | S n' => consv x (repeatv x n')\n  end.\n\nTheorem lengthv_repeatv : forall n X (x : X), lengthv (repeatv x n) = n.\nProof.\nAdmitted.\n(* Show that simpl is not enough here, but compute is, or unfold. *)\n\nNotation \"[[ x , .. , y ]]\" := (consv x .. (consv y nilv) ..).\n\n\n(* Skip here to talk about Curry-Howard *)\n\nCheck [1,2,3].\nCheck [[ 1 , 2 , 3 ]].\n\nCompute repeat true 3.\nCompute repeatv true 3.\n\nCheck @repeat bool.\n(* bool -> nat -> list bool *)\nCheck @repeatv bool.\n(* bool -> forall n : nat, vector bool n *)\n(* Wrong: bool -> nat -> vector bool nat *)\n\nCheck vector.\n\nDefinition repeatv2 : bool -> vector bool 2 :=\n  fun b => repeatv b 2.\nCheck fun b : bool => repeatv b 2.\n\nCheck repeatv true.\n\n\n(* Relation of 'forall' and '->' *)\n\nCheck forall n : nat, list bool.\n\nEnd ExampleList2.\n\nModule ExamplesC_H.\n\nParameter A B : Prop.\n\nPrint A.\n\nDefinition A_to_B := forall h : A, B.\n\nPrint A_to_B.\n\n(* h : A, \"means\" h is a proof of A *)\n(* At this point we had an exposition about Curry-Howard isomorphism. *)\n(* Look into Seminar4_Curry_Howard.hs for a Haskell side track. *)\n\n\nCheck forall n : nat, bool.\n\nCheck forall n : nat, A.\n\nTheorem A_to_B_to_A : A -> B -> A.\nProof.\n  intros.\n  assumption.\n  Show Proof.\nQed.\n\nDefinition P_to_Q_to_P : forall P Q : Prop, P -> Q -> P := fun _ _ x _ => x.\n\nCheck P_to_Q_to_P.\n\nTheorem whatever : B -> A -> B.\nProof.\n  apply P_to_Q_to_P.\nQed.\n\nCheck A_to_B.                   (* = A -> B *)\nCheck A_to_B_to_A.              (* : A -> B -> A *)\n\n(* two_times_n_plus_3 *)\n\nTheorem two_times_n_plus_3 : nat -> nat.\nProof.\n  intros n.\n  induction n.\n    exact 3.\n\n    exact (S (S IHn)).\n\n(* Qed. ---> makes the proof term 'opaque'. *)\nDefined.\n\nCompute two_times_n_plus_3 2.\nCompute two_times_n_plus_3.\n\n(* P -> True *)\n\nTheorem P_to_True : forall P : Prop, P -> True.\nProof.\n  intros.\n  trivial.\nQed.\n\nPrint True.\n(* haskell: data True = I *)\n\nDefinition P_to_True' : forall P : Prop, P -> True :=\n  fun _ _ => I.\nCheck P_to_True'.\n\nDefinition P_to_True'' (P : Prop) (H : P) : True :=\n  I.\nCheck P_to_True''.\n\n\n\n(* False -> P *)\n\nTheorem False_to_P : forall P : Prop, False -> P.\nProof.\n  intros.\n  (* induction H. also works! *)\n  contradiction.\n  Show Proof.\n  Print False_ind.\n  Print False_rect.\nQed.\n\nPrint False.\n\n(* Definition False_to_P' : forall P : Prop, False -> P := *)\nDefinition False_to_P' (P : Prop) (H : False) : P :=\n  match H with\n  end.\n\nPrint False_to_P'.  \n\n(* HW: 1 <> 0.  Hard! *)\n(* Unset Printing Notations. *)\nCheck 0 <> 1.\n\n(* Seminar 4 ends here *)\n(*****************************************************************************)\n\n(* Logical connectives and evidence *)\n\n(* We already know the connection between the imlication and forall,\n   and functions and functions with generalized product type *)\n\n(* And, Or, Iff *)\n\nTheorem a_and_b_to_a'n'b : A -> B -> A /\\ B.\nProof.\n  intros.\n  split ; assumption.\n  Show Proof.\nQed.\n\nLocate \"_ /\\ _\".\nLocate \"_ * _\".\nDefinition and' (A : Prop) (B : Prop) :=  prod A B.\n\nInductive and'' (A : Prop) (B : Prop) : Prop :=\n  es (_ : A) (_ : B).\nPrint and''.\n\nPrint and.\nCheck conj.\n\nTheorem a_and_b_to_a'n'b2 : A -> B -> A /\\ B.\nProof.\n  apply conj.\n  Show Proof.\nQed.\n\nTheorem a_and_b_to_a'n'b3 : A -> B -> A /\\ B.\nProof  (fun a => fun b => conj a b).\n\n(* Reminder for lambda expressions. *)\nCheck (fun x => x+1).\n\n\nLocate \"_ \\/ _\".\nPrint or.\nCheck or_introl.\n\nTheorem a_to_a'or'b : A -> A \\/ B.\nProof (fun a => or_introl _ a).\n(* @or_introl A B a *)\n(* Proof. *)\n(*   intros. *)\n(*   left. *)\n(*   assumption. *)\n(* Qed. *)\n\nTheorem b'or'a_to_a'or'b : B \\/ A -> A \\/ B.\nProof (fun ba => match ba with\n                   | or_introl x => or_intror _ x\n                   | or_intror y => or_introl _ y\n                 end).\nPrint or_introl.\nCheck or_introl.\n(* Work it out. *)\n\n\n\n(* How about not? *)\n(* Classical vs. Intuitionistic logic *)\n\nLocate \"~ _\".\nPrint not.\n\nTheorem a_to_notnota : A -> ~~A.\n(* Proof (fun x y => y x). *)\nProof.\n  intros.\n  unfold \"~\".\n  intros.\n  apply H0.\n  assumption.\nQed.\n\n(* Can we also prove this? *)\nTheorem notnota_to_a : ~~A -> A. Admitted.\n\n(* Seminar 5 ended here. *)\n(* ************************************************************ *)\n\n\nDefinition LEM := forall p, p \\/ ~p.\nPrint LEM.\n\nDefinition Peirce := forall (a b : Prop), ((a -> b) -> a) -> a.\nPrint Peirce.\n\n(* We will prove that LEM <-> Peirce. But what is it? As a function? *)\n\n\n\n\n(* Equality and non-equality. Or, where in hell is the assumption that\n   1 <> 0 is buried in Coq? *)\n\nTheorem true_neq_false : true <> false. Admitted.\n\n\n(* Frobenius rule *)\n\nTheorem Frobenius (A : Set) (p : A -> Prop) (q : Prop) :\n  (exists x : A, q /\\ p x) <-> (q /\\ exists x : A, p x).\nProof.\nAdmitted.\n\nTheorem dual_Frobenius (A : Set) p q :\n  (forall x : A, q \\/ p x) <-> (q \\/ forall x : A, p x).\nProof.\nAdmitted.\n\n\n(* Other inductive predicates. *)\n\n\nEnd ExamplesC_H.\n\n", "meta": {"author": "klao", "repo": "coq-learning", "sha": "e408913099774f2390bd5541c1d438d3c835d803", "save_path": "github-repos/coq/klao-coq-learning", "path": "github-repos/coq/klao-coq-learning/coq-learning-e408913099774f2390bd5541c1d438d3c835d803/work_sheets/Seminar6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.8475831099012934}}
{"text": "Inductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\nmatch n with \n| O => O\n| S n' => n'\nend.\n\nDefinition succ (n:nat) :nat :=\nmatch n with \n| O => (S O)\n| S n' => S (S n')\nend.\n\nDefinition minustwo (n: nat) : nat :=\nmatch n with\n| O => O\n| S O => O\n| S (S n') => n'\nend.\n\nFixpoint evenb (n:nat) : bool :=\nmatch n with \n| O => true\n| S O => false\n| S n' => negb (evenb n')\nend.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nFixpoint plus (n:nat) (m:nat) : nat :=\nmatch n with\n| O => m\n| S n' => S (plus n' m)\nend.\n\nFixpoint mult (n m :nat) : nat :=\nmatch n with\n| O => O\n| S O => m\n| S n' => plus m (mult n' m)\nend.\n\nFixpoint minus (n m : nat) : nat :=\nmatch n, m with \n| O, _ => O\n| S n', O => n\n| S n, S m => minus n m\nend.\n\nFixpoint exp (base power :nat) : nat :=\nmatch power with\n| O => S O\n| S n => mult base (exp base n)\nend.\n\nFixpoint factorial (n:nat) : nat :=\nmatch n with \n| O => S O\n| S O => S O\n| S n' => mult n (factorial n')\nend.\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\n\nNotation \"x - y\" := (minus x y)\n                        (at level 50,left associativity)\n                        : nat_scope.\n\nNotation \"x * y\" := (mult x y)\n                        (at level 40,left associativity)\n                        : nat_scope.\n\n\nFixpoint beq_nat (n m : nat) : bool :=\nmatch n with\n| O => match m with \n  | O => true\n  | S m' => false\nend\n| S n' => match m with\n  | O => false\n  | S m' => (beq_nat n' m')\nend\nend.\n\nFixpoint blt_nat (n m : nat) : bool :=\nmatch n with\n| O => match m with\n  | O => false\n  | S _ => true\nend\n| S n' => match m with\n  | O => false\n  | S m' => blt_nat n' m'\nend\nend.\n\nInductive bin : Type :=\n| Z : bin\n| T : bin -> bin\n| T' : bin -> bin.\n\nFixpoint incr (n : bin) : bin :=\nmatch n with\n| Z => T' Z\n| T n' => T' n'\n| T' n' => T (incr n')\nend.\n\nFixpoint bin_pred (n: bin) : bin :=\nmatch n with\n| Z => Z\n| T Z => Z\n| T' Z => Z\n| T' n' => T n'\n| T n' => T' (bin_pred n')\nend.\n\nFixpoint bin_to_nat (n: bin) : nat :=\nmatch n with \n| Z => O\n| T' n' => succ (bin_to_nat (T n'))\n| T n' => succ (bin_to_nat (T' (bin_pred n')))\nend.\n\n\n\n", "meta": {"author": "soumyadsanyal", "repo": "sf", "sha": "6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7", "save_path": "github-repos/coq/soumyadsanyal-sf", "path": "github-repos/coq/soumyadsanyal-sf/sf-6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7/nats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8474215371319747}}
{"text": "(***********************************************************************)\n(** * Definition of Finite numbers *)\n(***********************************************************************)\n\n(* Bound variables are represented using the 'fin' datatype shown below.\n\n   Elements of fin n can be seen as natural numbers in the set {m | m < n}.\n\n   The key idea is the index of this type says how many elements the type\n   has. For example, the type [fin 0] is an empty type, the type [fin 1] only\n   has a single value [fO], the type [fin 2] has two values ([fO] and [fS\n   fO]), etc.  \n\n   Some definitions in this library are from equations example \n   https://github.com/mattam82/Coq-Equations/blob/master/examples/Fin.v \n\n   There is a lot more we can do with [fin], but this is enough for \n   STLC (and we don't need all of it).\n\n*)\n\n(* ----------- imports --------------- *)\nRequire Import Program.Basics Program.Combinators.\nFrom Equations Require Import Equations.\nRequire Import Coq.Program.Equality. \nRequire Import Nat.\nRequire Import Lia.\n\nInductive fin : nat -> Set :=\n  | fO : forall {n}, fin (S n)\n  | fS : forall {n}, fin n -> fin (S n).\n\nDerive Signature NoConfusionHom NoConfusion for fin.\n\n(* decidable equality is derivable *)\nDerive EqDec for fin.\n\n(* ------- type coercions ------ *)\n\n(* Coerce [m] to a smaller range, as long as it is not k. \n   does not change the \"value\" of [m]. *)\n(* NB: used in \"open\" *)\nEquations decrease_fin (k : nat) (m : fin (S k)) : option (fin k) :=\n  decrease_fin O _ := None ;\n  decrease_fin (S _) fO := Some fO;\n  decrease_fin (S m) (fS n) := option_map fS (decrease_fin m n).\n\n(* Coerce [m] to a larger range, without changing its value. *)\n(* NB: used in \"close\" operation. *)\nEquations increase_fin {n : nat} (m : fin n) : fin (S n) :=\n  increase_fin fO  := fO;\n  increase_fin (fS m) := fS (increase_fin m). \n\n(* -------- isomorphism with {m : nat | m < n} ------- *)\n\n(* Coerce between [fin] and [nat], preserving value.\n\n    f0 <-> O\n    fS f0 <-> S O\n    fS (fS f0) <-> S (S O)\n*)\n  \n(* We can inject [fin n] into [nat]. Forget the rich type. *)\nEquations fog {n} (f : fin n) : nat :=\n  fog fO     := 0 ;\n  fog (fS f) := S (fog f).\n\nPrint fog_graph.\n\n(* And come back again. Note: we produce a [fin] with the \n   smallest possible range. *)\nEquations gof (n : nat) : fin (S n) :=\n  gof O := fO ;\n  gof (S n) := fS (gof n).\n\nPrint fog.\nPrint gof.\n\n(* ------- properties of definitions above ------- *)\n\nLemma fog_gof (n : nat) : fog (gof n) = n.\nProof with auto with arith.\n  intros. funelim (gof n). info_auto.\n  simp fog. congruence.\nQed.\n\nLemma fog_inj {n} (f : fin n) : fog f < n.\nProof with auto with arith. \n  intros.\n  funelim (fog f); simp fog...\n(*  induction f; simp fog...\n  dependent induction f; simp fog...\n  depind f; simp fog... *)\nQed.\n\nRequire Import Coq.Logic.EqdepFacts.\n\n(* increase_fin is injective *)\nLemma increase_fin_inj : forall {n} (f f0 : fin n),\n    (increase_fin f = increase_fin f0) -> f = f0.\nProof.\n  intros n f g.\n  funelim (increase_fin f).\n  all: dependent elimination g; simp increase_fin.\n  auto.\n  intros h. inversion h.\n  intros h. inversion h.\n  intros h. \n  noconf h. f_equal. auto.   (* no axiom *)\n  (* These two proofs work, but need an axiom *)\n(*  inversion h. dependent destruction H1. f_equal. auto. *)\n(*  inversion h. apply Eqdep.EqdepTheory.inj_pair2 in H1.\n  f_equal. auto. *)\nQed.\n\nPrint Assumptions increase_fin_inj.\n\n(* decrease fin is injective *)\nLemma decrease_fin_inj : forall {n} (f f0 : fin (S n)),\n    (decrease_fin n f = decrease_fin n f0) -> f = f0.\nProof.\n  intros.\n  dependent induction n;\n  dependent elimination f;\n  dependent elimination f0; auto.    \n  all: try solve [dependent elimination f].\n  all: try simp decrease_fin in H.\n  all: destruct (decrease_fin n f) eqn: E1.\n  all: try destruct (decrease_fin n f0) eqn: E2.\n  all: simpl in H.\n  all: try discriminate.\n  all: noconf H.\n  all: rewrite <- E2 in E1.\n  all: eapply IHn in E1.\n  all: f_equal; auto.\nQed.\n  \n(* increase always produces a number less than the max. *)\nLemma increase_not_n : forall {n}(f : fin n), \n         not (gof n = increase_fin f).\nProof. \n  intros.\n  dependent induction n;\n  dependent elimination f;\n  simp gof; simp increase_fin.\n  intros h. noconf h. \n  intros h. noconf h. eapply IHn. eauto.\nQed.\n\n\n(* If we can decrease a fin, then increasing it gives us the same number. *)\nLemma decrease_increase_fin :\n  forall {n1} (f0 : fin n1) (f : fin (S n1)),  \n    decrease_fin n1 f = Some f0 -> increase_fin f0 = f.\nProof.\n  intros.\n  dependent induction f.\n  destruct n1. inversion f0. simp decrease_fin in H. \n  inversion H. simp increase_fin. auto.\n  destruct n1. inversion f0. simp decrease_fin in H. \n  destruct (decrease_fin n1 f) eqn:E1. simpl in H. inversion H.\n  eapply IHf in E1; eauto. simp increase_fin. f_equal. auto.\n  simpl in H. discriminate.\nQed.  \n\n(* If we cannot decrease a fin, then we must have started with the maximum value. *)\nLemma decrease_to_fin : \n  forall {n1} (f: fin (S n1)), decrease_fin n1 f = None -> gof n1 = f.\nProof.\n  intros.\n  dependent induction f.\n  destruct n1; simp decrease_fin in H; simp gof. auto. discriminate.\n  destruct n1; simp decrease_fin in H; simp gof. \n  inversion f.\n  destruct (decrease_fin n1 f) eqn:E1. simpl in H. inversion H.\n  eapply IHf in E1; eauto. f_equal. auto.\nQed.\n\n(* If we had increased first, we can decrease *)\nLemma decrease_fin_increase_fin : \n  forall n1 (f : fin n1), decrease_fin n1 (increase_fin f) = Some f.\nProof. \n  intros.\n  dependent induction f.\n  all: simp increase_fin.\n  all: simp decrease_fin.\n  all: auto.\n  rewrite IHf.\n  reflexivity.\nQed.\n\n(* Since gof gives us the largest number in the range, we cannot decrease it. *)\nLemma decrease_fin_gof : forall n, decrease_fin n (gof n) = None.\nProof.\n  induction n.\n  all: simp gof. \n  all: simp decrease_fin. \n  auto. rewrite IHn. \n  reflexivity.\nQed.\n\nCreate HintDb fin.\n#[export] Hint Rewrite fog_gof : fin.\n#[export] Hint Rewrite decrease_fin_increase_fin : fin.\n#[export] Hint Rewrite decrease_fin_gof : fin.\n#[export] Hint Resolve decrease_to_fin : fin.\n#[export] Hint Resolve decrease_increase_fin : fin.\n#[export] Hint Resolve increase_not_n : fin.\n\n#[export] Hint Extern 1 (_ = _) => match goal with \n | [ H : increase_fin _ = increase_fin _ |- _ ] => apply increase_fin_inj end : fin.\n\n#[export] Hint Extern 1 (_ = _) => match goal with \n | [ H : gof _ = increase_fin _ |- _ ] => exfalso; eapply increase_not_n end : fin.\n\n(*\n\nInductive le : nat -> nat -> Type :=\n| le_O n : 0 <= n\n| le_S {n m} : n <= m -> S n <= S m\nwhere \"n <= m\" := (le n m).\nDerive Signature for le.\nHint Constructors le.\nEquations le_S_inv {n m} (p : S n <= S m) : n <= m :=\nle_S_inv (le_S p) := p.\n\nEquations fin_inj {n} {m} (f : fin n) (k : n <= m) : fin m :=\nfin_inj fO (le_S p) := fO;\nfin_inj (fS f) (le_S p) := fS (fin_inj f p).\n\nLemma foo : forall m n, m <= S (n + m). Admitted.\n\nEquations fin_plus {n m} (x : fin n) (y : fin m) : fin (n + m) := \nfin_plus (@fO n) f := fin_inj f _ ;\nfin_plus (@fS n x) y := fS (fin_plus x y). \nNext Obligation. apply foo. Defined.\n\nPrint fin_plus.\nPrint fin_plus_obligations_obligation_1.\n(** Won't pass the guardness check which diverges anyway. *)\n*)\n\n", "meta": {"author": "sweirich", "repo": "equations-ln", "sha": "b10a2c0de7403a84eeedb3f089449b59194838e9", "save_path": "github-repos/coq/sweirich-equations-ln", "path": "github-repos/coq/sweirich-equations-ln/equations-ln-b10a2c0de7403a84eeedb3f089449b59194838e9/Stlc/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8474144160018828}}
{"text": "Module Playground1.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nCheck true.\nCheck bool.\n\nCheck True.\nCheck (forall x : bool, x=x).\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\n(* comment *)\n\n(* Haskell: data Nat = O | S Nat *)\n\nCheck (S (S (S O))).\n\n\nEnd Playground1.\n\nPrint Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCheck (S (S (S O))).\nEval simpl in (minustwo 4).\n\nCheck minustwo.\nCheck S.\nCheck pred.\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\nPrint evenb.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1 : oddb (S O) = true.\nProof. unfold oddb. (* unfold evenb. *) simpl. reflexivity. Qed.\n\nExample test_oddb2 : oddb 4 = false.\nProof. reflexivity. Qed.\n\n\nModule Playground2.\n\nDefinition admit {T: Type} : T.  Admitted.\n\n(* Haskell: undefined *)\n\nFixpoint plus (n : nat) (m : nat) {struct n} : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n(* Comment about struct *)\n\nTheorem three_plus_two : plus 3 2 = 5.\nProof. reflexivity. Qed.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with \n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n    | O   , _    => O\n    | _   , O    => n          (* make this non-overlapping *)\n    | S n', S m' => minus n' m'\n  end.\n\nPrint minus.\n\nEnd Playground2.\n\nPrint minus.\n\nExample test_mult1 : (mult 3 4) <> 9.\nProof. simpl. discriminate. 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\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  intro n.\n  simpl.\n  reflexivity.\nQed.\n\n(* Explain the difference: *)\nEval simpl in (forall n:nat, 0 + n = n).\n\nEval simpl in (forall n:nat, n + 0 = n).\n\n(* End of first seminar. *)\n", "meta": {"author": "klao", "repo": "coq-learning", "sha": "e408913099774f2390bd5541c1d438d3c835d803", "save_path": "github-repos/coq/klao-coq-learning", "path": "github-repos/coq/klao-coq-learning/coq-learning-e408913099774f2390bd5541c1d438d3c835d803/work_sheets/Seminar1edited.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.9032942119105696, "lm_q1q2_score": 0.847401990587492}}
{"text": "(* We start with a boring input of 2 standard-library modules that we'll use. *)\nRequire Import Coq.Unicode.Utf8 Arith String.\n\n\n(** * A good example of general inductive types: syntax trees for a small programming language *)\n\n(** Specifically, here's a type of simple trees of arithmetic operations on natural numbers.\n  * [nat] is Coq's type for natural numbers, defined in the standard library.\n  * (More on those below!) *)\nInductive exp : Set :=\n| Constant : nat -> exp\n| Plus : exp -> exp -> exp\n| Times : exp -> exp -> exp.\n\n(** Recursive function to evaluate an arithmetic expression to a number. *)\nFixpoint eval (e : exp) : nat :=\n  match e with\n  | Constant n => n\n  | Plus e1 e2 => eval e1 + eval e2\n  | Times e1 e2 => eval e1 * eval e2\n  end.\n\n(** A mischievous function to swap the operands of all operators *)\nFixpoint commuter (e : exp) : exp :=\n  match e with\n    | Constant _ => e\n    | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n    | Times e1 e2 => Times (commuter e2) (commuter e1)\n  end.\n\n(** We of course want to be *proving* theorems about these definitions,\n  * but let's back up and look at a more basic type first. *)\n\n\n(** * The most basic inductive type that actually deserves the name: natural numbers *)\n\n(** Let's define these with different names than usual, to avoid clashing with the standard library. *)\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n(* [Succ] for \"successor\".  Any number [n] is represented as [Succ^n(Zero)]. *)\n\n(** Addition is easy to define recursively.  Here's we're working from first principles, instead of using a built-in type of machine numbers as in most programming languages. *)\nFixpoint add (n m : natural) : natural :=\n  match n with\n  | Zero => m\n  | Succ n' => Succ (add n' m)\n  end.\n\n(** Our first example of a proof!  Addition is associative. *)\nTheorem add_assoc : forall n m o, add (add n m) o = add n (add m o).\nProof.\n  (** Here we are writing *tactics*, or commands for reducing one proof goal into zero or more new goals.  In general, we use semicolon to sequence tactics, with each step run on all goals left over after the previous steps.  We use periods to terminate tactics that we want to run interactively to see the results. *)\n  induction n; simpl; intros.\n  (**\n    * You can guess what [induction] means.\n    * [simpl] triggers algebraic simplification.\n    * [intros] replaces [forall] quantifiers with new free variables. *)\n\n  reflexivity.\n  (** [reflexivity] proves any goal of the form [E = E]. *)\n\n  rewrite IHn.\n  (** [rewrite H] uses hypothesis or lemma [H] establishing some fact [E1 = E2] to replace all occurrences of [E1] in the goal with [E2]. *)\n  reflexivity.\nQed.\n(** If the [Qed] command succeeds, then we know that the theorem is really true, regardless of which tactics we chose. *)\n\n(** ** Proving commutativity of addition *)\n\n(** Sometimes it's useful to prove some lemmas, which formally are the same as theorems, but using the name \"lemma\" signifies that they just play a supporting role. *)\n\n(** Lemma #1: zero is a right identity of addition. *)\nLemma add_Zero : forall n, add n Zero = n.\nProof.\n  induction n; simpl.\n\n  reflexivity.\n\n  rewrite IHn.\n  reflexivity.\nQed.\n\n(** Lemma #2: we can pull a [Succ] from the 2nd operand to the front. *)\nLemma add_Succ : forall n m, add n (Succ m) = Succ (add n m).\nProof.\n  induction n; simpl; intros.\n\n  reflexivity.\n\n  rewrite IHn.\n  reflexivity.\nQed.\n\n(** The main event! *)\nTheorem add_comm : forall n m, add n m = add m n.\nProof.\n  induction n; simpl; intros.\n\n  rewrite add_Zero.\n  reflexivity.\n\n  rewrite add_Succ.\n  rewrite IHn.\n  reflexivity.\nQed.\n\n(** In the other examples, we'll show both these more manual proofs and more automated proofs.  For natural numbers, it's not even worth doing the automated proofs, since Coq has built-in automation for goals like these, when we use the [nat] type from the standard library. *)\n\n\n(** * Now we're ready to go back and prove properties of expressions. *)\n\n(** [commuter] has no effect on the meaning of an expression. *)\nTheorem eval_commuter : forall e, eval (commuter e) = eval e.\nProof.\n  induction e; simpl; intros.\n\n  reflexivity.\n\n  rewrite IHe1.\n  rewrite IHe2.\n  rewrite plus_comm.\n  reflexivity.\n\n  rewrite IHe1.\n  rewrite IHe2.\n  rewrite mult_comm.\n  reflexivity.\nQed.\n\n\n(** ** Let's see how we can automate that proof more thoroughly using Coq's language Ltac for scripted proof automation.  In general, Ltac details are beyond the scope of these lectures, so think of these automated examples as an advertisement for learning more, say via Adam's book \"Certified Programming with Dependent Types,\" and/or the Coq reference manual. *)\n\nLtac exp_solver := simpl; intuition;\n                   repeat match goal with\n                          | [ H : _ = _ |- _ ] => rewrite H\n                          end; intuition.\n\nTheorem eval_commuter_automated : forall e, eval (commuter e) = eval e.\nProof.\n  induction e; exp_solver.\nQed.\n\n\n(** * Next (and final) example: lambda terms *)\n\n(** Here's the syntax of the untyped lambda calculus, using the library type of strings. *)\nInductive term : Set :=\n| Var : string -> term\n| Abs : string -> term -> term\n| App : term -> term -> term.\n\n(** At this point, we might be tempted to begin by writing an interpreter, but we can't, since Coq only allows *terminating* functional programs!  Let's work with substitution instead. *)\nFixpoint subst (rep : term) (x : string) (e : term) : term :=\n  match e with\n  | Var y => if string_dec y x then rep else Var y\n  | Abs y e1 => Abs y (if string_dec y x then e1 else subst rep x e1)\n  | App e1 e2 => App (subst rep x e1) (subst rep x e2)\n  end.\n(** Warning: this version is only designed for [rep] that are *closed*, with no free variables! *)\n\n(** In Coq, [Prop] is the type of propositions, or mathematical statements.  It's subtlely different from the type [bool] of Booleans, in a way that may be clear from the OPLSS lectures on type-theory foundations, but it's also fine (for now) to pretend that [Prop] is just a peculiar kind of truth value or Boolean, with its own distinctive operators.  Let's define what it means for a variable not to appear free in a term.  We write [<>] for not-equal, [\\/] for logical \"or,\" and [/\\] for logical \"and.\" *)\nFixpoint notFreeIn (x : string) (e : term) : Prop :=\n  match e with\n  | Var y => y <> x\n  | Abs y e1 => y = x \\/ notFreeIn x e1\n  | App e1 e2 => notFreeIn x e1 /\\ notFreeIn x e2\n  end.\n\n(** We'd like to prove that the order of substitution operations doesn't matter, when the terms we are substituting ([rep] parameter in the [subst] definition) have no free variables.  A useful first lemma is that substitution has no effect on a term without free occurrences of the variable. *)\nLemma subst_notFree : forall rep x e,\n  notFreeIn x e\n  -> subst rep x e = e.\nProof.\n  induction e; simpl; intros.\n\n  destruct (string_dec s x).\n  (** [destruct] is for case analysis on the ways some term might be constructed.\n    * In this case, [string_dec] has a funny expressive Boolean type that we won't dwell on.\n    * The two cases considered are basically \"true\" and \"false,\" extending the context with information on what the case implies logically about the arguments to [string_dec]. *)\n  congruence.\n  (** [congruence] is a general decision procedure for the theory of equality.\n    * For instance, it knows that [a = b] and [b <> a] together are inconsistent, establishing any goal by contradiction.\n    * Though [congruence] subsumes [reflexivity], we'll keep using the latter where applicable, for clarity. *)\n  reflexivity.\n\n  destruct (string_dec s x).\n  reflexivity.\n  (** [destruct] also does double-duty when applied to an [\\/] (\"or\") hypothesis, splitting out two goals, one for each branch of the \"or.\" *)\n  destruct H.\n  congruence.\n  \n  rewrite IHe.\n  reflexivity.\n  assumption.\n\n  (** [destruct] will also split an [/\\] (\"and\") hypothesis into two. *)\n  destruct H.\n  rewrite IHe1.\n  rewrite IHe2.\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\n(** Now we prove the main fact about commutativity of substitution. *)\nTheorem subst_comm : forall rep1 x1 rep2 x2 e,\n  (* The two replacements have no free variables: *)\n  (forall x, notFreeIn x rep1)\n  -> (forall x, notFreeIn x rep2)\n\n  (* It's important to require that the two variables are different! *)\n  -> x1 <> x2\n\n  -> subst rep1 x1 (subst rep2 x2 e) = subst rep2 x2 (subst rep1 x1 e).\nProof.\n  induction e; simpl; intros.\n\n  destruct (string_dec s x1), (string_dec s x2); simpl.\n  congruence.\n  destruct (string_dec s x1).\n  rewrite subst_notFree.\n  reflexivity.\n  apply H.\n  (* [apply H] works to prove [P] when [H] is a hypothesis or lemma that establishes [P], perhaps given some other premises.  Those premises become new goals. *)\n  congruence.\n  destruct (string_dec s x2).\n  rewrite subst_notFree.\n  reflexivity.\n  apply H0.\n  congruence.\n\n  destruct (string_dec s x1), (string_dec s x2); simpl.\n  congruence.\n  congruence.\n  congruence.\n  reflexivity.\n\n  destruct (string_dec s x1), (string_dec s x2); simpl.\n  congruence.\n  congruence.\n  congruence.\n  rewrite IHe.\n  reflexivity.\n  assumption.\n  (* It's probably not hard to guess what [assumption] does. :-) *)\n  assumption.\n  assumption.\n\n  rewrite IHe1.\n  rewrite IHe2.\n  reflexivity.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n(** That was painfully repetitive proving.  Here's an Ltac script that can eat the whole thing for breakfast. *)\n\nLtac subst_solver := simpl; intuition;\n                     repeat (match goal with\n                             | [ H : _ = _ |- _ ] => rewrite H\n                             | [ |- context[string_dec ?X ?Y] ] => destruct (string_dec X Y)\n                             end; simpl in *; intuition; try congruence).\n\nLemma subst_notFree_automated : forall rep x e,\n  notFreeIn x e\n  -> subst rep x e = e.\nProof.\n  induction e; subst_solver.\nQed.\n\nHint Resolve subst_notFree_automated.\n(** We register a proved lemma as a hint, to be used automatically by the tactics we call in [subst_solver].  (It turns out to be [intuition] that is using the hints here; details are beyond the scope of these lectures.) *)\n\n(** It will be helpful to prove a mirror-image hint, too. *)\nLemma subst_notFree_automated_sym : forall rep x e,\n  notFreeIn x e\n  -> e = subst rep x e.\nProof.\n  intros; symmetry; auto.\nQed.\n\nHint Resolve subst_notFree_automated_sym.\n\n(** Now the main theorem is a piece of cake. *)\nTheorem subst_comm_automated : forall rep1 x1 rep2 x2 e,\n  (forall x, notFreeIn x rep1)\n  -> (forall x, notFreeIn x rep2)\n  -> x1 <> x2\n  -> subst rep1 x1 (subst rep2 x2 e) = subst rep2 x2 (subst rep1 x1 e).\nProof.\n  induction e; subst_solver.\nQed.", "meta": {"author": "kolemannix", "repo": "oplss2015", "sha": "d2973dfbcb3bc345bec49841fb6c8bbf78d65a16", "save_path": "github-repos/coq/kolemannix-oplss2015", "path": "github-repos/coq/kolemannix-oplss2015/oplss2015-d2973dfbcb3bc345bec49841fb6c8bbf78d65a16/chlipala/InductionAndRecursion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750380552895, "lm_q2_score": 0.8887587971755248, "lm_q1q2_score": 0.8472315761994716}}
{"text": "(** * Lists: Working with Structured Data *)\n\n(*Require Export Induction.*)\nRequire Export Basics.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is one way to construct\n    a pair of numbers: by applying the constructor [pair] to two\n    arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n    pattern matches (indeed, we've seen it already in the previous\n    chapter -- this works because the pair notation is actually\n    provided as part of the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    doesn't generate an extra subgoal here.  That's because [natprod]s\n    can only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when \n   you read them in a .v file.  The inner brackets, around 3, indicate \n   a list, but the outer brackets, which are invisible in the HTML \n   rendering, are there to instruct the \"coqdoc\" tool that the bracketed \n   part should be displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint countoddmembers (l:natlist) : nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\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 count (v:nat) (s:bag) : nat :=\n  match s with\n    | nil => 0\n    | h :: t =>\n      match beq_nat h v with\n        | true => 1 + count v t\n        | false => count v t\n      end\n  end.\n\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n Proof. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n  Proof. reflexivity. Qed.\n\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n    all the elements of [a] and of [b].  (Mathematicians usually\n    define [union] on multisets a little bit differently, which\n    is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag :=\napp.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n Proof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\ncons 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.\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    | nil => nil\n    | h :: t => match (beq_nat h v) with\n                   | true => t\n                   | false => h :: remove_one v t\n                 end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n match s with\n    | nil => nil\n    | h::t => if (beq_nat h v) \n        then (remove_all v t) \n            else h::(remove_all v t)\n end.\n\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\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\t\t\t| nil => true\n\t\t\t| h :: t => andb (member h s2)\n\t\t\t\t\t\t\t\t\t\t\t (subset t (remove_one h s2))\n\t\tend.\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(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match\n    \"scrutinee\" in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a list *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Proofs about reverse *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n   induction n as [|n'].\n    simpl. rewrite <- plus_n_O. reflexivity.\n    simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n(* ================================================================= *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [SearchAbout] command is quite helpful with this.  Typing\n    [SearchAbout foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line \n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [SearchAbout] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next 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  (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\n(* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs)  *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags earlier in the file. *)\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.\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n\tinduction s as [|s'].\n\t\t- reflexivity.\n\t\t- reflexivity.\nQed.\n\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. \n  induction s as [| s'].\n  simpl. reflexivity.\n  induction s'.\n    simpl. rewrite -> ble_n_Sn. reflexivity.\n    simpl. rewrite -> IHs. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\nTheorem rev_injective: forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof. \n  intros l1 l2 H. \n  rewrite <- rev_involutive.\n  rewrite <- H. rewrite -> rev_involutive.\n  reflexivity.\nQed.\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually allows conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish.\n\n    We'll also need an equality test for [id]s: *)\n\nDefinition beq_id x1 x2 :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nImport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (key : id) (value : nat)\n                  : partial_map :=\n  record key value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (key : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record k v d' => if beq_id key k\n                     then Some v\n                     else find key d'\n  end.\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (k : id) (v: nat),\n    find k (update d k v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (m n : id) (o: nat),\n    beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?  (Answer in English\n    or the natural language of your choice.)\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** $Date: 2016-07-11 21:31:32 -0400 (Mon, 11 Jul 2016) $ *)\n", "meta": {"author": "Rijndael9", "repo": "COQ", "sha": "4a206aa095995c11877d7e8e07c47589adbac212", "save_path": "github-repos/coq/Rijndael9-COQ", "path": "github-repos/coq/Rijndael9-COQ/COQ-4a206aa095995c11877d7e8e07c47589adbac212/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.9284088035267047, "lm_q1q2_score": 0.8471137684641632}}
{"text": "Require Export P01.\n\nLemma mult_0_l :\n  forall n, 0 * n = 0.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma mult_0_r :\n  forall n, n * 0 = 0.\nProof.\n  intros n. induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros [|n].\n  - intros m H. rewrite mult_0_l in H. left. apply H.\n  - intros [|m].\n    + intros H. rewrite mult_0_r in H. right. apply H.\n    + intros H. inversion H.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/05/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8962513731336202, "lm_q1q2_score": 0.8469528024174117}}
{"text": "Require Import Le.\nRequire Import List.\n\nRequire Import Logic.Nat.Max.\n\nFixpoint maximum (ns:list nat) : nat :=\n    match ns with\n    | nil       => 0\n    | cons n ns => max n (maximum ns)\n    end.    \n\nLemma maximum_lub : forall (ns:list nat) (N:nat), \n    (forall (n:nat), In n ns -> n <= N) -> maximum ns <= N.\nProof.\n    intros ns N. induction ns as [|n ns IH].\n    - intros _. apply le_0_n.\n    - intros H. simpl. apply max_lub.\n        + apply H. left. reflexivity.\n        + apply IH. intros m Hm. apply H. right. assumption.\nQed.\n\nLemma maximum_ubound : forall (ns:list nat) (n:nat),\n    In n ns -> n <= maximum ns.\nProof.\n    induction ns as [|n' ns IH].\n    - intros n H. inversion H.\n    - intros n [H|H].\n        + subst. apply n_le_max.\n        + apply le_trans with (maximum ns).\n            { apply IH. assumption. }\n            { apply m_le_max. }\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/Nat/Maximum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8469256266798496}}
{"text": "Require Import \n  Coq.Classes.Morphisms \n  Sigma.Algebra.Hierarchy\n  Sigma.Algebra.Monoid.\n\nSection Group. \n\n  Context \n    {T : Type} \n    {eq : T -> T -> Prop} \n    {op : T -> T -> T} \n    {id : T} \n    {inv : T -> T}\n    {Hgroup : @group T eq op id inv}.\n  \n    Local Infix \"=\" := eq : type_scope. \n    Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n    Local Infix \"*\" := op.\n    \n    \n    Lemma group_cancel_right : \n      forall z x y, x * z = y * z <-> x = y.\n    Proof. \n      intros ? ? ?; split; intro H.\n      eapply monoid_cancel_right with (iz := inv z).\n      instantiate (1 := z). \n      apply right_inverse.\n      exact H. \n      rewrite H; reflexivity.\n    Qed.\n\n    Lemma group_cancel_left : \n      forall z x y, z * x = z * y <-> x = y.\n    Proof. \n      intros ? ? ?; split; intro H.\n      eapply monoid_cancel_left with (iz := inv z).\n      instantiate (1 := z). \n      apply left_inverse.\n      exact H. \n      rewrite H; reflexivity.\n    Qed. \n\n    Lemma group_inv_inv : forall x, \n      inv (inv x) = x.\n    Proof.\n      intros ?.\n      eapply monoid_inv_inv;\n      try instantiate (1 := inv x);\n      apply left_inverse.\n    Qed. \n\n    Lemma group_inv_op_ext : \n      forall x y, (inv y * inv x) * (x * y) = id.\n    Proof. \n      intros ? ?.\n      eapply monoid_inv_op; \n      apply left_inverse.\n    Qed. \n\n    Lemma group_inv_flip : \n      forall x y, inv (x * y) = inv y * inv x.\n    Proof.\n      intros ? ?.\n      pose proof (group_cancel_right x (inv (x * y)) (inv y * inv x)) as Hg.\n      apply Hg; clear Hg. \n      assert (Ht : inv y * inv x * x = inv y * (inv x * x)) by \n       (rewrite associative; reflexivity).\n      rewrite Ht, left_inverse, right_identity.\n      pose proof (group_cancel_right y (inv (x * y) * x) (inv y)) as Hg.\n      apply Hg; clear Hg. \n      rewrite left_inverse.\n      assert (H : inv (x * y) * x * y = inv (x * y) * (x * y)) by \n        (rewrite associative; reflexivity). \n      rewrite H.\n      apply left_inverse.\n    Qed. \n    \n    Lemma group_inv_unique : \n      forall x y, y * x = id <-> y = inv x.\n    Proof.\n      intros ? ?; split; intros H.\n      pose proof (group_cancel_right (inv x) (y * x) id) as Hg.\n      apply Hg in H. \n      rewrite left_identity in H. \n      rewrite <- associative, right_inverse,\n        right_identity in H. \n      exact H.\n      rewrite H, left_inverse; reflexivity.\n    Qed.\n    \n    Lemma group_inv_bijective : \n      forall x y, inv x = inv y <-> x = y.\n    Proof.\n      intros ? ?; split; intros H.\n      apply group_cancel_right with (z := x) in H.\n      rewrite left_inverse in H.\n      apply group_cancel_left with (z := y) in H.\n      rewrite \n        associative, \n        right_inverse,\n        right_identity,\n        left_identity in H.\n      symmetry in H. \n      exact H.\n      rewrite H; reflexivity.\n    Qed. \n\n    Lemma group_inv_id : inv id = id.\n    Proof.\n      symmetry; \n      apply group_inv_unique,\n      right_identity.\n    Qed. \n\n    Lemma group_inv_id_iff : \n      forall x, inv x = id <-> x = id.\n    Proof.\n      intros ?; split; intros H.\n      apply group_inv_bijective.\n      rewrite group_inv_id.\n      exact H.\n      rewrite H; \n      apply group_inv_id.\n    Qed. \n\n    Lemma group_inv_nonzero_nonzero : \n      forall x, x <> id <-> inv x <> id.\n    Proof.\n      intros ?. \n      rewrite group_inv_id_iff; reflexivity.\n    Qed. \n\n    Lemma group_eq_r_opp_r_inv : \n      forall x y z, x = op z (inv y) <-> op x y = z.\n    Proof.\n      intros ? ? ?; split; intros H.\n      apply group_cancel_right with (z := y) in H.\n      rewrite \n        <- associative, \n        left_inverse, \n        right_identity in H. \n      exact H.\n      apply group_cancel_right with (z := inv y) in H.\n      rewrite \n        <- associative, \n        right_inverse, \n        right_identity in H. \n      exact H.\n    Qed. \n\n    Section ZeroNeqOne.\n      Context \n        {one : T} \n        {Hn : @is_zero_neq_one T eq id one}.\n      \n      Lemma opp_one_neq_zero : inv one <> id.\n      Proof.\n        intro Ht. \n        rewrite group_inv_id_iff in Ht.\n        pose proof zero_neq_one as H.\n        unfold not in H. \n        symmetry in Ht.\n        apply H in Ht. \n        exact Ht.\n      Qed. \n    End ZeroNeqOne.\nEnd Group.\n\n        \n  \n\n\n\n", "meta": {"author": "mukeshtiwari", "repo": "Dlog-zkp", "sha": "c291925d28609f57eab069bd8479d868e7e7f66c", "save_path": "github-repos/coq/mukeshtiwari-Dlog-zkp", "path": "github-repos/coq/mukeshtiwari-Dlog-zkp/Dlog-zkp-c291925d28609f57eab069bd8479d868e7e7f66c/src/Algebra/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620527726579, "lm_q2_score": 0.8824278556326343, "lm_q1q2_score": 0.8469207701457517}}
{"text": "\nInductive day : Type :=\n  | monday    : day\n  | tuesday   : day\n  | wednesday : day\n  | thursday  : day\n  | friday    : day\n  | saturday  : day\n  | sunday    : day\n.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n    | monday    => tuesday\n    | tuesday   => wednesday\n    | wednesday => thursday\n    | thursday  => friday\n    | friday    => monday\n    | saturday  => monday\n    | sunday    => monday\n  end.\n\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n(next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nInductive bool : Type :=\n  | true  : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n    | true  => false\n    | false => true\n  end.\n\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\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605 (nandb)\n\n\u6b21\u306e\u5b9a\u7fa9\u3092\u5b8c\u6210\u3055\u305b\u3001Example\u3067\u8a18\u8ff0\u3055\u308c\u305f\u78ba\u8a8d\u5185\u5bb9\u304cCoq\u306e\u30c1\u30a7\u30c3\u30af\u3092\u3059\u3079\u3066\u901a\u904e\u3059\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u306a\u3055\u3044\u3002\n\n\u3053\u306e\u95a2\u6570\u306f\u3069\u3061\u3089\u304b\u3001\u3082\u3057\u304f\u306f\u4e21\u65b9\u304cfalse\u306b\u306a\u3063\u305f\u3068\u304d\u306btrue\u3092\u8fd4\u3059\u3082\u306e\u3067\u3042\u308b\u3002\n *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  negb (andb b1 b2).\n  (* match b1 with *)\n  (*   | true  => negb b2 *)\n  (*   | false => true *)\n  (* end. *)\n\n(* \u4e0b\u306e\u5b9a\u7fa9\u304b\u3089Admitted.\u3092\u53d6\u308a\u53bb\u308a\u3001\u4ee3\u308f\u308a\u306b\"Proof. simpl. reflexivity. Qed.\"\u3067\u691c\u8a3c\u3067\u304d\u308b\u3088\u3046\u306a\u30b3\u30fc\u30c9\u3092\u8a18\u8ff0\u3057\u306a\u3055\u3044\u3002 *)\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(* \u2610 *)\n\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605 (andb3) *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n    | true  => andb b2 b3\n    | false => false\n  end.\n\nExample test_andb31: (andb3 true true true) = true.\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\nRequire Import Coq.Unicode.Utf8_core.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat\n.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O    => O\n    | S n' => n'\n  end.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O   => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCheck (S (S (S (S O)))).\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.\n\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nEval simpl in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n    | O , _ => O\n    | S _ , O => n\n    | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\n(* Example test_exp99: (exp 3 3) = 27. *)\n(* Proof. simpl. reflexivity. Qed. *)\n\n\n(* \u6f14\u7fd2\u554f\u984c: \u2605 (factorial) *)\n\n(* \u518d\u5e30\u3092\u4f7f\u7528\u3057\u305f\u3001\u4e00\u822c\u7684\u306afactorical\uff08\u968e\u4e57\uff09\u306e\u5b9a\u7fa9\u3092\u601d\u3044\u51fa\u3057\u3066\u304f\u3060\u3055\u3044 : *)\n\n(*     factorial(0)  =  1 *)\n(*     factorial(n)  =  n * factorial(n-1)     (if n>0) *)\n\n(* \u3053\u308c\u3092Coq\u3067\u306e\u5b9a\u7fa9\u306b\u66f8\u304d\u76f4\u3057\u306a\u3055\u3044\u3002 *)\n\nFixpoint factorial (n : nat) : nat :=\n  match n with\n    | O => S O\n    | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\n(* Module Playground20. *)\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(* End Playground20. *)\n\n(* Check (0%nat). *)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n    | O => match m with\n             | O => true\n             | S m' => false\n           end\n    | S n' => match m with\n                | O => false\n                | S m' => beq_nat n' m'\n              end\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n    | O => true\n    | S n' =>\n        match m with\n          | O => false\n          | S m' => ble_nat n' m'\n        end\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605\u2605 (blt_nat) *)\n\n(* blt_nat\u95a2\u6570\u306f\u3001\u81ea\u7136\u6570\u3092\u6bd4\u8f03\u3057\u3066\u5c0f\u3055\u3044\u3001\u3068\u3044\u3046\u3053\u3068\u3092\u8abf\u3079\u3066bool *)\n(* \u5024\u3092\u751f\u6210\u3057\u307e\u3059\uff08 natural numbers for less-than\uff09\u3002Fixpoint\u3092 *)\n(* \u4f7f\u7528\u3057\u3066\uff11\u304b\u3089\u4f5c\u6210\u3059\u308b\u306e\u3067\u306f\u306a\u304f\u3001\u3059\u3067\u306b\u3053\u308c\u307e\u3067\u5b9a\u7fa9\u3057\u305f\u95a2\u6570 *)\n(* \u3092\u5229\u7528\u3057\u3066\u5b9a\u7fa9\u3057\u306a\u3055\u3044\u3002 *)\n\n(* \u6ce8\uff1asimpl\u30bf\u30af\u30c6\u30a3\u30c3\u30af\u3092\u4f7f\u3063\u3066\u3046\u307e\u304f\u3044\u304b\u306a\u3044\u5834\u5408\u306f\u3001\u4ee3\u308f\u308a\u306b *)\n(* compute\u3092\u8a66\u3057\u3066\u304f\u3060\u3055\u3044\u3002\u305d\u308c\u306f\u3088\u308a\u3046\u307e\u304f\u4f5c\u3089\u308c\u305fsimpl\u3068\u8a00\u3048 *)\n(* \u308b\u3082\u306e\u3067\u3059\u304c\u3001\u305d\u3082\u305d\u3082\u30b7\u30f3\u30d7\u30eb\u3067\u30a8\u30ec\u30ac\u30f3\u30c8\u306a\u89e3\u304c\u66f8\u3051\u3066\u3044\u308c\u3070 *)\n(* \u3001simpl\u3067\u5341\u5206\u306b\u8a55\u4fa1\u3067\u304d\u308b\u306f\u305a\u3067\u3059\u3002 *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  andb (negb (beq_nat n m)) (ble_nat n m).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nRequire Import Coq.Unicode.Utf8_core.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  simpl. reflexivity. Qed.\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  reflexivity. Qed.\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605, optional (simpl_plus) *)\n\n(* \u3053\u306e\u554f\u3044\u5408\u308f\u305b\u306e\u7d50\u679c\u3001Coq\u304c\u8fd4\u3059\u5fdc\u7b54\u306f\u306a\u306b\u304b\uff1f *)\n\nEval simpl in (forall n:nat, n + 0 = n). (* \u53f3\u5358\u4f4d\u5143\u304c\u8a3c\u660e\u3055\u308c\u3066\u3044\u306a\u3044 *)\n\n(* \u307e\u305f\u6b21\u306e\u3082\u306e\u306e\u5834\u5408\u306f\u3069\u3046\u304b\uff1f *)\n\nEval simpl in (forall n:nat, 0 + n = n). (* \u5de6\u5358\u4f4d\u5143\u306f\u8a3c\u660e\u3055\u308c\u3066\u3044\u308b *)\n\n(* \u3053\u306e\u4e8c\u3064\u306e\u9055\u3044\u3092\u793a\u305b\u3002 \u2610 *)\n\n\nTheorem plus_O_n'' : forall n:nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m. intros H. rewrite -> H. reflexivity. Qed.\n\n(*\nTheorem plus_id_example' : forall n m:nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m. intros H. rewrite <- H. reflexivity. Qed.\n *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605 (plus_id_exercise)\n\nAdmitted.\u3092\u524a\u9664\u3057\u3001\u8a3c\u660e\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002\n *)\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 H0 H1.\n  rewrite -> H0, <- H1.\n  reflexivity.\nQed.\n(* \u2610 *)\n\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605\u2605, recommended (mult_1_plus) *)\n\nTheorem mult_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  rewrite -> plus_1_l.\n  reflexivity. Qed.\n(* \u2610 *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. simpl. Admitted.\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(*\nTheorem plus_1_neq_0' : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n']; reflexivity. Qed.\n*)\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605 (zero_nbeq_plus_1) *)\n\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.\n    reflexivity. Qed.\n(* \u2610 *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n    | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n    assert (x = v) as H by reflexivity;\n  clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n      set (x := name); move_to_top x\n    | assert_eq x name; move_to_top x\n    | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nTheorem andb_true_elim1 : forall b c : bool,\n  andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H. reflexivity. Qed.\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605 (andb_true_elim2)\n\ndestruct\u3092\u4f7f\u3044\u3001case\uff08\u3082\u3057\u304f\u306fsubcase\uff09\u3092\u4f5c\u6210\u3057\u3066\u3001\u4ee5\u4e0b\u306e\u8a3c\u660eandb_true_elim2\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\n\u3002\n*)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n  Case \"c = true\".\n    reflexivity.\n  Case \"c = false\".\n    rewrite <- H.\n    destruct b.\n    SCase \"b = true\".\n      reflexivity.\n    SCase \"b = false\".\n      reflexivity. Qed.\n\n(*\n  destruct b.\n  Case \"b = true\".\n    rewrite <- H.\n    reflexivity.\n  Case \"b = false\".\n    inversion H. Qed.\n*)\n\n(* \u2610 *)\n\nTheorem plus_0_r_firsttry : forall n : nat,\n  n + 0 = n.\nProof.\n  intros n.\n  simpl. Admitted.\n\nTheorem plus_0_r_secondtry : forall n : nat,\n  n + 0 = n.\nProof.\n  intros n. destruct n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. Admitted.\n\nTheorem plus_0_r : forall n : nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605\u2605, recommended (basic_induction) *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. 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    simpl. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = 0\".\n    simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\n(* \u2610 *)\n\n\nFixpoint double (n:nat) :=\n  match n with\n    | O => O\n    | S n' => S (S (double n'))\n  end.\n\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605\u2605 (double_plus) *)\n\nLemma double_plus : \u2200 n, double n = n + n .\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n   simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n(* \u2610 *)\n\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605 (destruct_induction)\n\ndestruct\u3068induction\u306e\u9055\u3044\u3092\u77ed\u304f\u8aac\u660e\u3057\u306a\u3055\u3044\u3002\n*)\n\n(* induction \u3060\u3051 Induction Hypothesis \u3092\u4f7f\u3048\u308b\u3002 *)\n\n(* \u2610 *)\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']. reflexivity.\n  simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = Sn'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605 (plus_comm_informal)\n\nplus_comm\u306e\u8a3c\u660e\u3092\u3001\u975e\u5f62\u5f0f\u7684\u306a\u8a3c\u660e\u306b\u66f8\u304d\u63db\u3048\u306a\u3055\u3044\u3002\n\n\u5b9a\u7406\uff1a\u52a0\u6cd5\u306f\u53ef\u63db\u3067\u3042\u308b\u3002\nProof: \u2610\n *)\n\n(*\n\u5b9a\u7406 : \u4efb\u610f\u306e n m \u306b\u3064\u3044\u3066\u4ee5\u4e0b\u304c\u6210\u308a\u7acb\u3064\n  n + m = m + n\n\n\u8a3c\u660e : n \u306b\u3064\u3044\u3066\u5e30\u7d0d\u6cd5\u3092\u9069\u7528\u3059\u308b\u3002\n  \u2610 \u307e\u305a n = 0 \u3068\u7f6e\u304f\u3068\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\n       0 + m = m + 0\n     + \u306e\u5b9a\u7fa9\u304b\u3089\n          m = m + 0\n     \u52a0\u6cd5+ \u306e\u53f3\u5358\u4f4d\u5143\u306e\u5b9a\u7406(plus_0_r)\u304b\u3089\u793a\u3055\u308c\u308b\n  \u2610 \u6b21\u306b n = S n' \u3068\u7f6e\u304d\u3001\u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a\u3092\n       n' + m = m + n'\n     \u3068\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u5f0f\u304c\u6210\u308a\u7acb\u3064\u3002\n       S (n' + m) = S (m + n')\n     \u307e\u305f\u52a0\u6cd5\u306e\u5de6+1\u306e\u5b9a\u7406(plus_n_Sm)\u304b\u3089\n       S (m + n') = m + S n'\n     \u3057\u305f\u304c\u3063\u3066\u3001\n       S (n' + m) = m + S n'\n     \u3053\u3053\u3067\u52a0\u6cd5+ \u306e\u5b9a\u7fa9\u3088\u308a\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5909\u5f62\u3067\u304d\u308b\u3002\n       S n' + m = m + S n'\n     \u3053\u308c\u306f\u3001\u76f4\u5f8c\u306e\u5024\u306b\u3064\u3044\u3066\u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u793a\u3057\u3066\u3044\u308b\u3002 \u2610\n *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605, optional (beq_nat_refl_informal)\n\n\u6b21\u306e\u8a3c\u660e\u3092\u3001plus_assoc \u306e\u975e\u5f62\u5f0f\u7684\u306a\u8a3c\u660e\u3092\u53c2\u8003\u306b\u66f8\u304d\u63db\u3048\u306a\u3055\u3044\u3002Coq\u306e\u30bf\u30af\u30c6\u30a3\u30c3\u30af\u3092\u5358\u306b\u8a00\u3044\u63db\u3048\u305f\u3060\u3051\u306b\u306a\u3089\u306a\u3044\u3088\u3046\u306b\uff01\n\n\u5b9a\u7406\uff1atrue=beq_nat n n forany n.\uff08\u4efb\u610f\u306en\u306b\u3064\u3044\u3066\u3001n\u306fn\u3068\u7b49\u3057\u3044\u3068\u3044\u3046\u547d\u984c\u304ctrue\u3068\u306a\u308b\uff09\nProof: \u2610\n*)\n\n(*\n\u5b9a\u7406 : true = beq_nat n n forany n.\n\u8a3c\u660e : n \u306b\u3064\u3044\u3066\u5e30\u7d0d\u6cd5\u3092\u9069\u7528\u3059\u308b\u3002\n  \u2610 \u307e\u305a n = 0 \u3068\u7f6e\u304f\u3068\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\n       true = beq_nat 0 0\n     \u3053\u308c\u306f beq_nat \u306e\u5b9a\u7fa9\u304b\u3089\u793a\u3055\u308c\u308b\n  \u2610 \u6b21\u306b n = S n' \u3068\u7f6e\u304d\u3001\u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a\u3092\n       true = beq_nat n' n'\n     \u3068\u3059\u308b\u3002\n     \u3053\u3053\u3067 beq_nat \u306e\u5b9a\u7fa9\u306b\u3088\u308a\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5909\u5f62\u3067\u304d\u308b\u3002\n       true = beq_nat (S n') (S n')\n     \u3053\u308c\u306f\u3001\u76f4\u5f8c\u306e\u5024\u306b\u3064\u3044\u3066\u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u793a\u3057\u3066\u3044\u308b\u3002 \u2610\n *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605, optional (beq_nat_refl)\n*)\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite <- IHn'. reflexivity. Qed.\n(* \u2610 *)\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n    Case \"Proof of assertion\". reflexivity.\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem plus_rearrange_firsttry :\n  forall n m p q : nat,\n    (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  rewrite -> plus_comm.\nAdmitted.\n\n\nTheorem plus_rearrange :\n  forall n m p q : nat,\n    (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n    Case \"Proof of assertion\".\n    rewrite -> plus_comm. reflexivity.\n  rewrite -> H. reflexivity. Qed.\n\n(* Print plus_rearrange. *)\n\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605\u2605 (mult_comm)\n\nassert\u3092\u4f7f\u7528\u3057\u3066\u4ee5\u4e0b\u306e\u8a3c\u660e\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002\u305f\u3060\u3057induction\uff08\u5e30\u7d0d\u6cd5\uff09\u3092\u4f7f\u7528\u3057\u306a\u3044\u3053\u3068\u3002\n *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  assert (H: n + m = m + n).\n    Case \"Proof assertion\".\n    rewrite -> plus_comm.\n    reflexivity.\n  rewrite <- H.\n  reflexivity.\n  Qed.\n\n(*\n\u3067\u306f\u3001\u4e57\u6cd5\u304c\u53ef\u63db\u3067\u3042\u308b\u3053\u3068\u3092\u8a3c\u660e\u3057\u307e\u3057\u3087\u3046\u3002\u304a\u305d\u3089\u304f\u3001\u88dc\u52a9\u7684\u306a\u5b9a\u7406\u3092\u5b9a\u7fa9\u3057\u3001\u305d\u308c\u3092\u4f7f\u3063\u3066\u5168\u4f53\u3092\u8a3c\u660e\u3059\u308b\u3053\u3068\u306b\u306a\u308b\u3068\u601d\u3044\u307e\u3059\u3002\u5148\u307b\u3069\u8a3c\u660e\u3057\u305fplus_swap\u304c\u4fbf\u5229\u306b\u4f7f\u3048\u308b\u3067\u3057\u3087\u3046\u3002\n *)\n\nTheorem mult_succ_r :\n  forall n m : nat,\n    n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> plus_swap.\n    rewrite <- IHn'.\n    reflexivity.\n  Qed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n  intros n m.\n  induction n as [| n'].\n    induction m as [| m'].\n    Case \"n = 0, m = 0\".\n      reflexivity.\n    Case \"n = 0, m = S m'\".\n      rewrite -> mult_0_r.\n      reflexivity.\n    induction m as [| m'].\n    Case \"n = S n', m = 0\".\n      rewrite -> mult_0_r.\n      reflexivity.\n    Case \"n = S n', m = S m'\".\n      simpl.\n      rewrite -> IHn'.\n      rewrite -> mult_succ_r.\n      rewrite -> plus_swap.\n      simpl.\n      reflexivity.\n    Qed.\n\n(* \u2610 *)\n\n\n(* \u7df4\u7fd2\u554f\u984c: \u2605\u2605, optional (evenb_n__oddb_Sn) *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n  evenb n = negb (evenb (S n)).\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    assert (H: forall b:bool, negb (negb b) = b).\n      intros b. destruct b. reflexivity. reflexivity.\n    rewrite -> IHn'.\n    rewrite -> H.\n    simpl.\n    reflexivity.\n  Qed.\n(* \u2610 *)\n\n(*\n\u3055\u3089\u306a\u308b\u7df4\u7fd2\u554f\u984c\n\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605, optional (more_exercises)\n\n\u7d19\u3092\u4f55\u679a\u304b\u7528\u610f\u3057\u3066\u3001\u4e0b\u306b\u7d9a\u304f\u5b9a\u7406\u304c(a)\u7c21\u7d04\u3068\u66f8\u304d\u63db\u3048\u3060\u3051\u3067\u8a3c\u660e\u53ef\u80fd\u304b\u3001(b)destruct\u3092\u4f7f\u3063\u305fcase\u5206\u5272\u304c\u5fc5\n\u8981\u306b\u306a\u308b\u304b\u3001(c)\u5e30\u7d0d\u6cd5\u304c\u5fc5\u8981\u3068\u306a\u308b\u304b\u3001\u306e\u3044\u305a\u308c\u306b\u5c5e\u3059\u304b\u3092\u3001\u7d19\u306e\u4e0a\u3060\u3051\u3067\u8003\u3048\u306a\u3055\u3044\u3002\u4e88\u6e2c\u3092\u7d19\u306b\u66f8\u3044\u305f\u3089\n\u3001\u5b9f\u969b\u306b\u8a3c\u660e\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002\u8a3c\u660e\u306b\u306fCoq\u3092\u7528\u3044\u3066\u304b\u307e\u3044\u307e\u305b\u3093\u3002\u6700\u521d\u306b\u7d19\u3092\u4f7f\u3063\u305f\u306e\u306f\u300c\u521d\u5fc3\u5fd8\u308c\u308b\u3079\u304b\n\u3089\u305a\u300d\u3068\u3044\u3063\u305f\u7406\u7531\u3067\u3059\u3002\n*)\n\n(*\n\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u7121\u3044\u306e\u3067\u7c21\u7d04\u3067\u304d\u306a\u3044\u3002\n\u307e\u305f\u3001destruct \u3057\u3066\u3082\u518d\u5e30\u7684\u306b\u4eee\u5b9a\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n (c)\n *)\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof.\n  intros.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(*\n\u7c21\u7d04\u306e\u6642\u70b9\u3067\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u306e\u533a\u5225\u3067\u5224\u5b9a\u3067\u304d\u308b\u3002\n (a)\n *)\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n. reflexivity. Qed.\n\n(*\n\u5de6\u5074\u306e\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u3042\u3089\u308f\u308c\u3066\u3044\u306a\u3044\u306e\u3067\u5834\u5408\u5206\u3051\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\nbool \u306f\u6709\u9650\u30c7\u30fc\u30bf\u306a\u306e\u3067\u5e30\u7d0d\u6cd5\u306f\u5fc5\u8981\u306a\u3044\u3002\n (b)\n *)\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros b. destruct b. reflexivity. reflexivity. Qed.\n\n(*\n\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u7121\u3044\u306e\u3067\u7c21\u7d04\u3067\u304d\u306a\u3044\u3002\n\u307e\u305f\u3001destruct \u3057\u3066\u3082\u518d\u5e30\u7684\u306b\u4eee\u5b9a\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n (c)\n *)\nTheorem plus_ble_compat_l : forall n m p : nat,\n  ble_nat n m = true \u2192 ble_nat (p + n) (p + m) = true.\nProof.\n  intros n m p H. induction p as [| p'].\n  Case \"p = 0\".\n    simpl. rewrite -> H. reflexivity.\n  Case \"p = S p'\".\n    simpl. rewrite -> IHp'. reflexivity. Qed.\n\n(*\n\u7c21\u7d04\u306e\u6642\u70b9\u3067\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u306e\u533a\u5225\u3067\u5224\u5b9a\u3067\u304d\u308b\u3002\n (a)\n *)\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n  intros n. reflexivity. Qed.\n\n(*\n\u7c21\u7d04\u3067\u304d\u308b\u304c\u3001\u305d\u306e\u5f8c\u3001\u52a0\u6cd5\u3067\u5e30\u7d0d\u6cd5\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n (c)\n *)\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  intros n. simpl. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(*\n\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u7121\u3044\u306e\u3067\u7c21\u7d04\u3067\u304d\u306a\u3044\u3002\nbool \u306f\u6709\u9650\u30c7\u30fc\u30bf\u306a\u306e\u3067\u5e30\u7d0d\u6cd5\u306f\u5fc5\u8981\u306a\u3044\u3002\n (b)\n *)\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n               (negb c))\n  = true.\nProof.\n  intros b c. destruct b. destruct c.\n  reflexivity. reflexivity. reflexivity. Qed.\n\n(*\n\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u7121\u3044\u306e\u3067\u7c21\u7d04\u3067\u304d\u306a\u3044\u3002\n\u307e\u305f\u3001destruct \u3057\u3066\u3082\u518d\u5e30\u7684\u306b\u4eee\u5b9a\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n (c)\n *)\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p. induction p as [| p'].\n  Case \"p = 0\".\n    rewrite -> mult_0_r. rewrite -> mult_0_r. rewrite -> mult_0_r.\n    reflexivity.\n  Case \"p = S p'\".\n    rewrite -> mult_succ_r.\n    rewrite -> mult_succ_r.\n    rewrite -> mult_succ_r.\n    rewrite -> plus_swap.\n    rewrite <- plus_assoc.\n    rewrite <- plus_assoc.\n    rewrite <- IHp'.\n    rewrite -> plus_swap.\n    reflexivity.\n  Qed.\n\n(*\n\u5f15\u6570\u306b\u30c7\u30fc\u30bf\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u304c\u7121\u3044\u306e\u3067\u7c21\u7d04\u3067\u304d\u306a\u3044\u3002\n\u307e\u305f\u3001destruct \u3057\u3066\u3082\u518d\u5e30\u7684\u306b\u4eee\u5b9a\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n (c)\n *)\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> mult_plus_distr_r. rewrite -> IHn'.\n    reflexivity. Qed.\n(* \u2610 *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605, optional (plus_swap')\n\nreplace\u30bf\u30af\u30c6\u30a3\u30c3\u30af\u306f\u3001\u7279\u5b9a\u306e\u30b5\u30d6\u30bf\u30fc\u30e0\u3092\u7f6e\u304d\u63db\u3048\u305f\u3044\u3082\u306e\u3068\u7f6e\u304d\u63db\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u307e\u3059\u3002\u3082\u3046\u5c11\u3057\u6b63\u78ba\u306b\n\u8a00\u3046\u3068\u3001replace (t) with (u)\u306f\u3001\u30b4\u30fc\u30eb\u306b\u3042\u308bt\u3068\u3044\u3046\u5f0f\u3092\u5168\u3066u\u306b\u304b\u304d\u304b\u3048\u3001t = u\u3068\u3044\u3046\u30b5\u30d6\u30b4\u30fc\u30eb\u3092\u8ffd\u52a0\n\u3057\u307e\u3059\u3002\u3053\u306e\u6a5f\u80fd\u306f\u3001\u901a\u5e38\u306erewrite\u304c\u30b4\u30fc\u30eb\u306e\u601d\u3044\u901a\u308a\u306e\u5834\u6240\u306b\u4f5c\u7528\u3057\u3066\u304f\u308c\u306a\u3044\u5834\u5408\u306b\u6709\u52b9\u3067\u3059\u3002\n\nreplace\u30bf\u30af\u30c6\u30a3\u30c3\u30af\u3092\u4f7f\u7528\u3057\u3066plus_swap'\u306e\u8a3c\u660e\u3092\u3057\u306a\u3055\u3044\u3002\u305f\u3060\u3057plus_swap\u306e\u3088\u3046\u306bassert (n + m = m + \nn)\u3092\u4f7f\u7528\u3057\u306a\u3044\u3067\u8a3c\u660e\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002\n*)\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. rewrite -> plus_assoc. rewrite -> plus_assoc.\n  replace (m + n) with (n + m). reflexivity.\n  rewrite -> plus_comm. reflexivity. Qed.\n\n(* \u2610 *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605\u2605, recommended (binary)\n\n\u3053\u308c\u307e\u3067\u3068\u306f\u7570\u306a\u308b\u3001\u901a\u5e38\u8868\u8a18\u306e\u81ea\u7136\u6570\u3067\u306f\u306a\u304f2\u9032\u306e\u30b7\u30b9\u30c6\u30e0\u3067\u3001\u81ea\u7136\u6570\u306e\u3088\u308a\u52b9\u7387\u7684\u306a\u8868\u73fe\u3092\u8003\u3048\u306a\u3055\u3044\u3002\n\u305d\u308c\u306f\u81ea\u7136\u6570\u3092\u30bc\u30ed\u3068\u30bc\u30ed\u306b1\u3092\u52a0\u3048\u308b\u52a0\u7b97\u5668\u304b\u3089\u306a\u308b\u3082\u306e\u3092\u5b9a\u7fa9\u3059\u308b\u4ee3\u308f\u308a\u306b\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a2\u9032\u306e\u5f62\u3067\u8868\u3059\u3082\n\u306e\u3067\u3059\u30022\u9032\u6570\u3068\u306f\u3001\n\n \u30fb \u30bc\u30ed\u3067\u3042\u308b\u304b,\n \u30fb 2\u9032\u6570\u30922\u500d\u3057\u305f\u3082\u306e\u304b,\n \u30fb 2\u9032\u6570\u30922\u500d\u3057\u305f\u3082\u306e\u306b1\u3092\u52a0\u3048\u305f\u3082\u306e.\n\n(a) \u307e\u305a\u3001\u4ee5\u4e0b\u306enat\u306e\u5b9a\u7fa9\u306b\u5bfe\u5fdc\u3059\u308b\u3088\u3046\u306a2\u9032\u578bbin\u306e\u5e30\u7d0d\u7684\u306a\u5b9a\u7fa9\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002 (\u30d2\u30f3\u30c8: nat\u578b\u306e\u5b9a\n\u7fa9\u3092\u601d\u3044\u51fa\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat \u2192 nat.\nnat\u578b\u306e\u5b9a\u7fa9O\u3084S\u306e\u610f\u5473\u304c\u4f55\u304b\u3092\u8a9e\u308b\u3082\u306e\u3067\u306f\u306a\u304f\u3001\uff08O\u304c\u5b9f\u969b\u306b\u4f55\u3067\u3042\u308d\u3046\u304c\uff09O\u304cnat\u3067\u3042\u3063\u3066\u3001n\u304cnat\u306a\u3089S\n\u304c\u4f55\u3067\u3042\u308d\u3046\u3068S n\u306fnat\u3067\u3042\u308b\u3001\u3068\u3044\u3046\u3053\u3068\u3092\u793a\u3057\u3066\u3044\u308b\u3060\u3051\u3067\u3059\u3002\u300cO\u304c\u30bc\u30ed\u3067\u3001S\u306f1\u3092\u52a0\u3048\u308b\u300d\u3068\u3044\u3046\u5b9f\u88c5\n\u304c\u305d\u308c\u3092\u81ea\u7136\u6570\u3068\u3057\u3066\u307f\u3066\u5b9f\u969b\u306b\u95a2\u6570\u3092\u66f8\u304d\u3001\u5b9f\u884c\u3057\u305f\u308a\u8a3c\u660e\u3057\u305f\u308a\u3057\u3066\u307f\u3066\u306f\u3058\u3081\u3066\u5b9f\u969b\u306b\u610f\u8b58\u3055\u308c\u307e\u3059\u3002\u3053\n\u3053\u3067\u5b9a\u7fa9\u3059\u308bbin\u3082\u540c\u69d8\u3067\u3001\u6b21\u306b\u66f8\u304f\u95a2\u6570\u304c\u66f8\u304b\u308c\u3066\u306f\u3058\u3081\u3066\u578bbin\u306b\u5b9f\u969b\u306e\u6570\u5b66\u7684\u306a\u610f\u5473\u304c\u4e0e\u3048\u3089\u308c\u307e\u3059\u3002)\n *)\n\nInductive bin : Type :=\n  | B0 : bin\n  | Be : bin -> bin\n  | Bo : bin -> bin\n.\n\n(*\n(b) \u5148\u306b\u5b9a\u7fa9\u3057\u305fbin\u578b\u306e\u5024\u3092\u30a4\u30f3\u30af\u30ea\u30e1\u30f3\u30c8\u3059\u308b\u95a2\u6570\u3092\u4f5c\u6210\u3057\u306a\u3055\u3044\u3002\u307e\u305f\u3001bin\u578b\u3092nat\u578b\u306b\u5909\u63db\u3059\u308b\u95a2\u6570\u3082\n\u4f5c\u6210\u3057\u306a\u3055\u3044\u3002\n *)\n\nFixpoint inc_bin (b : bin) : bin :=\n  match b with\n    | B0 => Bo B0\n    | Be b' => Bo b'\n    | Bo b' => Be (inc_bin b')\n  end.\n\nFixpoint bin2nat (b : bin) : nat :=\n  match b with\n    | B0 => O\n    | Be b' => 2 * bin2nat b'\n    | Bo b' => 1 + 2 * bin2nat b'\n  end.\n\nExample bin2nat_sixteen : bin2nat (Be (Be (Be (Be (Bo B0))))) = 16.\nProof. reflexivity. Qed.\n\nExample bin2nat_twenty_one : bin2nat (Bo (Be (Bo (Be (Bo B0))))) = 21.\nProof. reflexivity. Qed.\n\n(*\n(c) \u6700\u5f8c\u306bb\u3067\u4f5c\u6210\u3057\u305f\u30a4\u30f3\u30af\u30ea\u30e1\u30f3\u30c8\u95a2\u6570\u3068\u30012\u9032\u2192\u81ea\u7136\u6570\u95a2\u6570\u304c\u53ef\u63db\u3067\u3042\u308b\u3053\u3068\u3092\u8a3c\u660e\u3057\u306a\u3055\u3044\u3002\u3053\u308c\u3092\u8a3c\u660e\n\u3059\u308b\u306b\u306f\u3001bin\u5024\u3092\u307e\u305a\u30a4\u30f3\u30af\u30ea\u30e1\u30f3\u30c8\u3057\u305f\u3082\u306e\u3092\u81ea\u7136\u6570\u306b\u5909\u63db\u3057\u305f\u3082\u306e\u304c\u3001\u5148\u306b\u81ea\u7136\u6570\u5909\u63db\u3057\u305f\u5f8c\u306b\u30a4\u30f3\u30af\u30ea\n\u30e1\u30f3\u30c8\u3057\u305f\u3082\u306e\u306e\u5024\u3068\u7b49\u3057\u3044\u3053\u3068\u3092\u8a3c\u660e\u3059\u308c\u3070\u3088\u3044\u3002\n *)\n\nTheorem bin2nat_inc_bin_comm :\n  forall b : bin, bin2nat (inc_bin b) = S (bin2nat b).\nProof.\n  intros b.\n  induction b as [| be | bo].\n    Case \"b = B0\". reflexivity.\n    Case \"b = Be be\".\n      simpl. reflexivity.\n    Case \"b = Bo bo\".\n      simpl.\n      rewrite -> plus_0_r.\n      rewrite -> plus_0_r.\n      rewrite -> IHbo.\n      rewrite <- plus_n_Sm.\n      simpl.\n      reflexivity.\n    Qed.\n(* \u2610 *)\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605\u2605\u2605 (binary_inverse)\n\n\u3053\u306e\u7df4\u7fd2\u554f\u984c\u306f\u524d\u306e\u554f\u984c\u306e\u7d9a\u304d\u3067\u30012\u9032\u6570\u306b\u95a2\u3059\u308b\u3082\u306e\u3067\u3042\u308b\u3002\u524d\u306e\u554f\u984c\u3067\u4f5c\u6210\u3055\u308c\u305f\u5b9a\u7fa9\u3084\u5b9a\u7406\u3092\u3053\u3053\u3067\u7528\u3044\n\u3066\u3082\u3088\u3044\u3002\n\n(a) \u307e\u305a\u81ea\u7136\u6570\u30922\u9032\u6570\u306b\u5909\u63db\u3059\u308b\u95a2\u6570\u3092\u66f8\u304d\u306a\u3055\u3044\u3002\u305d\u3057\u3066\u300c\u4efb\u610f\u306e\u81ea\u7136\u6570\u304b\u3089\u30b9\u30bf\u30fc\u30c8\u3057\u3001\u305d\u308c\u30922\u9032\u6570\u306b\u30b3\n\u30f3\u30d0\u30fc\u30c8\u3057\u3001\u305d\u308c\u3092\u3055\u3089\u306b\u81ea\u7136\u6570\u306b\u30b3\u30f3\u30d0\u30fc\u30c8\u3059\u308b\u3068\u3001\u30b9\u30bf\u30fc\u30c8\u6642\u306e\u81ea\u7136\u6570\u306b\u623b\u308b\u3053\u3068\u3092\u8a3c\u660e\u3057\u306a\u3055\u3044\u3002\n*)\n\nFixpoint nat2bin (n:nat) : bin :=\n  match n with\n    | O => B0\n    | S n' => inc_bin (nat2bin n')\n  end.\n\nTheorem nat_bin_nat : forall n:nat, bin2nat (nat2bin n) = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> bin2nat_inc_bin_comm. rewrite -> IHn'.\n    reflexivity. Qed.\n\n(*\n(b) \u3042\u306a\u305f\u306f\u304d\u3063\u3068\u3001\u9006\u65b9\u5411\u306b\u3064\u3044\u3066\u306e\u8a3c\u660e\u3092\u3057\u305f\u307b\u3046\u304c\u3044\u3044\u306e\u3067\u306f\u3001\u3068\u8003\u3048\u3066\u3044\u308b\u3067\u3057\u3087\u3046\u3002\u305d\u308c\u306f\u3001\u4efb\u610f\u306e\n2\u9032\u6570\u304b\u3089\u59cb\u307e\u308a\u3001\u305d\u308c\u3092\u81ea\u7136\u6570\u306b\u30b3\u30f3\u30d0\u30fc\u30c8\u3057\u3066\u304b\u3089\u3001\u307e\u305f2\u9032\u6570\u306b\u30b3\u30f3\u30d0\u30fc\u30c8\u3057\u76f4\u3057\u305f\u3082\u306e\u304c\u3001\u5143\u306e\u81ea\u7136\u6570\u3068\n\u4e00\u81f4\u3059\u308b\u3001\u3068\u3044\u3046\u8a3c\u660e\u3067\u3059\u3002\u3057\u304b\u3057\u306a\u304c\u3089\u3001\u3053\u306e\u7d50\u679c\u306ftrue\u306b\u306f\u306a\u308a\u307e\u305b\u3093\u3002\uff01\uff01\u305d\u306e\u539f\u56e0\u3092\u8aac\u660e\u3057\u306a\u3055\u3044\u3002\n*)\n\n(* \u6570\u5024\u306b\u5bfe\u3057\u3066 nat \u4e00\u901a\u308a\u306b\u8868\u73fe\u304c\u6c7a\u5b9a\u3055\u308c\u308b\u304c\u3001bin \u306f\u8907\u6570\u306e\u8868\u73fe\u304c\u3042\u308a\u3046\u308b\u305f\u3081\u3002 *)\n\n(*\n(c) 2\u9032\u6570\u3092\u5f15\u6570\u3068\u3057\u3066\u53d6\u308a\u3001\u305d\u308c\u3092\u4e00\u5ea6\u81ea\u7136\u6570\u306b\u5909\u63db\u3057\u305f\u5f8c\u3001\u307e\u305f2\u9032\u6570\u306b\u5909\u63db\u3057\u305f\u3082\u306e\u3092\u8fd4\u3059normalize\u95a2\u6570\n\u3092\u4f5c\u6210\u3057\u3001\u8a3c\u660e\u3057\u306a\u3055\u3044\u3002\n*)\n\nDefinition normalize (b:bin) : bin := nat2bin (bin2nat b).\n\nTheorem normalize_refl : forall b:bin, normalize b = nat2bin (bin2nat b).\nProof. reflexivity. Qed.\n\nTheorem normalized_idempotent : forall b:bin, normalize (normalize b) = normalize b.\nProof.\n  intros b.\n  rewrite -> normalize_refl.\n  rewrite -> normalize_refl.\n  rewrite -> nat_bin_nat.\n  reflexivity. Qed.\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605, optional (decreasing)\n\n\u5404\u95a2\u6570\u306e\u5f15\u6570\u306e\u3044\u304f\u3064\u304b\u304c\"\u6e1b\u5c11\u7684\"\u3067\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3001\u3068\u3044\u3046\u8981\u6c42\u4ed5\u69d8\u306f\u3001Coq\u306e\u30c7\u30b6\u30a4\u30f3\u306b\u304a\u3044\u3066\u57fa\u790e\u3068\u306a\n\u3063\u3066\u3044\u308b\u3082\u306e\u3067\u3059\u3002\u7279\u306b\u3001\u305d\u306e\u3053\u3068\u306b\u3088\u3063\u3066\u3001Coq\u4e0a\u3067\u4f5c\u6210\u3055\u308c\u305f\u95a2\u6570\u304c\u3001\u3069\u3093\u306a\u5165\u529b\u3092\u4e0e\u3048\u3089\u308c\u3066\u3082\u5fc5\u305a\u3044\u3064\n\u304b\u7d42\u4e86\u3059\u308b\u3001\u3068\u3044\u3046\u3053\u3068\u304c\u4fdd\u969c\u3055\u308c\u3066\u3044\u307e\u3059\u3002\u3057\u304b\u3057\u3001Coq\u306e\"\u6e1b\u5c11\u7684\u306a\u89e3\u6790\"\u304c\u300c\u3068\u3066\u3082\u6d17\u7df4\u3055\u308c\u3066\u3044\u308b\u3068\u307e\u3067\n\u306f\u3044\u3048\u306a\u3044\u300d\u305f\u3081\u3001\u6642\u306b\u306f\u4e0d\u81ea\u7136\u306a\u66f8\u304d\u65b9\u3067\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3001\u3068\u3044\u3046\u3053\u3068\u3082\u3042\u308a\u307e\u3059\u3002\n\n\u3053\u308c\u3092\u5177\u4f53\u7684\u306b\u611f\u3058\u308b\u305f\u3081\u3001Fixpoint\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u3001\u3088\u308a\u300c\u5fae\u5999\u306a\u300d\u95a2\u6570\u306e\u66f8\u304d\u65b9\u3092\u8003\u3048\u3066\u307f\u307e\u3057\u3087\u3046\uff08\u81ea\u7136\u6570\n\u306b\u95a2\u3059\u308b\u7c21\u5358\u306a\u95a2\u6570\u3067\u304b\u307e\u3044\u307e\u305b\u3093\uff09\u3002\u305d\u308c\u304c\u5168\u3066\u306e\u5165\u529b\u3067\u505c\u6b62\u3059\u308b\u3053\u3068\u3068\u3001Coq\u304c\u305d\u308c\u3092\u3001\u3053\u306e\u5236\u9650\u306e\u305f\u3081\u53d7\n\u3051\u5165\u308c\u3066\u304f\u308c\u306a\u3044\u3053\u3068\u3092\u78ba\u8a8d\u3057\u306a\u3055\u3044\u3002\n*)\n\nFixpoint down_to_zero (n:nat) : nat :=\n  match oddb n with\n    | true => (* down_to_zero (S n) *)\n              match n with\n                | S n' => down_to_zero n'\n                | n'   => n'\n              end\n    | false => match n with\n                 | S (S n') => down_to_zero n'\n                 | n'       => n'\n               end\n  end.\n\n(*\n\u5947\u6570\u3060\u3063\u305f\u3089 1\u3092\u52a0\u3048\u3001\u5076\u6570\u3060\u3063\u305f\u3089 2\u4ee5\u4e0a\u306a\u30892\u5f15\u304f\u30020 \u306a\u3089\u7d42\u4e86\u3059\u308b\u95a2\u6570\u3002\nCoq\u3092\u901a\u3059\u305f\u3081\u306b 1 \u3092\u52a0\u3048\u308b\u4ee3\u308f\u308a\u306b 1\u3092\u5f15\u3044\u3066\u3044\u308b\u3002\n *)\n\nEval simpl in (down_to_zero 15).\n\n(* \u2610 *)\n", "meta": {"author": "khibino", "repo": "sfja-code", "sha": "2b9f6c561b56652aa67bbc0971db90a211c66373", "save_path": "github-repos/coq/khibino-sfja-code", "path": "github-repos/coq/khibino-sfja-code/sfja-code-2b9f6c561b56652aa67bbc0971db90a211c66373/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.9433475754883879, "lm_q1q2_score": 0.846838682500689}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    [Basics] chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p as [m n]. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p as [m n]. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n   you read them in a .v file.  The inner brackets, around 3, indicate\n   a list, but the outer brackets, which are invisible in the HTML\n   rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t =>\n    match h with\n    | O => nonzeros t\n    | _ => h :: nonzeros t\n    end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t =>\n    match oddb h with\n    | true => h :: oddmembers t\n    | false => oddmembers t\n    end\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1,l2 with\n  | nil, _ => l2\n  | _, nil => l1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t =>\n    match beq_nat v h with\n    | true => 1 + count v t\n    | false => count v t\n    end\n  end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\n\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := cons v s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  negb (beq_nat (count v s) 0).\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t =>\n    match beq_nat h v with\n    | true => t\n    | false => h :: remove_one v t\n    end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t =>\n    match beq_nat h v with\n    | true => remove_all v t\n    | false => h :: remove_all v t\n    end\n  end.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h1 :: t1 => member h1 s2 && subset t1 (remove_one h1 s2)\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\nTheorem bag_theorem_count_add : forall (n : nat) (b : bag),\n  count n (add n b) = 1 + count n b.\nProof.\n  intros n b. simpl.\n  replace (beq_nat n n) with true. reflexivity.\n  induction n as [|n' IHn].\n  - reflexivity. - simpl. rewrite <- IHn. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [|h t IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  induction l1 as [|h1 t1 IH].\n  - intro l2. simpl. rewrite app_nil_r. reflexivity.\n  - intro l2. simpl. rewrite IH. rewrite app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [|h1 t1 IH].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IH. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  replace ((l1 ++ l2) ++ l3) with (l1 ++ l2 ++ l3).\n  rewrite app_assoc. rewrite app_assoc. reflexivity.\n  rewrite app_assoc. reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [|h1 t1 IH].\n  - reflexivity.\n  - destruct h1 as [|h1'].\n    + simpl. rewrite IH. reflexivity.\n    + simpl. rewrite IH. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1,l2 with\n  | nil,nil => true\n  | (h1 :: t1), (h2 :: t2) => beq_nat h1 h2 && beq_natlist t1 t2\n  | _,_ => false\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  induction l as [|h t IH].\n  - reflexivity.\n  - simpl. rewrite IH. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs)  *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  reflexivity.\nQed.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  induction s as [|h t IH].\n  - reflexivity.\n  - destruct h as [|h'].\n    + simpl. rewrite ble_n_Sn. reflexivity.\n    + simpl. rewrite IH. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it.  (You may\n    find that the difficulty of the proof depends on how you defined\n    [count]!) *)\n\nTheorem bag_count_sum : forall (n : nat) (b1 b2 : bag),\n  count n b1 + count n b2 = count n (sum b1 b2).\nProof.\n  intros n b1 b2. induction b1 as [|h1 t1 IHb1].\n  - reflexivity.\n  - simpl. destruct (beq_nat n h1).\n    + simpl. rewrite IHb1. reflexivity.\n    + simpl. rewrite IHb1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  rewrite <- rev_involutive. rewrite <- H. rewrite rev_involutive. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | h :: _ => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default. induction l as [|h t IHl].\n  - reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  induction x. simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  simpl. intros d x.\n  rewrite <- beq_id_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o H. simpl. rewrite H. reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?  (Answer in English\n    or the natural language of your choice.)\n\n  \"baz\" has no element, because there isn't any \"base constructor\" availble.\n*)\n(** [] *)\n\n(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\n\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/revisit/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.9230391595405136, "lm_q1q2_score": 0.8467062801218196}}
{"text": "(** * Sorting *)\n\n(** In this module, we'll implement insertion sort, then state and\nprove its correctness. As a warm-up, we'll first write a verified\ninsertion sort that operates over only lists of [nat]s. We'll then\ngeneralize to an implementation that operates on polymorphic lists.\n\nThis module will only rely on the definitions introduced up to\nMoreLogic. That said, feel free to use Coq tactics discussed later in\nthe text, such as auto.\n\n*)\n\nRequire Export MoreLogic.\n\n(** * Permutations *)\n\n(** [perm] (5 pts): every sorting function should return a result that\nis a permutation of its input.  We'll first define the permutation\nrelationship over lists. The dependency between permutations and the\ntype of data stored in a list is very loose, so we'll go ahead and\njust define a permutation once, generalized over the type of data\nstored in the lists that we permuate.\n\nPlease define a [Prop]osition [perm] paramaterized on:\n\n(1) a type [T];\n\n(2) two lists of type [list T].\n\nFor each type [T]:\n\n(1) [perm T] should hold over the empty lists of type [T]:\n\n(2) for each element [n] of type [T] and all lists [l], [l0], and [l1]\nof [T] values, if [l] permutes to [l0 ++ l1], then [n :: l] permutes\nto [l0 ++ n :: l1].\n\n*)\n\n(* DEFINE perm HERE *)\n\nInductive perm (T:Type): list T -> list T -> Prop:=\n| perme : perm T [] []\n| permp : forall (l l0 l1 :list T) (n: T), perm T l (l0++l1) -> perm T (n::l) (l0++n::l1).\n\n(** [perm_refl (5 pts), perm_trans (20 pts)]: for each type [T], [perm\nT] defines a binary relation over [list T] that is in fact an\nequivalence relation. It'll help in some of our later proofs to use\nthe facts that [perm T] is reflexive and transitive, so please prove\nthese facts now. *)\n\nLemma perm_refl : forall T l, perm T l l.\nProof.\n  intros.\n  induction l.\n  Case \"perme\".\n      apply perme.\n  Case \"permp\".\n      apply permp with (l0:=[]) (l1:= l) (n:=x).\n      simpl.\n      assumption.      \n  Qed.\n\nLemma null_app: forall (T:Type) (l0 l1: list T),\n[] = l0++l1 -> l0 = [] /\\ l1=[].\nProof.\ninduction l0.\nsplit.\nreflexivity.\ngeneralize dependent l1.\ninduction l1.\nreflexivity.\nintros.\ninversion H.\nintros.\ninversion H.\nQed.\n\n\nLemma perm_trans :\n  forall T l0 l1 l2, perm T l0 l1 -> perm T l1 l2 -> perm T l0 l2.\nProof.\nintros.\ngeneralize dependent l0.\ninduction H0; intros.\nassumption.\ninversion H0; subst.\napply null_app in H3.\ndestruct H3.\nrewrite H1, H2.\nsimpl.\nassumption.\nrewrite <- H1 in H0.\napply permp with (n:=n0) in H0.\ninversion H; subst.\nadmit.\n\n  Qed.\n\n(** * Sorting [list nat]'s\n\nIn this module, we'll define when one list of [list nat]'s is a\nsorting of another, define insertion sort over [nat list]'s, and prove\nthat our definition returns a sorting of its input. *)\n\nModule SortingNats.\n\n(** ** Defining Sortedness \n\nWe'll now formulate under what conditions one [list nat] is a valid\nsorting of another [list nat].  *)\n\n(** [nat_sorted] (10 pts): please define a [Prop] named [nat_sorted]\nover a single [list nat]. [nat_sorted] should hold under one of the\nfollowing conditions:\n\n(1) [nat_sorted] holds for the empty list;\n\n(2) for each [nat] [n], [nat_sorted] holds for [[n]];\n\n(3) for all [nat]s [m] and [n] and each [list nat l], if [m <= n] and\n[nat_sorted] holds for [n :: l], then [nat_sorted] holds for [m :: n\n:: l].\n\nNote that this definition formalizes only \"local\" sortedness, not\n\"strong\" sortedness. *)\n\n(* TODO: define nat_sorted here. *)\n\nInductive nat_sorted: list nat -> Prop:=\n| natse : nat_sorted []\n| natsn : forall (n:nat), nat_sorted [n]\n| natsmn : forall (m n: nat) (l: list nat), m<= n -> nat_sorted (n::l) -> nat_sorted (m::n::l).\n\n(** [is_nat_sorting] (5 pts): now, please formulate when one [list\nnat] is a sorting of another [list nat].\n\nFor [nat list]'s [l0] and [l1], [l1] is a sorting of [l0] if both of\nthe following conditions hold:\n\n(1) [l1] is a sorted [list nat];\n\n(2) [l1] is a permutation of [l0]. *)\n\n(* TODO: define is_nat_sorting here. *)\n\nDefinition is_nat_sorting (l0 l1:list nat): Prop:= nat_sorted l1 /\\ perm nat l0 l1.\n\n(** ** Defining insertion sort \n\nWe'll now define an implementation of insertion sort over [nat\nlist]'s. *)\n\n(** [ble_nat_dec] (20 pts): one natural way to implement insertion\nsort would be to use [ble_nat], which returns a [bool] that denotes if\nits first input is less-than-or-equal-to the second. We could write an\nimplemenation using [ble_nat] that is correct, but its correctness\nwould be awkward to prove, because we would have to define, prove, and\nuse many simple lemmas for translating between the [bool] results of\n[ble_nat] and the actual ordering over [ble_nat]'s inputs.\n\nIn the unit on evidence-carrying Booleans, we saw that a similar\nawkwardness can be neatly sidestepped for reasoning about tests of\nequality over [nat]s with [beq_nat] by writing and using a proof\n[beq_nat_dec] that for all [nat]'s [m] and [n], either constructs a\nproof that [m = n] or [m <> n].\n\nTo write and prove the correctness of our sorting function, we'll\nwrite a similar proof [ble_nat_dec] that for all [nat]'s [m] and [n],\neither constructs a proof that [n <= m] or that [m <= n]. \n\nThe theorem is alrady stated. Please complete the proof.\n*)\n\n\nTheorem ble_nat_dec : forall (n m : nat), { n <= m } + { m <= n }.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      left. apply O_le_n.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. apply O_le_n.\n    SCase \"m = S m'\". \n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply n_le_m__Sn_le_Sm. assumption.\n      right. apply n_le_m__Sn_le_Sm. assumption.\nDefined.\n\n(** [nat_insert] (5 pts) takes:\n\n(1) a [nat] [n];\n\n(2) a sorted [nat list] [l].\n\n[nat_insert] returns a sorted [list nat] with [n] inserted into [l].\n\nPlease define [nat_insert]. One natural definition is a [Fixpoint]\nthat only uses [ble_nat_dec].  *)\n\n(* TODO: complete definition. *)\nFixpoint nat_insert n l : list nat:= \nmatch l with\n| [] => [n]\n| x :: t1 => if ble_nat_dec n x\n             then (n::x::t1)\n             else (x::(nat_insert n t1))\nend.\n\n(** [nat_insert_sort] (5 pts) takes:\n\n(1) a [list nat] [l]\n\n[nat_insert_sort] returns a sorting of [l].\n\nPlease write [nat_insert_sort]. One natural definition is a [Fixpoint]\nthat only uses [nat_insert].  *)\n\n(* TODO: complete definition *)\nFixpoint nat_insert_sort l : list nat:=\nmatch l with\n| [] => []\n| [x] => [x]\n| h::t1 => nat_insert h (nat_insert_sort t1)\nend.\n\nExample sort1 : nat_insert_sort [1;4;2;3;5] = [1;2;3;4;5].\nProof. simpl. reflexivity. Qed.\n\nExample sort2 : nat_insert_sort [5;4;3;2;1] = [1;2;3;4;5].\nProof. reflexivity. Qed.\n\nExample sort3 : nat_insert_sort [1;2;3;4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\n\n(** ** Proving correctness *)\n\n(** [insert_sorted] (10 pts): we now have a complete definition of\ninsertion sort over [list nat]'s, [nat_insert_sort]; we want to prove\nthat it returns a sorting of its input.\n\nOne observation that helps to simplify the proof is that we can prove\nthat (1) [nat_insert_sort] produces a permutation and (2)\n[nat_insert_sort] produces a sorted result completely\nindependently. Furthermore, the proofs of each sub-property can be\nbroken down into a key lemma about [insert], which is used in the\nproof of the sub-property for [nat_insert_sort].\n\nWe'll start by proving that [nat_insert] takes each [nat] and sorted\nlist to a sorted list.  *)\n\nLemma blah: forall l n x, \nx<=n -> nat_sorted (x::l) -> nat_sorted (nat_insert n (x::l)) -> nat_sorted (x::nat_insert n l).\nProof.\nintros.\ninduction l.\nsimpl.\nconstructor.\nassumption. constructor.\nsimpl.\ndestruct (ble_nat_dec n x0) eqn:B.\nconstructor. assumption. constructor. assumption.\ninversion H0; subst. assumption.\nconstructor.\ninversion H0; subst. assumption.\n\n\nAdmitted.\n\nLemma insert_sorted : forall l n, nat_sorted l -> nat_sorted (nat_insert n l).\nProof.\nintros.\ngeneralize dependent n.\ninduction l.\nsimpl.\nconstructor.\nintros.\nsimpl.\ndestruct (ble_nat_dec n x) eqn:B.\nconstructor.\nassumption. assumption.\ninversion H; subst.\nsimpl.\nconstructor.\nassumption. constructor.\ninversion H; subst.\ninduction H.\nsimpl.\n(*constructor.\nsimpl.\ndestruct (ble_nat_dec n n0) eqn:B.\nconstructor.\nassumption. constructor.\nconstructor. assumption. constructor.\ndestruct (ble_nat_dec n m) eqn:B1.\nsimpl.\nrewrite B1.\nconstructor. assumption.\nconstructor. auto.\nassumption.\ndestruct (ble_nat_dec n n0) eqn:B.\nsimpl.\nrewrite B1.\nrewrite B.\nsimpl in IHnat_sorted.\nrewrite B in IHnat_sorted.\nconstructor. assumption.\nconstructor. auto. assumption.\nsimpl.\nrewrite B1.\nrewrite B.\n\nconstructor. assumption.\ninduction l.\nsimpl. constructor. assumption. constructor.\nsimpl.*)\n\nAdmitted.\n\n\n(** [insertion_sorted] (5 pts): now, prove that [nat_insert_sort]\nproduces a sorted result. One natural proof requires only about 10\nlines, using [insert_sorted]. *)\n\nLemma insertion_sorted : forall l, nat_sorted (nat_insert_sort l).\nProof.\nintros.\ninduction l.\nsimpl.\nconstructor.\nsimpl.\ndestruct l.\nconstructor.\napply insert_sorted.\nassumption.\nQed.\n\n(** [insert_perm] (10 pts): now, prove that [nat_insert] takes each\n[nat] [n] and [list nat] [l] to a permutation of [n :: l]. One natural\nproof uses [perm_refl]. *) \n\n\nLemma insert_perm : forall l n, perm nat (n:: l) (nat_insert n l).  \nProof.\nintros.\ninduction l.\nsimpl.\napply perm_refl.\nsimpl.\ndestruct (ble_nat_dec n x) eqn:B.\napply perm_refl.\ninversion IHl; subst.\napply permp with (n:=x) in H0.\napply permp with (n:=n) in H0.\ninversion H0; subst.\nsimpl.\ndestruct (ble_nat_dec n x) eqn:B1.\n(*apply perm_refl.\nrewrite <- H2.\napply permp.\n\n\nrewrite l0 in B.\ninversion B.\nsimpl in IHl.\ninversion IHl; subst.\ninversion H0.\ninversion H.\napply perm_refl. *)\nAdmitted.\n\n(** [insertion_perm] (10 pts): now, prove that [nat_insert_sort]\npermutes its input. One natural proof is only ~15 lines, and uses\n[perm_trans].  *)\n\nLemma insertion_perm : forall l, perm nat l (nat_insert_sort l).\nProof.\nintros.\ninduction l.\nconstructor.\nsimpl.\ndestruct l.\nsimpl.\napply perm_refl.\ninversion IHl; subst.\nsimpl.\nAdmitted.\n\n(** [insertion_sorting] (5 pts): finally, prove that [nat_insert_sort]\nreturns a sorting of its input. One natural proof is extremely\nstraighforward and uses [insertion_sorted] and [insertion_perm]. *)\n\nTheorem insertion_sorting :\n  forall l, is_nat_sorting l (nat_insert_sort l).\nProof.\nintros.\nunfold is_nat_sorting.\nsplit.\napply insertion_sorted.\napply insertion_perm.\nQed.\n\nEnd SortingNats.\n\n(** * Sorting Polymorphic [list]s \n\nIf you've completed all of the definitions up to this point, then\nyou've actually defined and proven the correctness of an\nimplementation of insertion sort for [nat list]'s.\n\nHowever, sorting functions included in practical libraries are\ntypically polymorphic: they sort lists of arbitrary data of the same\ntype, as long as a user provides some function for ordering any two\nelements of the type of values stored in the list.\n\nIn this next module, we'll define, then state and prove the\ncorrectness of, sorting functions over polymorphic lists. If in\n[SortingNats], you (1) defined [nat_insert] to only operate on\nelements by applying [ble_nat_dec] and (2) wrote proofs that only\ninspected values in a list by considering the result of applying\n[ble_nat_dec] to the values, then your proofs from [SortingNats]\nshould go through after only superficial changes to various names. *)\n\nModule SortingGen.\n\n(** ** Defining sortedness\n\nWe'll now define sortedness over polymorphic lists.\n*)\n\n(** [binrel]: [binrel]'s will generalize the less-than-or-equal\nordering over [nat]'s used in the specfication of [nat_insert_sort].\n\nFor type [T], let [binrel T] be a binary relation over [T],\nrepresented as a function that takes two values of type [T] and\nreturns a [Prop]: *)\n\nDefinition binrel (T : Type) := T -> T -> Prop.\n\n(** [sorted] (5 pts): please generalize [nat_sorted] to be defined\nover polymorphic lists.\n\nFor type [T], binary relation [ord] over [T], and list l of type [list\nT], the [Prop]osition [sorted T ord l] should hold under conditions\ndirectly analogous to those given for [nat_sorted].  *)\n\n(* TODO: complete definition. *)\n\n(** [is_sorting] (5 pts): please generalize [is_nat_sorting] to be\ndefined over polymorphic lists.\n\nFor type [T], binary relation [ord] over [T], and lists [l0] and [l1]\nover values of type [T], the [Prop]osition [is_sorting T ord l0 l1]\nshould hold if all of the following conditions hold:\n\n(1) [l1] is sorted under [T] and [ord];\n\n(2) [l0] permutes to [l1].\n*)\n\n(* TODO: complete definition. *)\n\n(** ** Defining insertion sort \n\nWe'll now define an insertion sort over polymorphic lists.  *)\n\n(** [comparitor]: [comparitor]'s will generalize [ble_nat_dec] as used\nin the definition of [nat_insert].\n\nFor type [T] and [ord] a binary relation over [T], let a comparitor\nover [T] and [ord] be a function that for all elements [a] and [b] or\ntype [T], returns either evidence that the ordered pair [(a, b)] is in\n[ord] or the pair [(b, a)] is in [ord]. *)\n\nDefinition comparitor { T } (ord: binrel T) :=\n  forall (a b : T), { ord a b } + { ord b a }.\n\n(** [insert] (5 pts): please generalize [nat_insert] to operate over\npolymorphic lists.\n\n[insert] should take:\n\n(1) a type [T];\n\n(2) a binary relation [ord] over [T];\n\n(3) a comparitor [ble_dec] over [T] and [ord];\n\n(4) an element [n] of type [T];\n\n(5) a list [l] of [T] data.\n\nIf [l] is sorted, then [insert] returns a sorted list with [n]\ninserted into [l].\n\nYou can define [insert] by essentialy replacing uses of [ble_nat_dec]\nin [nat_insert] with uses of [ble_dec]. *)\n\n(* TODO: complete definition. *)\n\n(** [insert_sort] (5 pts): please generalize [nat_insert_sort] to\noperate over polymorphic lists.\n\n[insert_sort] sould take:\n\n(1) a type [T];\n\n(2) a binary relation [ord] over [T];\n\n(3) a comparitor [ble_dec] over [T] and [ord];\n\n(4) a list [l] of [T] values.\n\n[insert_sort] should return a sorting of [l] under [T] and [ord].\n\nYou can define [insert_sort] by essentially replacing uses of\n[nat_insert] in [nat_insert_sort] with [insert]. *)\n\n(* TODO: complete definition. *)\n\n(** ** Proving correctness *)\n\n(** [insert_sorted] (5 pts): please generalize\n[SortingNats.insert_sorted] for [insert], and prove the claim.\n\n[insert_sorted] should claim that for each type [T], binary relation\n[ord] over [T], and comparitor [ble_dec] over [T] and [ord], if [l] is\nsorted under [T] and [ord], then [insert ble_dec n l] is sorted under\n[T] and [ord].  *)\n\n(* TODO: define and prove. *)\n\n(** [insertion_sorted] (5 pts): please generalize\n[SortingNats.insertion_sorted] for [insert_sort], and prove the claim.\n\n[insertion_sorted] should claim that for each type [T], binary\nrelation [ord], comparitor [ble_dec] over [T] and [ord], and list [l] of\ntype [list T], [insert_sort T ord ble_dec l] is sorted.\n\nThe proof of insertion_sorted can be structured almost identically to\na proof of [SortingNats.insertion_sorted]. *)\n\n(* TODO: define and prove. *)\n\n(** [insert_perm] (5 pts): please generalize [SortingNats.insert_perm]\nfor [insert], and prove the claim.\n\n[insert_perm] should claim that for each type [T], binary relation\n[ord] over [T], comparitor [ble_dec] over [T] and [ord], element [n]\nof type [T], and list [l] of [T] values, [n :: l] permutes to [insert\nT ord ble_dec n l].\n\nThe proof can be structured almost identically to a clean proof of\n[insert_perm].  *)\n\n(* TODO: define and prove. *)\n\n(** [insertion_perm] (5 pts): please generalize\n[SortingNats.insertion_perm] to claim that [insert_sort] returns a\npermutation of its input, and then prove the claim.\n\n[insertion_perm] should claim that for each type [T], binary relation\n[ord] over [T], comparitor [ble_dec] over [T] and [ord], and list [l] of\nvalues of type [T], [l] permutes to [insert_sort ble_dec l]. *)\n\n(* TODO: define and prove. *)\n  \n(** [insertion_sorting] (5 pts): please generalize\n[SortNats.insertion_sorting] to claim the correctness of\n[insert_sort], then prove the claim.\n\n[insertion_sorting] should claim that for each type [T], binary\nrelation [ord] over [T], and comparitor [ble_dec] over [T] and [ord],\n[insert_sort T ord ble_dec l] is a sorting of [l].\n\nThe proof can be structured very similarly to the proof of\n[SortNats.insertion_sorting].  *)\n\n(* TODO: define and prove. *)\n\n(** It's now trivial to define [nat_insert_sort] as an application of\n[insert_sort]: *)\n\n(*Definition nat_insert_sort := insert_sort (SortingNats.ble_nat_dec).\n\n(** We could also prove that the [nat_insert_sort] that we wrote by\nhand is equivalent to the version produced as application of\n[insert_sort]. I.e., we could prove: *)\n\nTheorem eq_sorts :\n  forall l, SortingNats.nat_insert_sort l = nat_insert_sort l. *)\n\n(** However, assuming that the two programs were written with the same\nstructure, this proof wouldn't be terribly interesting. *)\n\n(** Having defined and verified implementations of insertion sort, a\nnatural next step is to determine what is involved to prove other\nfavorite sorting algorithms, namely ones with tighter worst-case\nperformance bounds, such as [quicksort] and [mergesort].\n\nThese can be implemented and verified in Coq; however, defining\nimplementations that will even be accepted by the Coq compiler is\nactually non-trivial. The complexity stems from the fact that the\nnatural definition of [mergesort] recurses on a split of its input\nlist, but the Coq compiler cannot determine that this definition of\n[mergesort] performs well-founded recursion (compare to insertion\nsort, which recurses on the tail of a list).\n\nIf you're interested in learning how to overcome this problem, Coq\nprovides a verified implementation of [mergesort] in its standard\nlibrary <https://coq.inria.fr/library/Coq.Sorting.Mergesort.html>. *)\n\nEnd SortingGen.\n", "meta": {"author": "SumithraSriram", "repo": "Software-Foundations", "sha": "e3d8739ca9f399266450c8a859e6f615e3eb352b", "save_path": "github-repos/coq/SumithraSriram-Software-Foundations", "path": "github-repos/coq/SumithraSriram-Software-Foundations/Software-Foundations-e3d8739ca9f399266450c8a859e6f615e3eb352b/sf/SortNatsProblems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.9416541585696252, "lm_q1q2_score": 0.8466613865105085}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\n(*\n    You are only allowed to use these tactics:\n\n    simpl, reflexivity, intros, rewrite, destruct, induction, apply, assert\n\n    You are not allowed to use theorems outside this file *unless*\n    explicitly recommended.\n*)\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nShow that 5 equals 5.\n\n *)\nTheorem ex1:\n  5 = 5.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\n(**\n\nShow that equality for natural numbers is reflexive.\n\n *)\nTheorem ex2:\n  forall (x:nat), x = x.\nProof.\n  intros x.\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\nShow that [1 + n] equals the successor of [n].\n\n *)\nTheorem ex3:\n  forall n, 1 + n = S n.\nProof.\n  intros n.\n  assert (H: 1 + n = S n). {reflexivity. }\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\nShow that if [x = y], then [y = x].\n\n *)\nTheorem ex4:\n  forall x (y:nat), x = y -> y = x.\nProof.\n  intros x.\n  intros y.\n  intros x_eq_y.\n  rewrite -> x_eq_y.\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\nShow that if the result of the conjunction and the disjunction equal,\nthen both boolean values are equal.\n\n\n *)\nTheorem ex5:\n  forall (b c : bool), (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  destruct b.\n- simpl.\n  intros x.\n  rewrite x.\n  reflexivity.\n- simpl.\n  intros y.\n  rewrite y.\n  reflexivity.\nQed.\n\n(**\n\nIn an addition, we can move the successor of the left-hand side to\nthe outer most.\n\n\n *)\nTheorem ex6:\n  forall n m, n + S m = S (n + m).\nProof.\n  intros n m.\n  induction n as [|n' IH].\n  - reflexivity.\n  - simpl.\n    rewrite <- IH.\n    reflexivity.\nQed.\n\n(**\n\nIf two additions are equal, and the numbers to the left of each addition\nare equal, then the numbers to the right of each addition must be equal.\nTo complete this exercise you will need to use the auxiliary\ntheorem: eq_add_S\n\n\n *)\nTheorem ex7:\n  forall x y n, n + x = n + y -> x = y.\nProof.\n  intros x y n.\n  intros nx_eq_ny.\n  induction n as [ | i IH].\n  - simpl in nx_eq_ny.\n    rewrite -> nx_eq_ny.\n    reflexivity.\n  - simpl in nx_eq_ny.\n    apply eq_add_S.\n    rewrite <- IH. \n    * reflexivity.\n    * apply eq_add_S.\n      rewrite <- nx_eq_ny.\n      reflexivity.\nQed.\n\n(**\n\nShow that addition is commutative.\nHint: You might need to prove `x + 0 = x` and `S (y + x) = y + S x`\nseparately.\n\n\n *)\nTheorem ex8:\n  forall x y, x + y = y + x.\nProof.\nAdmitted.\n\n(**\n\nIf two additions are equal, and the numbers to the right of each addition\nare equal, then the numbers to the left of each addition must be equal.\n\nHint: Do not try to prove this theorem directly. You should be using\nauxiliary results. You can use Admitted theorems.\n\n\n *)\nTheorem ex9:\n  forall x y n, x + n = y + n -> x = y.\nProof.\n\nAdmitted.\n\n\n\n", "meta": {"author": "javidan1", "repo": "cs420", "sha": "03edcef80b43dc84ed6a0beebd6ad3e201fa8834", "save_path": "github-repos/coq/javidan1-cs420", "path": "github-repos/coq/javidan1-cs420/cs420-03edcef80b43dc84ed6a0beebd6ad3e201fa8834/hw1/hw1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.9161096130168221, "lm_q1q2_score": 0.8466152050734003}}
{"text": "(* Software Foundations *)\n(* Exercice ** plus_swap' *)\nLemma  plus_0_r: forall n: nat, n+0=n.\nProof.\n    intros. induction n as [|n'].\n    reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma plus_succ: forall n m: nat, n + S m = S (n + m).\nProof.\n    intros. induction n as [|n'].\n    simpl. reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma plus_comm: forall n m: nat, n+m = m +n.\nProof.\n    intros. induction n as [|n'].\n    simpl. rewrite plus_0_r. reflexivity.\n    simpl. rewrite IHn'. rewrite plus_succ. reflexivity.\nQed.\n\nTheorem plus_swap: forall n m p: nat, n + (m + p) = m + (n + p).\nProof.\n    intros. rewrite plus_comm. induction m as [|m'].\n    simpl. rewrite plus_comm. reflexivity.\n    simpl. rewrite IHm'. reflexivity.\nQed.\n\n\n(* using only the Lemma plus_succ *)\nTheorem plus_swap': forall n m p: nat, n + (m + p) = m + (n + p).\nProof.\n    intros. induction n as [|n']. induction m as [|m'].\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHn'. (*remember (n'+p) as u*) rewrite plus_succ. 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/chapter4_Library_Induction/plus_swap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771661, "lm_q2_score": 0.9149009509324104, "lm_q1q2_score": 0.8464937732334384}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import Arith.\n\nRequire Extraction.\nRequire Import ExtrOcamlNatInt.\n\nDefinition filter_lte (a: nat) list := filter (fun n=> n <=? a) list.\nDefinition filter_gt (a: nat) list := filter (fun n=> negb(n <=? a)) list.\n\nFixpoint quicksort (l: list nat) :=\n    match l with\n      nil => nil\n    | h :: t => let sorted_t := quicksort t in\n                    filter_lte h sorted_t\n                    ++ h :: filter_gt h sorted_t\n    end.\n\nCompute quicksort (nil).\nCompute quicksort (1::2::3::6::1::2::1::0::nil).\n\nFixpoint length (l: list nat) : nat :=\n    match l with\n      nil => 0\n    | a :: tl => 1 + (length (tl))\n    end.\n\nTheorem lengthIsCommutative: forall l m : list nat, length(l ++ m) = length(m ++ l).\nProof.\n    induction l.\n    intros.\n    simpl.\n    rewrite app_nil_r.\n    reflexivity.\n    intros.\n    simpl.\n    rewrite IHl.\n    induction m.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite IHm.\n    reflexivity.\nQed.\n\nTheorem lengthIsDistributive: forall l j:(list nat), length (l ++ j) = length l + length j.\nProof.\n    induction j.\n    simpl.\n    rewrite app_nil_r.\n    firstorder.\n    rewrite lengthIsCommutative.\n    simpl.\n    rewrite Nat.add_succ_r with (n:=length l) (m:=length j).\n    rewrite lengthIsCommutative.\n    rewrite IHj.\n    firstorder.\nQed.\n\nTheorem twoFilterLengthEq: forall n l, length(filter_lte n l) + length(filter_gt n l) = length(l).\nProof.\n    intros.\n    induction l.\n    simpl.\n    reflexivity.\n    unfold filter_lte.\n    assert ((fun n0 : nat => n0 <=? n) a = true \\/ (fun n0 : nat => negb(n0 <=? n)) a = true).\n    case (a <=? n).\n    left; reflexivity.\n    right; simpl; reflexivity.\n    destruct H.\n    simpl.\n    rewrite H.\n    simpl.\n    assert (filter_lte n l = filter (fun n0 : nat => n0 <=? n) l).\n    unfold filter_lte.\n    firstorder.\n    rewrite <- H0.\n    rewrite IHl.\n    firstorder.\n    assert (filter_lte n (a::l) = filter (fun n0 : nat => n0 <=? n) (a::l)).\n    unfold filter_lte.\n    firstorder.\n    rewrite <- H0.\n    simpl.\n    rewrite H.\n    assert((a <=? n) = false).\n    rewrite <- negb_involutive with (b:=(a <=? n)).\n    rewrite H.\n    firstorder.\n    rewrite H1.\n    simpl.\n    rewrite Nat.add_succ_r with (n:=length(filter_lte n l)) (m:=(length (filter_gt n l))).\n    rewrite IHl.\n    firstorder.\nQed.\n\nTheorem sortLengthUnchanged :\n    forall l:(list nat),\n    length l = length (quicksort l).\nProof.\n    induction l.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite IHl.\n    rewrite lengthIsDistributive.\n    simpl.\n    rewrite Nat.add_succ_r with\n        (n:=length(filter_lte a (quicksort l)))\n        (m:=(length (filter_gt a (quicksort l)))).\n    rewrite twoFilterLengthEq.\n    reflexivity.\nQed.\n\n(* https://gist.github.com/adampalay/44b9ac3515469d92cb2f295e6179b8b9 *)\n\nExtraction \"quicksort.ml\" quicksort.", "meta": {"author": "elle-et-noire", "repo": "coq-wsl", "sha": "f3e43ed79fa6358d061e1bb574e234a36e298392", "save_path": "github-repos/coq/elle-et-noire-coq-wsl", "path": "github-repos/coq/elle-et-noire-coq-wsl/coq-wsl-f3e43ed79fa6358d061e1bb574e234a36e298392/ocaml/quicksort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.9086178944582997, "lm_q1q2_score": 0.8463435035768436}}
{"text": "From mathcomp Require Import ssreflect ssrnat.\n\nSection natrualNumber.\n  \nLemma add0nEqn (n : nat) : 0 + n = n.\nProof.\n  by [].\nQed.\n\nLemma addn3Eq2n1 (n : nat) : n + 3 = 2 + n + 1.\nProof.\n  rewrite addn1.\n  rewrite add2n.\n  rewrite addnC.\n  by [].\nQed.\n\nFixpoint sum n := if n is m.+1 then sum m + n else 0.\n(* n is m.+1 \u306e\u3068\u3053\u308d\u306f\u3044\u308f\u3086\u308b\u30d1\u30bf\u30fc\u30f3\u30de\u30c3\u30c1\uff1f *)\n\nLemma sumGauss (n : nat) : sum n * 2 = (n + 1) * n.\nProof.\n  (* move: n; elim.\n  move => //.\n  move =>  n.\n  move => IHn. *)\n  elim: n => [// | n IHn]. (* induction *)\n  rewrite mulnC.\n  rewrite (_ : sum (n.+1) = n.+1 + (sum n)); last first. (* replace *)\n  rewrite /=. (* simpl. *)\n  by rewrite addnC.\n  rewrite mulnDr.\n  rewrite mulnC in IHn. (* \u30b3\u30f3\u30c6\u30ad\u30b9\u30c8\u3078\u306e\u9069\u7528 *)\n  rewrite IHn.\n  rewrite 2!addn1. (* 2\u56de\u9069\u7528 *)\n  rewrite [_ * n]mulnC. (* \u30d1\u30bf\u30fc\u30f3\u30de\u30c3\u30c1\u9069\u7528 *)\n  rewrite -mulnDl. (* \u53f3\u8fba\u304b\u3089\u5de6\u8fba\u3078\u306e\u66f8\u304d\u63db\u3048 *)\n  by [].\nQed.\n\nEnd natrualNumber.\n", "meta": {"author": "matonix", "repo": "topprover", "sha": "c98d06ead25b865ef4b92313ef2a0d7f73422c33", "save_path": "github-repos/coq/matonix-topprover", "path": "github-repos/coq/matonix-topprover/topprover-c98d06ead25b865ef4b92313ef2a0d7f73422c33/CoqSSRefrectMathCompBook/NaturalNumber.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.9136765316406924, "lm_q1q2_score": 0.8463419851173263}}
{"text": "Require Import Arith List Sorting Permutation.\nImport ListNotations.\nFrom mathcomp Require Import ssreflect ssrnat ssrbool.\n\nFixpoint insert (i:nat) (l:list nat) :=\n  match l with\n  | [] => [i]\n  | h :: t => if i <= h then i :: h :: t else h :: insert i t\n  end.\n\nFixpoint sort (l:list nat) : list nat :=\n  match l with\n  | [] => []\n  | h :: t => insert h (sort t)\n  end.\n\nExample sort_pi :\n  sort [3;1;4;1;5;9;2;6;5;3;5]\n  = [1;1;2;3;3;4;5;5;5;6;9].\ncompute. reflexivity. Qed.\n\nInductive sorted : list nat -> Prop :=\n| sorted_nil : sorted []\n| sorted_1 : forall x, sorted [x]\n| sorted_cons : forall x y l,\n    x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\n\n\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l S. induction S; simpl.\n   -- apply sorted_1.\n   -- SearchPattern (forall n m, _ (n < m) -> _ (n <= m)). \n      case_eq (a <= x); intros H; apply sorted_cons; try apply sorted_1. \n      apply H. apply ltnW. by rewrite leqNgt ltnS H.\n   -- case_eq (a <= x); intros H1. apply sorted_cons. apply H1.\n    apply sorted_cons. apply H. apply S.\n    move: IHS. unfold insert. case_eq (a <= y); intros H2 IHS.\n    apply sorted_cons. apply /ltnW. by rewrite leqNgt ltnS H1. \n    apply IHS. fold insert. fold insert in IHS. \n    apply sorted_cons. apply H. apply IHS.\nQed.\n\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n  induction l.\n   -- apply sorted_nil.\n   -- apply (insert_sorted a _ IHl).\nQed.\n\nLemma insert_permute: forall x l, Permutation (x :: l) (insert x l).\nProof.\n  fix insert_permute 2.\n  intros x l. destruct l as [|a l'].\n   -- apply Permutation_refl.\n   -- simpl. case_eq (x <= a); intros H.\n   ---- apply Permutation_refl.\n   ---- apply (@perm_trans _ _ (a :: x :: l') _).\n    apply perm_swap. apply perm_skip. apply insert_permute.\n  Qed.\n\nTheorem sort_perm : forall l, Permutation l (sort l).\nProof.\n  induction l.\n   -- apply Permutation_refl.\n   -- simpl. apply (@perm_trans _ _ (a :: sort l) _).\n    apply perm_skip, IHl. \n    apply insert_permute.\nQed.\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) := \n  forall al, Permutation al (f al) /\\ sorted (f al).\n\nTheorem insertion_sort_correct : is_a_sorting_algorithm sort.\nProof.\n  intros l. apply conj. apply sort_perm. apply sort_sorted. Qed.\n  ", "meta": {"author": "elle-et-noire", "repo": "coq-wsl", "sha": "f3e43ed79fa6358d061e1bb574e234a36e298392", "save_path": "github-repos/coq/elle-et-noire-coq-wsl", "path": "github-repos/coq/elle-et-noire-coq-wsl/coq-wsl-f3e43ed79fa6358d061e1bb574e234a36e298392/sort/insersion01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.8962513662057089, "lm_q1q2_score": 0.8462198053292019}}
{"text": "Require Import Omega.\nOpen Scope list_scope.\n\n(* PAIR*)\nInductive is_even : nat -> Prop :=\n| is_even_O : is_even 0\n| is_even_S : forall n : nat , is_even n-> is_even (S (S n)).\n\n\nFixpoint even (n : nat) : Prop := \n  match n with\n  | 0 => True\n  | 1 => False\n  | (S (S n)) => even n\nend.\n\n\nFunctional Scheme even_ind := Induction for even Sort Prop.\n\nTheorem even_sound :\n forall (n : nat) (v : Prop) , (even n) = True -> is_even n.\nProof.\n  do 2 intro.\n  functional induction (even n) using even_ind; intros.\n  apply is_even_O.\n  elimtype False; rewrite H; auto.\n  apply is_even_S; apply IHP; assumption.\nQed.\n\n\n(* FACTORIELLE *)\n\nInductive is_fact : nat -> nat -> Prop :=\n| fact_0 :  is_fact 0 1\n| fact_S : forall n : nat , forall s : nat , is_fact n s  -> is_fact (S n) (s * (S n)).\n\n\nFixpoint fact (n : nat) : nat :=\n  match n with \n | 0 => 1\n | (S n) => (fact n * (S n))\n end.\n\n\nFunctional Scheme fact_ind := Induction for fact Sort Prop.\n\nTheorem fact_sound : \n  forall (n : nat) (r: nat) , (fact n ) = r -> is_fact  n r.\nProof. \n  intro.\n  functional induction (fact n) using fact_ind; intros.\n  elim H.\n  apply fact_0.\n  elim H.\n  apply fact_S.\n  apply (IHn0 (fact n0)).\n  reflexivity.\nQed.\n\n\n(* TRI PAR INSERTION *)\n\nInductive is_perm : (list nat) -> (list nat) -> Prop := \n| is_perm_refl : forall l1 : (list nat) , is_perm l1 l1\n| is_perm_transitive : forall l1 l2 l3 :(list nat) , is_perm l1 l2 -> is_perm l2 l3 -> is_perm l1 l3\n| is_perm_sym : forall l1 l2 : (list nat) , is_perm l1 l2 -> is_perm l2 l1\n| is_perm_cons : forall l1 l2 : (list nat) , forall a : nat , is_perm l1 l2 -> is_perm (a::l1) (a::l2)\n| is_perm_a : forall l1 : (list nat) , forall a : nat , is_perm(a::l1)(l1++ a::nil).\n\n\nDefinition l1 := 1::2::3::nil.\nDefinition l2 := 3::2::1::nil.\n\nLemma undeuxtrois : is_perm l1 l2.\nunfold l1.\nunfold l2.\napply (is_perm_transitive (1::(2::(3::nil))) ((2::(3::nil))++(1::nil)) (3::(2::(1::nil)))).\napply is_perm_a.\nsimpl.\napply (is_perm_transitive (2::(3::(1::nil))) ((3::(1::nil))++(2::nil)) (3::(2::(1::nil)))).\napply is_perm_a.\nsimpl.\napply is_perm_cons.\napply (is_perm_transitive (1::(2::nil)) ((1::nil)++(2::nil)) (2::(1::nil))).\nsimpl.\napply is_perm_cons.\napply is_perm_refl.\napply is_perm_a.\nQed.\n\nInductive is_sort :(list nat) -> Prop := \n| is_sort_0 : is_sort nil\n| is_sort_1 : forall n : nat , is_sort(n::nil)\n| is_sort_N : forall n m : nat , forall l :(list nat) ,  n <= m -> is_sort(m::l) -> is_sort (n::m::l).\n\nLemma sort123 : is_sort l1.\nunfold l1.\napply is_sort_N.\nomega.\napply is_sort_N.\nomega.\napply is_sort_1.\nQed.\n\n\nFixpoint Insert (x : nat) (l : (list nat)) : (list nat) := \n  match l with \n | (nil) => (x::nil)\n | h::t => match le_dec x h with\n      | left _ => x::h::t\n      | right _ => h::(Insert x t)\n      end\nend.\n\nFixpoint Sort (l : (list nat)) : (list nat) :=\n match l with \n | (nil) => (nil)\n | h::t => (Insert h (Sort t))\nend.\n\n\n(* Theor\u00e8me intermediaire 1 -- Il sert \u00e0 prouver le theoreme intermediaire 2 *)\n\nTheorem inter1 : forall (a1 : nat) (a2 : nat) (l : (list nat)) , (is_perm (a1 :: a2 :: l) (a2 :: a1 :: l)).\nProof.\nintro.\nintro.\nintro.\napply (is_perm_transitive  (a1 :: a2 :: l) ( a2 :: l ++ a1::nil ) (a2 :: a1 :: l)).\napply is_perm_a.\napply is_perm_cons.\napply is_perm_sym.\napply is_perm_a.\nQed.\n\n\n\n(* Theoreme interm\u00e9diaire 2 *)\nTheorem is_perm_insert :\nforall (a : nat)  (l : (list nat)) , (is_perm (a::l) (Insert a l)).\nProof.\ninduction l;\nsimpl.\napply is_perm_a.\nelim (le_dec a a0).\nintros.\napply is_perm_refl.\nintros.\napply (is_perm_transitive (a :: a0 :: l) (a0 :: a :: l) (a0 :: Insert a l)).\napply inter1.\napply is_perm_cons.\napply IHl.\nQed.\n\n\n(* Theoreme interm\u00e9diaire 3 *)\nTheorem is_sort_cons :\nforall ( a : nat) (l : (list nat)) , (is_sort l) -> (is_sort (Insert a l)).\nProof.\ninduction l.\nsimpl.\nintros.\napply is_sort_1.\nintros.\nsimpl.\nelim (le_dec a a0).\nintros.\napply is_sort_N.\napply a1.\napply H.\nintros.\n\n\n\n\n\nTheorem Insert_Sort_Sound :\n  forall (l : (list nat)) (l1 : (list nat)) ,(Sort l) = l1 -> (is_perm l l1) /\\ (is_sort l1).\nProof. \ninduction l.\nintros.\nsplit.\nsimpl in H.\nrewrite <- H. \napply is_perm_refl.\nsimpl in H.\nrewrite <- H.\napply is_sort_0.\nsplit.\nrewrite <- H.\nsimpl.\napply (is_perm_transitive (a::l)  (a:: (Sort l)) (Insert a (Sort l))).\napply is_perm_cons.\napply IHl.\nreflexivity.\napply is_perm_insert.\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "hogoww", "repo": "spec_formelles", "sha": "01818eac3794a70a6888c5a791971646dcf777af", "save_path": "github-repos/coq/hogoww-spec_formelles", "path": "github-repos/coq/hogoww-spec_formelles/spec_formelles-01818eac3794a70a6888c5a791971646dcf777af/Baptiste/factInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8962513641273355, "lm_q1q2_score": 0.8462197921042788}}
{"text": "Require Import List.\n\n(*Require Import CpdtTactics.*)\n\nSet Implicit Arguments.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nFixpoint plus (n m : nat) : nat :=\nmatch n with\n  | O => m\n  | S n' => S (plus n' m)\nend.\n\nTheorem O_plus_n : forall n:nat, plus O n = n.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem n_plus_O : forall n:nat, plus n O = n.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem plus_assoc_from_left : forall n m p : nat, \n  plus (plus n m) p = plus n (plus m p).\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  intros. \n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem plus_assoc_from_right : forall n m p : nat, \n  plus n (plus m p) = plus (plus n m) p.\n  induction n.\n  simpl.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma plus_succ_inside : forall n m : nat,\n  S(plus n m) = plus n (S m).\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem plus_commutativity : forall n m : nat,\n  plus n m = plus m n.\n\n  induction n.\n  simpl.\n  intros.\n  rewrite n_plus_O.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite IHn.\n  apply plus_succ_inside.\nQed.\n\nFixpoint mult (n m : nat) : nat :=\nmatch n with\n  | O => O\n  | S n' => plus (mult n' m) m\nend.\n\nDefinition I : nat := S O.\n\nTheorem n_plus_I : forall n:nat, plus n I = S n.\n  induction n.\n  simpl.\n  unfold I.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem I_mult_n : forall n:nat, mult I n = n.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem n_mult_I : forall n:nat, mult n I = n.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  simpl.\n  apply n_plus_I.\nQed.\n\nLemma n_mult_O : forall n:nat, mult n O = O.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  simpl.\n  reflexivity.\nQed.\n\nLemma O_mult_n : forall n:nat, mult O n = O.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem right_distributivity : forall n m p : nat,\n  mult (plus n m) p = plus (mult n p) (mult m p).\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite IHn.\n  rewrite plus_assoc_from_left.\n  assert (plus (mult m p) p = plus p (mult m p)).\n  rewrite plus_commutativity.\n  reflexivity.\n  rewrite H.\n  rewrite plus_assoc_from_right.\n  reflexivity.\nQed.\n\nTheorem left_distributivity : forall n m p : nat,\n  mult n (plus m p) = plus (mult n m) (mult n p).\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite IHn.\n  assert(plus (plus (mult n m) (mult n p)) (plus m p) \n    = plus (mult n m) (plus (mult n p) (plus m p))).\n  rewrite plus_assoc_from_left.\n  reflexivity.\n  rewrite H.\n  assert(plus (mult n p) (plus m p) = plus (plus (mult n p) m) p).\n  rewrite plus_assoc_from_right.\n  reflexivity.\n  rewrite H0.\n  assert(plus (mult n p) m = plus m (mult n p)).\n  rewrite plus_commutativity.\n  reflexivity.\n  rewrite H1.\n  assert(plus (plus (mult n m) m) (plus (mult n p) p) = plus (mult n m) (plus m (plus (mult n p) p))).\n  rewrite plus_assoc_from_left.\n  reflexivity.\n  rewrite H2.\n  rewrite plus_assoc_from_left.\n  reflexivity.\nQed. \n\nTheorem mult_assoc_from_left: forall n m p :nat,\n  mult (mult n m) p = mult n (mult m p).\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite right_distributivity.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem mult_assoc_from_right: forall n m p :nat,\n  mult n (mult m p) = mult (mult n m) p.\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite IHn.\n  rewrite right_distributivity.\n  reflexivity.\nQed.\n\nTheorem mult_commutativity: forall n m : nat,\n  mult n m = mult m n.\n  induction n.\n  intro.\n  simpl.\n  rewrite n_mult_O.\n  reflexivity.\n  intro.\n  simpl.\n  rewrite IHn.\n  assert(S n = plus n I).\n  rewrite n_plus_I.\n  reflexivity.\n  rewrite H.\n  rewrite left_distributivity.\n  rewrite n_mult_I.\n  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/natural.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.8457022012004886}}
{"text": "Set Warnings \"-notation-overriden,-parsing\".\n\nRequire Export Logic.\nRequire Coq.omega.Omega.\n\n\n(* CIC built from function types and inductive types *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall m:nat, ev m -> ev (S (S m)).\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS,ev_SS,ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : \n  forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. apply ev_SS, ev_SS. assumption.\nQed.\n\nDefinition double (n : nat) : nat :=\n  plus n n.\nCompute double 3.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' => n'\n  end.\n\nTheorem ev_double : forall n, ev (double n).\nProof.\n  intros n. unfold double. induction n.\n  - apply ev_0.\n  - simpl. rewrite <- plus_comm. simpl.\n    apply ev_SS. apply IHn.\nQed.\n\nTheorem ev_minus2 : forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n E. inversion E as [| n' E'].\n  - simpl. apply ev_0.\n  - simpl. apply E'.\nQed.\n\nTheorem ev_minus2' : forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n E. destruct E.\n  - simpl. apply ev_0.\n  - simpl. apply E.\nQed.\n\nTheorem evSS_ev : forall n, ev (S (S n)) -> ev n.\nProof.\n  intros n H. inversion H as [| m h1 h2]. apply h1.\nQed.\n\nTheorem one_not_even : not (ev 1).\nProof. intros H. inversion H. Qed.\n\nTheorem SSSSev__even: forall n, ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H. inversion H as [| m H1 H2].\n  apply evSS_ev in H1. apply H1.\nQed.\n\nTheorem even5_nonsense : ev 5 -> 2 + 2 = 9.\nProof.\n  intros H. simpl. inversion H as [| n' E H1].\n  inversion E as [| n'' E' H2]. inversion E'.\nQed.\n\n(*\nCheck eq.\nPrint eq_symm.\nTheorem eq_symm :  \n\nLemma ev_even_firsttry :  n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E. inversion E as [| n' E'].\n  - exists 0. reflexivity.\n  - assert (I : (exists k', double k' = n') ->\n                (exists k, double k = S (S n'))).\n    { intros [k' Hk']. rewrite <- Hk'. exists (S k').\n      unfold double. simpl. rewrite -> plus_comm. simpl. reflexivity. }\n  Search eq. rewrite -> eq_Symmetric.\n*)\n\nLemma add_S : forall n m: nat, n = m -> S n = S m.\nProof. intros n m E. rewrite E. reflexivity. Qed.\n\nLemma remove_S : forall n m:nat, S n = S m -> n = m.\nProof. intros n m E. inversion E. reflexivity. Qed.\n\nLemma succ_even : forall k:nat, double (S k) = S (S (double k)).\nProof.\n  intros k. unfold double.\n  simpl. apply add_S. apply plus_comm.\nQed.\n\nLemma ev_even : forall n, ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  { exists 0. reflexivity. }\n  { destruct IH as [k' Hk']. rewrite Hk'.\n    exists (S k'). apply eq_sym. apply succ_even.\n  }\nQed.\n\n(* when to use indprop and when to use decidable definition? *)\n(* maybe indprop more general? I think this is true *)\n\nLemma rev_SS : forall n, ev (S (S n)) -> ev n.\nProof.\n  intros n H. inversion H. assumption.\nQed.\n\nLemma exists_half_to_ev : forall n, ((exists k, n = double k) -> ev n).\nProof.\n  intros n [k H]. rewrite H. clear H. induction k.\n  { apply ev_0. } { rewrite succ_even. apply ev_SS. apply IHk. }\nQed.\n\nTheorem ev_even_iff : forall n,\n ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  { apply ev_even. }\n  { apply exists_half_to_ev. }\nQed.\n\n(* pose v assert? *)\n(* assert adds to subgoals, \n   pose creates definition maybe *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m En Em.\n  induction En as [|n' _ IH].\n  { simpl. apply Em. }\n  { simpl. apply ev_SS. apply IH. }\nQed.\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\n\n(* one disjuntive branch for each contructor *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros n. split.\n  { intros Ev'_n. induction Ev'_n as [| | m m' Ev'_m IHEv_m Ev'_m' IHEv_m'].\n    { apply ev_0. } \n    { apply ev_SS, ev_0. } \n    { apply ev_sum. { apply IHEv_m. } { apply IHEv_m'. }}\n  }\n  { intros Ev_n. induction Ev_n as [| n' Ev_n' IHEv'_n'].\n    { apply ev'_0. } \n    { replace (S (S n')) with (2 + n').\n      { apply ev'_sum. { apply ev'_2. } { apply IHEv'_n'. } }\n      { reflexivity. }\n    }\n  }\nQed.\n\nTheorem ev_ev__ev : forall n m, \n  ev (n + m) -> ev n -> ev m.\nProof.\n  intros n m Ev_nm Ev_n.\n  induction Ev_n as [| n' Ev_n' IH]. \n  { simpl in Ev_nm; assumption. }\n  { simpl in Ev_nm. apply rev_SS in Ev_nm.\n    apply IH. apply Ev_nm.\n  }\nQed.\n\n(*\nTheorem ev_plus_plus : forall n m p, \n  ev (n + m) -> ev (n + p) -> ev (m + p).\nProof.\n  intros n m p E_nm E_np.\n  assert (H := forall n m : (ev n -> ev m)).\n *) \n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8962513835254866, "lm_q1q2_score": 0.845476564680699}}
{"text": "(* week_36c_mul.v *)\n(* dIFP 2014-2015, Q1, Week 36 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nRequire Import unfold_tactic.\n\n(* ********** *)\n\nNotation \"A === B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_tests_for_multiplication (mul : nat -> nat -> nat) :=\n  (mul 0 0 === 0)\n  &&\n  (mul 0 1 === 0)\n  &&\n  (mul 1 1 === 1)\n  &&\n  (mul 2 1 === 2)\n  &&\n  (mul 2 0 === 0)\n  && \n  (mul 2 2 === 4)\n  &&\n  (mul 0 2 === 0)\n  &&\n  (mul 1 2 === 2).\n\n(* Exercise 0: flesh out the unit tests above with more tests. *)\n\n(* mult is the built-in multiplication in Coq (infix notation: * ): *)\nCompute (unit_tests_for_multiplication mult).\n(*\n     = true\n     : bool\n*)\n\n(* Exercise 1: why is there a space in the comment just above\n   on the right of the infix notation for multiplication?\n\n  Answer: It seems that when using the Notation ARG that the\n  ARG is composed of tokens separated by spaces. Seeing that \n  Notation \"a*b\" := (mult a b) will yield a parse error. So\n  I would say it's because that the definition of the infix\n  operator is Notation \"a * b\" that we write it like that.\n  Though we can still utilize the infix operator without\n  the spaces it was defined with seeing that\n  Compute(3*4) yields a correct response of 12.\n*)\n\n(* ********** *)\n\nDefinition 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\n(* ********** *)\n\n(* For the following exercise,\n   the following lemmas from the Arith library might come handy:\n   plus_0_l, plus_0_r, plus_comm, and plus_assoc.\n*)\n\nCheck plus_0_l.\nCheck mult_0_l.\n\n(* Helper for later *)\n(* Would we rather use unfold plus or the unfold_tactic with plus? *)\nProposition plus_1_S : \n  forall n : nat,\n    S n = plus 1 n.\nProof.\n  intro n.\n  (* unfold_tactic plus. *)\n  unfold plus.\n  reflexivity.\nQed.\n\n\n(*\n    show that 0 is left-absorbant for multiplication\n    (aka mult_0_l in Arith)\n*)\n\nProposition multiplication_bc_left :\n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall j : nat,\n      mul 0 j = 0.\nProof.\n  intro mult.\n  intro S_mult.\n  intro j.\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc _].\n  rewrite -> (H_mult_bc j).\n  reflexivity.\nQed.\n\n\n(*\n    show that 0 is right-absorbant for multiplication\n    (aka mult_0_r in Arith)\n*)\n\n\nProposition multiplication_bc_right : \n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall j : nat,\n      mul j 0 = 0.\nProof.\n  intro mult.\n  intro S_mult.\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  intro j.\n\n  induction j as [ | n' IHn'].\n  \n  (* Base case: *)\n  apply (H_mult_bc 0).\n\n  (* Induction case: *)\n  rewrite -> (H_mult_ic n' 0).\n  rewrite -> (plus_0_l (mult n' 0)).\n  apply IHn'.\nQed.\n\n(*\n   show that 1 is left-neutral for multiplication\n   (aka mult_1_l in Arith) x\n*)\n\nProposition multiplication_1_neutral_left :\n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall j : nat,\n      mul 1 j = j.\nProof.\n  intro mult.\n  intro S_mult.\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  intro j.\n  rewrite -> (H_mult_ic 0 j).\n  rewrite -> (H_mult_bc j).\n  rewrite -> (plus_0_r j).\n  reflexivity.\n Qed.\n\n(* COULD HAVE BEEN DONE WITH INDUCTION! *)\n\n(*\n    show that 1 is right-neutral for multiplication\n    (aka mult_1_r in Arith)\n*)\n\nProposition multiplication_1_neutral_right :\n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall j : nat,\n      mul j 1 = j.\nProof.\n  intro mult.\n  intro S_mult.\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  intro j.\n  induction j as [ | n' IHn'].\n\n  (* Base case: *)\n  apply (H_mult_bc 1).\n\n  (* Induction case: *)\n  rewrite -> (H_mult_ic n' 1).\n  Check(IHn').\n  rewrite -> (IHn').\n  symmetry.\n  rewrite -> (plus_1_S n').\n  reflexivity.\nQed.\n\n(*\n   show that multiplication is commutative\n   (aka mult_comm in Arith)\n*)\n\nCheck(mult_comm).\n\nProposition multiplication_ic_left : \n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall (x y : nat), \n      y + mul x y = mul (S x) y.\nProof.\n  intro mult.\n  intro S_mult.\n  intros x y.\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  rewrite -> (H_mult_ic x y).\n  reflexivity.\nQed.\n\nProposition multiplication_ic_right :\n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall (x y : nat),\n      x + mul x y = mul x (S y).\nProof.\n  intro mult.\n  intro S_mult.\n  intros x y.\n  assert (mul_s := S_mult).\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  induction x as [ | n' IHn'].\n  \n  (* Base case: *)\n  rewrite -> (H_mult_bc).\n  rewrite -> (multiplication_bc_left mult mul_s (S y)).\n  rewrite -> (plus_0_l 0).\n  reflexivity.\n\n  (* Induction case: *)\n  rewrite -> (H_mult_ic n' y).\n  rewrite -> (H_mult_ic n' (S y)).\n  rewrite <- (IHn').\n\n  rewrite -> (plus_assoc (S n') y (mult n' y)).\n  rewrite -> (plus_assoc (S y) n' (mult n' y)).\n\n  rewrite -> (plus_1_S n').\n  rewrite -> (plus_1_S y).\n\n  (* There must be an easier way to align the rest *)\n  rewrite -> (plus_comm (1 + n' + y) (mult n' y)).\n  rewrite -> (plus_comm (1 + y + n') (mult n' y)).\n  rewrite -> (plus_comm (1 + n') y).\n  rewrite -> (plus_comm 1 n').\n  rewrite -> (plus_assoc y n' 1).\n  rewrite -> (plus_assoc (mult n' y) (y + n') 1).\n\n  rewrite -> (plus_comm (1 + y) n').\n  rewrite -> (plus_comm 1 y).\n  rewrite -> (plus_assoc n' y 1).\n\n  rewrite -> (plus_assoc (mult n' y) (n' + y) 1).\n  rewrite -> (plus_comm n' y).\n  reflexivity.\nQed.\n\n\n\nProposition multiplication_is_commutative :\n  forall (mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall (x y : nat),\n      mul x y = mul y x.\nProof.\n  intro mult.\n  intro S_mult.\n  assert(mul_s := S_mult).\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  intros x y.\n  induction x as [ | n' IHn'].\n\n  (* Base case: *)\n\n  rewrite -> (multiplication_bc_left mult mul_s y).\n  rewrite -> (multiplication_bc_right mult mul_s y).\n  reflexivity.\n\n\n  (* Induction case: *)\n  rewrite -> (H_mult_ic n' y).\n  rewrite -> (IHn').\n  rewrite -> (multiplication_ic_right mult mul_s y n').\n  reflexivity.\nQed.\n\nCheck(mult_0_l).\n\n(* \n * show that the specification of multiplication is unique\n *)\n\nProposition there_is_only_one_multiplication : \n  forall mult1 mult2 : nat -> nat -> nat,\n    specification_of_multiplication mult1 ->\n    specification_of_multiplication mult2 ->\n    forall x y : nat,\n      mult1 x y = mult2 x y.\nProof.\n  intros mult1 mult2 S_mult1 S_mult2 x y.\n  induction x as [ | n' IHn'].\n  rewrite -> (multiplication_bc_left mult1 S_mult1 y).\n  rewrite -> (multiplication_bc_left mult2 S_mult2 y).\n  reflexivity.\n\n  rewrite <- (multiplication_ic_left mult1 S_mult1 n' y).\n  rewrite <- (multiplication_ic_left mult2 S_mult2 n' y).\n  rewrite -> (IHn').\n  reflexivity.\nQed.\n\n\n(*\n   * implement multiplication,\n     verify that your implementation passes the unit tests, and\n     prove that your implementation satisfies the specification\n*)\n\nFixpoint mult_v1 (x y : nat) : nat :=\n  match x with\n    | 0 => 0\n    | S x' => y + (mult_v1 x' y)\n  end.\n\n\nCompute(unit_tests_for_multiplication mult_v1).\n\nLemma unfold_mult_v1_bc :\n  forall (y: nat),\n    mult_v1 0 y = 0.\nProof.\n  unfold_tactic mult_v1.\nQed.\n\n(* Is this how we would do it otherwise? *)\nLemma unfold_mult_v1_bc2 :\n  forall (y: nat),\n    mult_v1 0 y = 0.\nProof.\n  intro y.\n  unfold mult_v1.\n  reflexivity.\nQed.\n\nLemma unfold_mult_v1_ic : \n  forall (i' j : nat),\n    mult_v1 (S i') j = j + mult_v1 i' j. \nProof.\n  unfold_tactic mult_v1.\nQed.\n\n\n\nTheorem mult_v1_satisfies_the_specification_of_multiplication : \n  specification_of_multiplication mult_v1.\nProof.\n  unfold specification_of_multiplication.\n  split.\n\n  apply unfold_mult_v1_bc.\n\n  apply unfold_mult_v1_ic.\n\nQed.\n\n\n\n(* Exercise:\n\n   * show that 0 is left-absorbant for multiplication\n     (aka mult_0_l in Arith) x\n\n   * show that 0 is right-absorbant for multiplication\n     (aka mult_0_r in Arith) x\n\n   * show that 1 is left-neutral for multiplication\n     (aka mult_1_l in Arith) x\n\n   * show that 1 is right-neutral for multiplication\n     (aka mult_1_r in Arith) x\n\n   * show that multiplication is commutative\n     (aka mult_comm in Arith)\n\n   * show that the specification of multiplication is unique\n\n   * implement multiplication,\n     verify that your implementation passes the unit tests, and\n     prove that your implementation satisfies the specification\n*)\n\n(*\n    show that multiplication distributes over addition on the left\n    (aka mult_plus_distr_l in Arith), and\n*)\n\nCheck(mult_plus_distr_l).\n\nProposition multiplication_plus_distribution_left :\n  forall(mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall(x y z : nat),\n      mul x (y + z) = mul x y + mul x z.\nProof.\n  intro mult.\n  intro S_mult.\n  intros x y z.\n  assert(mul_s := S_mult).\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  induction x as [ | n' IHn'].\n  rewrite -> (multiplication_bc_left mult mul_s (y + z)).\n  rewrite -> (multiplication_bc_left mult mul_s y).\n  rewrite -> (multiplication_bc_left mult mul_s z).\n  rewrite -> (plus_0_l 0).\n  reflexivity.\n\n  rewrite -> (H_mult_ic n' (y + z)).\n  rewrite -> (H_mult_ic n' y).\n  rewrite -> (H_mult_ic n' z).\n  rewrite -> (IHn').\n  rewrite -> (plus_assoc (y + mult n' y) z (mult n' z)).\n  rewrite -> (plus_assoc (y + z) (mult n' y) (mult n' z)).\n  rewrite -> (plus_comm y (mult n' y)).\n  Check(plus_assoc).\n  rewrite <- (plus_assoc (mult n' y) y z).\n  rewrite -> (plus_comm (mult n' y) (y + z)).\n  reflexivity.\nQed.\n\n(*\n   show that multiplication is associative\n   (aka mult_assoc in Arith),\n*)\n\nProposition multiplication_is_associative : \n  forall(mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall (x y z : nat),\n      mul x (mul y z) = mul (mul x y) z.\nProof.\n  intro mult.\n  intro S_mult.\n  assert(mul_s := S_mult).\n  unfold specification_of_multiplication in S_mult.\n  destruct S_mult as [H_mult_bc H_mult_ic].\n  intros x y z.\n  induction x as [ | n' IHn'].\n\n  (* Base case: *)\n  rewrite -> (multiplication_bc_left mult mul_s (mult y z)).\n  rewrite -> (multiplication_bc_left mult mul_s y).\n  rewrite -> (multiplication_bc_left mult mul_s z).\n  reflexivity.\n\n  (* Induction case: *)\n\n  rewrite -> (H_mult_ic n' (mult y z)).\n  rewrite -> (H_mult_ic n' y).\n  rewrite -> (IHn').\n  rewrite -> (multiplication_is_commutative mult mul_s (y + mult n' y) z).\n  rewrite -> (multiplication_plus_distribution_left mult mul_s z y (mult n' y)).\n  rewrite -> (multiplication_is_commutative mult mul_s (mult n' y) z).\n  rewrite -> (multiplication_is_commutative mult mul_s y z).\n  reflexivity.\nQed.\n\n\n(*\n    show that multiplication distributes over addition on the right\n    (aka mult_plus_distr_r in Arith).\n*)\n\nCheck(mult_plus_distr_r).\n\nProposition multiplication_plus_distribution_right :\n  forall(mul : nat -> nat -> nat),\n    specification_of_multiplication mul ->\n    forall (x y z : nat),\n      mul (x + y) z = mul x z + mul y z.\nProof.\n  intro mult.\n  intro S_mult.\n  assert(mul_s := S_mult).\n  intros x y z.\n  rewrite -> (multiplication_is_commutative mult mul_s (x + y) z).\n  rewrite -> (multiplication_is_commutative mult mul_s x z).\n  rewrite -> (multiplication_is_commutative mult mul_s y z).\n  apply (multiplication_plus_distribution_left mult mul_s z x y).\nQed.\n\n\n(* ********** *)\n\n(* Exercise for the over-achievers:\n\n   In no particular order,\n\n   * show that multiplication is associative\n     (aka mult_assoc in Arith),\n\n   * show that multiplication distributes over addition on the left\n     (aka mult_plus_distr_l in Arith), and\n\n   * show that multiplication distributes over addition on the right\n     (aka mult_plus_distr_r in Arith).\n*)\n\n(* ********** *)\n\n(* Exercise for the over-achievers with time on their hands:\n   repeat the exercises above with our own implementation\n   of the addition function.\n   (You will first need to compile week_36b_add.v with coqc.) \n*)\n\n(*\nRequire Import week_36b_add.\n\nDefinition specification_of_multiplication' (mul : nat -> nat -> nat) :=\n  (forall j : nat,\n    mul O j = 0)\n  /\\\n  (forall add : nat -> nat -> nat,\n     specification_of_addition add ->\n     forall i' j : nat,\n       mul (S i') j = add j (mul i' j)).\n*)\n\n(* ********** *)\n\n(* end of week_36c_mul.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_36c_mul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8450961962587515}}
{"text": "From mathcomp\nRequire Import ssreflect.\n\nRequire Classical_Prop.\n\nModule LogicPrimer.\n\nImport Classical_Prop.\nDefinition peirce_law := forall P Q: Prop, ((P -> Q) -> P) -> P.\n\n(**\n---------------------------------------------------------------------\nExercise [forall-distributivity]\n---------------------------------------------------------------------\n\nFormulate and prove the following theorem in Coq, which states the\ndistributivity of universal quantification with respect to implication:\n\\[\nforall P Q, \n  [(forall x, P(x) => Q(x)) => ((forall y, P(y)) => forall z, Q(z))]\n\\]\n\nBe careful with the scoping of universally-quantified variables\nand use parentheses to resolve ambiguities!\n*)\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. by move=> H1 H2 z; apply: H1; apply: H2. Qed.\n\n(**\n---------------------------------------------------------------------\nExercise [Or-And distributivity]\n---------------------------------------------------------------------\nProve the following theorems.\n*)\n\nTheorem or_distributes_over_and P Q R: \n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nsplit.\n- case; first by split; [left | left].\n- by case=>q r; split; [right | right].\nintuition.\nQed.\n\nTheorem or_distributes_over_and_2 P Q R :\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\ncase; case=>q; first by left.\ncase=>[p|r]; first by left.\nright; split=>//.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Home-brewed existential quantification]\n---------------------------------------------------------------------\n\nLet us define our own version [my_ex] of the existential quantifier\nusing the SSReflect notation for constructors: *)\n\nInductive my_ex A (S: A -> Prop) : Prop := my_ex_intro x of S x.\n\n(** You invited to prove the following goal, establishing the\nequivalence of the two propositions. *)\n\nGoal forall A (S: A -> Prop), my_ex A S <-> exists y: A, S y.\nProof.\nmove=> A S; split.\n- by case=> x Hs; exists x.\nby case=>y Hs; apply: my_ex_intro Hs.\nQed.\n \n(** \nHint: the propositional equivalence [<->] is just a conjunction of\ntwo implications, so proving it can be reduced to two separate goals\nby means of [split] tactics.\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [Distributivity of existential quantification]\n---------------------------------------------------------------------\nProve the following theorem.\n*)\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.\nsplit; first by case=>x; case=>H; [left | right]; exists x=> //.\nby case; case=>x H; exists x; [left | right].\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Two equals three]\n---------------------------------------------------------------------\nProve the following  theorem. Can you explain the proof?\n*)\n\nTheorem two_is_three A: (exists x : A, (forall R : A -> Prop, R x)) -> 2 = 3.\nProof.\nby case=>x H; apply: H.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Dyslexic implication and contraposition]\n---------------------------------------------------------------------\n\nThe \"dyslexic\" implication and contrapositions are the following\npropositions. \n*)\n\nDefinition dys_imp (P Q: Prop) := (P -> Q) -> (Q -> P).\nDefinition dys_contrap (P Q: Prop) := (P -> Q) -> (~P -> ~Q).\n\n(**\nThese propositions are inhabited, as otherwise one, given a proof of\nany of them, would be able to construct a proof of [False]. You are\ninvited to deomnstrate it by proving the following statements.\n*)\n\nTheorem di_false: (forall P Q: Prop, dys_imp P Q) -> False.\nProof. by move/(_ _ True); apply. Qed.\n\nTheorem dc_false: (forall P Q: Prop, dys_contrap P Q) -> False.\nProof. by move=>H; apply: (H False True)=>//. Qed.\n\n(**\n---------------------------------------------------------------------\nExercise [Irrefutability of the excluded middle]\n---------------------------------------------------------------------\n\nProof the following theorem that states that the assumption of the\nfalsehood of the excluded middle leads to inconsistencies, as is\nallows one to derive [False].\n*)\n\nTheorem excluded_middle_irrefutable: forall (P : Prop), ~~(P \\/ ~ P).\nProof.\nmove=>P H. \napply: (H); right=>p.\nby apply: H; left.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Equivalence of classical logic axioms]\n---------------------------------------------------------------------\n\nProve that the following five axioms of the classical are equivalent.\n\n*)\n\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. by move=>H P Hn; apply: (H _ False)=> /Hn. Qed.\n\nLemma dn_em : double_neg -> excluded_middle.\nProof. \nrewrite /double_neg /excluded_middle=> Dn P. \napply: (Dn (P \\/ ~ P))=>H1; apply: (H1).\nby left; apply: (Dn)=> H2; apply: H1; right.\nQed.\n\nLemma em_dmnan: excluded_middle -> de_morgan_not_and_not.\nProof.\nrewrite /excluded_middle /de_morgan_not_and_not=> H1 P Q H2.\nsuff: ~P -> Q.\n- move=>H3. move: (H1 P); case=>//X; first by left. \n  by right; apply: H3. \nmove=> Pn.\nmove: (H1 Q); case=>// Qn.\nsuff: False=>//; apply: H2; split=>//.\nQed.\n\nLemma dmnan_ito : de_morgan_not_and_not -> implies_to_or.\nProof.\nrewrite /de_morgan_not_and_not /implies_to_or=> H1 P Q Hi.\nsuff: ~P \\/ P.\ncase=>//; first by left.\n- by move/ Hi; right.\nmove: (H1 (~P) P)=> H2; apply: H2; case=> Hp p.\nsuff: (P -> False) \\/ False by case=>//.\nby apply: H1; case.\nQed.\n\nLemma ito_peirce : implies_to_or -> peirce.\nProof.\nrewrite /peirce /peirce_law /implies_to_or=> H1 P Q H2.\nhave X: P -> P by [].\nmove: (H1 P P) =>/(_ X); case=>{X}// Pn.\nby apply: (H2)=>p. \nQed.\n\n(**\n\nHint: Use [rewrite /d] tactics to unfold the definition of a value [d]\n and replace its name by its body. You can chain several unfoldings by\n writing [rewrite /d1 /d2 ...]  etc.\n\nHint: To facilitate the forward reasoning by contradiction, you can\n use the SSReflect tactic [suff: P], where [P] is an arbitrary\n proposition. The system will then require you to prove that [P]\n implies the goal _and_ [P] itself.\n\nHint: Stuck with a tricky proof? Use the Coq [admit] tactic as a\n \"stub\" for an unfinished proof of a goal, which, nevertheless will be\n considered completed by Coq. You can always get back to an admitted\n proof later.\n\n*)\n\n\n(**\n---------------------------------------------------------------------\nExercise [Inifinitary de Morgan laws]\n---------------------------------------------------------------------\n\nProve the following implication analogous to the Morgan law for\nconjunctions  and disjunctions.\n\n*)\n\nTheorem not_forall_exists A (P : A -> Prop): \n  (forall x: A, P x) -> ~(exists y: A, ~ P y).\nProof.\nby move=>H G; case: G=>y G; apply: G; apply: H.\nQed.\n\n(**\n\nThen, prove that the assumption of the excluded middle axiom allows one to\nestablish the implication from the negation of (exists) to (forall).\n\n*)\n\nTheorem not_exists_forall :\n  excluded_middle -> forall (X: Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\nmove=> Em X P H x; rewrite /excluded_middle in Em.\nmove: (Em (P x)); case=>// => H1.\nby suff: False =>//; apply:H; exists x. \nQed.\n\n\nEnd LogicPrimer.\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/solutions/LogicPrimer_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.9005297927918166, "lm_q1q2_score": 0.8448086241893151}}
{"text": "From mathcomp Require Import ssreflect ssrbool.\nFrom mathcomp Require ssrnat.\n\nSection Orders.\n  Context {T: Type} (leT: rel T).\n\n  Class Reflexive := reflexivity: reflexive leT.\n  Class Transitive := transitivity: transitive leT.\n  Class Antisymmetric := antisymmetry: antisymmetric leT.\n  Class Total := totality: total leT.\n\n  Class PreOrder :=\n    {\n      PreOrder_Reflexive :> Reflexive;\n      PreOrder_Transitive :> Transitive;\n    }.\n\n  Class PartialOrder :=\n    {\n      PartialOrder_PreOrder :> PreOrder;\n      PartialOrder_Antisymmetric :> Antisymmetric;\n    }.\n\n  Class TotalPreOrder :=\n    {\n      TotalPreOrder_PreOrder :> PreOrder;\n      TotalPreOrder_Total :> Total;\n    }.\nEnd Orders.\n\nArguments transitivity {T leT Transitive}.\nArguments antisymmetry {T leT Antisymmetric}.\n\nModule Nat.\n  Import ssrnat.\n\n  Instance Leq: TotalPreOrder leq := {}.\n  Proof.\n    constructor.\n    exact: leqnn.\n    exact: leq_trans.\n    exact: leq_total.\n  Defined.\nEnd Nat.\n", "meta": {"author": "hanazuki", "repo": "coq-dijkstra", "sha": "dacc99e49999bb48abc3bc2c42d5f0ec293a3892", "save_path": "github-repos/coq/hanazuki-coq-dijkstra", "path": "github-repos/coq/hanazuki-coq-dijkstra/coq-dijkstra-dacc99e49999bb48abc3bc2c42d5f0ec293a3892/src/ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.8446882102826574}}
{"text": "Require Import Arith.\nRequire Import Arith.Max.\n\nRequire Import set.\n\n(******************************************************************************)\n(*                         order : set -> nat                                 *)\n(******************************************************************************)\n\n(* The map order : set -> nat is a measure of the 'syntactic complexity' of the\n * expression defining a set. It will be useful as a way to prove many results\n * allowing us to carry induction arguments based on the 'order' of a set.\n *\n * order(0)   = 0\n * order({x}) = 1 + order(x)\n * order(xUy) = 1 + max(order(x), order(y))\n *)\n\nFixpoint order (s:set) : nat :=\n  match s with \n    | Empty         => 0\n    | Singleton x   => 1 + order x\n    | Union x y     => 1 + max (order x) (order y) \n  end.\n\n(*  order(a) = 0  =>  a = 0  *)\nLemma order_eq_0 : forall (a:set), order a = 0 -> a = Empty.\nProof.\n  intro a. elim a. auto. clear a. intro a. intro IH. intro H.\n  simpl in H. discriminate H. clear a. intro a. intro IH. intro b. intro H.\n  intro H'. simpl in H'. discriminate H'.\nQed.\n\n(* order(a) + order(b) = 0  =>  a = 0  *)\nLemma order_sum_eq_0_l : forall (a b:set),\n  order a + order b = 0 -> a = Empty.\nProof.\n  intros a b H. apply order_eq_0. \n  apply and_ind with (A:= order a = 0)(B:= order b = 0). trivial.\n  apply plus_is_O. exact H.\nQed.\n\n(* order(a) + order(b) = 0 =>  b = 0  *)\nLemma order_sum_eq_0_r : forall (a b:set),\n  order a + order b = 0 -> b = Empty.\nProof.\n  intros a b H. rewrite plus_comm in H. apply order_sum_eq_0_l\n  with (b:=a). exact H.\nQed.\n\n(* order({x}) + order(b) <= n+1  =>  order(x) + order(b) <= n  *)\nLemma order_sum_singleton_l : forall (n:nat) (x b:set),\n  order (Singleton x) + order b <= S n ->\n  order x + order b <= n.\nProof.\n  intros n x b H. apply le_S_n. apply le_trans with\n  (m:= order (Singleton x) + order b). simpl. apply le_n. exact H.\nQed.\n\n(* order(a) + order({y}) <= n+1  =>  order(a) + order(y) <= n  *)\nLemma order_sum_singleton_r : forall (n:nat) (a y:set),\n  order a + order (Singleton y) <= S n ->\n  order a + order y <= n.\nProof. \n  intros n a y H. rewrite plus_comm. apply order_sum_singleton_l.\n  rewrite plus_comm in H. exact H.\nQed.\n\n\n(* order({x}) + order({y}) <= n+1  =>  order(x) + order(y) < n *)  \nLemma order_sum_singleton_strong : forall (n:nat) (x y:set),\n  order (Singleton x) + order (Singleton y) <= S n ->\n  order x + order y < n.\nProof.\n  intros n x y H. unfold lt. apply le_S_n. apply le_trans with\n  (m:= order (Singleton x) + order (Singleton y)). simpl.\n  rewrite <- plus_Snm_nSm. simpl. reflexivity. exact H.\nQed.\n\n(* This is a weakening of the previous result *)\n(* order({x}) + order({y}) <= n+1  => order(x) + order(y) <= n *)\nLemma order_sum_singleton : forall (n:nat) (x y:set),\n  order (Singleton x) + order (Singleton y) <= S n ->\n  order x + order y <= n.\nProof.\n  intros n x y H. apply le_S_n. apply le_S. fold (order x + order y < n).\n  apply order_sum_singleton_strong. exact H.\nQed.\n\n\n(* 'L' refers to where 'Union' stands in the sum\n** while 'l' refers to the left argument of Union *)\nLemma order_sum_union_Ll : forall (n:nat) (x y b:set),\n  order (Union x y) + order b <= S n ->\n  order x + order b <= n.\nProof.\n  intros n x y b H. apply le_S_n. apply le_trans with\n  (m:= order (Union x y) + order b). simpl. apply le_n_S.\n  apply plus_le_compat_r. simpl. apply le_max_l. exact H.\nQed.\n  \n(* same proof, but use le_max_r instead of le_max_l *)\nLemma order_sum_union_Lr : forall (n:nat) (x y b:set),\n  order (Union x y) + order b <= S n ->\n  order y + order b <= n.\nProof.\n  intros n x y b H. apply le_S_n. apply le_trans with\n  (m:= order (Union x y) + order b). simpl. apply le_n_S.\n  apply plus_le_compat_r. simpl. apply le_max_r. exact H.\nQed.\n\n(* consequence of 'Ll' lemma and commutativity *)\nLemma order_sum_union_Rl : forall (n:nat) (a y z:set),\n  order a + order (Union y z) <= S n ->\n  order a + order y <= n.\nProof.\n  intros n a y z H. rewrite plus_comm. apply order_sum_union_Ll\n  with(x:= y)(y:=z). rewrite plus_comm in H. exact H.\nQed.\n\n(* consequence of 'Lr' lemma and commutativity *)\nLemma order_sum_union_Rr : forall (n:nat) (a y z:set),\n  order a + order (Union y z) <= S n ->\n  order a + order z <= n.\nProof.\n  intros n a y z H. rewrite plus_comm. apply order_sum_union_Lr\n  with(x:= y)(y:=z). rewrite plus_comm in H. exact H.\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/set2/order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251321, "lm_q2_score": 0.8887587817066392, "lm_q1q2_score": 0.8446861045499977}}
{"text": "(** * More Logic *)\n\nRequire Export \"Prop\".\nRequire Import Le.\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P]. \n\n*)\n\n\n(** *** *)\n(** Coq's [Notation] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** *** *)\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2). \n  reflexivity.  Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** *** *)\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n    time, we can use the convenient shorthand [exists e], which means\n    the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\n\n(** *** *)\n(** Conversely, if we have an existential hypothesis in the\n    context, we can eliminate it with [inversion].  Note the use\n    of the [as...] pattern to name the variable that Coq\n    introduces to name the witness value and get evidence that\n    the hypothesis holds for the witness.  (If we don't\n    explicitly choose one, Coq will just call it [witness], which\n    makes proofs confusing.) *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n H.\n  inversion H as [m Hm]. \n  exists (2 + m).  \n  apply Hm.  Qed.\n\n(** Here is another example of how to work with existentials. *)\nLemma exists_example_3 : \n  exists (n:nat), even n /\\ beautiful n.\nProof.\n(* WORKED IN CLASS *)\n  exists 8.\n  split.\n  unfold even. simpl. reflexivity.\n  apply b_sum with (n:=3) (m:=5).\n  apply b_3. apply b_5.\nQed.\n\n(** **** Exercise: 1 star, optional (english_exists) *)\n(** In English, what does the proposition \n      ex nat (fun n => beautiful (S n))\n]] \n    mean? *)\n\n(* FILL IN HERE *)\n\n(*\n*)\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n  intros. unfold not. intros. inversion H0 as [x Hx]. apply Hx. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros. unfold excluded_middle in H. destruct H with (P x).\n  - apply H1.\n  - unfold not in H0. apply ex_falso_quodlibet. apply H0.\n    exists x. fold (not (P x)). apply H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  split.\n  - intros. destruct H as [x Hx]. destruct Hx.\n    + left. exists x. apply H.\n    + right. exists x. apply H.\n  - intros. destruct H.\n    + destruct H as [x Hx]. exists x. left. apply Hx.\n    + destruct H as [x Hx]. exists x. right. apply Hx.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues.  The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests \nin _computations_.  While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious. \n*)\n\n(** *** *)\n(** \nIt turns out that we can get the benefits of both forms at once \nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B \n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" :=  (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction \nthat allows us to compute with them.) *) \n\n(** *** *)\n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  (* WORKED IN CLASS *)\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      right. intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. intros contra. inversion contra.\n    SCase \"m = S m'\". \n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply f_equal.  apply eq.\n      right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined. \n  \n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either \nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right] \nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean]. \n(Notice that we ended this proof with [Defined] rather than [Qed]. \nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n*) \n\n(** *** *)\n(** \nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 -> \n  (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f. intros Hx1.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).   (* observe what appears as a hypothesis *)\n  Case \"k1 = k2\".\n    rewrite <- e.\n    symmetry. apply Hx1.\n  Case \"k1 <> k2\". \n    reflexivity.  Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the \n   version of [override] defined using [beq_nat], where we had to\n   use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n   to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n  intros. unfold override'. destruct (eq_nat_dec k1 k2).\n  - reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n| all_nil  : all X P []\n| all_cons : forall (x : X) (xs : list X), P x -> all X P xs -> all X P (x :: xs)\n.\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Using the property [all], write down a specification for [forallb],\n    and prove that it satisfies the specification. Try to make your \n    specification as precise as possible.\n\n    Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\nTheorem all_forallb :\n  forall (X:Type) (xs:list X) (test : X -> bool),\n    forallb test xs = true <-> all X (fun x => test x = true) xs.\nProof.\n  intros. split.\n  - intros. induction xs as [|t ts].\n    + apply all_nil.\n    + simpl in H. apply all_cons.\n      * apply andb_true_elim1 in H. apply H.\n      * apply IHts. apply andb_true_elim2 in H. apply H.\n  - intros. induction H as [|t ts HP A].\n    + reflexivity.\n    + simpl. rewrite HP. simpl. apply IHA.\nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example, \n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\nInductive in_order_merge {X:Type} : list X -> list X -> list X -> Prop :=\n| merge_nil : in_order_merge [] [] []\n| merge_fst : forall (x : X) (xs ys zs : list X),\n                in_order_merge xs ys zs -> in_order_merge (x :: xs) ys (x :: zs)\n| merge_snd : forall (y : X) (xs ys zs : list X),\n                in_order_merge xs ys zs -> in_order_merge xs (y :: ys) (y :: zs).\n\nTheorem filter_spec_1 :\n  forall (X:Type) (test : X -> bool) (l : list X) (lt : list X) (lf : list X),\n    (forallb test lt = true) -> (forallb (fun x => negb (test x)) lf = true) ->\n    in_order_merge lt lf l -> filter test l = lt.\nProof.\n  intros X test l lt lf Pt Pf IM. induction IM as [|x xs ys zs M IHM|y xs ys zs M IHM].\n  - reflexivity.\n  - simpl. simpl in Pt. assert (test x = true) as C.\n    + apply andb_true_elim1 in Pt. apply Pt.\n    + rewrite C. apply f_equal. apply IHM.\n      * apply andb_true_elim2 in Pt. apply Pt.\n      * apply Pf.\n  - simpl. simpl in Pf. assert (test y = false) as C.\n    + apply andb_true_elim1 in Pf. rewrite <- negb_involutive with (test y).\n      rewrite Pf. reflexivity.\n    + rewrite C. apply IHM.\n      * apply Pt.\n      * apply andb_true_elim2 in Pf. apply Pf.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\nInductive sub_satisfy {X:Type} (f:X -> bool) : list X -> list X -> Prop :=\n| sub_nil : sub_satisfy f [] []\n| sub_f   : forall (x : X) (xs ls: list X),\n              sub_satisfy f xs ls -> (f x = true) -> sub_satisfy f (x :: xs) (x :: ls)\n| sub_skip : forall (l : X) (xs ls : list X),\n               sub_satisfy f xs ls -> sub_satisfy f xs (l :: ls).\n\nTheorem filter_is_sub_satisfy :\n  forall (X:Type) (l:list X) (test:X -> bool),\n    sub_satisfy test (filter test l) l.\nProof.\n  intros. induction l as [|h t].\n  - simpl. apply sub_nil.\n  - simpl. destruct (test h) eqn:C.\n    + apply sub_f. apply IHt. apply C.\n    + apply sub_skip. apply IHt.\nQed.\n\nTheorem filter_spec_2 :\n  forall (X:Type) (xs:list X) (l:list X) (f:X -> bool),\n    sub_satisfy f xs l ->\n    length xs <= length (filter f l).\nProof.\n  intros. induction H as [|x xs ls S IS f_true|l xs ls S IS].\n  - reflexivity.\n  - simpl. rewrite f_true. simpl. apply le_n_S. apply IS.\n  - simpl. destruct (f l) eqn:C.\n    + simpl. apply le_S. apply IS.\n    + apply IS.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l]. \n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X), \n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  intros. induction xs as [|t ts].\n  - right. apply H.\n  - simpl in H. inversion H.\n    + left. apply ai_here.\n    + destruct IHts.\n      * apply H1.\n      * left. apply ai_later.  apply H3.\n      * right. apply H3.\nQed.\n\nLemma app_appears_in : forall (X:Type) (xs ys : list X) (x:X), \n     appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n  intros. destruct H.\n  - induction H.\n    + apply ai_here.\n    + simpl. apply ai_later. apply IHappears_in.\n  - induction xs as [|h t].\n    + simpl. apply H.\n    + simpl. apply ai_later. apply IHt.\nQed.\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n    which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in common. *)\n\nDefinition disjoint (X:Type) (xs ys:list X) :=\n  forall x : X, appears_in x xs -> ~(appears_in x ys).\n\n(** Next, use [appears_in] to define an inductive proposition\n    [no_repeats X l], which should be provable exactly when [l] is a\n    list (with elements of type [X]) where every member is different\n    from every other.  For example, [no_repeats nat [1,2,3,4]] and\n    [no_repeats bool []] should be provable, while [no_repeats nat\n    [1,2,1]] and [no_repeats bool [true,true]] should not be.  *)\n\nInductive no_repeats (X:Type) : list X -> Prop :=\n| nr_nil : no_repeats X []\n| nr_cons : forall (x : X) (xs : list X),\n              ~(appears_in x xs) -> no_repeats X xs -> no_repeats X (x :: xs).\n\nExample no_repeats_ex1 : no_repeats nat [1;2;3;4].\nProof.\n  apply nr_cons.\n  unfold not. intros. inversion H. inversion H1. inversion H4. inversion H7.\n  apply nr_cons.\n  unfold not. intros. inversion H. inversion H1. inversion H4.\n  apply nr_cons.\n  unfold not. intros. inversion H. inversion H1.\n  apply nr_cons.\n  unfold not. intros. inversion H.\n  apply nr_nil.\nQed.\n\nExample no_repeats_ex2 : ~ no_repeats nat [1;2;1].\nProof.\n  unfold not. intros. inversion H. unfold not in H2. apply H2.\n  apply ai_later. apply ai_here.\nQed.\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\nTheorem not_appears_in_app :\n  forall (X:Type) (x:X) (xs ys:list X),\n    ~ appears_in x xs -> ~ appears_in x ys -> ~ appears_in x (xs ++ ys).\nProof.\n  intros. unfold not. intros. apply appears_in_app in H1. destruct H1.\n  - apply H. apply H1.\n  - apply H0. apply H1.\nQed.\n\nTheorem disjoint_no_repeats_app :\n  forall (X:Type) (xs ys:list X),\n    disjoint X xs ys -> no_repeats X xs -> no_repeats X ys -> no_repeats X (xs ++ ys).\nProof.\n  intros X xs. induction xs as [|h t].\n  - intros. simpl. apply H1.\n  - intros. simpl. apply nr_cons. unfold disjoint in H. apply not_appears_in_app.\n    + inversion H0. apply H4.\n    + apply H. apply ai_here.\n    + apply IHt.\n      * unfold disjoint. unfold disjoint in H. intros. apply H. apply ai_later. apply H2.\n      * inversion H0. apply H5.\n      * apply H1.\nQed.\n\nTheorem no_repeats_split_disjoint :\n  forall (X:Type) (xs ys:list X),\n    no_repeats X (xs ++ ys) -> disjoint X xs ys.\nProof.\n  intros X xs ys NR_xs_ys. unfold disjoint. unfold not. intros x x_ai_xs x_ai_ys.\n  induction x_ai_xs.\n  + inversion NR_xs_ys. apply H1. apply app_appears_in. right. apply x_ai_ys.\n  + apply IHx_ai_xs. inversion NR_xs_ys. apply H2.\nQed.\n\n(** [] *)\n\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n| ns_nil  : nostutter []\n| ns_unit : forall n:nat, nostutter [n]\n| ns_cons : forall (n x:nat) (xs:list nat),\n              nostutter (x :: xs) -> beq_nat x n = false -> nostutter (n :: x :: xs).\n\n(** Make sure each of these tests succeeds, but you are free\n    to change the proof if the given one doesn't work for you.\n    Your definition might be different from mine and still correct,\n    in which case the examples might need a different proof.\n   \n    The suggested proofs for the examples (in comments) use a number\n    of tactics we haven't talked about, to try to make them robust\n    with respect to different possible ways of defining [nostutter].\n    You should be able to just uncomment and use them as-is, but if\n    you prefer you can also prove each example with more basic\n    tactics.  *)\n\nExample test_nostutter_1:      nostutter [3;1;4;1;5;6].\nProof. repeat constructor; apply beq_nat_false; auto. Qed.\n\nExample test_nostutter_2:  nostutter [].\nProof. repeat constructor; apply beq_nat_false; auto. Qed.\n\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]).\n  Proof. intro.\n  repeat match goal with \n    h: nostutter _ |- _ => inversion h; clear h; subst \n  end.\n  apply beq_nat_false in H5; contradiction H5; auto. Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some \n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2. \nProof. \n  intros X l1. induction l1 as [|h t].\n  - intros. reflexivity.\n  - intros. simpl. apply f_equal. apply IHt.\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. induction H.\n  - exists nil. exists l. reflexivity.\n  - destruct IHappears_in as [l1 Hl1].\n    destruct Hl1 as [l2 Hl2].\n    exists (b :: l1). exists l2. simpl. apply f_equal. apply Hl2.\nQed.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n   exercise above), such that [repeats X l] asserts that [l] contains\n   at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  | cons_rep : forall (x:X) (xs:list X), appears_in x xs -> repeats (x :: xs)\n  | cons_any : forall (x:X) (xs:list X), repeats xs      -> repeats (x :: xs).\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n    represents a list of pigeonhole labels, and list [l1] represents\n    the labels assigned to a list of items: if there are more items\n    than labels, at least two items must have the same label.  This\n    proof is much easier if you use the [excluded_middle] hypothesis\n    to show that [appears_in] is decidable, i.e. [forall x\n    l, (appears_in x l) \\/ ~ (appears_in x l)].  However, it is also\n    possible to make the proof go through _without_ assuming that\n    [appears_in] is decidable; if you can manage to do this, you will\n    not need the [excluded_middle] hypothesis. *)\n\nTheorem app_nil_r : forall (T:Type) (xs:list T), xs ++ [] = xs.\nProof.\n  induction xs as [|xh xt].\n  reflexivity.\n  simpl. apply f_equal. apply IHxt.\nQed.\n\nTheorem snoc_cons_app :\n  forall (T:Type) (x:T) (xs ys:list T), snoc xs x ++ ys = xs ++ x :: ys.\nProof.\n  intros. induction xs as [|h t].\n  - reflexivity.\n  - simpl. apply f_equal. rewrite IHt. reflexivity.\nQed.\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X), \n   (forall x, appears_in x l1 -> appears_in x l2) -> \n   length l2 < length l1 -> \n   repeats l1.  \nProof.\n(* todo *)\nAdmitted.\n\nExample ex_pigeonhole : repeats [1; 2; 1].\nProof.\n  apply pigeonhole_principle with [1; 2].\n  intros. inversion H.\n  - apply ai_here.\n  - inversion H1.\n    + apply ai_later. apply ai_here.\n    + inversion H4. apply ai_here. inversion H7.\n  - unfold lt. simpl. apply le_n.\nQed.\n\n(** [] *)\n\n(* FILL IN HERE *)\n\n\n(* $Date: 2014-02-22 09:43:41 -0500 (Sat, 22 Feb 2014) $ *)\n", "meta": {"author": "bennofs", "repo": "software-foundations", "sha": "4278136ca18c0909603cab17fbc0c190dedf69c7", "save_path": "github-repos/coq/bennofs-software-foundations", "path": "github-repos/coq/bennofs-software-foundations/software-foundations-4278136ca18c0909603cab17fbc0c190dedf69c7/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850066369693, "lm_q2_score": 0.9019206738932334, "lm_q1q2_score": 0.8444548041421459}}
{"text": "(********************)\n\n(* The final goal of the exercise is to implement a dictionary (aka map).\n   We'll do this incrementally by defining auxiliary functions and testing them. *)\n\n\nRequire Import List.\nImport ListNotations. \n\n(* The mechanism of sections allows to modularize the proof in multiple ways.\n   We'll see its applications along the way. *)\nSection NatEq.\n\n  (* Implement a function that checks the equality of two natural numbers. \n     Use pattern matching and recursion. *)\n  Fixpoint nat_eq (x y: nat): bool\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* We're not _proving_ that our implementations are correct yet,\n     but we can still test them on some inputs. *)\n  (* Do not modify these test suits. *)\n  (* Try to understand the meaning of the 'nat_eq_tests' definition. *)\n  (* To do that, you may want to investigate the 'forallb': *)\n  Print forallb. \n  Let nat_eq_tests := forallb id\n                       [ nat_eq 0 0;\n                         negb (nat_eq 0 1);\n                         negb (nat_eq 10 0);\n                         nat_eq 10 10;\n                         negb (nat_eq 10 13) ].\n\n  (* Do not modify these '*_pass' definitions and proofs.  *)\n  (* If your implementations are correct, the execution of them should proceed, *)\n  (* otherwise an error should occur.  *)\n  Let nat_eq_tests_pass: nat_eq_tests = true.\n  Proof. tauto. Qed.\n\n  (* Now try to remove one of 'negb' in 'nat_eq_tests' definitions *)\n  (* and execute nat_eq_tests_pass. *)\n  (* Don't forget to restore the initial state of 'nat_eq_tests'. *)\n  \nEnd NatEq.\n\n(* The section hides 'Let' definitions. *)\nFail Print nat_eq_tests_pass. \nPrint nat_eq.\n\n\nSection Option. \n\n  (* A value of 'option' type instantiated with an arbitrary type A\n     contains either a value of the type A or a special value None. *)\n  Print option. \n  \n  (* Implement a function that checks if an optional actually contains a value. *)\n  (* Use 'if-then-else' syntax: *)\n  (* For a value 't' of an inductive type T with exactly two constructors T1 and T2, \n     an expression 'if t then X1 else X2' is equivalent to  \n     'match t with \n      | T1 => X1\n      | T2 => X2\n      end' *)\n  Definition has_some {A: Type} (o: option A) : bool\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n    \n  Let has_some_tests := forallb id\n                       [\n                         (* here A = nat is inferred because of (1: nat) *)\n                         has_some (Some 1);\n                       (* note that without an argument we can't automatically infer the type *)\n                         negb (has_some (@None nat));\n                         has_some (Some (@None bool))\n                       ].\n  \n  Let has_some_tests_pass: has_some_tests = true.\n  Proof. tauto. Qed.\n\n  (* Implement a function that compares two optional natural numbers. *)\n  (* Reuse the nat_eq you've defined before *)\n  Definition option_nat_eq (o1 o2: option nat) : bool\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  Let option_nat_eq_tests := forallb id\n                                     [option_nat_eq None None;\n                                     negb (option_nat_eq (Some 5) None);\n                                     option_nat_eq (Some 5) (Some 5)\n                                     ]. \n\n  Let option_nat_eq_tests_pass: option_nat_eq_tests = true.\n  Proof. tauto. Qed.\n                                     \nEnd Option.\n\nSection FunUpd.\n  \n  (* A handy primitive we'll use below is the function update. *)\n  (* Essentially, we'd like to take a function and override its value on a single input. *)\n  (* Here we'll only concentrate on functions whose input type is nat, \n     but which are still polymorphic on the output type. *)\n  (* Implement the function update using if-then-else expression and nat_eq. *)\n  Definition upd {V: Type} (f: nat -> V) (x: nat) (y: V): nat -> V\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  Let upd_tests := forallb id\n                           [\n                             nat_eq ((upd id 5 3) 5) 3;\n                             nat_eq ((upd (upd id 5 3) 5 7) 5) 7;\n                             nat_eq ((upd id 5 3) 123) 123;\n                             nat_eq ((upd (upd id 5 3) 7 10) 5) 3\n                           ]. \n\n  Let upd_tests_pass: upd_tests = true.\n  Proof. tauto. Qed.\n\nEnd FunUpd.  \n\nSection NatDict.\n  (* Now we're ready to provide the first implementation of a dictionary. *)\n  (* We'll work with dictionaries whose keys are natural numbers \n     and values have an arbitrary (but uniform) type. *)\n  \n  (* Remember that in previous sections we had to specify arguments like '{A: Type}' to keep the definitions polymorphic. *)\n  (* Instead of repeating them, we can specify that a particular type is a common argument for all functions in this section. *)  \n  Context {V: Type}. \n\n  (* The first implementation of dictionary is based on partial functions. *)\n  (* Remember that in Coq all functions are total, \n     that is, the function should return a value for all inputs. *)\n  (* If we're to implement a dictionary with a total function, it wont' be clear\n     how to represent a missing value. *)\n  (* But the absence of a value is naturally represented with None, \n     while a value 'v' contained in a dictionary can be wrapped in 'Some v' *)\n  Definition nat_dict_fun := nat -> option V.\n  Print nat_dict_fun. (* Note that here V is fixed *)\n  \n  (* Implement a function that creates an empty dictionary *)\n  Definition new_dict' : nat_dict_fun\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement an insertion using the 'upd' construct. *)\n  Definition insert' (d: nat_dict_fun) (k: nat) (v: V) : nat_dict_fun\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a deletion similarly. *)\n  Definition remove' (d: nat_dict_fun) (k: nat) : nat_dict_fun\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a function that retrieves a value by key. *)\n  (* Note that here the usage of option as a return type \n     is not due to the partial function implementation,\n     but rather due to a common sense: \n     if a dictionary (with an arbitrary implementation) doesn't contain a value,\n     a retrieval method should somehow reflect it. *)\n  Definition get' (d: nat_dict_fun) (k: nat) : option V\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a function that checks the presence of a given key. *)\n  (* You can either reuse existing dict methods or write an independent implementation. *)\n  Definition contains' (d: nat_dict_fun) (k: nat): bool\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \nEnd NatDict.\n\nSection NatDictTests.\n\n  Print nat_dict_fun. (* note that now nat_dict_fun is polymorphic on value type *)\n\n  (* To save some space we'll define common terms and reuse them\n     with 'let .. in ..' syntax. *)\n  Let tests :=\n    (* Note that we must specify the value type for an empty dictionary,\n       since there are no arguments which can be used to infer it *)\n    let new := @new_dict' nat in\n    let ins5 := insert' new 5 10 in\n    let ins5ins5 := insert' ins5 5 15 in\n    let ins5rm5 := remove' ins5 5 in\n    let ins5ins5rm5 := remove' ins5ins5 5 in\n    forallb id\n                       [ \n                         negb (contains' new 5);\n                         contains' ins5 5;\n                         contains' ins5ins5 5;\n                         negb (contains' ins5rm5 5);\n                         negb (contains' ins5ins5rm5 5);\n                         option_nat_eq (get' new 5) None;\n                         option_nat_eq (get' ins5 5) (Some 10);\n                         option_nat_eq (get' ins5ins5 5) (Some 15);\n                         option_nat_eq (get' ins5ins5rm5 5) None;\n                         option_nat_eq (get' ins5 3) None\n                       ].\n\n  Let nat_dict_fun_tests_pass: tests = true.\n  Proof. tauto. Qed.\n  \nEnd NatDictTests.\n\n\nSection NatDict'.\n  Context {V: Type}.\n\n  (* The other implementation of a dictionary is based on a list\n     that stores pairs of keys and values. *)\n  (* If there are multiple pairs with the same key, \n     the one closer to the list head is used. *)\n  \n  (* '*' in context of types means the product (aka pair) type. *)\n  Definition nat_dict_list := list (nat * V). \n\n  (* Since the functions below operate on list which is defined inductively, \n     some of them should also be inductively defined. *)\n  \n  (* Implement a function that creates an empty dictionary. *)\n  Definition new_dict'' : nat_dict_list\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement the insertion *)\n  Definition insert'' (d: nat_dict_list) (k: nat) (v: V) : nat_dict_list\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  \n  (* Implement the deletion. *)\n  (* Mind the case when the list contain multple occurences of the same key. *)\n  (* You may find useful that a pattern to be matched can be complex: *)\n  (*    '(k, v) :: d'     destructs the list into the head and tail (named d')\n     and, additionally, destructs the head into the key 'k' and value 'v' *)  \n  Fixpoint remove'' (d: nat_dict_list) (k: nat) : nat_dict_list\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* Implement the retrieval function. *)\n  Fixpoint get'' (d: nat_dict_list) (k: nat) : option V\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* Implement the check for key presence. *)\n  Fixpoint contains'' (d: nat_dict_list) (k: nat): bool\n  . Admitted.\n (* Replace the previous line with ':= (your implementation) . ' *)\n     \nEnd NatDict'.\n\nSection NatDict'Tests.\n\n  (* The tests here are the same as for the previous implementation. *)\n  Let tests :=\n    let new := @new_dict'' nat in\n    let ins5 := insert'' new 5 10 in\n    let ins5ins5 := insert'' ins5 5 15 in\n    let ins5rm5 := remove'' ins5 5 in\n    let ins5ins5rm5 := remove'' ins5ins5 5 in\n    forallb id\n                       [ \n                         negb (contains'' new 5);\n                         contains'' ins5 5;\n                         contains'' ins5ins5 5;\n                         negb (contains'' ins5rm5 5);\n                         negb (contains'' ins5ins5rm5 5);\n                         option_nat_eq (get'' new 5) None;\n                         option_nat_eq (get'' ins5 5) (Some 10);\n                         option_nat_eq (get'' ins5ins5 5) (Some 15);\n                         option_nat_eq (get'' ins5ins5rm5 5) None;\n                         option_nat_eq (get'' ins5 3) None\n                       ].\n\n  Let nat_dict_list_tests_pass: tests = true.\n  Proof. tauto. Qed.\n  \nEnd NatDict'Tests.\n\n\n\n(* The tasks below are additional and not required. *)\n\n\n\n(* As you can see, these two implementations comply to the same interface. *)\n(* Yet, since their types are different, we had to write separate test suites, \n   despite they're essentially the same. *)\n(* Functional languages allow to specify a general interface with typeclasses. *)\nSection DictGeneral.\n\n  (* General interface for a dict polymorphic on value type. *)\n  (* This actually defines a type whose elements are interface implementations. *)\n  Class Dict := {\n    D: Type -> Type; \n    new_dict: forall (V: Type), D V;\n    insert: forall {V: Type}, (D V) -> nat -> V -> (D V);\n    remove: forall {V: Type}, (D V) -> nat -> (D V);\n    get: forall {V: Type}, (D V) -> nat -> option V;\n    contains: forall {V: Type}, (D V) -> nat -> bool;\n  }.\n\n  (* Now we can specify expected behavior on the level of this interface. *)\n  (* The argument is an arbitrary dict implementation. *)\n  Let dict_tests (DictImpl: Dict) : bool :=\n    let new := @new_dict DictImpl nat in\n    let ins5 := insert new 5 10 in\n    let ins5ins5 := insert ins5 5 15 in\n    let ins5rm5 := remove ins5 5 in\n    let ins5ins5rm5 := remove ins5ins5 5 in\n    forallb id\n                       [\n                         negb (contains new 5);\n                         contains ins5 5;\n                         contains ins5ins5 5;\n                         negb (contains ins5rm5 5);\n                         negb (contains ins5ins5rm5 5);\n                         option_nat_eq (get new 5) None;\n                         option_nat_eq (get ins5 5) (Some 10);\n                         option_nat_eq (get ins5ins5 5) (Some 15);\n                         option_nat_eq (get ins5ins5rm5 5) None;\n                         option_nat_eq (get ins5 3) None\n                       ].\n            \n  (* Now we can state that our function-based implementation \n     complies to Dict interface. *)\n  Instance FunDict: Dict := {\n    D := @nat_dict_fun;\n    new_dict := @new_dict';\n    insert := @insert';\n    remove := @remove';\n    get := @get';\n    contains := @contains';\n  }.                       \n                       \n\n  (* Define instance of Dict class for the list-based implementation. *)\n   \n      (* place your code here *)\n  \n  (* Then, state and prove 'fun_dict_tests' and 'list_dict_tests' lemmas\n     by instantiating 'dict_tests' with instances you've just created. \n     These lemmas, as before, should be proved just by 'tauto'. *)\n\n      (* place your code here *)\n \nEnd DictGeneral.\n", "meta": {"author": "semantics-classroom", "repo": "coq-intro-sirius-2021", "sha": "6206e069c084f9cb1c5170c354a1c8d9c087fe5c", "save_path": "github-repos/coq/semantics-classroom-coq-intro-sirius-2021", "path": "github-repos/coq/semantics-classroom-coq-intro-sirius-2021/coq-intro-sirius-2021-6206e069c084f9cb1c5170c354a1c8d9c087fe5c/src/b1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8444547981559746}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Recdef.\n\nModule Pset1Bnat.\n\n  (* In this module, you'll prove some facts about *binary*\n     numbers, rather than Coq's default unary numbers.\n     We'll start out with some useful lemmas. *)\n  Lemma double_eq (n m:nat) : n + n = m + m <-> n = m.\n  Proof. omega. Qed.\n\n  Lemma double_lt (n m:nat) : n + n < m + m <-> n < m.\n  Proof. omega. Qed.\n\n  Lemma double_lt_n_Sm (n m:nat) : n + n < S (m + m) <-> n < S m.\n  Proof. omega. Qed.\n\n  (* The `clean_arithmetic` tactic cleans up a lot of arithmetic\n     identities typically occurring in these problems.\n     It replaces `x + 0` with `x`, `S x = S y` with `x = y`, and\n     `x + x = y + y` with `x = y`. *)\n  Ltac clean_arithmetic :=\n    repeat match goal with\n      | [H : context[_ + 0] |- _] => rewrite Nat.add_0_r in H\n      | [ |- context[_ + 0] ] => rewrite Nat.add_0_r\n      | [H : context[?a + ?a = ?b + ?b] |- _] => rewrite double_eq in H\n      | [ |- context[?a + ?a = ?b + ?b] ] => rewrite double_eq\n      | [H : context[S _ = S _] |- _] => apply eq_add_S in H\n      | [ |- context[S _ = S _] ] => apply eq_S\n    end.\n\n\n  (* Coq's Peano arithmetic defines natural numbers inductively,\n     based on two constructors: 0 and successor. So 10 is defined\n     as a structure of length 11:\n     (S (S (S (S (S (S (S (S (S (S Z)))))))))))\n     And in general N is defined in a structure of length O(N).\n\n     We're going to work with natural numbers based on *three*\n     constructors. That will lead to numbers defined in structures\n     of length O(log_2 N). *)\n\n  Inductive bnat : Type :=\n    | BZ : bnat              (* Zero *)\n    | BD1 : bnat -> bnat     (* BD1 X is the number 2*X + 1 *)\n    | BD2 : bnat -> bnat.    (* BD2 X is the number 2*X + 2 *)\n\n\n  (* EXERCISE: Write a function that computes the conventional\n     (Peano) value of bnat `b`. *)\n  Function bval (b:bnat) : nat :=\n    0.\n\n\n  (* EXERCISE: Prove that if `bval b = 0`, then `b = BZ`. *)\n  Lemma bval_zero (b:bnat) :\n    bval b = 0 -> b = BZ.\n  Proof.\n  Abort.\n\n\n  (* EXERCISE: Prove that every natural number has a unique\n     binary representation. *)\n  Lemma bval_uniq (b c:bnat) :\n    bval b = bval c -> b = c.\n  Proof.\n    (* Your first tactic should be `generalize c`.\n       Don't forget `discriminate`, `clean_arithmetic`, and `omega`. *)\n    generalize c.\n  Abort.\n\n\n  (* EXERCISE: Write a function that returns the successor of `b`.\n     You'll want to work this out on paper first, and there will\n     be at least one recursive call to `bsucc`. *)\n  Function bsucc (b:bnat) : bnat :=\n    0.\n\n\n  (* EXERCISE: Prove that your `bsucc` is correct. *)\n  Lemma bsucc_correct (b:bnat) :\n    bval (bsucc b) = S (bval b).\n  Proof.\n    (* If regular induction doesn't work, try\n       `functional induction (bval b)`, which runs induction over the\n       cases of the `bval` function. *)\n  Abort.\n\n\n  (* This function returns the length of a binary number. *)\n  Function blen (b:bnat) : nat :=\n    match b with\n    | BZ => 0\n    | BD1 b' => S (blen b')\n    | BD2 b' => S (blen b')\n    end.\n\n\n  (* The sum of the lengths of two binary numbers in a pair. *)\n  Definition bpairlen (x:bnat*bnat) : nat :=\n    blen (fst x) + blen (snd x).\n\n\n  (* EXERCISE: Write a function that adds two binary numbers.\n     You'll want to work this out on paper first too. Everything\n     works out easier if the numbers are passed in a pair; you\n     can decompose the pair with `fst` and `snd` (Check them),\n     or with matching.\n\n     After writing the function, you'll need to prove that its\n     recursion terminates. Do that too. *)\n  Function baddpair (x:bnat*bnat) {measure bpairlen x} : bnat :=\n    0.\n  (* Proof. ... Qed. *)\n\n  (* A more conventional adder function: *)\n  Definition badd (x y:bnat) := baddpair (x,y).\n\n\n  (* EXERCISE: Prove that your add function is correct. *)\n  Lemma baddpair_correct (x:bnat*bnat) :\n    bval (baddpair x) = bval (fst x) + bval (snd x).\n  Proof.\n  Abort.\n\n\n  (* EXERCISE: Write a function that determines whether\n     `fst x < snd x`. Return either False or True. *)\n  Function blesspair (x:bnat*bnat) {measure bpairlen x} : Prop :=\n    True.\n  (* Proof. ... Qed. *)\n\n  Definition bless (x y:bnat) : Prop := blesspair (x,y).\n\n\n  (* EXERCISE: Prove that `blesspair` is correct.\n     For me this was the hardest proof in this module. *)\n  Lemma blesspair_correct (x:bnat*bnat) :\n    bval (fst x) < bval (snd x) <-> blesspair x.\n  Proof.\n  Abort.\n\nEnd Pset1Bnat.\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/pset1/pset1bnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8918110475945173, "lm_q1q2_score": 0.844185372131373}}
{"text": "Inductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nDefinition pred (x : nat) : nat :=\n match x with\n   | O => O\n   | S x' => x'\nend.\n\nCompute pred (S(S O)).\n\nCompute pred (S(S(S(S(S(S(S(S(S(S(S(S(S(S(S O))))))))))))))).\n\nFixpoint plus (x y : nat) : nat :=\n  match x with\n   | O => y\n   | S x' => S \n(plus x' y)\nend.\n\nCompute plus (S O)(S O).\n\nFixpoint leb (x y : nat) : bool :=\n  match x with\n   | O => true\n   | S x' => match y with\n              | O => false\n              | S y' => leb x' y'\n               end\nend.\n\nFixpoint mult (x y : nat) : nat :=\n  match x with\n   | O => O\n   | S x => plus x (mult x y)\nend.\n\nLemma plus_O x : plus x O = x.\nProof.\ninduction x; simpl.\nreflexivity.\nrewrite IHx.\nreflexivity.\nQed.\n\nLemma plus_S x y : plus x (S y) = S (plus x y).\nProof.\ninduction x; simpl.\nreflexivity.\nrewrite IHx.\nreflexivity.\nQed.\n\nLemma plus_com x y : plus x y = plus y x.\nProof.\ninduction x; simpl.\nrewrite plus_O; reflexivity.\nrewrite plus_S; rewrite IHx.\nreflexivity.\nQed.\n\nLemma plus_asso x y z : plus (plus x y) z = plus x (plus y z).\nProof.\ninduction x; simpl.\nreflexivity.\nrewrite IHx.\nreflexivity.\nQed.\n\nPrint plus_asso.\n\nRequire Import Omega.\n\nLemma plus_AC x y z : plus y (plus x z) = plus (plus z y) x.\nProof.\nsetoid_rewrite plus_com at 3.\nsetoid_rewrite plus_com at 1.\napply plus_asso.\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_Logic2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.8902942312159383, "lm_q1q2_score": 0.844136511342941}}
{"text": "Require Import Arith.\n\nInductive even : nat -> Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\n\nHint Constructors even.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S (S (mult2 p))\n  end.\n\nLemma mult2_even : forall n:nat, even (mult2 n).\nProof. \n induction n; simpl; auto.\nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n + p).\nProof.\n intros n p Heven_n; induction  Heven_n; simpl; auto.\nQed.\n\nHint Resolve sum_even.\n\nLemma square_even : forall n:nat, even n -> even (n * n).\nProof.\n intros n Hn; elim Hn; simpl; auto.\n intros n0 H0 H1; rewrite (mult_comm n0 (S (S n0))).\n right; simpl;apply sum_even; auto.\nQed.\n\n\nLemma even_mult2 : forall n:nat, even n -> (exists p, n = mult2 p).\nProof.\n induction 1.\n -  exists 0; reflexivity.\n -  destruct IHeven as [p Hp]; exists (S p); simpl; now rewrite Hp. \nQed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch8_inductive_predicates/SRC/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.8437263347071141}}
{"text": "(** Exercise sheet for lecture 4: Tactics in Coq.\n\nWritten by Ralph Matthes (CNRS, IRIT, Univ. Toulouse, France).\n *)\n\n(** * Exercise 1\nFormalize the following types in UniMath and construct elements for them interactively - \nif they exist. Give a counter-example otherwise, i.e., give specific parameters and a\nproof of the negation of the statement.\n\n[[\n1.    A \u00d7 (B + C) \u2192 A \u00d7 B + A \u00d7 C, given types A, B, C\n2.    (A \u2192 A) \u2192 (A \u2192 A), given type A (for extra credit, write down five elements of this type)\n3.    Id_nat (0, succ 0)\n4.    \u2211 (A : Universe) (A \u2192 empty) \u2192 empty\n5.    \u220f (n : nat), \u2211 (m : nat), Id_nat n (2 * m) + Id_nat n (2 * m + 1),\n      assuming you have got arithmetic\n6.    (\u2211 (x : A) B \u00d7 P x) \u2192 B \u00d7 \u2211 (x : A) P x, given types A, B, and P : A \u2192 Universe\n7.    B \u2192 (B \u2192 A) \u2192 A, given types A and B\n8.    B \u2192 \u220f (A : Universe) (B \u2192 A) \u2192 A, given type B\n9.    (\u220f (A : Universe) (B \u2192 A) \u2192 A) \u2192 B, given type B\n]]\n\nMore precise instructions and hints:\n\n1.  Use [\u2a3f] in place of the + and pay attention to operator precedence.\n\n2.  Write a function that provides different elements for any natural number argument, \n    not just five elements; for extra credits: state correctly that they are different - \n    for a good choice of [A]; for more extra credits: prove that they are different.\n\n3.  An auxiliary function may be helpful (a well-known trick).\n\n4.  The symbol for Sigma-types is [\u2211], not [\u03a3].\n\n5.  Same as 1; and there is need for module [UniMath.Foundations.NaturalNumbers], e.g., \n    for Lemma [natpluscomm].\n\n6.-9. no further particulars\n*)\n\nRequire Import UniMath.Foundations.Preamble.\nRequire Import UniMath.Foundations.PartA.\nRequire Import UniMath.Foundations.NaturalNumbers.\n\n\n\n(** * Exercise 2\nDefine two computable strict comparison operators for natural numbers based on the fact\nthat [m < n] iff [n - m <> 0] iff [(m+1) - n = 0]. Prove that the two operators are\nequal (using function extensionality, i.e., [funextfunStatement] in the UniMath library).\n\nIt may be helpful to use the definitions of the exercises for lecture 2.\nThe following lemmas on substraction [sub] in the natural numbers may be\nuseful:\n\na) [sub n (S m) = pred (sub n m)]\n\nb) [sub 0 n = 0]\n\nc) [pred (sub 1 n) = 0]\n\nd) [sub (S n) (S m) = sub n m]\n\n*)\n\n\n(** from exercises to Lecture 2: *)\nDefinition ifbool (A : UU) (x y : A) : bool -> A :=\n  bool_rect (\u03bb _ : bool, A) x y.\n\nDefinition negbool : bool -> bool := ifbool bool false true.\n\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n  nat_rect (\u03bb _ : nat, A) a f.\n\nDefinition pred : nat -> nat := nat_rec nat 0 (fun x _ => x).\n\nDefinition is_zero : nat -> bool := nat_rec bool true (\u03bb _ _, false).\n\nDefinition iter (A : UU) (a : A) (f : A \u2192 A) : nat \u2192 A :=\n  nat_rec A a (\u03bb _ y, f y).\n\nNotation \"f \u0302 n\" := (\u03bb x, iter _ x f n) (at level 10).\n\nDefinition sub (m n : nat) : nat := pred \u0302 n m.\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/exercises_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.9184802473724224, "lm_q1q2_score": 0.8436059576399787}}
{"text": "Add LoadPath \"~/cpdt/src\".\n\nRequire Import CpdtTactics.\n\n(** propositional logic *)\n\n(* (10 minutes) Propositional logic often comes with an A <=> B form that is\ntrue when A and B have the same truth values. Show how to define \"iff\" as\na Coq Prop. *)\n\nDefinition iff' (a b : Prop) := a -> b /\\ b -> a.\n\nNotation \"a <=> b\" := (iff' a b) (at level 77, right associativity).\nHint Unfold iff'.\n\nTheorem iff'_refl : forall P : Prop, P <=> P.\n  auto.\nQed.\n\nTheorem iff'_sym : forall P Q : Prop, (P <=> Q) <=> (Q <=> P).\n  auto.\nQed.\n\n(* How automated can you make these proofs? *)\n\n(* (15 minutes) In college-level logic classes, we learn that implication can\nbe expressed in terms of not and or operations (rather than in terms of\nforall). *)\nDefinition implies (A B : Prop) : Prop := ~A \\/ B.\nNotation \"a => b\" := (implies a b) (at level 75, right associativity).\nHint Unfold implies.\n\n(* One might wonder whether this form of implication is \"the same as\" Coq's\nversion that uses forall. State two theorems claiming that each kind of\nimplication can be converted into the other. Which one(s) can you prove? *)\n\nTheorem imp1 : forall A B : Prop, (A => B) -> (A -> B).\nProof.\n  intros. unfold implies in H. intuition.\nQed.\n\n(*\nCan't prove:\nTheorem imp2 : forall A B : Prop, (A -> B) -> (A => B).\nProof.\n  intros. unfold implies. intuition.\nQed.\n*)\n\n(* How about... *)\nAxiom nowai : forall P : Prop, P \\/ ~P.\n(* ...now? *)\n\nTheorem imp2 : forall A B : Prop, (A -> B) -> (A => B).\nProof.\n  intros. unfold implies. destruct (nowai A); intuition.\nQed.\n\n(* Some handy imports:\n   Arith gives us nat, *, and +\n   Arith.Even gives us even and odd\n   Arith.Div2 gives us div2\n*)\nRequire Import Arith.\nRequire Import Arith.Even.\nRequire Import Arith.Div2.\nSet Implicit Arguments.\nHint Constructors even odd.\n\n(** propositions with implicit equality *)\n\n(* (35 minutes) The Collatz sequence starting at n is defined as the infinite\nsequence obtained by iterating the step function:\n\nstep(n) = n/2  if n is even\nstep(n) = 3n+1 if n is odd\n\nFor example, the sequence starting at 11 looks like\n\n11, 34, 17, 52, 26, 13, 40, 20, ...\n\nIt is conjectured that all collatz sequences eventually cycle (and in\nparticular reach 1 if they weren't 0 to begin with). Create an inductive\nproposition collatz_cycles which expresses the fact that a particular nat\neventually reaches a cycle, then state and prove the fact that the collatz\nsequence starting at 5 eventually cycles.\n\nDon't forget about \"Hint Constructors\" and \"auto n\" when creating proofs about\nconstants!\n*)\n\nDefinition step n :=\n  if even_odd_dec n\n  then div2 n\n  else 3 * n + 1.\n\nInductive cycles : nat -> Prop :=\n| cycles_1 : cycles 1\n| cycles_step : forall n, cycles (step n) -> cycles n\n.\nHint Constructors cycles.\n\nTheorem cycles_5 : cycles 5.\nProof.\n  (* 5 -> 16 -> 8 -> 4 -> 2 -> 1 : 5 step + 1 *)\n  auto 6.\nQed.\n\n(* (45 minutes) We say a list A is a \"subsequence\" of a list B when you can\nproduce list A by deleting some elements from list B.  For example, [1,2,3] is\na 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]\nbut 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\nDefine an inductive proposition subsequence that captures what it means to be\na subsequence, then prove that subsequence is transitive. Some hints on\nautomating this proof:\n\n1. Use Hint Constructors to add your inductive proposition's constructors to\nthe hint database.\n2. Choose which thing you do induction on carefully!\n3. Try \"crush\" and look where it fails -- then add that as a lemma and put it\nin your rewriting database. For example, on my first attempt, crush died here\nfirst:\n\n  A : Type\n  l1 : list A\n  H : subsequence l1 nil\n  l : list A\n  ============================\n   subsequence l1 l\n\nSo I added a lemma:\n\nLemma subsequence_nil_anything : forall A (l1 l2 : list A),\n    subsequence l1 nil -> subsequence l1 l2.\n(* ... ;-) *)\nQed.\n\nHint Resolve subsequence_nil_anything.\n\nThat let crush get a bit farther, and suggested the next lemma I would need to\nprove.\n*)\n\n(* I'm not really sure why we're not getting this notation for free, actually.\nBut we're not, se here it is for convenience. *)\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nInductive subsequence {T : Type} : list T -> list T -> Prop :=\n| subnil   : forall l, subsequence nil l\n| subdrop  : forall s y ry, subsequence s ry -> subsequence s (y :: ry)\n| submatch : forall x rx ry, subsequence rx ry -> subsequence (x :: rx) (x :: ry)\n.\nHint Constructors subsequence.\n\nDefinition sub123 := subsequence [1; 2; 3].\nDefinition notsub123 := fun l => ~(subsequence [1; 2; 3] l).\nHint Unfold sub123.\n\nExample e1 : sub123 [1; 2; 3]. auto 100. Qed.\nExample e2 : sub123 [1; 1; 1; 2; 2; 3]. auto 100. Qed.\nExample e3 : sub123 [1; 2; 7; 3]. auto 100. Qed.\nExample e4 : sub123 [5; 6; 1; 9; 9; 2; 7; 3; 8]. auto 100. Qed.\n(* optional; you'll like inversion and unfold a lot*)\n\nLtac solvesubseq := intro;\n  repeat (\n    match goal with\n    | [H : subsequence _ _ |- False] => inversion H; clear H; crush\n    end\n  ).\n\nExample e5 : notsub123 [1; 2]. solvesubseq. Qed.\nExample e6 : notsub123 [1; 3]. solvesubseq. Qed.\nExample e7 : notsub123 [5; 6; 2; 1; 7; 3; 8]. solvesubseq. Qed.", "meta": {"author": "Ptival", "repo": "coq-misc", "sha": "8e61de7b0ee1249190040ed964d90a985eb07aa8", "save_path": "github-repos/coq/Ptival-coq-misc", "path": "github-repos/coq/Ptival-coq-misc/coq-misc-8e61de7b0ee1249190040ed964d90a985eb07aa8/cis-670/HW5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.9173026612812897, "lm_q1q2_score": 0.8435905372363234}}
{"text": "Module Playground1.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCheck (S (S (S (S O)))).\nEval compute in (minustwo 4).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nEval compute in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.", "meta": {"author": "sguzman", "repo": "CoqRepo", "sha": "e802df1540b7cff7dad5731c6abfcbf8e669f44e", "save_path": "github-repos/coq/sguzman-CoqRepo", "path": "github-repos/coq/sguzman-CoqRepo/CoqRepo-e802df1540b7cff7dad5731c6abfcbf8e669f44e/numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.8433579220118123}}
{"text": "(* Standard set of imports. *)\nAdd LoadPath \"~/programming/coq/cpdt/src\".\nRequire Import Bool Arith List CpdtTactics.\nSet Implicit Arguments.\n\n(* An ADT *)\nInductive binop : Set := Plus | Times.\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n    | Plus => plus\n    | Times => mult\n  end.\n\n(*\nSugar for:\nDefinition binopDenote : binop -> nat -> nat -> nat := fun (b: binop) =>\n  match b with\n    | Plus => plus\n    | Times => mult\n  end.\n\nOr, without the types:\nDefinition binopDenote := fun b =>\n  match b with\n    | Plus => plus\n    | Times => mult\n  end.\n*)\n\n(* Fixpoint denotes recursive data type. *)\nFixpoint expDenote (e: exp) : nat :=\n  match e with\n    | Const n => n\n    | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\n(* We want to eval some things in order to test we have the right definitions. *)\nEval simpl in expDenote (Const 42).\nEval simpl in expDenote (Binop Plus (Const 2) (Const 2)).\nEval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\n(* The actual language. *)\nInductive instr : Set :=\n(* Push Const on the stack. *)\n| iConst : nat -> instr\n(* Pop two Const's apply the Binop and push on the stack. *)\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\nDefinition instrDenote (i : instr) (s: stack) : option stack :=\n  match i with\n    (* Push it on the stack. *)\n    | iConst n => Some (n :: s)\n    | iBinop b =>\n      match s with\n        (* Apply the operator. *)\n        | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n        (* Stack underflow. *)\n        | _ => None\n      end\n  end.\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n    (* No more instructions. *)\n    | nil => Some s\n    | i :: p' =>\n      (* Apply the instruction. *)\n      match instrDenote i s with\n        (* Stack underflow. *)\n        | None => None\n        | Some s' => progDenote p' s'\n      end\n  end.\n\n(* Compiler. *)\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(* Test the compiler. *)\nEval simpl in compile (Const 42).\nEval simpl in compile (Binop Plus (Const 2) (Const 2)).\nEval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nEval simpl in progDenote (compile (Const 42)) nil.\nEval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.\nEval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))) nil.\n\n(* Proving correctness. *)\nTheorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\n\n(* Our first attempt seems too hard, for what reason?\nLet's try something else. *)\nAbort.\n\nLemma compile_correct' : forall e p s, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n\n(* Let's try the induction tactic. *)\ninduction e.\n\n(* Use the intros tactic, whatever that is. *)\nintros.\n(* This seems to lift forall variables into a free state? *)\n\n(* Let's unfold the functions in our goal. *)\nunfold compile.\nunfold expDenote.\n(* We only need to unfold the LHS progDenote, why? *)\nunfold progDenote at 1.\n(* Now we can remove some of the cruft, since we know the first arg to progDenote *)\nsimpl.\n(* Now fold it back up. *)\nfold progDenote.\n(* It's trivial now. *)\nreflexivity.\n\n(* On to the next one. *)\nintros.\nunfold compile.\nfold compile.\nunfold expDenote.\nfold expDenote.\n(* Near as I can tell, this folding/unfolding is equivalent to simpl. *)\n\n(* The LHS almost looks like IHe2, we jus need to change the parens. *)\n(* Need associative law for lists. *)\nCheck app_assoc_reverse.\n(* We can also search like in hoogle. *)\nSearchRewrite ((_ ++ _) ++ _).\nrewrite app_assoc_reverse.\n(* Now we can rewrite it as the hypothesis. *)\nrewrite IHe2.\n(* If we do that again, we can get IHe1. *)\nrewrite app_assoc_reverse.\nrewrite IHe1.\n(* We're practically done. *)\nunfold progDenote at 1.\nsimpl.\nfold progDenote.\nreflexivity.\n\n(* But this was messy.  We can do better with coq. *)\nAbort.\n\nLemma compile_correct' : forall e s p, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n  induction e; crush.\nQed.\n\n(* Now we can actually prove our theorem. *)\nTheorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\n  intros.\n  (* We need to use the lemma we constructed, and it almost looks like it, just need a rewrite. *)\n  Check app_nil_end.\n  (* Have to state exactly what to rewrite. *)\n  rewrite (app_nil_end (compile e)).\n  (* Use our lemma. *)\n  rewrite compile_correct'.\n  (* Let's skip a step and let coq handle the nitty. *)\n  reflexivity.\nQed.", "meta": {"author": "joneshf", "repo": "cpdt-examples", "sha": "7528b7b5a14f0f1a16f8f3c7e0e7b4bfa6d754b2", "save_path": "github-repos/coq/joneshf-cpdt-examples", "path": "github-repos/coq/joneshf-cpdt-examples/cpdt-examples-7528b7b5a14f0f1a16f8f3c7e0e7b4bfa6d754b2/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8431626377285342}}
{"text": "\n(*\n\n  Script du Th\u00e8me 01 :  fonctions r\u00e9cursives\n\n*)\n\n(*\n\n * Fonctions simples\n\nlet id (e:'a) : 'a = e\nval id : 'a -> 'a = <fun>\n\n*)\n\nDefinition id {A:Set} (a:A) : A := a.\n\n(*\n\n# id 12 ;;\n- : int = 12\n# id true ;;\n- : bool = true\n\n\n*)\n\nEval compute in id 12.\n\nEval compute in id true.\n\nExample id_12: id 12 = 12.\nProof.\ncompute.\nreflexivity.\nQed.\n\nLemma id_id:\n  forall A : Set, forall a : A,\n    id a = a.\nProof.\nintros A a.\ncompute.\nreflexivity.\nQed.\n\n(**\n\n  ** Exercice : fonction constante\n\nD\u00e9finir en Ocaml puis traduire en Coq la fonction [constant] qui retourne toujours le premier\nde ses deux arguments.\n\nTester avec [constant 12 true]\n\nMontrer que [constant (id a) b = a].\n\n*)\n\nDefinition constant {A B : Set} (a: A) (b : B) : A := a.\n\nExample cst_12: constant 12 true = 12.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nLemma cst_ab:\n  forall A B : Set,  forall a : A, forall b : B,  constant (id a) b = a.\nProof.\n  intros A B a b.\n  compute.\n  reflexivity.\nQed.\n\n\n\n(*\n\n  Un autre exemple de fonction.\n\n*)\n\nDefinition flip {A B C:Set} (f:A -> B -> C) : B -> A ->  C :=\n  fun (b:B) (a:A) => f a b.\n\n(*\n\nlet flip (f:'a -> 'b -> 'c) : 'b -> 'a -> 'c =\n   fun (b:B) (a:A) -> f a b.\n\n*)\n\nLemma flip_flip:\n  forall A B C : Set, forall f : A -> B -> C,\n    flip (flip f) = f.\nProof.\nintros A B C f.\nunfold flip.\nreflexivity.\nQed.\n\nLemma flip_flip_flip_flip:\n  forall A B C : Set, forall f : A -> B -> C,\n    f = flip (flip (flip (flip f))).\nProof.\nintros A B C f.\nrewrite flip_flip.\nrewrite flip_flip.\nreflexivity.\nQed.\n\nLemma flip_flip_flip_flip':\n  forall A B C : Set, forall f : A -> B -> C,\n    f = flip (flip (flip (flip f))).\nProof.\nrepeat rewrite flip_flip ; reflexivity.\nQed.\n\n\n(*\n\n ** Fonctions totales\n\n# let rec until (pred: 'a -> bool) (f:'a -> 'a) (a:'a) : 'a =\n     if pred a then until pred f (f a)\n     else a ;;\n\n*)\n\n(*\n\n<<DECOMMENTER POUR ESSAYER>>\n\nFixpoint until {A:Set} (pred: A -> bool) (f:A -> A) (a:A) : A :=\n  if pred a then until pred f (f a)\n  else a.\n\n*)\n\nFixpoint untiln {A:Set} (n:nat) (pred: A -> bool) (f:A -> A) (a:A) : A :=\n  if pred a then match n with\n                     | 0 => a\n                     | S n' => untiln n' pred f (f a)\n                 end\n  else a.\n\nLemma untiln_id:\n  forall A : Set, forall n:nat,\n  forall pred:A -> bool, forall a : A,\n    untiln n pred id a = a.\nProof.\nintros A n pred a.\ninduction n as [|n'].\n  - (* cas n=0 *)\n    simpl.\n    case (pred a) ; reflexivity.\n  - (* cas n=S n' *)\n    simpl.\n    destruct (pred a).\n    + (* cas (pred a) = True *)\n      rewrite id_id.\n      rewrite IHn'.\n      reflexivity.\n    + (* cas (pred a) = False *)\n      reflexivity.\nQed.\n\n\n(*\n\n  * Fonctions sur les listes\n\n*)\n\nRequire Import List.\n\nPrint list.\n\nCheck cons 1 (cons 2 (cons 3 nil)).\n\nExample cons_infixe:\n 1::2::3::nil = cons 1 (cons 2 (cons 3 nil)).\nProof.\nreflexivity.\nQed.\n\n\n(*\n\n ** Une premi\u00e8re fonction\n\nlet rec concat (l1 : 'a list) (l2 : 'a list) : 'a list =\n  match l1 with\n  | [] -> l2\n  | e::l1' -> e::(concat l1' l2)\n\n*)\n\nFixpoint concat {A : Set} (l1 l2 : list A) : list A :=\n  match l1 with\n    | nil => l2\n    | e::l1' => e::(concat l1' l2)\n  end.\n\nEval compute in concat (1::2::nil) (3::4::5::nil).\n\nExample concat_ex1:\n  concat (1::2::3::nil) (4::5::nil)  = 1::2::3::4::5::nil.\nProof.\ncompute.\nreflexivity.\nQed.\n\nLemma nil_concat:\n  forall A : Set, forall l : list A,\n    concat nil l = l.\nProof.\nintros A l.\nsimpl.\nreflexivity.   (* ou [trivial] *)\nQed.\n\nLemma concat_nil_fails:\n  forall A : Set, forall l : list A,\n  concat l nil = l.\nProof.\nintros A l.\nsimpl.  (* bloqu\u00e9 *)\nAbort.\n\nLemma concat_nil_destruct:\n  forall A : Set, forall l : list A,\n  concat l nil = l.\nProof.\nintros A l.\ndestruct l as [| e l'].\n  - (* cas nil : l=nil *)\n    simpl.\n    reflexivity.\n  - (* cas cons: l=e::l' *)\n    simpl.  (* bloqu\u00e9 *)\nAbort.\n\nLemma concat_nil:\n  forall A : Set, forall l : list A,\n  concat l nil = l.\nProof.\ninduction l as [|e l'].\n  - (* cas de base : l=nil *)\n    simpl.\n    reflexivity.\n  - (* cas inductif: l=e::l' *)\n    simpl.\n    rewrite IHl'.\n    reflexivity.\nQed.\n\n(* Le sch\u00e9ma de preuve qui a \u00e9t\u00e9\nsuivi : *)\n\nCheck list_ind.\n\n(*\n\n  ** Fonctions partielles\n\n# exception Boum ;;\nexception Boum\n# let boum (e:'a) = raise Boum ;;\nval boum : 'a -> 'b = <fun>\n\n*)\n\nPrint option.\n\nDefinition head {A:Set} (l:list A) : option A :=\n  match l with\n      | nil => None\n      | e::_ => Some e\n  end.\n\nExample head_ex1:\n  head (1::2::3::4::nil) = Some 1.\nProof.\ncompute.\nreflexivity.\nQed.\n\nLemma head_concat:\n  forall A : Set, forall l1 l2 : list A,\n    head (concat l1 l2) =\n    match l1 with\n      | nil => head l2\n      | e1::l1' =>  Some e1\n    end.\nProof.\nintros A l1 l2.\ndestruct l1 as [| e1'' l1''].\n  - (* cas l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* cas l1 = e1''::l1'' *)\n    simpl.\n    reflexivity.\nQed.\n\n(*\n\none-liner\n\n*)\n\nLemma head_concat':\n  forall A : Set, forall l1 l2 : list A,\n    head (concat l1 l2) =\n    match l1 with\n      | nil => head l2\n      | e1::l1' =>  Some e1\n    end.\nProof.\n  destruct l1 ; trivial.\nQed.\n\nDefinition tail {A:Set} (l:list A) : list A :=\n  match l with\n      | nil => nil\n      | _::l' => l'\n  end.\n\nLemma tail_amb:\n  forall A : Set, forall e : A,\n    tail nil = tail (e::nil).\nProof.\nintros A e.\nsimpl.\nreflexivity.\nQed.\n\nLemma head_tail:\n  forall A : Set, forall e : A, forall l : list A,\n    head l = Some e -> e :: tail l = l.\nProof.\nintros A e l Hhead.\ndestruct l as [| e' l'].\n  - (* cas l = nil *)\n    inversion Hhead. (* contradiction *)\n  - (* cas l = e'::l' *)\n    simpl.\n    inversion Hhead as [ He ].\n    reflexivity.\nQed.\n\n\n(*\n\n ** Exercice : [untiln] partielle\n\nLa fonction [untiln] vue pr\u00e9c\u00e9demment devrait \u00eatre r\u00e9\u00e9crite pour\n\u00eatre une fonction partielle. En particulier, si la borne d'approximation\nest atteinte, le r\u00e9sultat devrait \u00eatre [None].\n\nR\u00e9\u00e9crire la fonction [untiln] en cons\u00e9quence. Que faire du lemme d\u00e9montr\u00e9\n sur cette fonction ?\n\n*)\n\nFixpoint untiln_part { A : Set } ( n : nat ) ( pred : A -> bool ) ( f : A -> A ) ( a : A ) : option A :=\n  if pred a\n  then Some(a)\n  else\n    match n with\n      | 0 => None\n      | S n' => untiln_part n' pred f ( f a )\n    end.\n\n(*\nR\u00e9ponse : On oublie le lemme, (c'est plus compliqu\u00e9)\n*)\n\nLemma untiln_part_id:\n  forall A : Set, forall n:nat,\n  forall pred:A -> bool, forall a : A, forall x:A,\n    untiln_part n pred id a = Some(x) -> x = a.\nProof.\nintros A n pred a x.\ninduction n as [|n'].\n  - (* cas n=0 *)\n    simpl.\n    case (pred a).\n      +intros H.\n      inversion H.\n      reflexivity.\n      +intros H.\n      inversion H.\n  - (* cas n=S n' *)\n    simpl.\n    destruct (pred a).\n    + intros H.\n      inversion H.\n      reflexivity.\n    + (* cas (pred a) = False *)\n      exact IHn'.\nQed.\n\n(*\n\n ** Exercice : Renversement de liste\n\n *** Question 1\n\nD\u00e9finir la fonction [rev] qui renverse les \u00e9l\u00e9ment d'une liste.\n\n*)\n\nFixpoint rev {A: Set} (l : list A) : list A :=\nmatch l with\n  | nil => nil\n  | e :: l1' => concat (rev l1') (e :: nil)\nend .\n\n\n(*\n *** Question 2\n\nCompl\u00e9ter l'exemple suivant :\n\n*)\n\n\nExample rev_ex1:\n  rev (1::2::3::4::5::nil) = 5::4::3::2::1::nil.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n(**\n\n *** Question 3\n\nOn souhaite montrer que [rev] est idempotent, mais la preuve suivante\n bloque.\n\n*)\n\nTheorem rev_rev_fails:\n  forall A : Set, forall l : list A,\n    rev (rev l) = l.\nProof.\nintros A l.\ninduction l as [| e l'].\n  - (* cas l=nil *)\n    simpl.\n    reflexivity.\n  - (* cas l=e::l' *)\n    simpl. (* bloqu\u00e9 *)\nAbort.\n\n(*\n\nIl nous manque une propri\u00e9t\u00e9 importante reliant [rev], [concat] et [nil].\n\nD\u00e9monter le lemme [rev_concat_nil] correspondant. En d\u00e9duire une preuve\ncompl\u00e8te pour le th\u00e9or\u00e8me [rev_rev].\n\n*)\n\n\nLemma rev_concat_nil:\n    forall A : Set, forall l : list A, forall e : A, \n    rev (concat l (e::nil)) = e :: rev l.\nProof.\n  induction l as [|e' l'].\n  -intro.\n   simpl.\n   reflexivity.\n\n  -intro.\n   simpl.\n   rewrite IHl'.\n   simpl.\n   reflexivity.\n   Qed.\n\nTheorem rev_rev:\n  forall A : Set, forall l : list A,\n    rev (rev l) = l.\nProof.\n  intros A l.\n  induction l as [|e l'].\n\n  -simpl.\n   reflexivity.\n\n  -simpl.\n   rewrite rev_concat_nil.\n   rewrite IHl'.\n   reflexivity.  \nQed.\n\n\n(*\n\n ** Exercice : dernier \u00e9l\u00e9ment\n\n *** Question 1\n\nD\u00e9finir la fonction [last] qui retourne le dernier \u00e9l\u00e9ment d'une\nliste non-vide.  Cette fonction prendra un argument [d]  (pour d\u00e9faut) que l'on retournera si la liste est vide.\n\n*)\n\nFixpoint last {A : Set} (l : list A) (d:A) : A :=\n  match l with\n    | nil => d\n    | e :: nil => e\n    | e :: l' => last l' d\n  end.\n    \n       \n\n(*\n\n*** Question 2\n\nMontrer le lemme suivant.\n\n*)\n\nLemma last_single:\n  forall A : Set, forall d e : A,\n    last (e::nil) d = e.\nProof.\n  intros A d e.\n  simpl.\n  trivial.\nQed.\n\n\n(*\n\n*** Question 3\n\nMontrer par induction le lemme suivant.\n\n*)\n\nLemma concat_cons_not_nil:\n  forall A : Set, forall l1 l2 : list A, forall e : A,\n    concat l1 (e::l2) <> nil.\nProof.\n  intros A l1 l2 e.\n  unfold not.\n  intro Hcontra.\n  destruct l1 as [| e1 l1'].\n  - (* cas l1=nil *)\n    simpl in Hcontra.\n    inversion Hcontra.\n  - (* cas l1=e1::l1' *)\n    simpl in Hcontra.\n    inversion Hcontra.\nQed.\n\nLemma last_concat:\n  forall A : Set, forall l1 l2 : list A, forall d e : A,\n    last (concat l1 (e::l2)) d = last (e::l2) d.\nProof.\n  intros A l1 l2 d e.\n  induction l1 as [|e1 l1'].\n\n  -rewrite nil_concat.\n   trivial.\n\n  - cut (concat (e1 :: l1') (e :: l2) = e1 :: (concat l1' (e :: l2) )).\n    +intros H.\n    rewrite H.\n    cut (last (e1 :: concat l1' (e :: l2)) d = last (concat l1' (e::l2)) d).\n    *intros H1.\n    rewrite H1.\n    exact IHl1'.\n    *\n    simpl.\n    destruct (concat l1' (e :: l2)).\n      {-simpl.\n    Abort.\n\n\n(*\n\n  * Fonctions d'ordre sup\u00e9rieur\n\n ** Exercice : la fonction map\n\n*)\n\nFixpoint map {A B :Set} (f:A -> B) (l:list A) : list B :=\n  match l with\n    | nil => nil\n    | e::l' => (f e) :: map f l'\n  end.\n\n(**\n\n  *** Question\n\nD\u00e9montrer les lemmes suivants :\n\n*)\n\n\nLemma head_map:\n  forall A B : Set, forall e : A, forall l : list A, forall f : A -> B,\n    head (map f (e::l)) = Some (f e).\nProof.\n  intros A B e l f.\n  simpl.\n  reflexivity.\nQed.\n\n\nLemma map_id:\n  forall A : Set, forall l : list A,\n    map id l = l.\nProof.\n  intros A l.\n  induction l as [|e l'].\n  - simpl.\n    reflexivity.\n\n  - simpl.\n    rewrite IHl'.\n    reflexivity.\nQed.\n   \nLemma map_concat:\n  forall A B : Set, forall l1 l2 : list A, forall f : A -> B,\n    map f (concat l1 l2) = concat (map f l1) (map f l2).\nProof.\n  intros A B l1 l2 f.\n  induction l1 as [|e l1'].\n\n  - simpl.\n    reflexivity.\n\n  -simpl.\n   rewrite IHl1'.\n   reflexivity.\nQed.\n\n(*\n\n  ** Exercice : la fonction foldr\n\n*)\n\nFixpoint foldr {A B :Set} (f:A -> B -> B) (u:B) (l:list A) : B :=\n  match l with\n    | nil => u\n    | e::l' => f e (foldr f u l')\n  end.\n\n(*\n\n  *** Question 1\n\nD\u00e9finir une fonction [folder_id] : *)\n\nDefinition folder_id {A :Type} (a : A) (b : list A) : list A := a :: b.\n\n(* telle que l'exemple suivant est prouvable : *)\n\n\nExample foldr_id_ex1:\n  foldr folder_id nil (1::2::3::nil) = (1::2::3::nil).\nProof.\n  compute.\n  reflexivity.\nQed.\n\n(* En d\u00e9duire le th\u00e9or\u00e8me g\u00e9n\u00e9ral suivant : *)\n\nTheorem foldr_id:\n  forall A : Set, forall l : list A,\n    foldr folder_id nil l = l.\nProof.\n  intros A l.\n  induction l as [|e l'].\n    - simpl.\n      reflexivity.\n\n    -simpl.\n     rewrite IHl'.\n     reflexivity.     \nQed.\n\n\n(*\n\n  *** Question 2\n\nEn vous inspirant de l'exemple suivant  (\u00e0 compl\u00e9ter) :\n\n*)\n\nExample folder_id_ex2:\n foldr folder_id (4::5::6::nil) (1::2::3::nil) = 1::2::3::4::5::6::nil.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nTheorem fold_concat:\n  forall A : Set, forall l1 l2 : list A,\n    foldr folder_id l2 l1 = concat l1 l2.\nProof.\n  intros A l1 l2.\n  induction l2 as [|e2' l2'].\n    +rewrite concat_nil.\n     rewrite foldr_id.\n     reflexivity.\n    +\nAbort.\n\n\n(*\n\n  *** Question 3\n\nSelon les m\u00eames principes, red\u00e9finir la fonction [map] en utilisant [foldr].\n\nTester avec l'exemple correspondant \u00e0 [map (fun n : nat => S n) (1::2::3::4::5::nil)].\n\nD\u00e9montrer le th\u00e9or\u00e8me g\u00e9n\u00e9ral reliant [map] et [foldr].\n\n*)\n\nDefinition foldmap {A B :Set} (f:A -> B) (l:list A) : list B :=\nfoldr (fun (le :A) (les :(list B)) => (f le)::les) nil l.\n\nExample foldmap_ex1:\nfoldmap (fun n : nat => S n) (1::2::3::4::5::nil) = (2::3::4::5::6::nil).\nProof.\ncompute.\nreflexivity.\nQed.\n\n\n(*\n\n  *** Question 4\n\nM\u00eames questions pour la fonction [rev]\n\n*)\n\nDefinition foldrev {A:Set} (l:list A) : list A :=\n foldr (fun (le :A) (les :(list A)) => concat les (le::nil)) nil l.\n\nExample foldrev_ex1:\nfoldrev (1::2::3::4::5::nil) = (5::4::3::2::1::nil).\nProof.\ncompute.\nreflexivity.\nQed.\n\n(*\n\n  ** Exercice : pliage \u00e0 gauche (difficile)\n\nLa fonction de pliage \u00e0 gauche est la suivante :\n\n*)\n\nFixpoint foldl {A B :Set} (f:A -> B -> A) (u:A) (l:list B) : A :=\n  match l with\n    | nil => u\n    | e::l' => foldl f (f u e) l'\n  end.\n\n(*\n\n  *** Question 1\n\nD\u00e9finir une fonction _non-r\u00e9cursive_ [foldl'] de pliage \u00e0 gauche \u00e0 partir de [foldr].\n\n*)\n\n(* wrong def*)\nDefinition foldl' {A B :Set} (f:A -> B -> A) (u:A) (l:list B) : A :=\n  foldr (fun (b:B)(g:A -> B)(x:A) =>  (g (f (x) (b)))) u l.\n\n(* D\u00e9montrer le th\u00e9or\u00e8me suivant : *)\n\nTheorem foldl'_foldl:\n  forall A B : Set, forall f : A -> B -> A,\n  forall l : list B, forall u : A,\n    foldl f u l = foldl' f u l.\nProof.\n  intros A B f l u.\n  induction l as [|e l'].\n\n  - compute.\n    reflexivity.\n\n  - simpl.\n unfold foldl' in IHl'.\n    unfold foldl'.\n    simpl.\n    rewrite <- IHl'.\n    fold.\nAbort.\n\n\n(*\n\n  *** Question 2\n\nReconstruire les fonctions [id], [concat], [rev] et [map] avec\n [foldl] et [foldl'].\n\nD\u00e9montrer les lemmes et th\u00e9or\u00e8mes qui\nsemblent les plus pertinents. Alterner des preuves pour [foldl]\n et des preuves pour [foldl']   ainsi que des preuves\n exploitant le th\u00e9or\u00e8me [foldl'_foldl] ci-dessus.\n\n*)\n\n", "meta": {"author": "ebtaleb", "repo": "SVP", "sha": "cac36c82a07248ccfc078207e43678b5f5b19e3d", "save_path": "github-repos/coq/ebtaleb-SVP", "path": "github-repos/coq/ebtaleb-SVP/SVP-cac36c82a07248ccfc078207e43678b5f5b19e3d/TD01/theme01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.9263037226647285, "lm_q1q2_score": 0.8428502469717616}}
{"text": "Require Import Lia.\n(* Note that we can talk about binary numbers by introducing\n   three new constructors; B0, B1, and the termination Z;\n    3_10 == B1 (B1 Z)_2 == S (S (S 0)_1 *)\n\nInductive bin : Type :=\n  | Z\n  | B0 (n : bin)\n  | B1 (n : bin).\n\nFixpoint incr (m : bin) : bin :=\n  match m with\n  | Z => B1 Z\n  | B0 m' => B1 m'\n  | B1 m'' => B0 (incr m'')\n  end.\n\nExample bin_incr1: (incr (B1 Z)) = B0 (B1 Z).\nProof. simpl. reflexivity. Qed.\n\nExample bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. simpl. reflexivity. Qed. \n\nExample bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. simpl. reflexivity. Qed.\n\nFixpoint bin_to_nat (m : bin) : nat :=\n  match m with\n  | Z => O\n  | B0 m' => 2 * (bin_to_nat m')\n  | B1 m'' => 2 * (bin_to_nat m'') + 1 \n  end.\n\nExample test_bin_incr6: \n  bin_to_nat (B0 (B0 (B0 (B1 Z)))) = S (S (S (S (S (S (S (S O))))))).\nProof. simpl. reflexivity. Qed.\n\n(* Proof that the increment function commutes *)\nTheorem bin_incr_nat_succ_commu:\n  forall (b : bin),\n  bin_to_nat (incr b) = (bin_to_nat b) + 1.\nProof.\n  induction b.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IHb. lia.\nQed.\n\n", "meta": {"author": "hanleyc01", "repo": "soft-foundations", "sha": "59f868db62de7629e8b14b449193c35f21debf12", "save_path": "github-repos/coq/hanleyc01-soft-foundations", "path": "github-repos/coq/hanleyc01-soft-foundations/soft-foundations-59f868db62de7629e8b14b449193c35f21debf12/src/more_exercices1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8427495567611377}}
{"text": "Parameter E : Set.\nParameters P Q : E -> Prop.\n\nLemma ex1_1 : (forall x : E, (P x) -> (Q x)) -> (exists x : E, (P x)) -> (exists x : E, (Q x)).\nintros.\nelim H0.\nintros.\nexists x.\napply H.\nassumption.\nQed.\n\nLemma ex1_2 : (exists x : E, (P x)) \\/ (exists x : E, (Q x)) -> exists x : E, (P x) \\/ (Q x).\nintros.\nelim H.\nintros.\nelim H0.\nintros.\nexists x.\nleft.\nassumption.\nintros.\nelim H0.\nintros.\nexists x.\nright.\nassumption.\nQed.\n\nRequire Import Lists.List.\n\nOpen Scope list_scope.\n\nLemma ex2_1 : forall (F : Set) (l1 l2 : list F), length (l1++l2) = (length l1) + (length l2).\nintros.\ninduction l1.\ninduction l2.\nauto.\nauto.\nsimpl.\nrewrite IHl1.\nauto.\nQed.\n\nInductive is_even : nat -> Prop :=\n| is_even_O : is_even 0\n| is_even_S : forall n : nat, is_even n -> is_even (S (S n)).\n\nInductive is_even_list : list nat -> Prop :=\n| is_even_zero : is_even_list nil\n| is_even_rec : forall (a : nat) (l : list nat), (is_even a) -> (is_even_list l) -> is_even_list (a::l).\n\nLemma ex3_2 : is_even_list (0::2::4::nil).\napply is_even_rec.\napply is_even_O.\napply is_even_rec.\napply is_even_S.\napply is_even_O.\napply is_even_rec.\napply is_even_S.\napply is_even_S.\napply is_even_O.\napply is_even_zero.\nQed.\n\nLemma ex3_3 : ~ is_even_list (0::1::2::4::nil).\nintro.\ninversion H.\ninversion H3.\ninversion H6.\nQed.\n\n", "meta": {"author": "thomasbernardi", "repo": "Formal-Methods-2018", "sha": "ea79b0012012b5e1eff32e6a548e67da26cb3b50", "save_path": "github-repos/coq/thomasbernardi-Formal-Methods-2018", "path": "github-repos/coq/thomasbernardi-Formal-Methods-2018/Formal-Methods-2018-ea79b0012012b5e1eff32e6a548e67da26cb3b50/controle1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.842749544471245}}
{"text": "From LF Require Export Logic.\nFrom LF Require Export Basics.\nRequire Coq.omega.Omega.\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n\nCheck ev_0.\nCheck ev_SS.\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(*Exercise 1*)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros. unfold double.\n  induction n as [|n'].\n  - apply ev_0.\n  - apply ev_SS. apply IHn'.\nQed.\n\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion  E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(*Exercise 2*)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n\n\n(*Exercise 3*)\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros. simpl. exfalso.\n  inversion H. inversion H1. inversion H3.\nQed.\n\nLemma ev_even_firsttry : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E. 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 *)\n\nAdmitted.\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n(*Exercise 4*)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m In Im. induction In.\n  - simpl. apply Im.\n  - simpl. apply ev_SS. apply IHIn.\nQed.\n\n\n(*Exercise 5*)\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros. split.\n  - intros. induction H.\n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum. apply IHev'1. apply IHev'2.\n  - intros. induction H.\n    + apply ev'_0.\n    + apply (ev'_sum 2).\n      * apply ev'_2.\n      * apply IHev.\nQed.\n\n(*Exercise 6*)\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros. induction H0.\n  simpl in H. apply H. apply IHev.\n  simpl in H. inversion H. apply H2.\nQed.\n  \n  \nLemma helper_ex7: forall n, ev(n + n).\nProof.\nintros. induction n. simpl. apply ev_0.\n simpl. rewrite <- plus_n_Sm. apply ev_SS. apply IHn.\nQed. \n\n(*Exercise 7*)\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\nintros.\n  apply ev_ev__ev with (n:=(n+n)).\n  - rewrite <- plus_assoc.\n    rewrite plus_assoc with (m:=m).\n    rewrite plus_comm.\n    rewrite <- plus_assoc.\n    rewrite plus_comm with (n:= p).\n    apply ev_sum. apply H. apply H0.\n  - apply helper_ex7. Qed.\n\nLemma helper: ev 1.\n  Proof. apply (ev_sum 1). Admitted.\n\n(*Exercise 8*)\nTheorem ex_mid_ev:\n  forall n, ev n \\/ ~ ev n.\n\nProof.\n  intros. assert (helper: (forall n, if evenb n then ev n else ~ ev n)).\n  { intros.  destruct n0. simpl. apply ev_0. \n    \n}Admitted.\n\n\n(*Exercise 9*)\nTheorem ev_n_not_ev_Sn:\n  forall n,\n  ev n -> ~ ev (S n).\n\nProof.\n  intros. unfold not. destruct n. \nAdmitted.\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/CA16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.9314625069680098, "lm_q1q2_score": 0.8426480457770321}}
{"text": "(** * Lists: Working with Structured Data *)\n\n(* REMINDER: Please do not put solutions to the exercises in\n   publicly accessible places! *)\n\nRequire Export Induction.\nModule NatList.\n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is one way to construct\n    a pair of numbers: by applying the constructor [pair] to two\n    arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n    pattern matches (indeed, we've seen it already in the previous\n    chapter -- this works because the pair notation is actually\n    provided as part of the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    doesn't generate an extra subgoal here.  That's because [natprod]s\n    can only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (By the way, it's worth noting in passing that expressions like \"[1\n   + 2 :: [3]]\" can be a little confusing when you read them in a .v\n   file.  The inner brackets, around 3, indicate a list, but the outer\n   brackets, which are invisible in the HTML rendering, are there to\n   instruct the \"coqdoc\" tool that the bracketed part should be\n   displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(** *** Repeat *)\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(** *** Length *)\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** *** Append *)\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(** *** Head (with default) and Tail *)\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n(** *** Exercises *)\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  (* FILL IN HERE *) admit.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n    all the elements of [a] and of [b].  (Mathematicians usually\n    define [union] on multisets a little bit differently, which\n    is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag :=\n  (* FILL IN HERE *) admit.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  (* FILL IN HERE *) admit.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_member1:             member 1 [1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_member2:             member 2 [1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  (* When remove_one is applied to a bag without the number to remove,\n     it should return the same bag unchanged. *)\n  (* FILL IN HERE *) admit.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  (* FILL IN HERE *) admit.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2:          count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3:          count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4:          count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  For\n    this, replace the [admit] command below with the statement of your\n    theorem. Note that, since this problem is somewhat open-ended,\n    it's possible that you may come up with a theorem which is true,\n    but whose proof requires techniques you haven't learned yet.  Feel\n    free to ask for help if you get stuck! *)\n\nTheorem bag_theorem :\n  (* FILL IN HERE *) admit.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the match\n    \"scrutinee\" in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ###################################################### *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n     (the induction hypothesis). We must show\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n     By the definition of [++], this follows from\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n     which is immediate from the induction hypothesis.  []\n*)\n\n(** *** Reversing a list *)\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** *** Proofs about reverse *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma.\n*)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n        length ([] ++ l2) = length [] + length l2,\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n        length (l1' ++ l2) = length l1' + length l2.\n      We must show\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n          length (rev []) = length [],\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n          length (rev l') = length l'.\n        We must show\n          length (rev (n :: l')) = length (n :: l').\n        By the definition of [rev], this follows from\n          length ((rev l') ++ [n]) = S (length l')\n        which, by the previous lemma, is the same as\n          length (rev l') + length [n] = S (length l').\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [SearchAbout] command is quite helpful with this.  Typing\n    [SearchAbout foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following to\n    see a list of theorems that we have proved about [rev]: *)\n\n(*  SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [SearchAbout] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next 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  (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\n(* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs)  *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n(There is a hard way and an easy way to do this.)\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short...\n    *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** This example is also an opportunity to introduce one more\n    small feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually allows conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  (* FILL IN HERE *) admit.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ###################################################### *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish.\n\n    We'll also need an equality test for [id]s: *)\n\nDefinition beq_id x1 x2 :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nImport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (key : id) (value : nat)\n                  : partial_map :=\n  record key value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (key : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record k v d' => if beq_id key k\n                     then Some v\n                     else find key d'\n  end.\n\n\n(** *** *)\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (k : id) (v: nat),\n    find k (update d k v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (m n : id) (o: nat),\n    beq_id m n = false -> find m (update d n o) = find m d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** $Date: 2016-01-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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.9324533097989076, "lm_q1q2_score": 0.8422796703357118}}
{"text": "(* -------------------------------------- Homework 3 --------------------------------------\n * Partners: David Klock, Kartikeya Bhardwaj\n *)\n\nRequire Import Frap.\n\n(* --- SECTION 1: An alternate defenition of trc --- *)\n\n(* Consider the following alternative definition of trc. *)\n\nInductive different_trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| DiffTrcRefl : forall x, different_trc R x x\n| DiffTrcBack : forall x y z,\n    different_trc R x y ->\n    R y z ->\n    different_trc R x z.\n\n(* PROBLEM 1 [5 points, ~2 sentences]\n * Describe what's different between `trc` and `different_trc`.  Then explain briefly\n * and intuitively why they are equivalent.\n *\n * Hint: To have a coherent answer, you'll probably need to look at the definition of\n * `trc` again.\n *\n * Hint: The names of the constructors are useful to think about.\n *)\n(* trc's TrcFront differs from different_trc's DiffTrcBack.  TrcFront states\n   that if x can *step to* y, and if y can *reach* z, then x can reach z.\n   DiffTrcBack flips this -- it states that if x can *reach* y, and y can\n   *reach* z, then x can reach z.\n\n   These are the same; they just reverse the order of induction.  TrcFront has\n   one induct *forwards* from x, toward z.  DiffTrcBack has one induct *backwards*\n   from z, toward x. *)\n\n\n(* Now we have an intuitive understanding of why `trc` and `different_trc` are\n * equivalent. Let's prove it!\n *)\n\n(* PROBLEM 2 [5 points, ~10 tactics]\n * Prove the first half of the equivalence, that `different_trc` implies `trc`.\n *\n * Hint: Proceed by induction on the evidence of `different_trc`.\n *\n * Hint: Remember the rules of thumb for working with inductive predicates.\n * In the goal, you might find `constructor` or `econstructor` useful,\n * or you can use `apply`/`eapply` with the name of the constructor.\n *\n * Hint: You might find the lemma `trc_trans` useful with `eapply`.\n *)\nLemma R_x_y_implies_trc_R_x_y :\n  forall A (R : A -> A -> Prop) x y,\n    R x y -> trc R x y.\nProof.\n  intros.\n  assert (trc R y y).\n  - apply TrcRefl.\n  - eapply TrcFront.\n    + apply H.\n    + apply TrcRefl.\nQed.\n\nTheorem different_trc_implies_trc :\n  forall A (R : A -> A -> Prop) x y,\n    different_trc R x y ->\n    trc R x y.\nProof.\n  induct 1.\n  + apply TrcRefl.\n  + eapply trc_trans.\n    - apply IHdifferent_trc.\n    - apply R_x_y_implies_trc_R_x_y.\n      assumption.\nQed.\n\n(* PROBLEM 3 [5 points, ~20 tactics]\n * Now prove the second half of the equivalence, that `trc` implies `different_trc`.\n *\n * Hint: Proceed by induction on the evidence of `trc`.\n *\n * Hint: `trc_trans` was useful in the previous problem. You might consider proving\n * an analogous helper lemma for `different_trc`. Be *extremely* careful stating this\n * lemma deciding how to prove it, since there are lots of pitfalls.\n *\n * Hint: There's more than one way to do it, so feel free to explore approaches that\n * are not analogous to your proof of the previous problem.\n *\n * Hint: Ask for help if you're stuck!!\n *)\n\nTheorem different_trc_trans :\n  forall {A} (R : A -> A -> Prop) y z,\n    different_trc R y z ->\n      forall x,\n        different_trc R x y ->\n          different_trc R x z.\nProof.\n  induct 1.\n  - intros. assumption.\n  - intros. eapply DiffTrcBack.\n    + apply IHdifferent_trc.\n      assumption.\n    + assumption.\nQed.\n\nLemma R_x_y_implies_different_trc_R_x_y :\n  forall A (R : A -> A -> Prop) x y,\n    R x y -> different_trc R x y.\nProof.\n  intros.\n  assert (different_trc R y y).\n  - apply DiffTrcRefl.\n  - eapply DiffTrcBack.\n    + apply DiffTrcRefl.\n    + apply H.\nQed.\n\nTheorem trc_implies_different_trc_implies :\n  forall A (R : A -> A -> Prop) x y,\n    trc R x y ->\n    different_trc R x y.\nProof.\n  induct 1.\n  + apply DiffTrcRefl.\n  + eapply different_trc_trans.\n    - apply IHtrc.\n    - apply R_x_y_implies_different_trc_R_x_y.\n      assumption.\nQed.\n\n\n(* --- SECTION 2: Inductive predicates for \"and\" and \"or\" --- *)\n\n(* Very very few things are \"built in\" to Coq. We have already seen that numbers and booleans\n * are not built in, but defined in the standard library as inductive types. In fact, even\n * basic logical connectives such as \"and\" and \"or\" are not built in, but are also defined\n * in the standard library as inductive predicates. Let's explore these definitions a bit.\n *)\n\n(* Here is an inductive definition of \"and\" (called `my_and` just so it doesn't conflict\n * with the definition of `and` from the standard library).\n *)\nInductive my_and (A B : Prop) : Prop :=\n| MakeAnd : A -> B -> my_and A B.\n\n(* And here's a simple proof about `my_and`, which says \"if you give me evidence of\n * `my_and A B`, I can give you evidence of A\".\n *)\nLemma my_and_project1 :\n  forall A B : Prop,\n    my_and A B ->\n    A.\nProof.\n  simplify.\n\n  (* rule of thumb: (non-recursive) inductively defined predicate above the line, use `invert` *)\n  invert H.\n\n  (* now we have a hypothesis showing `A`! *)\n  assumption.\nQed.\n\n(* PROBLEM 4 [5 points, ~2 sentences]\n * Using your mental model for what `invert` does, explain why `invert H` adds two hypotheses,\n * one for `A` and one for `B`.\n *)\n(* `invert` determines what facts are implied (in the logical sense of implication)\n   by a hypothesis, and adds them as hypotheses.  In this case, my_and A B is implied\n   by A and B, so `invert` deduces that they must be true as well. *)\n\n(* PROBLEM 5 [2 points, ~4 tactics]\n * Prove the analogous property about `my_and` and its second argument.\n *\n * Hint: Similar to above. It's supposed to be easy :)\n *)\nLemma my_and_project2 :\n  forall A B : Prop,\n    my_and A B ->\n    B.\nProof.\n  simplify.\n  invert H.\n  assumption.\nQed.\n\n\n(* PROBLEM 6 [3 points, ~6 tactics]\n * Prove that you can swap arguments to `my_and`.\n *\n * Hint: You'll need to use the rules of thumb for inductive predicates above the line\n * (like the previous problem) *and* below the line (described in the hints to\n * problem `different_trc_implies_trc`).\n *)\nLemma my_and_swap :\n  forall A B : Prop,\n    my_and A B ->\n    my_and B A.\nProof.\n  intros.\n  invert H.\n  constructor.\n  - assumption.\n  - assumption.\nQed.\n\n(* Here's a defenition of \"or\". *)\nInductive my_or (A B : Prop) : Prop :=\n| OrFirst : A -> my_or A B\n| OrSecond : B -> my_or A B.\n\n(* PROBLEM 7 [5 points, ~3 sentences]\n * Explain why the proof we used for `my_and_project1` doesn't work for `my_or`.\n *\n * Structure your explanation in two parts: (1) a low-level explanation of why `invert`\n * behaves differently with `my_or` compared to `my_and`; (2) a high-level explanation\n * of why the lemma statement of `my_or_project1` is just not provable.\n *\n * Hint: Start by trying to use the same proof from `my_and_project1` and see where\n * you get stuck. Then base your low-level explanation on that experience.\n *)\nLemma my_or_project1 :\n  forall A B : Prop,\n    my_or A B ->\n    A.\nProof.\n  simplify.\n  invert H.\n  + assumption.\n  + \nAbort.\n(* my_or has two constructors, unlike my_and.  We know by hypothesis that my_or A B\n   is true, but we don't know which constructor was used to prove it.  `invert`\n   therefore requires that we prove that A follows *regardless* of which constructor\n   was used.  And that cannot be proven for OrSecond.\n\n   At a higher level, that this cannot be proven is obvious.  We are asked to prove\n   that if (A || B) is true, A must be true.  Manifestly, though, (A || B) can be\n   true when A is false and B is true, a counterexample. *)\n\n\n(* PROBLEM 8 [2 points, ~7 tactics]\n * Prove that you can swap arguments to `my_or`.\n *\n * Hint: Use your rules of thumb.\n *)\nLemma my_or_swap :\n  forall A B : Prop,\n    my_or A B ->\n    my_or B A.\nProof.\n  intros.\n  invert H.\n  + apply OrSecond. assumption.\n  + apply OrFirst. assumption.\nQed.\n\n(* PROBLEM 9 [3 points, ~15 tactics]\n * Prove the following relationship between `my_and` and `my_or`.\n *\n * Hint: Use your rules of thumb.\n *)\nLemma and_or_distr :\n  forall A B C : Prop,\n    my_and A (my_or B C) ->\n    my_or (my_and A B) (my_and A C).\nProof.\n  intros.\n  invert H.\n  invert H1.\n  - apply OrFirst. constructor.\n    + assumption.\n    + assumption.\n  - apply OrSecond. constructor.\n    + assumption.\n    + assumption.\nQed.\n\n\n(* --- SECTION 3: Transition systems and inductive invariants --- *)\n\n(* In lecture 5 we looked at some transition systems that incremented numbers.\n * In the next two sections, we'll look at a transition the decrements two numbers.\n *\n * Consider the following pseudocode:\n *\n *     // initially x can be any non-negative number\n *     y = 42\n *     done = false\n *     while x > 0:\n *         x = x - 1\n *     while y > 0:\n *         y = y - 1\n *     done = true\n *     assert x == 0\n *\n * After initializing y and done, it decrements x until x is 0. Then, it decrements y\n * until it's 0. We'd like to prove that the assert at the end is always true.\n *\n * Let's encode this as a transition system. We need to define the state, initial predicate,\n * and step relation.\n *)\n\n(* Our state will consist of the values of the three variables x, y, and done. *)\nRecord decr_state : Type := {\n  var_x : nat;\n  var_y : nat;\n  var_done: bool\n}.\n\n(* Initially, x is arbitrary, y is 42, and done is false. *)\nInductive decr_init : decr_state -> Prop :=\n| DecrInit :  forall nx, decr_init {| var_x := nx; var_y := 42; var_done := false |}.\n\n(* PROBLEM 10 [3 points, ~4 LOC]\n * Give an alternate definition of decr_init using Definition instead of Inductive.\n *)\nDefinition decr_init_alternative (s : decr_state) : Prop :=\n  exists nx,\n    s = {| var_x := nx; var_y := 42; var_done := false |}.\n\n(* PROBLEM 11 [5 points, ~10 tactics]\n * Prove your alternative definition equivalent to the original.\n *)\nLemma decr_init_alternative_ok :\n  forall s,\n    decr_init_alternative s <-> decr_init s.\nProof.\n  intros.\n  unfold decr_init_alternative.\n  constructor.\n  + propositional.\n    invert H.\n    constructor.\n  + propositional.\n    invert H.\n    eexists.\n    equality.\nQed.\n\n(* Ok, back to encoding that program as a transition system. We're ready for the step relation.\n * There are three steps:\n *   - if x is not yet 0, we can decrement it\n *   - if x is 0, but y isn't, we can decrement y, leaving x alone\n *   - if y is 0, we set done to true\n * This is encoded with the following inductive definition.\n *)\nInductive decr_step : decr_state -> decr_state -> Prop :=\n| decr_x : forall n_x n_y, decr_step {| var_x := S n_x; var_y := n_y; var_done := false |}\n                                {| var_x := n_x; var_y := n_y; var_done := false|}\n| decr_y : forall n_y, decr_step {| var_x := 0; var_y := S n_y; var_done := false |}\n                            {| var_x := 0; var_y := n_y; var_done := false|}\n| decr_var_done : forall n_x, decr_step {| var_x := n_x; var_y := 0; var_done := false |}\n                                   {| var_x := n_x; var_y := 0; var_done := true |}.\n\n(* Packaging things up into a transition system . *)\nDefinition decr_sys : trsys decr_state := {|\n  Initial := decr_init;\n  Step := decr_step\n|}.\n\n(* The safety property we want to prove is that when done is true, x is 0. *)\nDefinition decr_safe (s : decr_state) : Prop :=\n  match s with\n  | {| var_x := nx; var_y := ny; var_done := true |} => nx = 0\n  | _ => True\n  end.\n\n(* PROBLEM 12 [15 points, ~30 tactics total, including 1 helper lemma]\n * Prove this transition system safe.\n *\n * Hint: First try to proceed directly by induction (using `apply invariant_induction`).\n * Think about how you get stuck in the inductive case.\n *\n * Hint: State your strengthened invariant and prove it as a helper lemma by induction.\n * Then use `invariant_weaken` to show decr_safe is also an invariant.\n *\n * Hint: As always, finding the right strengthened invariant is the hard part. It took\n * me a couple tries to get it right. Ask for help if you're stuck!\n *)\nDefinition decr_safe_strong (s : decr_state) : Prop :=\n  match s with\n  | {| var_x := nx; var_y := 0; var_done := _|} => nx = 0\n  | {| var_x := nx; var_y := S _; var_done := true|} => False\n  | _ => True\n  end.\n\nTheorem decr_ok_strong :\n  invariantFor decr_sys decr_safe_strong.\nProof.\n  apply invariant_induction.\n  + intros. invert H. unfold decr_safe_strong. trivial.\n  + intros. invert H0.\n    - unfold decr_safe_strong. cases n_y.\n      * invert H.\n      * trivial.\n    - unfold decr_safe_strong. cases n_y.\n      * equality.\n      * trivial.\n    - unfold decr_safe_strong. invert H. trivial.\nQed.\n\nTheorem decr_ok :\n  invariantFor decr_sys decr_safe.\nProof.\n  apply invariant_weaken with (invariant1 := decr_safe_strong).\n  + apply decr_ok_strong.\n  + intros.\n    unfold decr_safe.\n    unfold decr_safe_strong in H.\n    cases s.\n    cases var_done0.\n    - cases var_y0.\n      * assumption.\n      * equality.\n    - trivial.\nQed.\n\n\n(* --- SECTION 4: Abstraction and model checking --- *)\n\n(* Let' prove this invariant a different way, by using abstraction and model checking\n * to avoid having to come up with the strengthening ourselves.\n *\n * Notice that the system only really distinguishes zero and nonzero numbers. We can\n * use that to build a boolean abstraction of x and y, that just remembers whether they\n * are 0 or not.\n *\n * Here's the definition of an abstract transition system.\n *)\n\nRecord decr_bool_state : Type := {\n  var_x_bool : bool;\n  var_y_bool : bool;\n  var_done_bool : bool\n}.\n\n(* There are now five steps, since when decrementing a variable, we distinguish between\n * whether the new value is zero or nonzero, so we get two steps for each decrement step\n * in the original system.\n *)\nInductive decr_bool_step : decr_bool_state -> decr_bool_state -> Prop :=\n| decr_bool_x_more : forall b_y, decr_bool_step\n                              {| var_x_bool := false; var_y_bool := b_y; var_done_bool := false |}\n                              {| var_x_bool := false; var_y_bool := b_y; var_done_bool := false|}\n| decr_bool_x_done : forall b_y, decr_bool_step\n                              {| var_x_bool := false; var_y_bool := b_y; var_done_bool := false |}\n                              {| var_x_bool := true; var_y_bool := b_y; var_done_bool := false|}\n| decr_bool_y_more : decr_bool_step\n                       {| var_x_bool := true; var_y_bool := false; var_done_bool := false |}\n                       {| var_x_bool := true; var_y_bool := false; var_done_bool := false|}\n| decr_bool_y_done : decr_bool_step\n                       {| var_x_bool := true; var_y_bool := false; var_done_bool := false |}\n                       {| var_x_bool := true; var_y_bool := true; var_done_bool := false|}\n| decr_bool_done : forall b_x, decr_bool_step\n                            {| var_x_bool := b_x; var_y_bool := true; var_done_bool := false |}\n                            {| var_x_bool := b_x; var_y_bool := true; var_done_bool := true |}.\n\nInductive decr_bool_init : decr_bool_state -> Prop :=\n| DecrBoolInit :  forall bx, decr_bool_init {| var_x_bool := bx; var_y_bool := false; var_done_bool := false |}.\n\nDefinition decr_bool_sys := {|\n  Initial := decr_bool_init;\n  Step := decr_bool_step\n|}.\n\n(* Our next task is to prove that this actually *is* an abstraction of the original.\n * For that, we'll use a simulation argument, so we need to define a simulation relation.\n *\n * The core of this abstraction is that the boolean version of x captures whether x is 0.\n * We formalize this as follows.\n *)\nInductive decr_R_var : nat -> bool -> Prop :=\n| decr_R_var_O : decr_R_var O true\n| decr_R_var_S : forall n, decr_R_var (S n) false.\n\n(* PROBLEM 13 [3 points, ~6 tactics]\n * Prove the following lemma about decr_R_var, which says that for any natural number n,\n * n is abstracted by the boolean `Nat.eqb n 0`. (Nat.eqb is a function that compares\n * two natural numbers for equality, returning a boolean.)\n *\n * Hint: Proceed by *case analysis* on whether `n` is zero or not.\n *)\nLemma decr_R_var_eqb :\n  forall n,\n    decr_R_var n (Nat.eqb n 0).\nProof.\n  intros.\n  cases n.\n  - simplify. constructor.\n  - simplify. constructor.\nQed.\n\n\n(* A state of the original system is related to an abstract state if x and y are related\n * by decr_R_var and the value of done is identical.\n *)\nInductive decr_R : decr_state -> decr_bool_state -> Prop :=\n| Decr_R : forall n_x n_y b_x b_y done,\n    decr_R_var n_x b_x ->\n    decr_R_var n_y b_y ->\n    decr_R {| var_x := n_x; var_y := n_y; var_done := done |}\n           {| var_x_bool := b_x; var_y_bool := b_y; var_done_bool := done |}.\n\n\n(* PROBLEM 14 [7 points, ~65 tactics]\n * Prove that decr_R is a simulation relation for these two systems.\n *)\nLemma decr_sim :\n  simulates decr_R decr_sys decr_bool_sys.\nProof.\n  constructor.\n  - intros.\n    cases st1.\n    cases var_x0.\n    + eexists.\n      constructor.\n      * constructor.\n        -- constructor.\n        -- invert H. constructor.\n      * assert (var_done0 = false).\n        -- invert H. equality.\n        -- rewrite H0. constructor.\n    + eexists.\n      constructor.\n      * constructor.\n        -- constructor.\n        -- invert H. constructor.\n      * assert (var_done0 = false).\n        -- invert H. equality.\n        -- rewrite H0. constructor.\n- intros.\n    cases st1.\n    cases var_x0; cases var_y0; cases var_done0.\n    + invert H0.\n    + eexists.\n      propositional; invert H0; invert H; invert H4; invert H5; constructor; constructor.\n    + invert H0.\n    + cases var_y0; eexists;\n      propositional; invert H0; invert H; invert H4; invert H5; constructor; constructor.\n    + invert H0.\n    + cases var_x0; simplify; propositional; invert H0; eexists;\n      propositional; invert H; invert H4; invert H5; constructor; constructor.\n    + invert H0.\n    + cases var_x0; cases var_y0; eexists;\n      propositional; invert H; invert H5; invert H6; invert H0; constructor; constructor.\nQed.\n\n(* Ok, the tedious part is over. Now we can prove the original system safe\n * using model checking on the abstract system. But first, we need to express\n * the initial states of the abstract system as a finite set.\n *)\nLemma decr_bool_sys_init_set :\n  decr_bool_init = { {| var_x_bool := true; var_y_bool := false; var_done_bool := false |},\n                     {| var_x_bool := false; var_y_bool := false; var_done_bool := false |}\n                   }.\nProof.\n  apply sets_equal; simplify.\n  propositional; subst.\n  - invert H. destruct bx; equality.\n  - constructor.\n  - constructor.\nQed.\n\n(* This line registers the lemma so that the model checker knows about it. *)\nHint Rewrite decr_bool_sys_init_set.\n\n(* PROBLEM 15 [3 points, ~20 additional tactics]\n * Prove the system safe again, this time using model checking and abstraction.\n *)\nTheorem decr_ok_via_simulation :\n  invariantFor decr_sys decr_safe.\nProof.\n  eapply invariant_weaken with (invariant1 := invariantViaSimulation decr_R _).\n  - apply invariant_simulates with (sys2 := decr_bool_sys).\n    + apply decr_sim.\n    + model_check_infer.\n  - intros.\n    invert H. invert H1.\n    + invert H0. constructor.\n    + invert H0.\n      invert H1; invert H2; invert H; invert H0;\n      try cases done; try constructor; invert H; invert H0.\nQed.\n\n\n(* --- SECTION 5: Operational semantics for expressions --- *)\n\n(* To practice with operational semantics, let's explore using them to define the meaning\n * of arithmetic expressions, instead of using an interpreters.\n *)\n\n(* Here's a copy of our old friend again. *)\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\nDefinition valuation := fmap var nat.\n\n(* And here's the interpreter again. *)\nFixpoint interp (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match v $? x with\n    | None => 0\n    | Some n => n\n    end\n  | Plus e1 e2 => interp e1 v + interp e2 v\n  | Minus e1 e2 => interp e1 v - interp e2 v\n  | Times e1 e2 => interp e1 v * interp e2 v\n  end.\n\n(* First, let's see how give meaning to arithmetic expressions via a big-step operational semantics. *)\n\n(* PROBLEM 16 [3 points, ~20 LOC]\n * Complete the definition of arith_eval. The final definition will need one constructor\n * for every constructor of `arith`. We have filled in the first one for you.\n *\n * Hint: Notice how similar the case we did for you is to the corresponding case in `interp`.\n * They should all be that similar.\n *\n * Hint: It is hard to know if you got this definition right except by trying to prove the\n * problems before.\n *)\nInductive arith_eval : valuation -> arith -> nat -> Prop := (* this semantics relates a valuation and an expression to its value (a nat) *)\n| ArithEvalConst : forall v n, arith_eval v (Const n) n  (* think of this as: \"in any valuation, Const n evaluates to n\" *)\n| ArithEvalVar : forall v x, arith_eval v (Var x) (interp (Var x) v)\n| ArithEvalPlus :\n  forall v e1 e2 n1 n2,\n    arith_eval v e1 n1 -> arith_eval v e2 n2 -> arith_eval v (Plus e1 e2) (n1 + n2)\n| ArithEvalMinus :\n  forall v e1 e2 n1 n2,\n    arith_eval v e1 n1 -> arith_eval v e2 n2 -> arith_eval v (Minus e1 e2) (n1 - n2)\n| ArithEvalTimes :\n  forall v e1 e2 n1 n2,\n    arith_eval v e1 n1 -> arith_eval v e2 n2 -> arith_eval v (Times e1 e2) (n1 * n2)\n.\n(* TODO: Is this right? *)\n\n(* Now we have two different semantics for arithmetic expressions: `interp` and `arith_eval`.\n * Let's prove that these two semantics agree.\n *)\n\n(* PROBLEM 17 [2 points, ~25 tactics, or many fewer using semicolons]\n * Prove the first half of the equivalence, that `interp` implies `arith_eval`.\n *\n * Hint: Proceed by induction on e.\n *)\nLemma interp_eval :\n  forall v e n,\n    interp e v = n ->\n    arith_eval v e n.\nProof.\n  induct e; intros; simplify; invert H.\n  + constructor.\n  + cases (v $? x).\n    - assert (n = interp (Var x) v).\n      * simplify. rewrite Heq. equality.\n      * rewrite H. constructor.\n    - assert (0 = interp (Var x) v).\n      * simplify. rewrite Heq. equality.\n      * rewrite H. constructor.\n  + econstructor.\n    - apply IHe1. equality.\n    - apply IHe2. equality.\n  + econstructor.\n    - apply IHe1. equality.\n    - apply IHe2. equality.\n  + econstructor.\n    - apply IHe1. equality.\n    - apply IHe2. equality.\nQed.\n\n\n(* PROBLEM 18 [3 points, ~10 tactics, or many fewer using semicolons]\n * Prove the second half of the equivalence, that `arith_eval` implies `interp`.\n *\n * Hint: Proceed by induction on e.\n *)\nLemma eval_interp :\n  forall v e n,\n    arith_eval v e n ->\n    interp e v = n.\nProof.\n  induct e; intros; simplify; invert H.\n  + equality.\n  + simplify. equality.\n  + f_equal.\n    - apply IHe1 in H3. assumption.\n    - apply IHe2 in H5. assumption.\n  + f_equal.\n    - apply IHe1 in H3. assumption.\n    - apply IHe2 in H5. assumption.\n  + f_equal.\n    - apply IHe1 in H3. assumption.\n    - apply IHe2 in H5. assumption.\nQed.\n\n\n(* We can also give a small-step operational semantics to arithmetic expressions. *)\n(* PROBLEM 19 [5 points, ~30 LOC]\n * Fill in the definition of `arith_step`. In this semantics, an expression is \"done\"\n * running when it is a `Const`.\n *\n * Hint: You'll need a constructor saying how to finish evaluating a Var.\n *\n * Hint: You'll need two more constructors for Plus, one for \"making progress on the left\"\n * and one for \"making progress on the right\". These should be vaguely similar to `StepSeq1`\n * in OperationalSemantics.v.\n *\n * Hint: Minus and Times are analogous to Plus.\n *\n * Hint: You don't need a constructor corresponding to Const (for the same reason we don't\n * have a constructor corresponding to Skip in OperationalSemantics.v).\n *\n * Hint: It is hard to know if you got this definition right except by trying to prove the\n * problems before.\n *)\nInductive arith_step : valuation -> arith -> arith -> Prop := (* this semantics relates a valuation and an expression to a \"next\" expression *)\n\n| ArithStepPlus : forall v n1 n2,\n    arith_step v (Plus (Const n1) (Const n2)) (Const (n1 + n2))\n| ArithStepPlusLeft : forall v e1 e2 e1',\n    arith_step v e1 e1' -> arith_step v (Plus e1 e2) (Plus e1' e2)\n| ArithStepPlusRight : forall v n1 e2 e2',\n    arith_step v e2 e2' -> arith_step v (Plus (Const n1) e2) (Plus (Const n1) e2')\n| ArithStepMinus : forall v n1 n2,\n    arith_step v (Minus (Const n1) (Const n2)) (Const (n1 - n2))\n| ArithStepMinusLeft : forall v e1 e2 e1',\n    arith_step v e1 e1' -> arith_step v (Minus e1 e2) (Minus e1' e2)\n| ArithStepMinusRight : forall v n1 e2 e2',\n    arith_step v e2 e2' -> arith_step v (Minus (Const n1) e2) (Minus (Const n1) e2')\n| ArithStepTimes : forall v n1 n2,\n    arith_step v (Times (Const n1) (Const n2)) (Const (n1 * n2))\n| ArithStepTimesLeft : forall v e1 e2 e1',\n    arith_step v e1 e1' -> arith_step v (Times e1 e2) (Times e1' e2)\n| ArithStepTimesRight : forall v n1 e2 e2',\n    arith_step v e2 e2' -> arith_step v (Times (Const n1) e2) (Times (Const n1) e2')\n| ArithStepVar : forall v x,\n    arith_step v (Var x) (Const (interp (Var x) v))\n.\n(* TODO: Is this right? *)\n\n(* Let's prove the small step semantics equivalent to the big step. *)\n\n(* PROBLEM 20 [8 points, ~90 tactics total, including 6 helper lemmas]\n * Prove the first half of the equivalence, that the big step implies the\n * (transitive-reflexive closure of) the small step.\n *)\nLemma arith_eval_step :\n  forall v e n,\n    arith_eval v e n ->\n    (arith_step v)^* e (Const n).\nProof.\n  induct 1.\n  - constructor.\n  - econstructor.\n    + econstructor.\n    + econstructor.\n  - econstructor.\n    + admit.\n    + econstructor.\n  - econstructor.\n    + admit.\n    + econstructor.\n  - econstructor.\n    + admit.\n    + econstructor.\nAdmitted. (* Change to Qed when done *)\n\n\n(* PROBLEM 21 [8 points, ~65 tactics total, including 2 helper lemmas]\n * Prove the second half of the equivalence, that the (transitive-reflexive closure of)\n * the small step implies the big step.\n *)\nLemma arith_step_eval :\n  forall v e n,\n    trc (arith_step v) e (Const n) ->\n    arith_eval v e n.\nProof.\n  induct 1.\n  - econstructor.\n  - invert H. invert H0.\n      + econstructor.\n      + invert H. \n      + invert H0. invert H1. invert H. invert H2. econstructor. invert H.\nAdmitted. (* Change to Qed when done *)\n", "meta": {"author": "KartikeyaBh", "repo": "principles_of_programming_languages", "sha": "7070e90d127e4e9c3c7c69d899e42a5a51747c86", "save_path": "github-repos/coq/KartikeyaBh-principles_of_programming_languages", "path": "github-repos/coq/KartikeyaBh-principles_of_programming_languages/principles_of_programming_languages-7070e90d127e4e9c3c7c69d899e42a5a51747c86/HW3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.9230391621868804, "lm_q1q2_score": 0.8422143135113443}}
{"text": "From LF Require Export Basics.\n\nTheorem add_0_l_firsttry: forall n:nat,\n  0 + n = n.\nProof. simpl. reflexivity. Qed.\n(** it can be done simply with reflexivity.**)\n\n\nTheorem add_0_r_firsttry: forall n:nat,\n  n + 0 = n.\nProof.\n  intros n.\n  destruct n as [|n'] eqn:E.\n  - simpl. reflexivity.\n  - simpl. Abort.\n(** If we try to use reflexivity\nabove, we get Unable to unify \"S n\" with \"S (n + 0)\" \nbecause S n is a inductive type, we would need to\ndestruct it again. **)\n\n(** Given a proposition P, we need to:\n  1 - show that P(O) holds; \n  2 - show that, for any n', if P(n') holds, then so does P(S n'); \n  conclude that P(n) holds for all n. \n**)\n\nTheorem add_0_r : forall n: nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n' IHn']. (*n: the arbitrary natural number, IHn': the inductive hypothesis.*)\n  - reflexivity.\n  - simpl.\n    rewrite IHn'. reflexivity. Qed.\n\n(**\n  the inductive tactics here replaces n' + 0 = n' by S n' + 0 = S n',\n  what is: we are effectively applying the second criteria we defined\n  from the principle of Induction.\n**)\n\nTheorem minus_n_n : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite <- IHn'. simpl. reflexivity. Qed.\n\n(** Exercise 1 - basic induction, 2 stars **)\nTheorem mul_0_r: forall n: nat, n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - induction m as [| m' IHm'].\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. rewrite <- IHn'. \n    reflexivity.\n  Qed.\n\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros m n.\n  induction n as [| n' IHn'].\n  - rewrite add_0_r. reflexivity.\n  - simpl. \n    rewrite <- plus_n_Sm. \n    rewrite IHn'. \n    reflexivity.\n  Qed.\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  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\n  Qed.\n\n(** Exercise 2 - double plus, 2 stars**)\n\nFixpoint double (n: nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n\n(** Use induction to prove this fact **)\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.\n  Qed.\n\n\n(**\nFixpoint even (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => even n'\n  end.\n**)\n\n(** Optional exercise - using induction to prove a lemma about even function **)\nTheorem even_S : forall n : nat,\n  even (S n) = negb (even n).\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite IHn'. \n    rewrite negb_involutive. \n    simpl. reflexivity.\nQed.\n\n(** Differences destruct and induction **)\n\n(**\n  \n  TL;DR Their main difference is the subgoal hypothesis.  \n  \n  The destruct tactic gives us a subgoal for each constructor of \n  an inductive type. It means that we have to prove that a proposition\n  holds for both O or S n' for a nat type, for example.\n  This creates as many goals as there are constructors in type T.\n  \n  On the other hand, induction generates subgoals as many as \n  there are constructors, and adds the inductive hypotheses in \n  the contexts. \n  \n**)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n(** Assert is a way to create a quick proof\n  about some statement, that is used in the goal\n  we are trying to prove. \n\n  Assert generates:\n  1 - A subgoal where we must prove the asserted fact\n  2 - A second subgoal where we can use the asserted \n  fact to make progress on whatever we were trying to \n  prove in the first place. \n**)\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n). { reflexivity. }\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* We just need to swap (n + m) for (m + n)... seems\n     like add_comm should do the trick! *)\n  rewrite add_comm.\n  (* Doesn't work... Coq rewrites the wrong plus! :-( *)\nAbort.\n\n(** To use [add_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    [add_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 add_comm. reflexivity. }\n  rewrite H. reflexivity.  Qed.\n\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(* TODO *)\n\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** In the theorem below, assert helps us\n  to change the order of elements; after \n  the two rewrites, we get n + m + p = m + n + p\n  what is, we only need to change the positions\n  of m and n, so assert does it for us here.\n  Basically we use the same hypothesis defined\n  previously, but we are kind of telling\n  Coq how to replace stuff properly.**)\n\nTheorem add_shuffle3: forall n m p: nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.  \n  rewrite add_assoc. \n  rewrite add_assoc. \n  assert (H: n + m = m + n).\n  { rewrite add_comm. reflexivity. }\n  rewrite H. reflexivity.\nQed.\n\n\n(** Commutativity of multiplication **)\n\n(**\n  Before proving the commutativity of multiplication, we have\n  to prove that the multiplication distributes over addition.\n**)\n\nTheorem mul_dist: forall n m: nat,\n  n * (S m) = n + n * m.\n  intros n m.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. \n    rewrite add_shuffle3. \n    reflexivity.\n  Qed.\n\n\nTheorem mul_comm: forall n m: nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction n as [| n' IHn'].\n  - simpl. rewrite mul_0_r. reflexivity.\n  - simpl. \n    rewrite IHn'.\n    rewrite mul_dist. \n    reflexivity.\n    Qed.\n\n(** \n  The goal for the exercises below is to \n  think about the necessity for the use of\n  simplification and rewriting, case analysis\n  (destruct) or if it also requires induction.\n  \n  My hypothesis: when the case is covered in the\n  definition, it can be checked with simpl, which\n  does an \"unfolding\".\n **)\n\nCheck leb.\n\n(** Requires induction bc is an arbitrary number **)\nTheorem leb_refl: forall n: nat,\n  (n <=? n) = true.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\n  Qed.\n\n(** simpl, because this case is defined\n   **)\n\nTheorem zero_neqb_S : forall n:nat,\n  0 =? (S n) = false.\nProof. (*simp: same as unfold eqb here*)\n  simpl. reflexivity.\nQed.\n\n(** case analysis bc the match takes\n  the first argument first **)\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\n\n(* Induction and rewrite (?) *)\nTheorem plus_leb_compat_l : forall n m p : nat,\n  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n  intros n m p H.\n  induction p as [| p' IHp'].\n  - simpl. rewrite H. reflexivity.\n  - simpl. rewrite IHp'. reflexivity.\n  Qed.\n\n(* simpl, because this case is already defined in eqb *)\nTheorem S_neqb_0 : forall n:nat,\n  (S n) =? 0 = false.\nProof.\n  simpl. reflexivity. Qed.\n\n(**\n  Needs induction, to create a hypothesis that\n  holds for both 0 and S n.\n**)\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite add_comm. reflexivity.\nQed. \n\n(* Case analysis *)\nTheorem all3_spec : forall b c : bool,\n  orb\n    (andb b c)\n    (orb (negb b)\n         (negb c))\n  = true.\nProof.\n  intros b c.\n  destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  Qed.\n\n(* Rewrite with mult_dist after induction on n *)\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'.\n    rewrite add_assoc.\n    reflexivity.\n  Qed.\n\n(* Induction on n', rewrite *)\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'.\n    rewrite mult_plus_distr_r.\n    reflexivity.\n  Qed.\n    \n(** [] *)\n\nTheorem eqb_refl: forall n: nat,\n  (n =? n) = true.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\n  Qed.\n\n(** \n  We can specify a particular subterm to \n  perform the rewrite using replace (t) with (u).\n\n  Previously, we have defined that n + m = m + n\n  with the use of the keyword \"assert\". Assert \n  generates a hypothesis and a subgoal to prove\n  that hypothesis.\n  \n  By using replace, we edit the goal directly and\n  have to prove that this rewriting is possible\n  as a subgoal.\n**)\n\nTheorem add_shuffle3': forall n m p: nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. \n  rewrite add_assoc.\n  rewrite add_assoc.\n  replace (n + m) with (m + n).\n  - reflexivity.\n  - rewrite add_comm. reflexivity.\n  Qed.\n\n\n(** **** Exercise: 3 stars, standard, especially useful (binary_commute) **)\n(* TODO *)", "meta": {"author": "wrongbyte", "repo": "software-foundations", "sha": "c1721a53d73f9ce405537ff974b7a11edf2bbc63", "save_path": "github-repos/coq/wrongbyte-software-foundations", "path": "github-repos/coq/wrongbyte-software-foundations/software-foundations-c1721a53d73f9ce405537ff974b7a11edf2bbc63/lf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.9252299632771662, "lm_q1q2_score": 0.8418732280426328}}
{"text": "(*\n  Team Members:\n\tChenglong Wang\n\tDalton Black\n*)\n\n(* Homework 01 (90 total points) *)\n\n(*\n  In this homework, you'll do some programming in Coq and do some simple proofs.\n\n  Each problem should be independent of the others, but subproblems\n   may depend on each other.\n\n  Later problems aren't necessarily harder than earlier ones, so if you get\n   stuck on a problem, move on and come back to it later.\n\n  You'll know most of what you need for this homework after the first lecture,\n   and everything by the second. Get started early so you have time to ask questions!\n\n  For all proofs, please use bullets ( -, +, * ) as shown in class. For this homework,\n   we won't take points off for proof style, but we may start doing so in future.\n\n*)\n\n(* Multiplication of natural numbers, used in problem 1 *)\nFixpoint mult m n :=\n  match m with\n    | 0 => 0\n    | S m' => plus n (mult m' n)\n  end.\n\n(* [PROBLEM 1 (5 points)]: Prove that multiplication by 1 is the identity.\n   Hint: this should be similar to add_O from Lecture 1 *)\n\nLemma mult_1 :\n  forall m,\n    mult m 1 = m.\nProof.\n  (* about 7 tactics *)\n  intros m.\n  induction m.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IHm.\n    reflexivity.\nQed.\n(* Change \"Admitted\" to \"Qed\" when the proof is completed. *)\n(* END PROBLEM 1 *)\n\n(* Decide if two nats are equal *)\nFixpoint nat_eq (m n: nat) : bool :=\n  match m, n with\n    | O, O => true\n    | S mp, S np => nat_eq mp np\n    | _, _ => false\n  end.\n\n\n(* [PROBLEM 2 (10 points)]:\n    a (5 points). Correct the definition of nat_le, which returns\n      true when m is less than or equal to n and false otherwise.\n      Hint: this definition should be similar to nat_eq\n    b (5 points). Complete the proof of nat_eq_nat_le, which states\n      that if m = n, then m <= n.\n      Hint: as is often the case, you may want to induct before intro-ing.\n*)\n\n\nFixpoint nat_le (m n : nat) : bool := \n  (* fix this definition *)\n  match m, n with\n    | O, _ => true\n    | S mp, S np => nat_le mp np\n    | _, _ => false\n  end.\n\n(* Use these to test your function *)\nEval cbv in (nat_le 5 5). (* true *)\nEval cbv in (nat_le 3 5). (* true *)\nEval cbv in (nat_le 5 3). (* false *)\n\nTheorem nat_eq_nat_le :\n  forall m n,\n    nat_eq m n = true ->\n    nat_le m n = true.\nProof.\n  (* about 10 tactics *)\n  induction m.\n  intros.\n  - simpl. reflexivity.\n  - intros.\n    rewrite <- H.\n    simpl.\n    destruct n.\n    + reflexivity.\n    + simpl in H.\n      rewrite IHm.\n      * rewrite H. reflexivity.\n      * rewrite H. reflexivity.\nQed.\n\nTheorem nat_eq_nat_le_secondtry :\n  forall m n,\n    nat_eq m n = true ->\n    nat_le m n = true.\nProof.\n  induction m.\n  - intros. simpl. reflexivity.\n  - intros. simpl.\n    destruct n.\n    + inversion H.\n    + simpl in H.\n      apply IHm.\n      apply H.\nQed.\n\n(* END PROBLEM 2 *)\n\n(* The following definitions are used in Problems 3-4 *)\n\n(* \"Counting\" numbers *)\n\nInductive counting : Set :=\n| one : counting\n| next : counting -> counting.\n\n(* integers *)\nInductive int : Set :=\n| zero : int\n| pos : counting -> int\n| neg : counting -> int.\n\n(* [PROBLEM 3 (8 points)]: Here are two other possible definitions of the integers:\n\nInductive int1 :=\n| O : int1\n| pred : int1 -> int1\n| succ : int1 -> int1.\n\nInductive int2 :=\n| pos : nat -> int2\n| neg : nat -> int2.\n\nFixpoint pos_int (int : int1, intb : int 1) :=\n  match int with\n  | O -> false\n  | pred n1, succ n2 -> \n\npred (succ (pred (succ O)))\n\nWhat is a potenial problem with these definitions? Explain briefly in a comment. \n\nMy opinion: 1) Given an integer, we cannot get its sign from it without using another type. (first one)\n            2) Comparing the equivalence/greater/less relations of two integer is not possible  (first one)\n            3) pos O and neg O, equivlence is not defined. (second one)\n*)\n\n(* END PROBLEM 3 *)\n\n(* Predecessor of an integer. Used in Problem 4. *)\nDefinition pred (x : int) : int :=\n  match x with\n    | zero => neg one\n    | pos n => match n with\n                | one => zero\n                | next n' => pos n'\n              end\n    | neg n => neg (next n)\n  end.\n\n(* [Problem 4 (12 points)]:\n   a (6 points). Correct the definition of succ, below.\n      succ should return the successor of its argument,\n       i.e., the next larger integer.\n   b (6 points). Complete the proofs of pred_succ and succ_pred.\n      Hint: induction is not necessary.\n *)\n\nDefinition succ (x : int) : int := \n  match x with\n    | zero => pos one\n    | pos n => pos (next n)\n    | neg n => \n        match n with\n          | one => zero\n          | next n2 => neg n2\n        end\n    end.\n\nLemma pred_succ :\n  forall x, pred (succ x) = x.\nProof.\n  (* about 12 tactics *)\n  intros x.\n  destruct x.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - destruct c.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\nQed.\n\nLemma succ_pred :\n  forall x, succ (pred x) = x.\nProof.\n  (* about 12 tactics *)\n  intros x.\n  destruct x.\n  - simpl. reflexivity.\n  - simpl.\n    destruct c.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n(* END PROBLEM 4 *)\n\n(* Binary trees of nats. Used in the remaining problems. *)\nInductive nat_tree : Set :=\n| Leaf : nat_tree\n| Branch : nat -> nat_tree -> nat_tree -> nat_tree.\n\n(* size returns the number of nats in a tree. *)\nFixpoint size (nt: nat_tree) : nat :=\n  match nt with\n    | Leaf => 0\n    | Branch n ntl ntr => S (plus (size ntl) (size ntr))\n  end.\n\n(* [PROBLEM 5 (5 points)]: Define sum to add up all the nats in a nat_tree. *)\n\nFixpoint sum (nt: nat_tree) : nat := \n  match nt with \n  | Leaf => 0\n  | Branch n ntl ntr => plus n (plus (sum ntl) (sum ntr)) \n  end.\n\n(* END PROBLEM 5 *)\n\n(* [PROBLEM 6 (5 points)]: Define prod to multiply all the nats in a nat_tree.\n     Hint: prod should call mult, defined above. *)\n\nFixpoint prod (nt: nat_tree) : nat := \n  match nt with\n  | Leaf => 0\n  | Branch n ntl ntr => mult n (mult (prod ntl) (prod ntr))\n  end.\n\n(* END PROBLEM 6 *)\n\n(* fold over nat_trees *)\nFixpoint fold {T: Type} (base: T) (f: T -> nat -> T) (nt: nat_tree) : T :=\n  match nt with\n    | Leaf => base\n    | Branch n l r => f (fold (fold base f l) f r) n\n  end.\n\n(* [PROBLEM 7 (3 points)]: Define sum' to add up all the nats in a nat_tree.\nFor full credit, do not use recursion (keep the Definition, don't change to Fixpoint).\n*)\n\nCheck (fold 0).\n\nDefinition sum' (nt: nat_tree):= \n  fold 0 plus nt.\n\nEval cbv in (sum' (Branch 1 (Branch 3 Leaf (Branch 9 Leaf Leaf)) Leaf)).\n\n(* END PROBLEM 7 *)\n\n(* [PROBLEM 8 (3 points)]: Define prod' to multiply up all the nats in a nat_tree.\nFor full credit, do not use recursion (keep the Definition, don't change to Fixpoint).\n *)\n\nDefinition prod' (nt: nat_tree):= fold 1 mult nt.\n\nEval cbv in (prod' (Branch 1 (Branch 3 Leaf (Branch 9 Leaf Leaf)) Leaf)).\n\n(* END PROBLEM 8 *)\n\n(* [PROBLEM 9 (5 points)]: Define increment_all to add one to all the nats in a nat_tree.\n*)\n\nFixpoint increment_all (nt: nat_tree) : nat_tree :=\n  match nt with\n  | Leaf => Leaf\n  | Branch n l r => Branch (plus 1 n) (increment_all l) (increment_all r)\n  end.\n\nEval cbv in (increment_all (Branch 1 (Branch 3 Leaf (Branch 9 Leaf Leaf)) Leaf)).\n\n(* END PROBLEM 9 *)\n\n(* [PROBLEM 10 (5 points)]: Define double to multiply all the nats in a nat_tree by 2.\n*)\n\nFixpoint double (nt: nat_tree) : nat_tree :=\n  match nt with\n  | Leaf => Leaf\n  | Branch n l r => Branch (mult n 2) (double l) (double r)\n  end.\n\nEval cbv in (double (Branch 1 (Branch 3 Leaf (Branch 9 Leaf Leaf)) Leaf)).\n\n(* END PROBLEM 10 *)\n\n(* [PROBLEM 11 (12 points)]:\n   a (6 points). Define map to apply a function of type nat -> nat\n     to every nat in a nat_tree.\n     The resulting tree should have exactly the same structure as the initial tree.\n   b (6 points). Complete the proof of size_map, which proves that map preserves the\n     size of a tree.\n *)\n\nFixpoint map (f: nat -> nat) (nt: nat_tree) : nat_tree :=\n   match nt with\n    | Leaf => Leaf\n    | Branch n l r => Branch (f n) (map f l) (map f r)\n   end.\n\nTheorem size_map : forall f t, size (map f t) = size t.\nProof.\n  (* about 7 tactics *)\n  induction t.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IHt1.\n    rewrite IHt2.\n    reflexivity.\nQed.\n\n(* END PROBLEM 11 *)\n\n(* [PROBLEM 12 (12 points)]:\n   a (6 points). Define mirror to flip all the branches in the tree:\n               5              5\n              / \\            / \\\n             3   4     =>   4   3\n            / \\                / \\\n           1   6              6   1\n      (leaves are not displayed above)\n   b (6 points). Complete the proof of size_mirror, which proves that mirror preserves the\n     size of a tree.\n*)\n\nLemma add_O :\n  forall n,\n    n + O = n.\nProof.\n  intro n.\n  induction n.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IHn. (** find the left-hand side of IHn in the goal\n                    and replace it by the right-hand side *)\n    reflexivity.\nQed.\n\nTheorem S_n_m :\n  forall n m,\n    S (n + m) = n + S m.\nProof.\n  induction n.\n  - intros. reflexivity.\n  - intros. simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem add_comm :\n  forall m n,\n    m + n = n + m.\nProof.\n  induction m.\n  - intros. simpl. rewrite add_O. reflexivity.\n  - intros. simpl. rewrite IHm.\n    rewrite S_n_m. reflexivity.\nQed.\n\nFixpoint mirror (nt: nat_tree) : nat_tree :=\n  (* fill in your definition of mirror here *)\n  match nt with\n    | Leaf => Leaf\n    | Branch n l r => Branch n (mirror r) (mirror l)\n   end.\n\nTheorem size_mirror : forall t, size (mirror t) = size t.\nProof.\n  (* about 8 tactics *)\n  induction t.\n  - simpl. reflexivity.\n  - simpl. \n    rewrite IHt1.\n    rewrite IHt2.\n    rewrite add_comm.\n    reflexivity.\nQed.\n\nEval cbv in (mirror (Branch 1 (Branch 3 Leaf (Branch 9 Leaf Leaf)) Leaf)).\n\n(* END PROBLEM 12 *)\n\n(* [PROBLEM 13 (10 points)]:\nConsider this alternate definition of fold:\n*)\nFixpoint fold' {T: Type} (base: T) (f: T -> nat -> T) (nt: nat_tree) : T :=\n  match nt with\n    | Leaf => base\n    | Branch n l r => fold' (f (fold' base f l) n) f r\n  end.\n(*\nIn a short English paragraph, describe how fold and fold' differ.\n*)\n\n(* WRITE HERE *)\n\n(*Answer: The difference between these two functions is that the fold function would firstly\ncompute the value of the left tree, then compute the value of the right tree based\non the result of left tree, then finally add the value of the current node to the \ncomputation result after finished computing the right sub tree. However, the fold'\nfunction would 1) visit the left tree, 2) compute the value of the current node to\nthe result and then 3) compute the value of the right tree based on the result.\n\nIn another word, fold visits the tree in post-order (after the the visit of both \nleft and right sub tree) while fold' visits the tree in in-order (visit the left \nsub-tree, then the current node, and finally the rightsub-tree).\n\nThese functions can produce different results if f is not commutative.\n *)\n\n(* END PROBLEM 13 *)\n\n(*\nOPTIONAL Bonus:\n\nWhat should be true about a particular f for the following to hold:\n\n  forall b nt, fold b f nt = fold' b f nt\n\n  (* TODO write here *)\n  The condition is that: forall x:T y:nat z:nat f (f x y) z = f (f x z) y.\n\nOptional Bonus 2: Formalize this property in Coq, and prove that\n  forall f b nt, <property> f -> fold b f nt = fold' b f nt.\n*)\n\n(* Lemma f_fold': forall f nt, (forall y z (x:bool), f (f x y) z = f (f x z) y) \n  -> forall  u v, f (fold' u f nt) v = fold' (f u v) f nt.\nProof.\n  induction nt.\n  - simpl. reflexivity.\n  - simpl.\n    intros.\n    rewrite <- IHnt1.\n    rewrite H.\n    rewrite -> IHnt2.\n    reflexivity.\n    * apply H.\n    * apply H.\nQed.\n*)\nLemma f_fold: forall f nt, (forall y z (x:bool),\n  f (f x y) z = f (f x z) y) ->\n      forall  u v, f (fold u f nt) v = fold (f u v) f nt.\nProof.\n  induction nt.\n  - simpl. reflexivity.\n  - simpl.\n    intros.\n    rewrite <- IHnt1.\n    rewrite H.\n    rewrite -> IHnt2.\n    reflexivity.\n    * apply H.\n    * apply H.\nQed.\n\nLemma zach: forall f nt b, (forall y z (x:bool), f (f x y) z = f (f x z) y) \n  -> fold b f nt = fold' b f nt.\nProof.\n  induction nt.\n  - simpl. reflexivity.\n  - simpl.\n    intros.\n    rewrite <- IHnt1.\n    + destruct nt1.\n      *  simpl. rewrite f_fold.\n         intros. rewrite <- IHnt2.\n          reflexivity. apply H. apply H.\n      * simpl. rewrite f_fold.\n        rewrite <- IHnt2.\n        reflexivity. apply H. apply H.\n    + apply H.\nQed.\n", "meta": {"author": "Mestway", "repo": "CourseWork", "sha": "912cf0e4a7127f2f0940cbdf1e7af274f6e2680c", "save_path": "github-repos/coq/Mestway-CourseWork", "path": "github-repos/coq/Mestway-CourseWork/CourseWork-912cf0e4a7127f2f0940cbdf1e7af274f6e2680c/CSE505/hw01/HW1-Chenglong-Dalton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.9086178975514608, "lm_q1q2_score": 0.8416561423681267}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Extraction.\n\nPrint nat.\n\nDefinition plus2 n := n+2.\n\nFixpoint factorial n := \n  match n with\n    0 => 1\n  | S m => n*fact m\nend.\n\nEval compute in factorial 3.\n\nPrint list.\n\nCheck @nil nat.\n\nCheck @nil.\n\nCheck nil.\n\nCheck @cons.\n\nCheck cons 3 nil.\n\nCheck @cons nat 3 nil.\n\n\nFixpoint map (A B: Type)(f: A-> B) l := \n  match l with\n    nil => nil\n  | x::xs => (f x) ::  map A B f xs\nend.\n\nCheck map.\n\nFixpoint mapi {A B: Type}(f: A-> B) l := \n  match l with\n    nil => nil\n  | x::xs => (f x) ::  mapi f xs\nend.\n\nCheck mapi.\n\n\n(* Types are first-class values *)\n\nFixpoint AddernatType (n:nat) := \nmatch n with \n  0 => nat\n| (S k) => nat -> AddernatType k \nend.\n\nCheck AddernatType.\n\n\nFixpoint addernat (numargs : nat) (acc: nat): AddernatType numargs :=\nmatch numargs with \n  0 => acc\n| (S k) => fun next => addernat k (next + acc)\nend.\n\n\nEval compute in (addernat 3 0 1 2 3).\n\n\n(* Propositions and proofs are first-class values *)\n\nFixpoint len {A: Type} (l: list A) :=\n  match l with\n    nil => 0\n  | x::xs => 1 + len xs\nend.\n\nCheck len.\n\n\nLemma lenEqZero: forall A (l:list A), length l = 0 -> l = nil.\nProof.\nintros.\ndestruct l.\n* trivial.\n* simpl in H.\n  congruence.\nQed.\n\nPrint lenEqZero.\n\n\nPrint le.\nPrint \"<=\".\nPrint \"<\".\nPrint \">\".\n\nLemma lenGeZero: forall A (l:list A), 0 <= length l. \nProof.\nintros.\ninduction l.\n- simpl. trivial.\n- simpl. constructor. trivial.\nQed.\n\nCheck lenGeZero.\nPrint lenGeZero. \n\n\n(* forall A (l:list A), 0 <= length l is a dependent type...*)\n\n\nInductive vector {T:Type} : nat -> Type :=\n  | Vnil : vector 0\n  | Vcons : forall n, T -> vector n -> vector (S n).\n\nCheck @Vcons.\n\nDefinition vhead {T:Type}{n:nat}(v:vector (S n)):T :=\nmatch v with\n  Vcons n h t => h\nend. \n\n\nExtraction vector.\nExtraction vhead.\n\n\n\n(* congruence - decision procedure for ground equlities \n                with uninterpreted symbols *)\n\nLemma T (A:Type) (f:A -> A) (g: A -> A -> A) a b: \na=(f a) -> (g b (f a))=(f (f a)) -> (g a b = f (g b a)) -> g a b = a.\nProof. \nintros.\ncongruence.\nQed.", "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/examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.9005297914570319, "lm_q1q2_score": 0.8414506759258897}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    [Basics] chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a slightly peculiar way, we can complete\n    proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. \nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n    + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with \n  | nil => 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. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist := \n  match l with\n    | nil => nil\n    | h :: t => \n      match (oddb h) with\n        | true => h :: (oddmembers t)\n        | false => (oddmembers t)\n      end\n  end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat := (length (oddmembers l)).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    | nil, nil => nil\n    | x :: x', nil => x :: x'\n    | nil, y :: y' => y :: y'\n    | x :: x', y :: y' => x :: y :: (alternate x' y')\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match v, s with\n    | v, nil => O\n    | v, s :: s' => \n      match (beq_nat v s) with\n        | true => S (count v s')\n        | false => (count v s')\n      end\n  end.\n  \n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := (alternate).\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match (count v s) with\n    | O => false\n    | S n' => true\n  end.\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n(*\nFixpoint remove_one (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n*)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bag_theorem : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and state it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction 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. induction l1 as [| n l' IHl'].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl'. 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    - simpl. reflexivity.\n    - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. simpl. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4. 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 l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. destruct n.\n    + reflexivity.\n    + simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | x :: x', nil => false\n  | nil, y :: y' => false\n  | x :: x', y :: y' =>\n    match (beq_nat x y) with\n      | true => (beq_natlist x' y')\n      | false => false\n    end\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star (count_member_nonzero)  *)\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. simpl. reflexivity.\nQed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count)  *)\n(*Theorem 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 as [| n' s' IHs'].\n  - simpl. \n(** [] *)*)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n    (There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_rev_injective : option (prod nat string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map by shadowing it with a new one (or simply adds a new\n    entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n    (Explain your answer in words, preferrably English.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (prod nat string) := None.\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/jkstpierre/software foundations/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.9173026618464795, "lm_q1q2_score": 0.8414441734306366}}
{"text": "From mathcomp\nRequire Import ssreflect ssrfun eqtype ssrnat ssrbool.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\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 my_eq_sym A (x y: A) : x === y -> y === x.\nProof. by case. Qed.\n\nLemma disaster : 2 === 1 -> False.\nProof.\nmove=> H.\npose D x := if x is 2 then False else True.\nhave D1: D 1 by [].\nby case: H D1. \nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Discriminating [===]]\n---------------------------------------------------------------------\nLet us change the statement of a lemma [disaster] for a little bit:\n*)\n\nLemma disaster2 : 1 === 2 -> False.\n\n(**\nNow, try to prove it using the same scheme. What goes wrong and how to\nfix it?\n*)\nProof.\n(* by move=>H; move/disaster: (my_eq_sym H). *)\nProof.\nmove=> H.\npose D x := if x is 1 then False else True.\nhave D2: D 2. \nby [].\nby case: H D2=> /=.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Fun with rewritings]\n---------------------------------------------------------------------\nProve the following lemma by using the [rewrite] tactics.\n\n*)\n\nLemma rewrite_is_fun T (f : T -> T -> T) (a b c : T):\n  commutative f -> associative f ->\n  f (f b a) c = f a (f c b).     \nProof.\nmove=> H1 H2.\nby rewrite [(f b a)]H1 -H2 [(f c b)]H1.\nQed.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Properties of maxn]\n---------------------------------------------------------------------\nProve the following lemmas about [maxn].\n*)\n\nLemma max_l m n: n <= m -> maxn m n = m.\nProof.\nrewrite /maxn. \nby case: (leqP n m)=>//.\nQed.\n\nLemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).\nProof.\nrewrite /maxn.\ncase: leqP=>//H; case:leqP=>//.\n- by rewrite -[n.+1]addn1 -[m.+1]addn1 ltn_add2r ltnNge H.\nby rewrite ltnS leqNgt H.\nQed.\n\nLemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.\nProof.\nrewrite /maxn.\ncase: leqP=>// H1; case: leqP=>//.\n- suff: m <= n by rewrite ltnNge=>H; move/negP.\n  by rewrite leq_add2l in H1.\nsuff: n < m by move=>H; rewrite leqNgt H. \nby rewrite ltn_add2l in H1.\nQed.\n\n(** \n\nHint: it might be useful to employ the lemmas [ltnNge], [leqNgt],\n[ltnS] and similar to them from SSReflect's [ssrnat] module. Use the\n[Search] command to find propositions that might help you to deal with\nthe goal.\n\nHint: Forward-style reasoning via [suff] and [have] might be more\nintuitive.\n\nHint: A hypothesis of the shape [H: n < m] is a syntactic sugar for\n[H: n < m = true], since [n < m] in fact has type [bool], as will be\nexplained in the next lecture.\n\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [More custom rewriting rules]\n---------------------------------------------------------------------\n\nLet us consider an instance of a more sophisticated custom rewriting\nrule, which now encodes a three-variant truth table for the ordering\nrelations on natural numbers.\n\n*)\n\nInductive nat_rels m n : bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : nat_rels m n true false false\n  | CompareNatGt of m > n : nat_rels m n false true false\n  | CompareNatEq of m = n : nat_rels m n false false true.\n\n(** \n\nThe following rewriting lemma establishes a truth table for\n[nat_rels]. Step through the proofs (splitting the combined tactics\nwhenever it's necessary) to see what's going on.\n\n*)\n\nLemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).\nProof.\nrewrite ltn_neqAle eqn_leq; case: ltnP; first by constructor.\nby rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.\nQed.\n\n(** \nLet us define the minimum function [minn] on natural numbers as\nfollows:\n*)\n\nDefinition minn m n := if m < n then m else n.\n\n(**\nProve the following lemma about [minm] and [maxn]:\n*)\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof.\nrewrite /minn /maxn; by case: natrelP=>//; rewrite addnC.\nQed.\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/solutions/Rewriting_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.9161096216057903, "lm_q1q2_score": 0.8414285908506265}}
{"text": "(* Proof by Induction *)\n\n(* The following proof works, but the one after does not *)\nTheorem  plus_left_side: forall n : nat, 0 + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem plus_n_O_firsttry : forall n : nat, \n  n = n + 0.\nProof. intros n. simpl. (* Does nothing! *) Abort.\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof. 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 *)\n  Abort.\n \n\n(* \nHere is the principle of induction over natural numbers: \nIf P(n) is some proposition involving a natural number n \nand we want to show that P holds for all numbers n, we can \nreason like this:\n  > show that P(O) holds; show that, for any n', if P(n')\n  > holds, then so does P(S n'); conclude that P(n) holds\n  > for all n.\n\n\n*)\n\nTheorem plus_N_O : forall n : nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0*) reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'.\n  reflexivity. Qed.\n\n(* \nThe previous Theorem and proof written on paper \n\nTheorem : For any n,\n  n = n + 0\n\nProof : By induction on n.\n  First, suppose n = 0. We must show\n    0 = 0 + 0\n    \n    This follows directly from the definition of +\n \n  Next, suppose n = S n', where (as our IH)\n    n' = n' + 0\n    \n    We must show \n      S n' = (S n') + 0\n      \n      which is immediate from the induction hypothesis. \n  Qed.\n\n*)\n\nTheorem minus_diag : forall n, minus n n = 0.\nProof. intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n(* \nWhen applied to a goal that contains quantified variables, \nthe induction tactic will automatically move them into the \ncontext as needed.\n*)\n\n(* Exercise 1 *)\nTheorem mult_0_r : forall n : nat,\n  n * 0 = 0.\nProof. 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. intros n m. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity. Qed.\n\n(* My weird attempts\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof. intros n m. induction n as [|n' IHn'].\n  - simpl. induction m as [|m' IHm'].\n    + reflexivity.\n    + simpl. rewrite <- IHm'. reflexivity.\n  - simpl. induction m as [|m' IHm'].\n    + rewrite -> IHn'. simpl. reflexivity.\n    + rewrite -> IHn'. simpl. rewrite <- IHm'.\n      * simpl. rewrite <- IHn'.\n\nrewrite <- IHm'.\n     -- rewrite -> IHn'. simpl. reflexivity. rewrite <- IHn'.\n\n    + simpl. rewrite -> IHn'. rewrite <- IHm'. simpl. rewrite <- IHn'.\n    \n*)\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\n\nProof. intros n m. induction n as [|n' IHn'].\n  - simpl. rewrite <- plus_N_O. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed. \n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\n\nProof. intros n m p. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn. reflexivity. \nQed.\n\n(* Proofs within proofs *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "dschneck", "repo": "coq-code", "sha": "3f8455c41488d95b7295b03b078d8499c6dc0034", "save_path": "github-repos/coq/dschneck-coq-code", "path": "github-repos/coq/dschneck-coq-code/coq-code-3f8455c41488d95b7295b03b078d8499c6dc0034/chapters/proof-by-induction/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.9184802451409948, "lm_q1q2_score": 0.8414285824656326}}
{"text": "Require Import ZArith.\n\nRequire Import List.\n\nRequire Extraction. \n\nSet Implicit Arguments.\n\nExtraction Language Haskell.\n\n(************************\n**** Exerc\u00edcio 1.\n************************)\n\n(**** (a) ****)\n\nInductive mkList (A:Type) : nat -> A -> (list A) -> Prop :=\n  | mkNil : forall (a:A), mkList 0 a nil\n  | mkSec : forall (n:nat) (a:A) (l:list A), mkList n a l -> mkList (S n) a (a::l).\n\nTheorem mkList_correct : forall (A:Type) (n:nat) (x:A), { l:list A | mkList n x l }.\nProof.\n  intros.\n  induction n.\n  - exists nil. constructor.\n  - destruct IHn. exists (x::x0). constructor. assumption.\nQed.\n\n(* Extra\u00e7\u00e3o do c\u00f3digo *)\nRecursive Extraction mkList_correct.\n\n(**** (b) ****)\n\nInductive pairSum : list (nat*nat) -> list nat -> Prop :=\n  | sumNil : pairSum nil nil\n  | sumSec : forall (p: (nat*nat)) (inp: list (nat*nat)) (res: list nat), pairSum inp res -> pairSum (p::inp) (((fst p)+(snd p))::res).\n\nTheorem pairSum_correct : forall (inp: list(nat*nat)), {res: list nat | pairSum inp res}.\nProof.\n  intros.\n  induction inp.\n  - exists nil. constructor.\n  - elim IHinp.\n    + intros. exists ( ((fst a) + (snd a))::x ). constructor. assumption.\nQed.\n\n(* Extra\u00e7\u00e3o do c\u00f3digo *)\nRecursive Extraction pairSum_correct.\n\n\n(************************\n**** Exerc\u00edcio 2.\n************************)\nOpen Scope Z_scope. \n\nFixpoint count (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat\n  | (z' :: l') => if (Z.eq_dec z z')\n                  then S (count z l')\n                  else count z l'\n  end.\n\n(**** (a) ****)\nLemma count_corr : forall (x:Z) (a:Z) (l:list Z), x <> a ->  count x (a :: l) = count x l.\nProof.\n  intros.\n  simpl.\n  elim (Z.eq_dec x a).\n  - intros. contradiction.\n  - intros. trivial.\nQed.\n\n(**** (b) ****)\nInductive countRel : Z -> list Z -> nat -> Prop :=\n  | countNil : forall e:Z, countRel e nil 0\n  | countIf : forall (e:Z) (l: list Z) (n: nat), countRel e l n -> countRel e (e::l) (S n)\n  | countElse : forall (e e':Z) (l: list Z) (n: nat), e <> e' -> countRel e l n -> countRel e (e'::l) n.\n\n(**** (c) ****)\nLemma count_correct : forall (x:Z) (l:list Z), countRel x l (count x l).\nProof.\n  intros.\n  induction l.\n  - simpl. constructor.\n  - simpl. elim (Z.eq_dec x a).\n    + intros. rewrite <- a0. constructor. assumption.\n    + intros. destruct IHl. \n      * constructor.\n        -- assumption.\n        -- constructor.\n      * constructor.\n        -- assumption.\n        -- constructor. assumption.\n      * constructor.\n        -- assumption.\n        -- constructor.\n          ++ assumption.\n          ++ assumption.\nQed.\n\nClose Scope Z_scope.\n(************************************************************* END *************************************************************)", "meta": {"author": "Th0l", "repo": "VF", "sha": "2c7393433656dc395fd6a3c7c79e1051f53afcf3", "save_path": "github-repos/coq/Th0l-VF", "path": "github-repos/coq/Th0l-VF/VF-2c7393433656dc395fd6a3c7c79e1051f53afcf3/TPCs/8_CoqTpc3/A81716_Coq3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.8414285816218575}}
{"text": "Require Export ProofObjects.\n\n\n(* ================================================================ *)\n\n(** * O operador \"fix\" *)\n\n(**\nO operador [fix] est\u00e1 para [Fixpoint] assim como [fun] est\u00e1 para\n[Definition], ou seja, [fix] serve para definir e usar localmente uma\nfun\u00e7\u00e3o recursiva, sem registrar no contexto um nome para ela.\n\nA nota\u00e7\u00e3o \u00e9\n\n  fix nome_local_da_fun\u00e7\u00e3o (argumentos...) : tipo_de_retorno := corpo\n\ncomo ilustrado abaixo:\n*)\n\nCompute\n  (\n  fix last (l : list nat) : option nat\n    :=\n    match l with\n    | [] => None\n    | h1::t1 => match t1 with\n                | [] => Some h1\n                | h2::t2 => last t1\n                end\n    end\n  )\n  [1; 2; 3; 4; 5].\n\nFail Check last. (** Observe: [last] n\u00e3o est\u00e1 \"registrada\". *)\n\n\n(* ================================================================ *)\n\n(** * Provando Teoremas via [fix] *)\n\n(**\nRecapitule primeiramente que\n\n  \"Coq treats as \"the same\" any two terms that are _convertible_\n   according to a simple set of computation rules. These rules, which\n   are similar to those used by [Compute], include evaluation of\n   function application, inlining of definitions, and simplification\n   of [match]es.\"\n\nPor exemplo:\n*)\n\n\n(**\nAgora, recapitule o argumento deste teorema:  [forall n, n + 0 = n].\n\n  ... (Explicado em sala)\n\nIsso pode ser formalizado diretamente por uma fun\u00e7\u00e3o recursiva:\n*)\n\nCheck f_equal.\n\nDefinition plus_0_r_po: forall n, n + 0 = n\n  :=\n  fix f (n : nat) : n + 0 = n\n    :=\n    match n with\n    | O => @eq_refl nat 0 : 0 = 0\n           (* Ou simplesmente:  @eq_refl nat 0 *)\n           (* Ou simplesmente:  eq_refl *)\n    | S n' => f_equal nat nat S (n' + 0) n' (f n')\n              (* Ou simplesmente:  f_equal _ _ _ _ _ (f n') *)\n    end.\n\n\n(** EXERC\u00cdCIO: prove por meio de uma fun\u00e7\u00e3o recursiva: *)\n\nDefinition plus_assoc_po: forall m n o, m + (n+o) = (m+n) + o :=\n  fix f m n o : m + (n + o) = (m + n) + o :=\n    match m with\n    | O => eq_refl\n    | S m' => f_equal _ _ S (m' + (n + o)) (m' + n + o) (f m' n o)\n    end.\n\n\n(* ================================================================ *)\n\n(** * Provando Princ\u00edpios de Indu\u00e7\u00e3o de Conjuntos via [fix] *)\n\n(**\nO mesmo tipo de racioc\u00ednio permite provarmos _princ\u00edpios de indu\u00e7\u00e3o_\npor meio de fun\u00e7\u00f5es recursivas.\n\nNo caso de [nat], por exemplo, temos:\n *)\n\n(* Inductive nat : Type :=\n   | O : nat\n   | S : nat -> nat *)\n\nDefinition nat_ind_po :\n  forall P : nat -> Prop,\n  P O ->\n  ( forall x, P x -> P (S x) ) ->\n  forall n : nat, P n\n    :=\n    fun P p0 ps  (* Essa fun\u00e7\u00e3o adicional recebe os argumentos\n                    que n\u00e3o mudam durante as chamadas recursivas *)\n      =>\n      fix f n : P n\n        :=\n        match n with\n        | O => p0\n        | S n' => ( ps n' (f n') ) : P (S n')\n                  (* Ou simplesmente:  ( ps n' (f n') ) *)\n        end.\n\n\n(** EXERC\u00cdCIO: defina um tipo [listbool] e enuncie e prove um\n    princ\u00edpio de indu\u00e7\u00e3o para ele: *)\n\nInductive listbool : Type :=\n  | bnil : listbool\n  | bcons : bool -> listbool -> listbool.\n\nCheck listbool_ind.\n\nDefinition listbool_ind_po :\n  forall P : listbool -> Prop,\n       P bnil ->\n       (forall (b : bool) (l : listbool), P l -> P (bcons b l)) ->\n       forall l : listbool, P l :=\n  fun P pn pc =>\n    fix f l : P l :=\n    match l with\n    | bnil => pn\n    | bcons b l' => pc b l' (f l')\n    end.  \n\n(** EXERC\u00cdCIO: Enuncie e prove o princ\u00edpio de indu\u00e7\u00e3o para [list].\n               (Observe que, ao faz\u00ea-lo, voc\u00ea estar\u00e1 provando um\n    princ\u00edpio de indu\u00e7\u00e3o para um tipo polim\u00f3rfico, mas a ideia n\u00e3o\n    muda.) *)\n\n\nDefinition list_ind_po : 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  fun X P pn pc =>\n    fix f l : P l :=\n    match l with\n    | nil => pn\n    | cons x l' => pc _ _ (f l')\n    end.  \n\nPrint list.\n(** EXERC\u00cdCIO: Defina um tipo polim\u00f3rfico para \u00e1rvores bin\u00e1rias, e\n    prove o princ\u00edpio de indu\u00e7\u00e3o correspondente. *)\n\nInductive btree (X : Type) : Type :=\n  | bempty : btree X\n  | bleaf : X -> btree X\n  | nbranch : X -> btree X -> btree X -> btree X.\n\n\nDefinition btree_ind_po : forall (X : Type) (P : btree X -> Prop),\n  P (bempty X) -> (forall (x : X) , P (bleaf X x)) ->\n  (forall (x : X) (l : btree X) (r : btree X), P l -> P r -> P (nbranch X x l r)) ->\n  forall b : btree X, P b \n  :=\n  fun X P pe pl pb =>\n    fix f bt : P bt :=\n    match bt with\n    | bempty => pe\n    | bleaf x => pl x\n    | nbranch x l' r' => pb x l' r' (f l') (f r') \n    end.\n\n(** EXERC\u00cdCIO: Escreva um princ\u00edpio de indu\u00e7\u00e3o para [nat] cujo passo\n    \"v\u00e1 de 2 em 2\", ou seja, de P(n) provamos P(S(S n)).\n\n    Dica: Como fica a base?\n\n    Observa\u00e7\u00e3o: Numa prova com t\u00e1ticas, e supondo que nat_ind2 \u00e9 o\n    objeto de prova que voc\u00ea escreveu acima, voc\u00ea pode us\u00e1-lo assim:\n\n      induction n using nat_ind2. *)\n\n\n(* ================================================================ *)\n\n(** * Provando Princ\u00edpios de Indu\u00e7\u00e3o de IndProp's via [fix] *)\n\n(** EXEMPLO: essencialmente a mesma t\u00e9cnica ilustrada acima nos\n             permite provar princ\u00edpios de indu\u00e7\u00e3o para proposi\u00e7\u00f5es\n    indutivamente definidas.\n\n    Em geral, por\u00e9m, n\u00f3s precisamos de um recurso t\u00e9cnico novo: o\n    \"casamento de padr\u00e3o dependente\" (\"dependent pattern matching\"),\n    que ainda n\u00e3o foi explicado.\n\n    Para ilustrar, segue abaixo o princ\u00edpio indutivo para [ev] (o\n    recurso t\u00e9cnico novo est\u00e1 no \"match ... in ... return ... with\",\n    mas ele serve apenas para convencer o Coq de que os termos\n    retornados t\u00eam os tipos corretos, e pode ser ignorado por ora): *)\n\n(* Inductive ev : nat -> Prop :=\n   | ev_0 : ev 0\n   | ev_SS : forall x : nat, ev x -> ev (S (S x)) . *)\n\nDefinition ev_ind_po:\n  forall P : nat -> Prop,\n  P 0 ->\n  (forall n, ev n -> P n -> P (S (S n)) ) ->\n  forall n, ev n -> P n\n    :=\n    fun P p0 ps\n      =>\n      fix f n pevn : P n\n        :=\n        match pevn in ev a return P a with\n        | ev_0 => p0\n        | ev_SS n' evn' (* n = S (S n') *) =>\n            ps n' evn' (f n' evn')\n        end.\n\n\n(** Os exerc\u00edcios abaixo s\u00e3o recomendados, e podem ser feitos usando\n    apenas o tipo simples e j\u00e1 conhecido de casamento de padr\u00e3o. *)\n\n\n(** EXERC\u00cdCIO: Enuncie e prove o princ\u00edpio de indu\u00e7\u00e3o para [and]. *)\n\n(* Inductive and (A B : Prop) : Prop :=  conj : A -> B -> A /\\ B . *)\nCheck and_ind.\n\nDefinition and_ind_po: forall A B P : Prop, (A -> B -> P) -> A /\\ B -> P :=\n  fun A B P  (HABP : A -> B -> P) (H : A /\\ B)\n  => match H with\n     | conj HA HB =>  HABP HA HB\n     end.  \n\n(** EXERC\u00cdCIO: Enuncie e prove o princ\u00edpio de indu\u00e7\u00e3o para [False]. *)\n\n(*  Inductive False : Prop := .  *)\n\nDefinition False_ind_po : forall P : Prop, False -> P :=\n  fun P f => match f with\n             end.\n\n(** EXERC\u00cdCIO: Enuncie e prove o princ\u00edpio de indu\u00e7\u00e3o para [True]. *)\n\n(*  Inductive True : Prop :=  I : True .  *)\n\nDefinition True_ind_po : forall P : Prop, P -> True -> P :=\n  fun P (HP : P) (HT : True) => HP.\n\n(* ================================================================ *)", "meta": {"author": "marcosfmmota", "repo": "software-foundations", "sha": "667f50300f3d2c117b3df2aa9175fdfb1f8c4be1", "save_path": "github-repos/coq/marcosfmmota-software-foundations", "path": "github-repos/coq/marcosfmmota-software-foundations/software-foundations-667f50300f3d2c117b3df2aa9175fdfb1f8c4be1/Proof_Objects_for_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.9273632896242073, "lm_q1q2_score": 0.8414080463172353}}
{"text": "\n(*\n\nScript du th\u00e8me 2 : arithm\u00e9tique.\n\n*)\n\nRequire Import Arith.\n\nPrint nat.\n\nExample Zero: 0 = O.\nProof. reflexivity. Qed.\n\nExample Cinq: 5 = S (S (S (S (S O)))).\nProof. reflexivity. Qed.\n\nDefinition double (n : nat) : nat := 2 * n. \n\nExample square_2_is_2plus2: \n  double 2 = 2 + 2.\nProof.\ncompute.\nreflexivity.\nQed.\n\nLemma double_plus:\nforall n : nat, double n = n + n.\nProof.\ndestruct n as [| n']. (* raisonnement par cas *)\n  - (* cas de base: n=0 *)\n    compute.  (* remarque : terme clos *)\n    reflexivity.\n  - (* cas r\u00e9cursif: n=S n' *)\n    unfold double.\n    simpl.\n    SearchPattern ( S _ = S _ ).\n    (* eq_S: forall x y : nat, x = y -> S x = S y *)\n    apply eq_S.\n    SearchPattern ( ?X + 0 = ?X).\n    (* plus_0_r: forall n : nat, n + 0 = n *)\n    rewrite plus_0_r.\n    reflexivity.\nQed.\n\nLemma double_plus':\nforall n : nat, double n = n + n.\nProof.\nintro n.\nunfold double.\nring.\nQed.\n\nCheck nat_ind.\n\nLemma plus_0_r':\n  forall n : nat, n + 0 = n.\nProof.\nintro n.\ninduction n as [| n'].\n  - (* cas n=0 *)\n    trivial.\n  - (* cas n = S n' *)\n    simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nLemma plus_0_r'':\n  forall n : nat, n + 0 = n.\nProof.\n  auto with arith.\nQed.\n\n(* ** Exercice\n\nLa relation naturelle entre les listes et les entiers naturels est bien s\u00fbr la notion de longueur de liste.\n\n *** Question 1\n\nD\u00e9finir une fonction [longueur] retournant la longueur d'une liste.\n\n*)\nPrint length.\nRequire Import List.\nFixpoint longueur {A: Set}(l : list A) : nat :=\n  match l with\n    | nil => 0\n    | (e::l') => S (longueur l')\nend.\n\n(**\n\n  *** Question 2\n\n*)\n\nPrint length.\n\n(**\n\nMontrer que les deux fonctions [longueur] et [length]\neffectuent le m\u00eame calcul.\n  \n*)\n\nLemma len_long : forall A : Set, forall l : list A,\n length l = longueur l.\nProof.\ninduction l as [|e l'].\n-compute.\n trivial.\n\n-simpl.\ninversion IHl'.\ntrivial.\nQed.\n\n\n(**\n\n *** Question 3\n\nD\u00e9montrer le lemme suivant :\n\n*)\n\nLemma length_app:\n  forall A : Set, forall l1 l2 : list A,\n    length (l1 ++ l2) = (length l1) + (length l2).\nProof.\nintros A l1 l2.\ninduction l1 as [|e l'].\n-simpl.\n trivial.\n\n-simpl.\nrewrite IHl'.\ntrivial.\n\nQed.\n\n(** \n\n *** Question 4\n\nMontrer que [length (map f l) = length l].\n\n*)\nRequire Import List.\nLemma id_lenmap_len:\n  forall A B : Set, forall l: list A, forall f : A -> B, \n   length (map f l) = length l.\nProof.\nintros A B l f.\ninduction l as [|e l'].\n-simpl.\n trivial.\n\n-simpl.\n rewrite IHl'.\n trivial.\n\nQed.\n\n\n(** \n\n** Exercice \n\n*** Question 1\n\nD\u00e9finir la fonction [sum] calculant : $\\sum_{i=0}^{n} i$.\n\n*)\n\n(*Fixpoint sum_it (n : nat) (a : nat) : nat :=\n  match n with\n   | 0 => a\n   | S m => sum (m) (a + n)\nend.*)\n\nFixpoint sum (n : nat) : nat :=\n  match n with\n   | 0 => 0\n   | S m => n + sum m\nend.\n\n(**\n\n  *** Question 2  (un peu plus cors\u00e9e)\n\nD\u00e9montrer le th\u00e9or\u00e8me classique de la somme : $2 \\times \\sum^n_{i=1} = n * (n + 1)$.\n\n*)\n\nExample sum1 : forall n : nat, sum 3 = 6.\nProof.\ncompute.\nreflexivity.\nQed.\n\nTheorem arith_sum :\nforall n: nat, 2 * sum n = n * (n + 1).\n\nProof.\ninduction n as [| n'].\n-simpl.\n trivial.\n\n-simpl.\n SearchRewrite ( _ * S (_) ).\n rewrite mult_succ_r.\n SearchPattern ( S _ = S _ ).\n apply eq_S.\n rewrite <- IHn'.\n ring.\nQed.\n\n(**\n\n ** Exercice : la factorielle\n\n\n *** Question 1\n\nSoit la fonction factorielle sur les entiers naturels.\n\n*)\n\nFixpoint fact (n:nat) : nat :=\n  match n with\n    | O => 1\n    | S m => fact m * n\n  end.\n\nExample fact_5: fact 5 = 120.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n(**\n\nD\u00e9finir une version [fact_it] r\u00e9cursive terminale de la factorielle.\n\n*)\n\nFixpoint fact_it (n:nat) (a:nat) : nat :=\n  match n with\n    | O => a\n    | S m => fact_it m (a * n)\n  end.\n\nExample factit_5: fact_it 5 1 = 120.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n(**\n\n *** Question 2\n\nD\u00e9montrer le lemme suivant :\n\n*)\n\nLemma fact_it_lemma:\n  forall n k:nat, fact_it n k = k * (fact n).\nProof.\nintros n.\ninduction n as [| n'].\n-intro k.\n simpl.\n SearchRewrite( _ * 1).\n rewrite mult_1_r.\n reflexivity.\n\n- intro k.\n  simpl.\n  rewrite IHn'.\n  SearchRewrite ( _ * ( _ * _) ).\n  rewrite mult_assoc.\n  ring.\nQed.\n\n\n(** \n\n *** Question 3\n\nEn d\u00e9duire un th\u00e9or\u00e8me permettant de relier\n les deux versions de la factorielle.\n\n*)\n\nTheorem eq_fact_factit :\n  forall n:nat, fact_it n 1 = fact n.\nProof.\nintros n.\ninduction n as [| n'].\n\n-simpl.\n trivial.\n\n-simpl.\nrewrite fact_it_lemma.\nring.\nQed.\n\n\n(**\n\n  ** Exercice : Fibonacci\n\n  *** Question 1\n\nD\u00e9finir une fonction [fib] de calcul de la suite\n de Fibonacci.\n\n*)\n\nFixpoint fib (n:nat) : nat :=\nmatch n with\n  | 0 => 1\n  | 1 => 1\n  | S m => fib (S m) + fib (m)\nend.\n\nExample fib_ex: fib 4 = 5.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n(**\n\n  *** Question 2\n\nD\u00e9montrer par cas le lemme suivant :\n\n*)\n\nLemma fib_plus_2: \n  forall n:nat, fib (S (S n)) = fib n + fib (S n).\nProof.\nintro n.\ninduction n as [| n'].\n\n-simpl.\n reflexivity.\n\n-Abort.\n\n\n(**\n\n *** Question 3 :\n\nDonner une d\u00e9finition [fib_it] r\u00e9cursive terminale de Fibonacci. \n\n*)\n\nFixpoint fib_aux (n:nat) (a:nat) (b:nat) : nat :=\n    match n with\n      | 0 => b\n      | S (m) => fib_aux m (b) (a + b)\nend.\n\nDefinition fib_it (n:nat) : nat := fib_aux n 0 1.\n\n(**\n\n  *** Question 4\n\nD\u00e9montrer le th\u00e9or\u00e8me suivant :\n\n*)\n \nTheorem fib_it_fib:\n  forall n:nat, fib_it n 1 1 = fib n.\nProof.\n  (* <<COMPLETER ICI>> *)\n\n\n", "meta": {"author": "ebtaleb", "repo": "SVP", "sha": "cac36c82a07248ccfc078207e43678b5f5b19e3d", "save_path": "github-repos/coq/ebtaleb-SVP", "path": "github-repos/coq/ebtaleb-SVP/SVP-cac36c82a07248ccfc078207e43678b5f5b19e3d/TD02/arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.9032942125614059, "lm_q1q2_score": 0.841384696917919}}
{"text": "(**\n* Induction in Coq\n*)\n\nRequire Import List.\nImport ListNotations.\n\n(**********************************************************************)\n\n(** Recursive functions *)\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\nTheorem nil_app : forall (A:Type) (lst : list A),\n  [] ++ lst = lst.\nProof.\n  intros A lst.\n  simpl.\n  trivial.\nQed.\n\nTheorem app_nil : forall (A:Type) (lst : list A),\n  lst ++ [] = lst.\nProof.\n  intros A lst. \n  simpl. (* cannot simplify *)\n  destruct lst. (* case analysis *)\n  - trivial.\n  - simpl.  (* can't proceed *)\nAbort.\n\n(* Case analysis doesn't work. We need to apply _induction_ *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(**********************************************************************)\n\n(** Induction on lists\n\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\nFor the base case, \n\nCase:  lst = []\nShow:  P([])\n\nFor the inductive case, \n\nCase:  lst = h::t\nIH:    P(t)\nShow:  P(h::t)\n\nQED.\n>>\n\nHere's how that proof could be written:\n\n<<\nTheorem:  for all lists lst, lst ++ [] = lst.\n\nProof:  by induction on lst.\nP(lst) = lst ++ [] = lst.\n\nCase:  lst = []\nShow:\n  P([])\n= [] ++ [] = []\n= [] = []\n\nCase:  lst = h::t\nIH: P(t) = (t ++ [] = t)\nShow\n  P(h::t)\n= (h::t) ++ [] = h::t     // by definition of P\n= h::(t ++ []) = 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.\n intros A lst. \n induction lst. (* new tactic *)\n- simpl. trivial.\n- simpl.\n  rewrite -> IHlst. (* new tactic *)\n  trivial.\nQed.\n\nPrint app_nil.\n\nCheck list_ind.\n\nTheorem app_assoc : forall (A:Type) (l1 l2 l3 : list A),\n  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n  intros A l1 l2 l3.\n  induction l1.\n  - simpl. trivial.\n  - simpl. rewrite <- IHl1. trivial.\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** Induction on natural numbers\n\nProve [0 + 1 + ... + n = n * (n+1) / 2].\n\nThe structure of a proof by induction on the 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\nIn Coq, natural numbers are encoded using Peano numerals, credited to Giuseppe Peano (1858-1932).\n\n<<\ntype nat = O | S of nat\n>>\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\nThe Coq definition of [nat] is much the same:\n*)\n\nPrint nat.\n\n(** We can even write computations using those constructors: *)\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(**\n\nLet's get back to our goal. To prove [1+2+...+n = n * (n+1) / 2].\n\nIn Coq, it will turn out to be surprisingly tricky...\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(**********************************************************************)\n\n** Recursive functions, revisited\n\nHere's a first attempt at defining [sum_to] *)\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n = 0 then 0 else n + sum_to (n-1).\n(* [Fail] keyword -- expect definition to fail *)\n\n(**\n[=] returns [Prop]. We need something that returns [bool]. Such an operator is defined in the [Arith] library for us: \n*)\n\nRequire Import Arith.\n\nLocate \"=?\".\nCheck Nat.eqb.\n\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n =? 0 then 0 else n + sum_to (n-1).\n\n(** A digression. Let's look at a different recursive function---one that implements an infinite loop: *)\n\nFail Fixpoint inf (x:nat) : nat := inf x.\n\n(**\n  + Coq does not permit any infinite loops\n\nConsider [inf] in OCaml:\n\n<<\n# let rec inf x = inf x\nval inf : 'a -> 'b = <fun>\n>>\n\n  + Type ['a -> 'b] would be [A -> B] in Coq. \n  + If [A] is [True] and [B] is [False], then [inf] would be evidence for [True -> False].\n  + We can derive contradiction by [inf I]!!!\n  \nCan't we just rule out infinite programs?\n\n  + But _halting problem_ is undecidable:  we can't write a program that precisely determines whether another program will terminate.\n  + Coq goes for imprecise solution -- recursive calls must be on syntactically smaller term.\n    - [n] syntactically smaller than [n+1]\n    - [n-1] syntactically larger than [n].\n*)\n\nFail Fixpoint sum_to (n:nat) : nat :=\n  if n =? 0 then 0 else n + sum_to (n-1).\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\nPrint nat.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(**********************************************************************)\n\n(** Inductive proof of the summation formula\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.\n  - simpl. trivial.\n  - simpl. rewrite -> IHn.\nAbort.\n\n(** [Nat.divmod] is integer division. \n\nTo avoid having to reason about division, multiply both sides by 2 *)\n\nTheorem sum_sq_no_div : forall n : nat,\n  2 * sum_to n = n * (n+1).\nProof.\n  intros n.\n  induction n.\n  - trivial.\n  - simpl.\nAbort.\n\n(** [simpl] is too agressive! Let's define a helper _lemma_. *)\n\n(* + Natural numbers with [+] and [*] form a _ring_\n     - https://en.wikipedia.org/wiki/Ring_(mathematics)\n   + Coq has good support for proofs on rings\n*)\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.\n  ring. (* new tactic *)\nQed.\n\n(** Now 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.\n  - trivial.\n  - rewrite sum_helper.\n    rewrite IHn.\n    ring.\nQed.\n\n(** \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\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 [b * a / b].  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.\n\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\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\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 IHn.\nAbort.\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.\n    rewrite (IHn (acc * S n)). (* to get the correct term to reduce *)\n    rewrite (IHn (S (n + 0))).\n    ring.\nQed.\n\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*)", "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/Induction_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.9059898248255074, "lm_q1q2_score": 0.8411289211978314}}
{"text": "(* Taken from: http://www.enseignement.polytechnique.fr/informatique/INF551/TD/TD5/ *)\n\nRequire Import List ssreflect ssrbool.\nFrom mathcomp Require Import eqtype ssrnat.\n\n(* Let's see how one would define insertion sort in OCaml:\n\n   let rec insert n l =\n     match l with\n       | [] -> [n]\n       | x::xs -> if n <= x then n::x::xs else x::(insert n xs)\n\n   let rec sort l =\n     match l with\n       | [] -> []\n       | x::xs -> insert x (sort xs)\n\n   As you saw during the lesson, the [insert] function is just some\n   particular proof of [nat -> list nat -> list nat]: it is the proof\n   that builds a new list by inserting its first arguments into its\n   second one. As any proof, it thus can be defined in Coq using tactics.\n *)\n\nDefinition insert (n:nat) (l:list nat) : list nat.\nProof.\n  (* The OCaml program is a recursive definition over l. I just do\n     exactly the same with the elim tactic. The induction hypothesis ih\n     is a proof of insert n xs : in fact it is the recursive call. *)\n  elim:l => [|x xs ih].\n  (* We start with the base case: we return the singleton list\n     containing only n. *)\n   apply:(n::nil).\n  (* We are now in the recursive case. We need to distinguish two cases\n     whether n <= x or not. *)\n  case h:(n <= x).\n  (* We are in the branch where n <= x. In this case, we can immediately\n     return the list n::x::xs *)\n    apply:(n::x::xs).\n  (* We now are in the branch where n > x. In this case, we want to\n     return x::(insert n xs). As we said, the recursive call is in fact\n     ih. *)\n  apply:(x::ih).\n  (* Our function is now defined using tactics. [Defined] checks that it\n     actually have the right type and defines it. *)\n Defined.\n\n\n(* We can check on some examples that it is indeed the insert function\n   we add in mind. Coq can actually compute with it! *)\n\nCompute (insert 5 (1::2::3::4::6::7::8::9::nil)).\nCompute (insert 5 (1::2::3::4::nil)).\n\n\n(* Now do the same for the sort function, and test it on some examples.\n   Hint: it takes only three tactics to define it! *)\n\nDefinition sort (l:list nat) : list nat.\nProof.\n  (* Break up the recursive definition and get the induction hypothesis. *)\n  elim:l => [|x xs ih].\n  (* first the base case which is the empty list *)\n  apply:(nil).\n  (* the step case which is the recursive call which inserts the current element\n     and sorts the rest of the list. *)\n  apply:(insert x ih).\nDefined.\n\n\nCompute (sort (7::9::5::3::0::4::2::1::8::6::nil)).\n(* Add your own examples... *)\nCompute (sort (1::0::2::3::nil)).\nCompute (sort (0::1::2::nil)).\n\n(* Ok, so far we have understood that we can define function using\n   tactics. But our sorting function is no more that the OCaml version:\n   we did not prove it was actually returning a list that is sorted!\n   With tactics, we will be able to build the sorting function AND proof\n   its correctness at the same time... *)\n\n\n(* First, we need to define for a list of integers what it means to be\n   sorted: each element is smaller than all the following elements *)\n\nFixpoint smaller n l : Prop :=\n  match l with\n    | nil => true\n    | x::xs => n <= x /\\ smaller n xs\n  end.\n\n\nFixpoint sorted l : Prop :=\n  match l with\n    | nil => true\n    | x::xs => smaller x xs /\\ sorted xs\n  end.\n\n\n(* We give a very simple fact about smaller: if a is smaller than all\n   the elements of a list l, and n <= a, then n is also smaller than all\n   the elements of l. *)\n\nLemma smaller_trans n a l : smaller a l -> n <= a -> smaller n l.\nProof.\n  elim:l => /=.\n    done.\n  move => b l ih. \n  move => [h1 h2] h3.\n  split.\n    move/(_ a n b):leq_trans => h4.\n    by apply:h4.\n  by apply:ih.\nDefined.\n\n\n(* For a matter of time, we also give you some arithmetic lemmas that\n   you will need:\n\n   o leq_false_lt m n : (m <= n) = false -> (n < m)\n   o leq_false_leq n x : (n <= x) = false -> x <= n\n   o eq_refl (n:nat) : n == n\n   o gtn_eqF m n : m < n -> n == m = false\n   o leq_false_neq n a : (n <= a) = false -> n == a = false\n\n   Do not look at the proofs, just look at the statements above. *)\n\nLemma leq_trans n m p : m <= n -> n <= p -> m <= p.\nProof.\n  elim: n m p => [|i IHn] [|m] [|p]; try reflexivity.\n        move => h _. apply:h.\n      compute. discriminate 1.\n    move => _. compute => h. apply:h.\n  by move/(_ m p):IHn.\nDefined.\n\n\nLemma ltnW m n : m < n -> m <= n.\nProof. by apply:leq_trans. Defined.\n\n\nLemma leq_false_lt m n : (m <= n) = false -> (n < m).\nProof.\n  elim: m n => [|m IHm] [|n].\n        compute. discriminate 1.\n      compute. discriminate 1.\n    reflexivity.\n  by move/(_ n):IHm.\nDefined.\n\n\nLemma leq_false_leq n x : (n <= x) = false -> x <= n.\nProof.\n  move => h.\n  apply:ltnW.\n  by apply:leq_false_lt.\nDefined.\n\n\nLemma eq_refl (n:nat) : n == n.\nProof.\n  elim:n => [|n ih].\n    reflexivity.\n  exact:ih.\nDefined.\n\n\nLemma leqNgt m n : (m <= n) = ~~ (n < m).\nProof. by elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.\n\n\nLemma eqn_leq m n : (m == n) = (m <= n <= m).\nProof. elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.\n\n\nLemma gtn_eqF m n : m < n -> n == m = false.\nProof. by rewrite eqn_leq (leqNgt n) => ->. Defined.\n\n\nLemma leq_false_neq n a : (n <= a) = false -> n == a = false.\nProof.\n  move => h.\n  apply:gtn_eqF.\n  by apply: leq_false_lt.\nDefined.\n\n\n(* We are now ready to build the insert function and prove its\n   correctness at the same time. To do so, the Coq writing {l | P l}\n   that designates a list l that satisfies the predicate P: P is the\n   specification of the function.\n\n   The specification of the insert function is the following:\n   o if a is smaller that all the elements of l and a <= n then a is\n     smaller than all the elements of (insert n l)\n   o if l is sorted then (insert n l) is sorted *)\n\nDefinition insert_spec n l :\n  {l' |\n    (forall a, smaller a l -> a <= n -> smaller a l') /\\\n    (sorted l -> sorted l')}.\nProof.\n  (* The proof is a refinement of the proof of [insert], in which we\n     also build the proof of the specification of the function. So like\n     for defining [insert], we do an induction. *)\n  elim:l => [|x xs ih].\n  (* We present the base case. The answer is the singleton list\n     containing only n, together with a proof that this list satisfies\n     the specification. We first give the list, using the exists tactic.\n     *)\n    exists (n::nil).\n    (* Let's now prove the specification. It is a conjunction. *)\n    split.\n    (* On the first branch, we introduce a. *)\n      move => a.\n      (* We can simplify this goal: we know what [smaller a nil] and\n         [smaller a (n :: nil)] mean. *)\n      simpl.\n      (* In fact, this goal is trivially proved with done. *)\n      done.\n      (* Let's simplify the second branch: we know what [sorted nil] and\n         [sorted (n :: nil)] mean. *)\n    simpl.\n    (* In fact, this goal is trivially proved with done. *)\n    done.\n    (* Now do the recursive case. Do not forget to make a case analysis\n       whether n <= x or not. You can destruct a proof of {l | P l}\n       using the [case] tactic as usual. *)\n  case:ih => [l4 [ih1 ih2]].\n  case h:(n <= x).\n    (* n is smaller then x *)\n    exists (n::x::xs).\n    split => //.\n    move => [h1 h2].\n    split => //.\n    split => //.\n    apply:(smaller_trans _ _ _ h1).\n    done.\n    (* n is greater then x *)\n    exists (x::l4) => /=.\n    split.\n    move => a.\n    move => [h1 h2].\n    move => h3.\n    split => //.\n     by apply ih1.\n    move => [h1 h2].\n    split.\n    apply:ih1 => //.\n     by apply leq_false_leq.\n      by apply ih2.\nDefined.\n\n\n(* Let do the same for the sort function. *)\n\nDefinition sort_spec (l:list nat) : {l' | sorted l'}.\nProof.\n  elim:l => [| x xs [l4 ih]].\n  (* base case *)\n  exists (nil).\n  done.\n  (* step case *)\n  case (insert_spec x l4) => [l5 [h1 h2]].\n  exists (l5).\n   by apply h2.\nDefined.\n\n\n(* We now have defined functions that are correct (with respect to our\n   specification) by construction. Finally, Coq offers an extraction\n   mechanism, that automatically export them to OCaml, so we are sure\n   that the OCaml program is correct by construction. *)\n\nRequire Extraction.\nExtraction Language Ocaml.\nSet Extraction AccessOpaque.\n\n\nExtraction \"insert_sort.ml\" sort_spec.\n\n\n(* Have a look at the file \"insert_sort.mli\". You observe that the\n   function [sort_spec] has type [nat list -> nat list]: the extraction\n   mechanism \"forgets\" the proof of the correctness of this function,\n   since it has no signification in OCaml. You can test this extracted\n   function using the file \"test_sort.ml\". *)\n\n\n(* TO GO FURTHER *)\n\n\n(* I am sure you all have noticed that our specification is incomplete:\n   the sort function must not only return a sorted list, but this list\n   must be a permutation of the initial list! We now do the same job\n   with a complete specification. *)\n\n(* We first define our notion of permutation: (x::xs) and l2 are a\n   permutation if and only if xs and (remove x l2) are. *)\n\nFixpoint remove a (l:list nat) :=\n  match l with\n    | nil => None\n    | x::xs =>\n      if a == x then\n        Some xs\n      else\n        match remove a xs with\n          | Some xs' => Some (x::xs')\n          | None => None\n        end\n  end.\n\n\nFixpoint permutation l1 l2 : Prop :=\n  match l1, l2 with\n    | nil, nil => true\n    | nil, _ => False\n    | x::xs, _ =>\n      match remove x l2 with\n        | Some l2' => permutation xs l2'\n        | None => False\n      end\n  end.\n\n\n(* First prove that this relation is reflexive. *)\n\nLemma permutation_refl l: permutation l l.\nProof.\n  (* TODO *)\nDefined.\n\n\n(* Now define insertion and sort with the complete specification. *)\n\nDefinition insert_complete n l :\n  {l' |\n    (forall a, smaller a l -> a <= n -> smaller a l') /\\\n    (remove n l' = Some l) /\\\n    (sorted l -> sorted l' /\\ permutation (n::l) l')}.\nProof.\n  (* TODO *)\nDefined.\n\n\nDefinition sort_complete (l:list nat) : {l' | sorted l' /\\ permutation l l'}.\nProof.\n  (* TODO *)\nDefined.\n\n\nExtraction Language Ocaml.\nSet Extraction AccessOpaque.\n\n\nExtraction \"insert_sort.ml\" sort_complete.\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/extraction/Insert_Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.911179702173019, "lm_q1q2_score": 0.8410545566116845}}
{"text": "Module Playgroud1.\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 Playgroud1.\n\n\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | (S O) => false\n  | (S (S a)) => evenb a\n  end.\n\nDefinition oddb (n:nat) : bool :=\n  negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O)))))\n                    = false.\nProof. reflexivity. Qed.\n\nModule Playground2.\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | (S n') => S (plus n' m)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. reflexivity. Qed.\n\nFixpoint minus (m n : nat) :=\n  match m, n with\n  | O, _ => 0\n  | S m', O => m\n  | (S m'), (S n') => minus m' n'\n  end.\n\nEnd Playground2.\n\nFixpoint exp (a n : nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => (mult a (exp a n'))\n  end.\n\n\nFixpoint factorial (n : nat) : nat :=\n  match n with\n  | O => 1\n  | 1 => 1\n  | (S n') => (mult n (factorial n'))\n  end.\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. 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.\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | _ => false\n    end\n  | S n' => match m with\n            | O => false\n            | S m' => (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\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\nDefinition blt_nat (n m : nat) : bool :=\n  (andb (ble_nat n m) (negb (beq_nat n m))).\n\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nDefinition bgt_nat (n m : nat) : bool := negb (ble_nat n m).\nDefinition bge_nat (n m : nat) : bool := negb (blt_nat n m).\n\n\n\n(* proof by simplification *)\n\nTheorem plus_0_n : forall n: nat, 0 + n = n.\nProof.\n  intro n.\n  reflexivity.\nQed.\n\n\nTheorem plus_1_l : forall n: nat, 1 + n = S n.\nProof.\n  intro n.\n  reflexivity.\nQed.\n\n\nTheorem mult_0_l : forall n: nat, 0 * n = 0.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\n\n(* proof by rewriting *)\n\nTheorem plus_id_example : forall n m : nat,\n  n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intro H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H H'.\n  rewrite H.\n  rewrite H'.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_0_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intro H.\n  rewrite plus_1_l.\n  rewrite H.\n  reflexivity.\nQed.\n\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intro n.\n  destruct n as [| n'].\n  reflexivity.\n  simpl. reflexivity.\nQed.\n\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intro n.\n  destruct n as [| n']; reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall b : bool, f (f b) = b.\nProof.\n  intros.\n  rewrite H.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = negb x) ->\n  forall b : bool, f (f b) = b.\nProof.\n  intros.\n  rewrite H.\n  rewrite H.\n  destruct b; (compute; reflexivity).\nQed.\n\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  destruct b, c; simpl.\n  reflexivity.\n  intro. rewrite H. reflexivity.\n  intro. rewrite H. reflexivity.\n  reflexivity.\nQed.\n\n\nInductive bin : Type :=\n  | O : bin\n  | T2 : bin -> bin\n  | T1 : bin -> bin.\n\nFixpoint inc(n : bin) :=\n  match n with\n  | O => T1 O\n  | T1 a => T2 (inc a)\n  | T2 a => T1 a\n  end.\n\nExample inc_O_is_T1O : inc O = T1 O.\nProof. reflexivity. Qed.\nExample inc_1_is_T2T1O : inc (T1 O) = T2 (T1 O).\nProof. reflexivity. Qed.\nExample inc_2_is_T1T10 : inc (T2 (T1 O)) = T1 (T1 O).\nProof. reflexivity. Qed.\nExample inc_3_is_T2T20 :\n  inc (T1 (T1 O)) = T2 (T2 (T1 O)).\nProof. reflexivity. Qed.\n\nFixpoint bin2nat(n : bin) : nat :=\n  match n with\n  | O => 0\n  | T1 a => (bin2nat a) * 2 + 1\n  | T2 a => (bin2nat a) * 2\n  end.\n\n\n(* TODO *)\n\n(*\nFixpoint nat2bin(n : nat) : bin :=\n  match n with\n  | 0 => O\n  | evenb n     => T2 (nat2bin n)\n  | oddbb 1 => T1 (nat2bin n)\n  end.\n  *)\n\n(*\n   exercise: write a fix-point definition that\n   does terminate on all input but coq does not\n   accept because of this restriction.\n*)\n\n(*\nFixpoint plus' (n m : nat) : nat :=\n  match n with\n  | 0 => m\n  | S 0 => S (plus' 0 m)\n  | S (S n') => S (plus' n' (S m))\n  end.\n*)\n\n(* this is cool *)\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/A002nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.8409900446817162}}
{"text": "Require Import Arith.\nTheorem restricted_excluded_middle\n  : forall P b, (P <-> b = true) -> P \\/ not P.\nProof.\n  intros P b H.\n  destruct b.\n  - left. apply H. reflexivity.\n  - right. intros F. apply H in F. inversion F.\nQed.\n\nTheorem restricted_excluded_middle_eq\n  : forall (n m: nat), n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n = m) (Nat.eqb n m)).\n  symmetry.\n  apply Nat.eqb_eq.\nQed.\n\n", "meta": {"author": "elle-et-noire", "repo": "coq-wsl", "sha": "f3e43ed79fa6358d061e1bb574e234a36e298392", "save_path": "github-repos/coq/elle-et-noire-coq-wsl", "path": "github-repos/coq/elle-et-noire-coq-wsl/coq-wsl-f3e43ed79fa6358d061e1bb574e234a36e298392/exmid/exmid01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8408470912698157}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export BasicTactics.\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives.\n\n*)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions \n    ([forall x, P]).  \n*)\n\n\n(** In Coq, the type of things that can (potentially) \n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated \n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P]. \n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.  \nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on\nequality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat \n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that\ntakes evidence for [P] as input and produces evidence for [Q] as its\noutput.\n*)     \n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?  \n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other\n      datatype.\n\n    - Sometimes a proposition is declared to be true without\n      substantiating evidence.  Such propositions are called _axioms_.\n\n    In this and subsequent chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" conjunctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  - (* left *) reflexivity.\n  - (* right *) reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    - (* left *) reflexivity.\n    - (* right *) reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [destruct] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  destruct H as [HP HQ]. \n  split.  \n    - (* left *) apply HQ. \n    - (* right *) apply HP.  Qed.\n  \n\n(** **** Exercise: 2 stars (and_assoc)  *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [destruct] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  destruct H as [HP [HQ HR]].\n   - split.\n     + split. \n       * apply HP.\n       * apply HQ.\n     + apply HR.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) \n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  destruct H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  destruct H as [HAB HBA].\n  split.\n    - (* -> *) apply HBA.\n    - (* <- *) apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [destruct] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    - (* left *) apply or_intror. apply HP.\n    - (* right *) apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    - (* left *) right. apply HP.\n    - (* right *) left. apply HQ.  Qed.\n\n\n\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. destruct H as [HP | [HQ HR]]. \n    - (* left *) split.\n      + (* left *) left. apply HP.\n      + (* right *) left. apply HP.\n    - (* right *) split.\n      + (* left *) right. apply HQ.\n      + (* 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 as [HPQ HPR]. inversion HPQ as [HP | HQ].\n  - left. apply HP.\n  - inversion HPR as [ HP | HR ].\n    + left. apply HP.\n    + right. apply conj.\n      * apply HQ. \n      * apply HR.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    - (* b = true *) destruct c.\n      + (* c = true *) apply conj. reflexivity. reflexivity.\n      + (* c = false *) inversion H.\n    - (* b = false *) inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct H.\n  rewrite H. rewrite H0. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (andb_false)  *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (orb_false)  *)\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (orb_false_elim)  *)\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True)  *)\n(** Define [True] as another inductively defined proposition.  (The\n    intuition is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. destruct H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not. unfold not in H0. intros HP. apply H0. apply H. apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [~P] \n     from evidence for [P]. *) \n  Abort.\n  (** **** 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\nTheorem classic_implies_peirce : classic -> peirce.\nProof.\n  unfold peirce. unfold classic.\n  intros. apply H. intros negP. unfold not in negP. apply negP. \n  apply H0. intros Hp. apply ex_falso_quodlibet. \n  apply negP. apply Hp.\nQed.\n\n(* helper lemma *)\nLemma demorgan_neg_or_implies_and_neg : forall A B, ~ (A \\/ B) -> (~ A) /\\ (~ B).\nProof.\n  intros. split.\n  - unfold not. unfold not in H. intros Ha. apply H. left. apply Ha.\n  - unfold not. unfold not in H. intros Hb. apply H. right. apply Hb.\nQed.\n\nTheorem classic_implies_excluded_middle : classic -> excluded_middle.\nProof.\n  unfold classic. unfold excluded_middle.\n  intros. apply H. intros Hp. apply demorgan_neg_or_implies_and_neg with (A:=P) (B:=P->False) in H.\n  - destruct H. apply H0. apply H.\n  - apply double_neg. apply Hp. \nQed.\n\nTheorem excluded_middle_implies_classic : excluded_middle -> classic.\nProof.\n  unfold classic. unfold excluded_middle. \n  intros. destruct (H P).\n  - apply H1.\n  - apply H0 in H1. inversion H1.\nQed.\n\nTheorem classic_implies_de_morgan_not_and_not :\n  classic -> de_morgan_not_and_not.\nProof.\n  unfold classic. unfold de_morgan_not_and_not. \n  intros. apply H. intros neg_P_or_Q. \n  apply H0. apply demorgan_neg_or_implies_and_neg. apply neg_P_or_Q.\nQed.\n\nTheorem de_morgan_not_and_not_implies_excluded_middle : de_morgan_not_and_not -> excluded_middle.\nProof.\n  unfold de_morgan_not_and_not. unfold excluded_middle.\n  intros. apply H. \n  intros neg_negP_and_negnegP. \n  destruct neg_negP_and_negnegP. apply H1. apply H0. \nQed.\n\nTheorem excluded_middle_implies_implies_to_or : excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle. unfold implies_to_or.\n  intros. destruct (H P).\n  - right. apply H0. apply H1.\n  - left. apply H1.\nQed.\n\nTheorem implies_to_or_implies_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or. unfold excluded_middle.\n  intros. destruct (H P P).\n  - intros. apply H0. \n  - right. apply H0.\n  - left. apply H0.\nQed.\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).  \nProof.\n  intros. unfold not. intros. apply H. right.  intros. apply H. left. apply H0.\nQed.\n  \n\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  - (* b = true *) reflexivity.\n  - (* b = false *)\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n\n\n\n(** **** Exercise: 2 stars (false_beq_nat)  *)\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof. \n   intros n.\n   induction n.\n   -  intros. unfold not in H. destruct m.\n     +  simpl. apply ex_falso_quodlibet. apply H. reflexivity.\n     +  simpl.  reflexivity.\n   - intros.  unfold not in H. destruct m.\n     + simpl. reflexivity.\n     + simpl. apply IHn. unfold not. intros Hnm. apply H. rewrite Hnm. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_false)  *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  intros n. induction n.\n  - intros. unfold not. intros. rewrite <- H0 in H. simpl beq_nat in H. inversion H.\n  - intros. unfold not. intros. rewrite <- H0 in H. simpl beq_nat in H. \n    assert (H_n_eq_n: forall k, beq_nat k k = true).\n    { induction k.\n      + simpl. reflexivity.\n      + simpl. apply IHk.\n    }\n    rewrite H_n_eq_n in H. inversion H.\n\n  Qed.\n(** [] *)\n\n\n(** $Date: 2015-08-17 20:23:49 +0200 (Mon, 17 Aug 2015) $ *)\n\n", "meta": {"author": "jam231", "repo": "Software-Foundations", "sha": "c9a889edd379333153ffcf14fbdfba050b357000", "save_path": "github-repos/coq/jam231-Software-Foundations", "path": "github-repos/coq/jam231-Software-Foundations/Software-Foundations-c9a889edd379333153ffcf14fbdfba050b357000/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.9381240116814386, "lm_q1q2_score": 0.8407949414381972}}
{"text": "From LF Require Export Basics.\nFrom Coq Require Import Unicode.Utf8.\nSet Printing All.\n\nTheorem add_0_r : \u2200 n : nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem minus_n_n : \u2200 n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) simpl. reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nTheorem mul_0_r : \u2200 n : nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nTheorem plus_n_Sm : \u2200 n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nTheorem add_comm : \u2200 n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *) simpl. rewrite -> add_0_r. reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. \n  Qed.\n\nTheorem add_assoc : \u2200 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 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nFixpoint double (n : nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : \u2200 n, double n = n + n .\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. \n  Qed.\n\nTheorem eqb_refl : \u2200 n : nat,\n  (n =? n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. \n  Qed.\n\nTheorem even_S : \u2200 n : nat,\n  even (S n) = negb (even n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) \n    rewrite -> IHn'.\n    rewrite -> negb_involutive.\n    reflexivity.\n  Qed.\n\nTheorem mult_0_plus' : \u2200 n m : nat,\n  (n + 0 + 0) * m = n * m.\nProof.\n  intros n m.\n  assert (H: n + 0 + 0 = n).\n    { rewrite add_comm. simpl. rewrite add_comm. reflexivity. }\n  rewrite -> H.\n  reflexivity. \n  Qed.\n\nTheorem add_shuffle3 : \u2200 n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> add_assoc.\n  rewrite -> add_assoc.\n  assert (H: n + m = m + n).\n  { rewrite -> add_comm. reflexivity. }\n  rewrite -> H. reflexivity.\n  Qed.\n\nTheorem mul_comm : \u2200 m n : nat,\n  m * n = n * m.\nProof.\n  intros m n. \n  destruct m as [| m'].\n  - (* m = 0 *) simpl. rewrite -> mul_0_r. reflexivity.\n  - (* m = S m' *) induction n as [| n' IHn']. \n    + (* n = 0 *) \n      simpl. rewrite -> mul_0_r. reflexivity.\n    + (* n = S n' *) \n      simpl. rewrite <- IHn'. simpl. rewrite <- mult_n_Sm.\n      assert (H1: m' + (n' + m' * n') = n' + (m' + m' * n')).\n      { rewrite -> add_shuffle3. reflexivity. }\n      assert (H2: m' * n' + m' = m' + m' * n').\n      { rewrite -> add_comm. reflexivity. }\n      rewrite -> H1. rewrite -> H2.\n      reflexivity.\n  Qed.\n\nTheorem plus_leb_compat_l : \u2200 n m p : nat,\n  n <=? m = true \u2192 (p + n) <=? (p + m) = true.\nProof.\n  intros n m p H. induction p as [| p' IHp'].\n  - (* p = 0 *) simpl. rewrite -> H. reflexivity.\n  - (* p = S p' *) simpl. rewrite -> IHp'. reflexivity.\n  Qed.\n\nTheorem leb_refl : \u2200 n:nat,\n  (n <=? n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity.\n  Qed.\n\nTheorem zero_nbeq_S : \u2200 n : nat,\n  0 =? (S n) = false.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem zero_nbeq_S' : \u2200 n : nat,\n  0 =? (S n) = false.\nProof.\n  induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. reflexivity.\n  Qed.\n\nTheorem andb_false_r : \u2200 b : bool,\n  andb b false = false.\nProof.\n  intros b. destruct b.\n  - (* b = true *) reflexivity.\n  - (* b = false *) reflexivity.\n  Qed.\n\nTheorem mult_1_l : \u2200 n:nat, 1 * n = n.\nProof.\n  intros n. simpl. rewrite -> add_0_r. reflexivity.\n  Qed.\n\nTheorem all3_spec : \u2200 b c : bool,\n  orb\n    (andb b c)\n    (orb (negb b)\n         (negb c))\n  = true.\nProof.\n  intros b c. destruct b.\n  - (* b = true *) destruct c.\n    + (* c = true *) reflexivity.\n    + (* c = false *) reflexivity.\n  - (* b = false *) destruct c.\n    + (* c = true *) reflexivity.\n    + (* c = false *) reflexivity.\n  Qed.\n\nTheorem mult_plus_distr_r : \u2200 n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p. induction n as [| n' IHn'].\n  - (* n = 0 *) simpl. rewrite <- add_0_r. rewrite -> add_0_r. reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. rewrite -> add_assoc. reflexivity.\n  Qed.\n\n\nInductive bin : Type :=\n  | Z\n  | B0 (n : bin)\n  | B1 (n : bin)\n.\n\nFixpoint incr (m:bin) : bin\n  := match m with\n     | Z    => B1 Z\n     | B0 n => B1 n\n     | B1 n => B0 (incr n)\n     end.\n\nFixpoint bin_to_nat (m:bin) : nat\n  := match m with\n     | Z    => O\n     | B0 n => (bin_to_nat n) + (bin_to_nat n)\n     | B1 n => S ((bin_to_nat n) + (bin_to_nat n))\n     end.\n\nTheorem bin_to_nat_pres_incr : forall b : bin,\n  bin_to_nat (incr b) = 1 + bin_to_nat b.\nProof.\n  intros b.\n  induction b as [| b' | b' ].\n  - reflexivity.\n  - reflexivity.\n  - simpl.\n    rewrite -> IHb'.\n    simpl. rewrite <- plus_n_Sm.\n    reflexivity.\nQed.\n\nFixpoint nat_to_bin (n : nat) : bin\n  := match n with\n     | 0    => Z\n     | S n' => incr (nat_to_bin n')\n     end.\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n  induction n as [|n'].\n  - reflexivity.\n  - simpl.\n    rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem bin_nat_bin_fails : \u2200 b, nat_to_bin (bin_to_nat b) = b.\nAbort.\n\nLemma double_incr : \u2200 n : nat, double (S n) = S (S (double n)).\nProof.\n  intros n. reflexivity.\n  Qed.\n\nDefinition double_bin (b : bin) : bin :=\n  match b with\n  | Z => Z\n  | B0 n => B0 (B0 n)\n  | B1 n => B0 (B1 n)\n  end.\n\nLemma double_incr_bin : \u2200 b,\n  double_bin (incr b) = incr (incr (double_bin b)).\nProof.\n  intros b. induction b as [| b0' | b1' ].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nFixpoint normalize (b : bin) : bin :=\n  match b with\n  | Z     => Z\n  | B0 b' => double_bin (normalize b')\n  | B1 b' => incr (double_bin (normalize b'))\n  end.\n\nLemma nat_to_bin_double : forall n : nat,\n  nat_to_bin (double n) = double_bin (nat_to_bin n).\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite -> double_incr_bin. rewrite <- IHn.\n    reflexivity.\nQed.\n\nTheorem bin_nat_bin : forall b, nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  intros b.\n  induction b as [|b'|b'].\n  - reflexivity.\n  - simpl. rewrite <- IHb'.\n    destruct (bin_to_nat b').\n    + reflexivity.\n    + rewrite <- double_plus. rewrite nat_to_bin_double.\n      reflexivity.\n  - simpl. rewrite <- IHb'.\n    rewrite <- double_plus. rewrite nat_to_bin_double.\n    reflexivity.\n  Qed.\n", "meta": {"author": "abooishaaq", "repo": "sf", "sha": "dea49114df778f597d295594056eccfbc825e38f", "save_path": "github-repos/coq/abooishaaq-sf", "path": "github-repos/coq/abooishaaq-sf/sf-dea49114df778f597d295594056eccfbc825e38f/lf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.9005297847831082, "lm_q1q2_score": 0.8405822507016061}}
{"text": "Require Import nat.\nRequire Import bool.\n\n\nTheorem minus_diag : forall n:nat, n - n = 0.\nProof.\n    intros n. induction n.\n    - simpl. reflexivity.\n    - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem minus_diagi' : forall n:nat, n - n = 0. \nProof.\n    induction n.\n    - simpl. reflexivity.\n    - simpl. rewrite IHn. reflexivity.\nQed. \n\nFixpoint double (n:nat) : nat :=\n    match n with\n        | O     => O\n        | S p   => S (S (double p))\n    end.\n\nLemma double_plus : forall n:nat, double n = n + n.\nProof.\n    induction n as [|n IH].\n    - reflexivity.\n    - simpl. rewrite plus_n_Sm. rewrite IH. reflexivity.\nQed.\n\n\nTheorem evenb_S : forall n:nat, evenb (S n) = negb (evenb n).\nProof.\n    induction n.\n    - reflexivity.\n    - rewrite IHn. simpl. rewrite negb_involutive. reflexivity.\nQed.\n\n\n\nTheorem all3_spec: forall a b:bool,\n    orb (andb a b) (orb (negb a) (negb b)) = true.\nProof.\n    destruct a, b.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\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    replace (n + (m + p)) with ((n + m) + p).\n    replace (m + (n + p)) with ((m + n) + p).\n    replace (m + n) with (n + m).\n    reflexivity.\n    - apply plus_comm.\n    - apply plus_assoc.\n    - apply plus_assoc.\nQed.\n\n\n\nTheorem double_injective : forall (n m:nat),\n    double n = double m -> n = m.\nProof.\n    induction n as [|n H].\n    - intros m H. destruct m as [|m].\n        + reflexivity.\n        + simpl in H. inversion H.\n    - intros m H'. destruct m as [|m].\n        + simpl in H'. inversion H'.\n        + simpl in H'. inversion H' as [H1]. clear H'.\n            apply H in H1. rewrite H1. reflexivity.\nQed.\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 H0 H1 H2 H3. induction m as [| m H].\n    - induction n as [| n H].\n        + exact H0.\n        + apply H2. exact H.\n    - destruct n.\n        + assert (forall q, P q 0).\n            { induction q as [|q H'].\n                - exact H0.\n                - apply H1. exact H'.\n            } \n            apply H4.\n        + apply H3. apply H.\nQed.\n            \n\nLemma plus_comm3 : forall (n m p:nat),\n    n + (m + p) = (p + m) + n.\nProof.\n    intros n m p.\n    rewrite plus_comm.\n    assert (H : m + p = p + m). { rewrite plus_comm. reflexivity. }\n    rewrite H. reflexivity.\nQed.\n    \n\nLemma plus_comm3' : forall (n m p:nat),\n    n + (m + p) = (p + m) + n.\nProof.\n    intros n m p. rewrite plus_comm. rewrite (plus_comm m). reflexivity.\nQed.\n\nTheorem evenb_double : forall (k:nat), evenb (double k) = true.\nProof.\n    induction k as [|k H].\n    - reflexivity.\n    - simpl. exact H.\nQed.\n\nLemma evenb_negb_gen : forall (n:nat),\n(forall b:bool, evenb n = b -> evenb (S n) = negb b) /\\\n(forall b:bool, evenb (S n) = b -> evenb n = negb b).\nProof.\n    induction n as [|n [H1 H2]].\n    - split. \n        + intros b H'. rewrite <- H'. reflexivity.\n        + intros b H'. rewrite <- H'. reflexivity.\n    - split.\n        + intros b H'. apply H2. exact H'.\n        + intros b H'. apply H1. exact H'.\nQed.\n\n\nLemma evenb_negb : forall (n:nat) (b:bool),\n    evenb n = b -> evenb (S n) = negb b.\nProof.\n    intros n b. assert (\n    (forall b:bool, evenb n = b -> evenb (S n) = negb b) /\\\n    (forall b:bool, evenb (S n) = b -> evenb n = negb b) ) as [H1 H2]. \n        { apply evenb_negb_gen. }\n    apply H1.\nQed.\n\n\nTheorem evenb_double_conv : forall (n:nat), \n    exists k, n = if evenb n \n        then double k\n        else S (double k).\nProof.\n    induction n as [|n H].\n    - exists 0. reflexivity.\n    - destruct (evenb n) eqn: H'. \n        + destruct H as [k H]. exists k. \n            apply evenb_negb in H'. rewrite H'. rewrite H. reflexivity.\n        + destruct H as [k H]. exists (S k).\n            apply evenb_negb in H'. rewrite H'. simpl. rewrite H. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall (n:nat),\n    evenb n = true <-> exists k, n = double k.\nProof.\n    intros n. split.\n    - intros H. assert ( exists k, n = if evenb n \n        then double k\n        else S (double k) ) as [k H']. { apply evenb_double_conv. }\n            rewrite H in H'. exists k. exact H'.\n    - intros [k H]. rewrite H. apply evenb_double.\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/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.9032941982430049, "lm_q1q2_score": 0.8404775404114043}}
{"text": "Require Import Reals.\nRequire Import Classical_Prop.\nRequire Import Waterproof.AllTactics.\nRequire Import Waterproof.notations.notations.\nRequire Import Waterproof.load.\nImport databases_RealsAndIntegers.\nRequire Import Waterproof.set_search_depth.To_5.\n\nOpen Scope R_scope.\nOpen Scope subset_scope.\n\n(** Definitions *)\nDefinition open_ball (p : R) (r : R) : subset R := as_subset _ (fun x => | x - p | < r).\n\nDefinition is_interior_point (a : R) (A : R -> Prop) :=\n  there exists r : R, (r > 0) /\\ (for all x : R, x : (open_ball a r) -> A x).\n\nDefinition is_open (A : R -> Prop) := for all a : R, A a -> is_interior_point a A.\n\nDefinition complement (A : R -> Prop) : subset R := as_subset _ (fun x => not (A x)).\n\nDefinition is_closed (A : R -> Prop) := is_open (complement A).\n\n\n(** Notations *)\nNotation \"B( p , r )\" := (open_ball p r) (at level 68, format \"B( p ,  r )\").\nLocal Ltac2 unfold_open_ball    ()          := unfold open_ball, pred.\nLocal Ltac2 unfold_open_ball_in (h : ident) := unfold open_ball, pred in $h.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"B\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_open_ball unfold_open_ball_in cl.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"open\" \"ball\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_open_ball unfold_open_ball_in cl.\n\nNotation \"a 'is' 'an' '_interior' 'point_' 'of' A\" := (is_interior_point a A) (at level 68).\nNotation \"a 'is' 'an' 'interior' 'point' 'of' A\" := (is_interior_point a A) (at level 68, only parsing).\nLocal Ltac2 unfold_is_interior_point    ()          := unfold is_interior_point.\nLocal Ltac2 unfold_is_interior_point_in (h : ident) := unfold is_interior_point in $h.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"interior\" \"point\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_is_interior_point unfold_is_interior_point_in cl.\n\nNotation \"A 'is' '_open_'\" := (is_open A) (at level 68).\nNotation \"A 'is' 'open'\" := (is_open A) (at level 68, only parsing).\nLocal Ltac2 unfold_is_open    ()          := unfold is_open.\nLocal Ltac2 unfold_is_open_in (h : ident) := unfold is_open in $h.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"open\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_is_open unfold_is_open_in cl.\n\n\nNotation \"'\u211d\\' A\" := (complement A) (at level 20, format \"'\u211d\\' A\").\nNotation \"'\u211d' '\\' A\" := (complement A) (at level 20, only parsing).\nLocal Ltac2 unfold_complement    ()          := unfold complement, pred.\nLocal Ltac2 unfold_complement_in (h : ident) := unfold complement, pred in $h.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"\u211d\\\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_complement unfold_complement_in cl.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"complement\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) := \n  expand_def_framework unfold_complement unfold_complement_in cl.\n\nNotation \"A 'is' '_closed_'\" := (is_closed A) (at level 68).\nNotation \"A 'is' 'closed'\" := (is_closed A) (at level 68, only parsing).\nLocal Ltac2 unfold_is_closed    ()          := unfold is_closed.\nLocal Ltac2 unfold_is_closed_in (h : ident) := unfold is_closed in $h.\nLtac2 Notation \"Expand\" \"the\" \"definition\" \"of\" \"closed\" cl(opt(seq(\"in\", \"(\", ident, \")\"))) :=\n  expand_def_framework unfold_is_closed unfold_is_closed_in cl.\n\n\n(** Hints *)\nLemma zero_in_interval_closed_zero_open_one : (0 : [0,1)).\nProof.\n  We need to show that (0 <= 0 /\\ 0 < 1).\n  We show both (0 <= 0) and (0 < 1).\n  - We conclude that (0 <= 0).\n  - We conclude that (0 < 1).\nQed.\n#[export] Hint Resolve zero_in_interval_closed_zero_open_one : wp_reals.\n\nLemma one_in_complement_interval_closed_zero_open_one : (1 : \u211d \\ [0,1)).\nProof.\n  We need to show that (~ ((0 <= 1) /\\ (1 < 1))).\n  It suffices to show that (~ 1 < 1).\n  We conclude that (~ 1 < 1).\nQed.\n#[export] Hint Resolve one_in_complement_interval_closed_zero_open_one : wp_reals.\n\n#[export] Hint Resolve Rabs_def1 : wp_reals.\n#[export] Hint Resolve not_and_or : wp_classical_logic.\n\nLemma not_in_compl_implies_in (A : subset R) (x : R) : (\u00ac x : \u211d\\A) -> (x : A).\nProof. Assume that (\u00ac x : \u211d\\A). It holds that (\u00ac \u00ac x : A). We conclude that (x : A). Qed.\nLemma in_implies_not_in_compl (A : subset R) (x : R) : (x : A) -> (\u00ac x : \u211d\\A).\nProof. Assume that (x : A). We conclude that (\u00ac x : \u211d\\A). Qed.\n#[export] Hint Resolve not_in_compl_implies_in : wp_negation_reals.\n#[export] Hint Resolve in_implies_not_in_compl : wp_negation_reals.\n\n\nClose Scope subset_scope.\nClose Scope R_scope.\n", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/theory/analysis/open_and_closed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8991213813246444, "lm_q1q2_score": 0.8401346643190323}}
{"text": "(* initial declaration *)\nParameter A B C D : Prop.\n\n\n\n(* The first set of exercises are concerned with minimal logic.\n   The question is to prove the lemma's\n   and to print (and read) the lambda term corresponding\n   to the proof. *)\n\n(* NB: if the name of a bound variable does not matter\n   then Coq may print \"_\" instead of for instance \"x\". *)\n\n(* first an example *)\nLemma example : (A -> B) -> (B -> C) -> A -> C.\nProof.\nintros x y z.\napply y.\napply x.\nexact z.\nQed.\n\nPrint example.\n(* fun (x : A -> B) (y : B -> C) (z : A) => y (x z) *)\n\n(* exercise one_a *)\nLemma one_a : (A -> B -> C) -> A -> (A -> C) -> B -> C.\nProof.\nintro x.\nintro y.\nintro z.\nintro w.\napply z.\napply y.\n\nQed.\n\nPrint one_a.\n\n(* exercise one_b *)\nLemma one_b : ((A -> B) -> (C ->D)) -> C -> B -> D.\nProof.\nintro x.\nintro y.\nintro z.\n\napply x.\nintro w.\napply z.\napply y.\n\n\nQed.\n\nPrint one_b.\n\n(* exercise one_c *)\nLemma one_c : (A -> B) -> (A -> C) -> A -> B -> C.\nProof.\nintro x.\nintro y.\nintro z.\nintro w.\n\napply y.\napply z.\n\nQed.\n\nPrint one_c.\n\n\n\n(* The second set of exercises is concerned with negation.\n   Recall that ~A is defined as A -> False.\n   The negation in the goal can be unfolded by \"unfold not.\". *)\n\n(* NB: a lemma Name that is proved earlier can be used\n   by \"apply Name.\"\n   NB: if you want to proceed upwards using the elimination\n   rule for false, then the Coq tactic is \"elimtype False.\" *)\n\n(* exercise two_a; see Chapter 1 of the course notes\n   NB: the converse is not true intuitionistically *)\nLemma AnotnotA : A -> ~ ~ A .\nProof.\nunfold not.\n\nintro x.\nintro y.\napply y.\napply x.\n\nQed.\n\n(* exercise two_b; see Chapter 1 of the course notes *)\nLemma notnotnot : ~ ~ ~ A -> ~ A.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise two_c; see Chapter 1 of the course notes *)\nLemma herman : ~ ~ (~ ~ A -> A).\nProof.\n(*! proof *)\n\nQed.\n\nPrint herman.\n\n\n\n(* The third set of exercises consist of incomplete\n   lambda terms. The question is to add types in such\n   a way that a typable lambda term is obtained.\n   Use \"Check <term>.\" to see whether it is ok. *)\n\n(* example:\n   question:  Check fun (x:?) => x.\n   answer:   Check fun (x:A) => x. *)\n\n(* exercises: *)\n(*\n\nCheck fun (x : ?) (y : ?) (z : ?) => x y z.\nCheck fun (x : ?) (y : ?) (z : ?) => x (y z).\nCheck fun (x : ?) (y : ?) => x y .\nCheck fun (x : ?) (y : ?) (z : ?) => x z y .\n\n*)\n\n\n\n(* In the fourth set of exercises, a type is given and\n   the question is to define (using \"Definition\") an\n   inhabitant of that type.\n   You can define an inhabitant with or without using Coq.\n   Use \"Check <name>.\" to see whether it is correct. *)\n\n(* example:\n   question: A -> A\n   answer: Definition example := fun (x :A) => x .\n           Check example.                           *)\n\n(* exercises *)\n\n(* four_a: (A -> B) -> (A -> C) -> A -> B -> C *)\nDefinition four_a := (*! term *)\n  .\n\nCheck four_a.\n\n(* four_b : A -> A -> A *)\nDefinition four_b := (*! term *)\n  .\n\nCheck four_b.\n\n(* four_c : A -> A -> A  but different from four_b*)\nDefinition four_c := (*! term *)\n  .\n\nCheck four_c.\n\n(* four_d : A -> B -> A *)\nDefinition four_d := (*! term *)\n  .\n\nCheck four_d.\n\n(* four_e : (A -> A) -> A -> A *)\nDefinition four_e := (*! term *)\n  .\n\nCheck four_e.\n\n(* four_f : (A -> A) -> A -> A but different from four_e *)\nDefinition four_f := (*! term *)\n  .\n\nCheck four_f.\n\n(* four_g : (A -> A -> B) -> A -> B *)\nDefinition four_g := (*! term *)\n  .\n\nCheck four_g.\n\n\n", "meta": {"author": "danalvi", "repo": "imc010-type-theory-coq", "sha": "13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8", "save_path": "github-repos/coq/danalvi-imc010-type-theory-coq", "path": "github-repos/coq/danalvi-imc010-type-theory-coq/imc010-type-theory-coq-13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8/ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.9099069980980297, "lm_q1q2_score": 0.8398798028241747}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\nCheck 3 = 3.\n\nCheck forall n m : nat, n + m = m + n.\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\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\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n (* standard (and_exercise)*)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m. induction n as [|n' IHn'].\n  - intro H. split. simpl in H. reflexivity. apply H.\n  - simpl. intro H. inversion H.\nQed.\n (* /standard (and_exercise)*)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP. Qed.\n\n(*standard, optional (proj2)*)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ. Qed.\n(*/standard, optional (proj2)*)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - apply HQ.\n    - apply HP. Qed.\n\n(*standard (and_assoc)*)\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split. \n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR. Qed.\n(*/standard (and_assoc)*)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  -\n    rewrite Hn. reflexivity.\n  -\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(*standard (mult_eq_0)*)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. destruct n as [|n'].\n  - left. reflexivity.\n  - destruct m as [|m'].\n    + right. reflexivity.\n    + inversion H.\n  Qed.\n(*/standard (mult_eq_0)*)\n\n(*standard (or_commut)*)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q [HP | HQ].\n  - right. apply HP.\n  - left. apply HQ.\n  Qed.\n(*/standard (or_commut)*)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra. Qed.\n\n(*standard, optional (not_implies_our_not)*)\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros. apply H in H0. destruct H0. Qed. \n(*/standard, optional (not_implies_our_not)*)\n\nNotation \"x <> y\" := (~(x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not. intros contra. discriminate contra. Qed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\n(*standard, recommended (contrapositive)*)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H. unfold not. intros G I. apply H in I. apply G in I. destruct I. Qed.\n(*/standard, recommended (contrapositive)*)\n\n(*standard (not_both_true_and_false)*)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intro P. unfold not. intros [H1 H2]. apply H2 in H1. destruct H1. Qed.\n(*/standard (not_both_true_and_false)*)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  -\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  -\n    reflexivity.\nQed.\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  -\n    unfold not in H.\n    exfalso.     apply H. reflexivity.\n  - reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - apply HBA.\n  - apply HAB. Qed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros b. split.\n  - apply not_true_is_false.\n  -\n    intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\n(*standard, optional (iff_properties)*)\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intro P. reflexivity. Qed.\n  \n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [PQ QP] [QR RQ]. split.\n  - (* P -> R *)\n    intros HP. apply QR. apply PQ. apply HP.\n  - (* R -> P*)\n    intros HR. apply QP. apply RQ. apply HR. Qed.\n(*/standard, optional (iff_properties)*)\n\n(*standard (or_distributes_over_and)*)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - intros [HP | [HQ HR]].\n    + split; left; apply HP.\n    + split; right; try (apply HQ); try (apply HR).\n  - intros [[HPl | HQ] [HPr | HR]].\n    + left. apply HPl.\n    + left. apply HPl.\n    + left. apply HPr.\n    + right. split. apply HQ. apply HR.\nQed.\n(*/standard (or_distributes_over_and)*)\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].   exists (2 + m).\n  apply Hm. Qed.\n\n(*standard, recommended (dist_not_exists)*)\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  unfold not. intros X P A. intros [x NP]. apply NP. apply A.\nQed.\n(*/standard, recommended (dist_not_exists)*)\n\n(*standard (dist_exists_or)*)\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n intros X P Q. split.\n  - intros [x [HP | HQ]].\n    + left. exists x. apply HP.\n    + right. exists x. apply HQ.\n  - intros [[x HP] | [x HQ]].\n    + exists x. left. apply HP.\n    + exists x. right. apply HQ.\nQed.\n(*/standard (dist_exists_or)*)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  -\n    simpl. intros [].\n  -\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(*standard (In_map_iff)*)\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\n  - induction l as [| h t IHt].\n    + simpl. intros [].\n    + simpl. intros [H1 | H2].\n      * exists h. split. apply H1. left. reflexivity.\n      * apply IHt in H2. destruct H2 as [w [F I]]. exists w. split.\n        apply F. right. apply I.\n  - intros [x [H1 H2]]. rewrite <- H1. apply In_map. apply H2. Qed.\n(*/standard (In_map_iff)*)\n\n(*standard (In_app_iff)*)\nLemma In_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a. split.\n  - induction l as [|h t IHt].\n    + simpl. intro H. right. apply H.\n    + simpl. intros [H1 | H2]. left. left. apply H1. apply IHt in H2. \n      destruct H2 as [H3 | H4]. left. right. apply H3. right. apply H4.\n  - induction l as [| h t IHt]. \n    + intros [H1 | H2]. destruct H1. simpl. apply H2.\n    + simpl. intros [[H1 | H2] | H3]. \n      * left. apply H1.\n      * right. apply IHt. left. apply H2.\n      * right. apply IHt. right. apply H3.\nQed.\n(*/standard (In_app_iff)*)\n\n(*standard, recommended (All)*)\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | nil => True\n  | h :: t => P h /\\ All P t\n  end.\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  intros T P l. split.\n  - (*(forall x : T, In x l -> P x) -> All P l*)\n    induction l as [|h t IHt].\n    + intro H. simpl. reflexivity.\n    + intro H. simpl. split.\n      * apply H. simpl. left. reflexivity.\n      * apply IHt. intros x H1. apply H. simpl. right. apply H1.\n  - (*All P l -> forall x : T, In x l -> P x*)\n    induction l as [|h t IHt].\n    + intros. destruct H0.\n    + simpl. intros [H1 H2] x [H3|H4].\n      * rewrite <- H3. apply H1.\n      * apply IHt. apply H2. apply H4. \nQed. \n(*/standard, recommended (All)*)\n\n(*standard (combine_odd_even)*)\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n =>\n    match oddb n with\n    | true => Podd n\n    | false => Peven n\n    end.\n\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n. destruct (oddb n) eqn:H.\n  - intros H1 H2. unfold combine_odd_even. rewrite -> H. apply H1. reflexivity.\n  - intros H1 H2. unfold combine_odd_even. rewrite -> H. 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. unfold combine_odd_even. \n  intros H1 H2. rewrite -> H2 in H1. apply H1. \nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n. unfold combine_odd_even. intros H1 H2.\n  rewrite -> H2 in H1. apply H1.\nQed.\n(*/standard (combine_odd_even)*)\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction m as [| m' IHm'].\n  - (* m = 0 *)\n    simpl. rewrite <- plus_n_O. reflexivity.\n  - (* m = S m' *)\n    simpl. rewrite <- IHm'. rewrite <- plus_n_Sm.\n    reflexivity.  Qed.\n\nCheck plus_comm.\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite plus_comm.\nAbort.\n\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  Fail apply in_not_nil.\nAbort.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take5 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\nAbort.\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n\n(*standard (tr_rev_correct)*)\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X. apply functional_extensionality. unfold tr_rev. induction x as [| h t IHt].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt. Admitted.\n(*/standard (tr_rev_correct)*)\n\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\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. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(*standard (evenb_double_conv)*)\nLemma  evenb_S : forall n : nat, evenb (S n) = negb (evenb n).\nProof. \n  intro n. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. assert(H: forall b:bool, b=negb(negb b)). \n    intro b. destruct b;reflexivity. apply H. Qed.\n\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  intro n. induction n as [|n' IHn'].\n  - simpl. exists 0. reflexivity.\n  - destruct IHn' as [m IHm]. destruct (evenb n') eqn:H.\n    + rewrite -> evenb_S. rewrite -> H. simpl. rewrite -> IHm. \n      exists m. reflexivity. \n    + rewrite -> evenb_S. rewrite -> H. simpl. rewrite -> IHm. exists (S m).\n      simpl. reflexivity. Qed. \n(*/standard (evenb_double_conv)*)\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\nRequire Import PeanoNat.\n\n(* standard (logical_connectives)*)\nNotation \"x && y\" := (andb x y).\n\nNotation \"x || y\" := (orb x y).\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  - destruct b1 eqn:H. \n    + intro H1. split. reflexivity. simpl in H1. apply H1.\n    + intro H1. inversion H1.\n  - intros [H1 H2]. rewrite -> H1. rewrite -> H2. reflexivity. Qed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - destruct b1 eqn:H.\n    + intro H1. left. reflexivity.\n    + intro H1. simpl in H1. right. apply H1.\n  - intros [H1|H2].\n    + rewrite -> H1. reflexivity.\n    + rewrite -> H2. destruct b1 eqn:H.\n      * reflexivity.\n      * reflexivity.\nQed.\n(* /standard (logical_connectives)*)\n\n(*standard (eqb_neq)*)\nTheorem eqb_refl: forall n: nat,\n  true = (n =? n).\nProof.\n  induction n as [|n' IH].\n  - reflexivity.\n  - rewrite IH. reflexivity.\nQed.\n\nTheorem eqb_eq:\n  forall n1 n2: nat,\n  n1 =? n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply eqb_true.\n  - intros H. rewrite H. rewrite <- eqb_refl. reflexivity.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  intros x y.\n  rewrite <- not_true_iff_false.\n  rewrite <- eqb_eq.\n  reflexivity.\nQed.\n(*/standard (eqb_neq)*)\n\n(*standard (eqb_list)*)\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 => andb (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. induction l1 as [|h1 t1 IHt1].\n  - induction l2 as [| h2 t2 IHt2].\n    + split. \n      * simpl. intro H1. reflexivity.\n      * simpl. intro H1. reflexivity.\n    + split.\n      * simpl. intro H1. discriminate H1.\n      * simpl. intro H1. discriminate H1.\n  - induction l2 as [| h2 t2 IHt2].\n    + split.\n      * simpl. intro H1. discriminate H1.\n      * simpl. intro H1. discriminate H1.\n    + split.\n      * simpl. intro H1. apply andb_true_iff in H1. destruct H1 as [H2 H3].\n        apply H in H2. apply IHt1 in H3. rewrite -> H2. rewrite -> H3. reflexivity.\n      * simpl. intro H1. apply andb_true_iff. split.\n        apply H. inversion H1. reflexivity. apply IHt1. inversion H1. reflexivity. \nQed. \n(*/standard (eqb_list)*)\n\n(*standard, recommended (All_forallb)*)\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.  \n  intros X test l. split.\n  - induction l as [|h t IHt].\n    + simpl. reflexivity.\n    + simpl. intro H. split.\n      * apply andb_true_iff in H. destruct H as [H1 H2]. apply H1.\n      * apply IHt. apply andb_true_iff in H. destruct H as [H1 H2]. apply H2.\n  - induction l as [|h t IHt].\n    + simpl. reflexivity.\n    + simpl. intros [H1 H2]. apply andb_true_iff. split.\n      * apply H1.\n      * apply IHt. apply H2.\nQed.\n(*/standard, recommended (All_forallb)*)\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\n(*standard (excluded_middle_irrefutable)*)\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  intros P H.\n  unfold not in H.\n  apply H.\n  right.\n  intros HP.\n  apply H.\n  left.\n  apply HP.\nQed.\n(*/standard (excluded_middle_irrefutable)*)\n\n(* Exercise 20 *)\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.\n  unfold not.\n  intros H.\n  intros x.\n\n  destruct (EM (P x)) as [EM1 | EM2].\n  - apply EM1.\n  - exfalso. apply H.\n    exists x.\n    apply EM2.\nQed.\n\n(* Exercise 21 *)\n(* Definition excluded_middle := forall P: Prop, P \\/ ~P. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q) -> P) -> P.\n\nDefinition double_negation_elimination := forall P: Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q: Prop,\n  ~(~P /\\ ~Q) -> P \\/ Q.\n\nDefinition implies_to_or := forall P Q: Prop,\n  (P -> Q) -> (~P \\/ Q).\n\nFact dne_eq_lem: double_negation_elimination <-> excluded_middle.\nProof.\n  split.\n  - intros dne.\n    intros P.\n    apply dne.\n    apply excluded_middle_irrefutable.\n  - intros lem.\n    intros P H.\n    destruct (lem P) as [lem1 | lem2].\n    + apply lem1.\n    + destruct (H lem2).\nQed.\n\nFact dmnn_eq_lem: de_morgan_not_and_not <-> excluded_middle.\nProof.\n  split.\n  - intros dmnn.\n    intros P.\n    apply dmnn.\n    intros [H1 H2].\n    destruct (H2 H1).\n  - intros lem.\n    intros P Q H.\n    destruct (lem P) as [H1 | H2].\n    + left. apply H1.\n    + destruct (lem Q) as [H3 | H4].\n      * right. apply H3.\n      * exfalso. apply H.\n        split. apply H2. apply H4.\nQed.\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "unisuke82", "repo": "SoftwareFoundation", "sha": "1911ed60b7dff597eac434734cb26d67162b6805", "save_path": "github-repos/coq/unisuke82-SoftwareFoundation", "path": "github-repos/coq/unisuke82-SoftwareFoundation/SoftwareFoundation-1911ed60b7dff597eac434734cb26d67162b6805/volume1/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.9099070023734244, "lm_q1q2_score": 0.8398797971387415}}
{"text": "(******************************)\n(******************************)\n(****                      ****)\n(****   Proof techniques   ****)\n(****                      ****)\n(******************************)\n(******************************)\n\n(****************************)\n(* Equality of applications *)\n(****************************)\n\n(*\n  To prove two applications of a function or constructor are equal, we can\n  prove the arguments are pairwise equal.\n*)\n\nDefinition successorsEqual n1 n2 : n1 = n2 -> S n1 = S n2 :=\n  fun H =>\n    match H in _ = x return S n1 = S x with\n    | eq_refl => eq_refl (S n1)\n    end.\n\n(* We can use the `rewrite` tactic to prove this with forward reasoning. *)\n\nGoal forall n1 n2, n1 = n2 -> S n1 = S n2.\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n(* We can use the `f_equal` tactic to prove this with backward reasoning. *)\n\nGoal forall n1 n2, n1 = n2 -> S n1 = S n2.\nProof.\n  intros.\n  f_equal.\n  apply H.\nQed.\n\n(*******************************)\n(* Injectivity of constructors *)\n(*******************************)\n\n(*\n  Given an equality between two applications of a constructor, we can conclude\n  the arguments are pairwise equal.\n*)\n\nDefinition successorInjective n1 n2 : S n1 = S n2 -> n1 = n2 :=\n  fun H =>\n    match H in _ = x return pred (S n1) = pred x with\n    | eq_refl => eq_refl (pred (S n1))\n    end.\n\n(* We can use the `inversion` (or `injection`) tactic to prove this. *)\n\nGoal forall n1 n2, S n1 = S n2 -> n1 = n2.\nProof.\n  intros.\n  inversion H. (* Generate a proof of `n1 = n2` and substitute in the goal. *)\n  reflexivity.\nQed.\n\n(********************************)\n(* Disjointness of constructors *)\n(********************************)\n\n(*\n  Here we show how to refute the equality between applications of two different\n  constructors. This only works for constructors of types in the `Set` or\n  `Type` universes, not `Prop`. See Lessons 5 and 6 for details about\n  universes.\n*)\n\nDefinition trueNeqFalse : true <> false :=\n  fun H =>\n    match H\n    in _ = x\n    return\n      match x with\n      | true => True\n      | false => False\n      end\n    with\n    | eq_refl => I\n    end.\n\n(* Fortunately, the `discriminate` tactic automates this. *)\n\nGoal true <> false. (* Unfolds to `true = false -> False` *)\nProof.\n  discriminate. (* Prove the goal via an impossible structural equality. *)\nQed.\n\n(*************)\n(* Induction *)\n(*************)\n\n(* Let's prove that zero is a left identity for addition. *)\n\nDefinition zeroPlusNEqualsN n : 0 + n = n := eq_refl n.\n\nGoal forall n, 0 + n = n.\nProof.\n  intros.\n  reflexivity.\nQed.\n\n(* That was easy! Now let's try to prove that zero is also a right identity. *)\n\nFail Definition nPlusZeroEqualsN n : n + 0 = n := eq_refl n.\n\n(*\n  ```\n  The command has indeed failed with message:\n  In environment\n  n : nat\n  The term \"eq_refl\" has type \"n = n\" while it is expected to have type\n  \"n + 0 = n\".\n  ```\n*)\n\nGoal forall n, n + 0 = n.\nProof.\n  intros.\n  (* `reflexivity.` reports `Unable to unify \"n\" with \"n + 0\".` *)\nAbort.\n\n(* What went wrong? Recall the definition of addition. *)\n\nPrint \"+\".\n\n(*\n  ```\n  fix add (n m : nat) {struct n} : nat :=\n    match n with\n    | 0 => m\n    | S p => S (add p m)\n    end\n  ```\n*)\n\n(*\n  From this, it's clear why `0 + n = n`. But how do we prove `n + 0 = n`? We\n  need *induction*. Just as we defined recursive functions with `Fixpoint` in\n  Lesson 1, we can use `Fixpoint` to write a proof by induction.\n*)\n\nFixpoint nPlusZeroEqualsN n : n + 0 = n :=\n  match n return n + 0 = n with\n  | O => eq_refl 0\n  | S p =>\n    match nPlusZeroEqualsN p in _ = x return S p + 0 = S x with\n    | eq_refl => eq_refl ((S p) + 0)\n    end\n  end.\n\n(*\n  To help with doing induction in proof mode, Coq automatically constructs an\n  induction principle for every inductive type. For example, here's the\n  induction principle for `nat`:\n*)\n\nCheck nat_ind.\n\n(*\n  ```\n  forall P : nat -> Prop,\n  P 0 ->\n  (forall n : nat, P n -> P (S n)) ->\n  forall n : nat, P n\n  ```\n\n  Let's use that induction principle to prove our theorem.\n*)\n\nGoal forall n, n + 0 = n.\nProof.\n  intros.\n\n  (*\n    We could write `apply (nat_ind (fun q => q + 0 = q))`, but it's easier to\n    just write `induction n`.\n  *)\n  induction n.\n\n  (* Two subgoals are generated: *)\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite IHn.\n    reflexivity.\nQed.\n\n(*\n  To illustrate a few more useful techniques, let's prove addition is\n  commutative.\n*)\n\nTheorem commutativity : forall n1 n2, n1 + n2 = n2 + n1.\nProof.\n  intros.\n  induction n1.\n  - rewrite nPlusZeroEqualsN. (* We can use our previous theorem! *)\n    reflexivity.\n  - cbn. (* `cbn` simplifies the goal by computation. *)\n    rewrite IHn1.\n    clear IHn1. (* We won't need this hypothesis anymore, so remove it. *)\n    induction n2. (* An induction proof within an induction proof! *)\n    + reflexivity. (* Use `+` instead of `-` for nested subgoals. *)\n    + cbn.\n      rewrite IHn2.\n      reflexivity.\nQed.\n\n(**************************)\n(* Automation with `auto` *)\n(**************************)\n\n(*\n  We can often save time by asking Coq to find proofs automatically. The first\n  step is to create a database of *hints* (e.g., lemmas) that Coq is allowed to\n  use when synthesizing proofs. Let's create one called `myHintDb`.\n*)\n\nCreate HintDb myHintDb.\n\n(*\n  Now let's add our `commutativity` theorem to the database. Change `local` to\n  `export` if you want the hint to also work in other modules that `Import`\n  this one.\n*)\n\n#[local] Hint Resolve commutativity : myHintDb.\n\n(*\n  Now we can use `auto with myHintDb` to do automatic proof search using our\n  hint database.\n*)\n\nGoal forall n, n + 42 = n \\/ n + 42 = 42 + n.\nProof.\n  auto with myHintDb. (* Coq found a proof for us! *)\nQed.\n\n(* Without automation, the proof looks like this: *)\n\nGoal forall n, n + 42 = n \\/ n + 42 = 42 + n.\nProof.\n  intros.\n  right.\n  apply commutativity.\nQed.\n\n(*\n  Coq has a few built-in hint databases. One such database is `core`, which has\n  basic facts about logical connectives, e.g., `forall (A : Type) (x y : A),\n  x <> y -> y <> x`. By default, `auto` uses `core` implicitly, so there's no\n  need to write `with core`.\n*)\n\nGoal forall (A : Type) (x y : A), x = y -> False \\/ (True /\\ y = x).\nProof.\n  auto. (* The `core` database has everything we need here. *)\nQed.\n\n(*\n  Another built-in database is `arith`, which contains useful facts about\n  natural numbers when the appropriate modules are loaded. For example, it\n  contains a commutativity theorem just like ours.\n*)\n\nRequire Import Coq.Arith.Arith.\n\nGoal forall n, n + 42 = n \\/ n + 42 = 42 + n.\nProof.\n  auto with arith.\nQed.\n\n(*\n  If `auto` doesn't find a proof of your goal, you can always try asking it to\n  search harder. This will make `auto` take more time, though.\n*)\n\nGoal False \\/ False \\/ False \\/ False \\/ False \\/ True.\nProof.\n  auto. (* Nothing? *)\n  auto 6. (* Increase the maximum search depth. The default is 5. *)\nQed.\n\n(***********************************)\n(* Other useful automation tactics *)\n(***********************************)\n\n(* The `congruence` tactic can solve many goals by equational reasoning. *)\n\nGoal forall f (n1 n2 n3 : nat), f n1 = n2 -> f n2 = n3 -> f (f n1) = n3.\nProof.\n  congruence.\nQed.\n\n(* The `lia` tactic can solve many goals that deal with integers. *)\n\nRequire Import Coq.micromega.Lia.\n\nGoal forall n1 n2 n3, n1 * (n2 + n3) = n1 * n2 + n1 * n3.\nProof.\n  lia.\nQed.\n\n(*************)\n(* Exercises *)\n(*************)\n\n(*\n  1. Prove `0 <> 1`.\n  2. Prove that addition is associative, i.e.,\n     `forall n1 n2 n3, n1 + (n2 + n3) = (n1 + n2) + n3`.\n  3. Look up the induction principle for `eq` with `Check eq_ind.`. Informally,\n     what does it mean?\n  4. Prove the *strong induction* principle for natural numbers:\n\n     ```\n     forall P : nat -> Prop,\n     (forall n1, (forall n2, n2 < n1 -> P n2) -> P n1) ->\n     forall n, P n.\n     ```\n\n     Hint: Start the proof with `intros`, then use a tactic called `assert` to\n     prove a fact involving `P` and `n`. The goal should easily follow from\n     that fact.\n*)\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/Tutorial/Lesson4_ProofTechniques.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.9136765234137297, "lm_q1q2_score": 0.8391938361852129}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.\n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros.\n  induction n as [|n'].\n  Case \"n = 0\".\n    apply ev_0.\n  Case \"n = S n'\".\n    simpl. apply ev_SS. apply IHn'.\nQed.\n\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n(** *** *)\n(**\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* Infinite, because you can keep adding 0 to all the numbers involved (prolonging use of b_3 and b_5). *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(**\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros n B.\n  simpl. rewrite plus_0_r.\n  apply b_sum.\n  apply B. apply B.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros n m BN.\n  induction m as [|m'].\n  Case \"m = 0\". apply b_0.\n  Case \"m = S m'\".\n    simpl.\n    apply b_sum.\n    SCase \"n\". apply BN.\n    SCase \"m' * n\". apply IHm'.\nQed.\n\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n---------- (g_0)\ngorgeous 0\n\ngorgeous n\n---------------- (g_plus3)\ngorgeous (3 + n)\n\ngorgous n\n---------------- (g_plus5)\ngorgeous (5 + n)\n\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros.\n  apply g_plus5 with (n := 8 + n).\n  apply g_plus5 with (n := 3 + n).\n  apply g_plus3.\n  apply H.\nQed.\n\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\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 GN GM.\n  induction GN as [| n' | n' ].\n  Case \"n = 0\".\n    induction GM as [| m' | m' ].\n    SCase \"m = 0\". apply g_0.\n    SCase \"m = 3 + m'\". apply g_plus3. apply IHGM.\n    SCase \"m = 5 + m'\". apply g_plus5. apply IHGM.\n  Case \"n = 3 + n'\".\n    apply g_plus3 with (n := n' + m). apply IHGN.\n  Case \"n = 5 + n'\".\n    apply g_plus5 with (n := n' + m). apply IHGN.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous)  *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros n BN.\n  induction BN as [ | | | n' m'].\n  Case \"n = 0\". apply g_0.\n  Case \"n = 3\".\n    apply g_plus3. apply g_0.\n  Case \"n = 5\".\n    apply g_plus5. apply g_0.\n  Case \"n = n' + m'\".\n    apply gorgeous_sum. apply IHBN1. apply IHBN2.\nQed.\n\n(** [] *)\n\n\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n  intros.\n  rewrite plus_assoc.\n  rewrite plus_comm with (n := x) (m := z).\n  reflexivity.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   rewrite -> plus_0_r.\n   induction H.\n   Case \"n is 0\". apply g_0.\n   Case \"n is 3 + n\".\n     rewrite -> helper_g_times2. rewrite -> helper_g_times2.\n     apply g_plus3 with (n := 3 + n + n).\n     apply g_plus3 with (n := n + n).\n     apply IHgorgeous.\n   Case \"n is 5 + n\".\n     rewrite -> helper_g_times2. rewrite -> helper_g_times2.\n     apply g_plus5 with (n := 5 + n + n).\n     apply g_plus5 with (n := n + n).\n     apply IHgorgeous.\nQed.\n\n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *)\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* No, induction on n always gives an induction hypothesis in terms of\n   n - 1, which is useless for proving things about evenness because the\n   evenness of n - 1 implies that n isn't even! *)\n\n(** [] *)\n\n(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n   A useless induction hypothesis.\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros n m EN EM.\n  induction EN.\n  Case \"n is 0\". apply EM.\n  Case \"n is S (S n')\". simpl. apply ev_SS. apply IHEN.\nQed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we\n   can _look_ at that evidence for more information. For example, consider\n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead\n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* We get stuck with useless hypotheses. *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** 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. inversion H. inversion H1. inversion H3.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m EPLUS EN.\n  induction EN.\n  Case \"n is 0\". apply EPLUS.\n  Case \"n i S (S n)\".\n    inversion EPLUS.\n    apply IHEN.\n    apply H0.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros.\n  apply ev_ev__ev with (n := n + n) (m := (m + p)).\n  Case \"total is even\".\n    apply ev_sum with (n := (n + m)) (m := (n + p)) in H.\n    rewrite plus_assoc in H.\n    rewrite <- plus_assoc with (n := n) (m := m) (p := n) in H.\n    rewrite plus_comm with (n := m) (m := n) in H.\n    rewrite plus_assoc with (n := n) (m := n) (p := m) in H.\n    rewrite <- plus_assoc in H.\n    apply H.\n    apply H0.\n  Case \"n + n is even\".\n    rewrite <- double_plus.\n    apply double_even.\nQed.\n\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However,\n   we can define inductive predicates about any type of data. For example,\n   suppose we would like to characterize lists of _even_ length. We can\n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof.\n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H.\n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil.\n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l.\n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n\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 [pal_app_rev] that\n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that\n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X : Type} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_one : forall x, pal [x]\n  | pal_add : forall mid x, pal mid -> pal (x :: (snoc mid x)).\n\nLemma pal_app_rev : forall {X : Type} (l : list X), pal (l ++ rev l).\nProof.\n  intros X l.\n  induction l as [|h t].\n  Case \"l = []\".\n    apply pal_nil.\n  Case \"l = h :: t\".\n    simpl.\n    rewrite <- snoc_with_append.\n    apply pal_add.\n    apply IHt.\nQed.\n\nLemma pal_rev : forall {X : Type} (l : list X), pal l -> l = rev l.\nProof.\n  intros.\n  induction H.\n  Case \"pal_nil\". reflexivity.\n  Case \"pal_one\". reflexivity.\n  Case \"pal_add\".\n    simpl.\n    rewrite rev_snoc.\n    simpl.\n    rewrite <- IHpal.\n    reflexivity.\nQed.\n\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* Skipped (hard) *)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation (n m : nat) : Prop :=\n  | total_rel : total_relation n m.\n\nExample total_is_total : forall (n m : nat), total_relation n m.\nProof. apply total_rel. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop := .\n\nExample empty_is_empty : forall (n m : nat), ~(empty_relation n m).\nProof.\n  unfold not.\n  intros.\n  inversion H.\nQed.\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\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o MN NO.\n  induction NO as [|o' NO'].\n  Case \"n = o\". apply MN.\n  Case \"n <= S o'\".\n    apply le_S.\n    apply IHNO'.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\". apply le_n.\n  Case \"n = S n'\". apply le_S. apply IHn'.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m NM.\n  induction NM as [|m'].\n  Case \"n = m\".\n    apply le_n.\n  Case \"n <= S m'\".\n    apply le_S. apply IHNM.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m SNM.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m = 0\".\n    intros.\n    inversion SNM.\n    SCase \"n = 0\". apply le_n.\n    SCase \"S n <= 0\". inversion H0.\n  Case \"n = S n'\".\n    intros.\n    inversion SNM.\n    SCase \"n = S m'\". apply le_n.\n    SCase \"S n <= S m'\".\n      apply le_S.\n      apply IHm'.\n      apply H0.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros.\n  induction b as [|b'].\n  Case \"b = 0\". rewrite plus_0_r. apply le_n.\n  Case \"b = S b'\".\n    rewrite <- plus_n_Sm.\n    apply le_S. apply IHb'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt.\n  intros.\n  induction H as [|m'].\n  Case \"S (n1 + n2) = m\".\n    constructor.\n    SCase \"left\".\n      apply n_le_m__Sn_le_Sm.\n      apply le_plus_l.\n    SCase \"right\".\n      apply n_le_m__Sn_le_Sm.\n      rewrite plus_comm.\n      apply le_plus_l.\n  Case \"S (n1 + n2) <= m'\".\n    destruct IHle.\n    constructor.\n    SCase \"left\". apply le_S. apply H0.\n    SCase \"right\". apply le_S. apply H1.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros.\n  apply le_S.\n  apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m = 0\".\n    intros.\n    destruct n as [|n']. reflexivity. inversion H.\n  Case \"m = Sm'\".\n    intros.\n    destruct n as [|n'].\n    SCase \"n = 0\". apply O_le_n.\n    SCase \"n = S n'\".\n      simpl in H.\n      apply IHm' in H.\n      apply n_le_m__Sn_le_Sm.\n      apply H.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m = 0\".\n    intros. inversion H. subst n. reflexivity.\n  Case \"m = S m'\".\n    intros.\n    destruct n as [|n'].\n    SCase \"n = 0\". reflexivity.\n    SCase \"n = S n'\".\n      apply Sn_le_Sm__n_le_m in H.\n      apply IHm' in H.\n      simpl. apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  intros n m o NM MO.\n  apply ble_nat_true in NM.\n  apply ble_nat_true in MO.\n  apply le_ble_nat.\n  apply le_trans with (n := m) (m := n) (o := o).\n  apply NM.\n  apply MO.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  unfold not.\n  intros.\n  apply le_ble_nat in H0.\n  rewrite H0 in H.\n  inversion H.\nQed.\n\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2] YES\n      - [R 2 2 6] NO\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n      No! c2 and c3 provide equivalent operations and c4 treats m and n the same.\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      No, as c4 reverses the application of a c2 and a c3, by not applying\n      them in the first place you get the same set of propositions.\n\n      Also, R is +.\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\nTheorem R_is_plus : forall n m o, R n m o -> n + m = o.\nProof.\n  intros.\n  induction H.\n  Case \"c1\". reflexivity.\n  Case \"c2\". simpl. apply f_equal. apply IHR.\n  Case \"c3\". rewrite <- plus_n_Sm. apply f_equal. apply IHR.\n  Case \"c4\". inversion IHR. rewrite <- plus_n_Sm in H1. inversion H1. reflexivity.\n  Case \"c5\". rewrite plus_comm. apply IHR.\nQed.\n\nTheorem plus_is_R : forall n m o, n + m = o -> R n m o.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    simpl.\n    induction m as [|m'].\n    SCase \"m = 0\". intros. subst o. apply c1.\n    SCase \"m = S m'\".\n      intros.\n      destruct o as [|o']. inversion H.\n      apply c3.\n      apply IHm'.\n      inversion H.\n      reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    intros.\n    destruct o as [|o']. inversion H.\n    apply c2.\n    apply IHn'.\n    inversion H.\n    reflexivity.\nQed.\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is,\n      any list is a subsequence of itself.\n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is\n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n      is a subsequence of [l3], then [l1] is a subsequence of [l3].\n      Hint: choose your induction carefully!\n*)\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | subseq_nil : forall l, subseq [] l\n  | subseq_match : forall v l1 l2, subseq l1 l2 -> subseq (v :: l1) (v :: l2)\n  | subseq_skip : forall v l1 l2, subseq l1 l2 -> subseq l1 (v :: l2).\n\nTheorem subseq_refl : forall l, subseq l l.\nProof.\n  intros.\n  induction l as [|h t].\n  Case \"l = []\".\n    apply subseq_nil.\n  Case \"l = h :: t\".\n    apply subseq_match.\n    apply IHt.\nQed.\n\nTheorem subseq_app : forall l1 l2 l3, subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H.\n  Case \"subseq_nil\". apply subseq_nil.\n  Case \"subseq_match\".\n    simpl.\n    apply subseq_match.\n    apply IHsubseq.\n  Case \"subseq_skip\".\n    simpl.\n    apply subseq_skip.\n    apply IHsubseq.\nQed.\n\n(* SKIPPED subseq_trans *)\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(* SKIPPED *)\n\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.\n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.\n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) (n : nat) : Prop :=\n  match evenb n with\n  | true => Peven n\n  | false => Podd n\n  end.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  unfold oddb. unfold combine_odd_even.\n  intros.\n  destruct (evenb n).\n  Case \"n is even\". apply H0. reflexivity.\n  Case \"n is odd\". apply H. 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 oddb. unfold combine_odd_even.\n  intros.\n  apply f_equal with (f := negb) in H0.\n  rewrite negb_involutive in H0.\n  simpl in H0.\n  rewrite H0 in H.\n  apply H.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  unfold oddb. unfold combine_odd_even.\n  intros.\n  apply f_equal with (f := negb) in H0.\n  rewrite negb_involutive in H0.\n  simpl in H0.\n  rewrite H0 in H.\n  apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(*\nFixpoint true_upto_n__true_everywhere\n(* SKIPPED *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n\n", "meta": {"author": "michaelsproul", "repo": "sf-progress", "sha": "850bd15e0bff4bce5ae8423eb004f781cf4994e3", "save_path": "github-repos/coq/michaelsproul-sf-progress", "path": "github-repos/coq/michaelsproul-sf-progress/sf-progress-850bd15e0bff4bce5ae8423eb004f781cf4994e3/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.8388097328135597}}
{"text": "(** * Lists: Trabajando con Datos Estructurados *)\n\nRequire Export Induction.\n\nModule NatList. \n\n(* ###################################################### *)\n(** * Pares de Numeros *)\n\n(** En una definicion de tipo inductivo ([Inductive]), cada\n    constructor puede tomar cualquier numero de argumentos -- ninguno\n    (como con [true] y [O]), uno (como con [S]), o mas de uno, como en\n    esta definicion: *)\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\n\n(** Esta declaracion puede ser leida como: \"Hay una unica manera de\n    construir un par de numeros: aplicando el constructor [pair] a dos\n    argumentos de tipo [nat]\". *)\n\n(** Podemos construir un elemento de [natprod] asi: *)\n\nCheck (pair 3 5).\n\n(** Aqui hay dos funciones sencillas para extraer el primer y el\n    segundo componente de un par.  (Las definiciones tambien ilustran\n    como hacer pattern matching con constructores con dos\n    argumentos). *)\n\nDefinition fst (p : natprod) : nat := \n  match p with\n  | pair x y => x\n  end.\nDefinition snd (p : natprod) : nat := \n  match p with\n  | pair x y => y\n  end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Como los pares se usan seguido, es mejor poder trabajar con la\n    notacion matematica standard [(x,y)] en vez de [pair x y].\n    Podemos hacer esto con el comando [Notation] de Coq. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** La nueva notacion puede ser utilizada tanto en expresiones como en\n    pattern matches (de hecho, ya vimos esto en el capitulo anterior\n    -- esta notacion es provista en la libreria estandard de Coq): *)\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat := \n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod := \n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Intentemos probar algunos teoremas basicos de pares.  De acuerdo a\n    como definimos un teorema, vamos a poder probarlo simplemente con\n    [reflexivity] (y su simplificacion interna): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** Note que [reflexivity] no es suficiente si escribimos el lema en\n    una forma mas natural: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* No reduce nada! *)\nAbort.\n\n(** Tenemos que exponer la estructura de [p] de forma tal que [simpl]\n    pueda realizar el patern matching en [fst] y [snd].  Podemos hacer esto con \n    [destruct].\n\n    Note que, a diferencia de para [nat]urales, [destruct] no genera\n    un sub-objetivo extra.  Esto es porque los [natprod]s solo pueden\n    ser construidos en una sola forma.  *)\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(** **** Ejercicio: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Listas de Numeros *)\n\n(** Generalizando la definicion de pares un poco, vamos a describir el\n    tipo de _listas_ de numeros de la siguiente forma: \"Una lista es o\n    la lista vacia, o un par conteniendo un numero y otra\n    lista\". *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** Por ejemplo, aqui hay una lista con tres elementos: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** Como con pares, es conveniente escribir listas con la notacion\n    familiar.  Las siguientes declaraciones nos permite escribir [::]\n    como operador infijo de [cons], y corchetes como notacion para\n    construir listas. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** No es necesario entender enteramente estas declaraciones, pero en\n    caso de que este interesado, aqui hay una descripcion breve de lo\n    que esta pasando.\n\n    La anotacion [right associativity] le dice a Coq como parentizar\n    expresiones involucrando varios usos de [::] de forma que, por\n    ejemplo, las siguientes declaraciones signifiquen exactamente lo\n    mismo: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** La anotacion [at level 60] dice a Coq como parentizar expresiones\n    que involucren tanto a [::] como a otro operador infijo.  Por\n    ejemplo, como definimos [+] como operador infijo para la funcion\n    [plus] a nivel 50, \n\n    Notation \"x + y\" := (plus x y) (at level 50, left associativity).  \n\n    el operador [+] va a tener prioridad por sobre [::] de forma que\n    [1 + 2 :: [3]] va a ser interpretado, como esperariamos, como [(1\n    + 2) :: [3]] en vez de [1 + (2 :: [3])].\n\n   (Dicho sea de paso, es importante recalcar que la expresion como\n   \"[1 + 2 :: [3]]\" puede ser un poco confusa de leer en un archivo\n   .v.  Los corchetes internos, alrededor de 3, indican una lista,\n   pero los externos, que son invisibles en la version HTML, indican a\n   la herramienta de impresion \"coqdoc\" que lo que esta entre\n   parentesis deben ser mostrados como codigo Coq en vez de texto\n   plano).\n\n   La segunda y tercer declaracion [Notation] de arriba introducen las\n   notaciones estandard de listas con corchetes.  En el lado derecho\n   de la tercera se puede apreciar la notacion para declarar\n   notaciones n-arias, en este caso resultando en una sequencia de\n   [cons] anidados. *)\n\n(** A continuacion, una serie de funciones utiles para manipular\n    listas.  Por ejemplo, la funcion [repeat] que toma un numero [n] y\n    otro [count] y produce una lista con [count] repeticiones del\n    elemento [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(** La funcion [length] calcula el largo de una lista. *)\n\nFixpoint length (l:natlist) : nat := \n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** La funcion [app] (\"append\" en ingles) concatena dos listas. *)\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(** Como [app] va a ser utilizado en muchas partes a continuacion,\n    creamos una notacion infija. *)\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(** Aqui hay dos pequenios ejemplos de programacion con listas.  La\n    funcion [hd] retorna el primer elemento (la cabeza, \"head\") de una\n    lista, mientras que [tl] retorna la lista sin la cabeza (es decir,\n    la cola, \"tail\").  Por supuesto, la lista vacia no tiene primer\n    elemento, asi que debemos pasar un valor para ser retornado en ese\n    caso.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil  \n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n(** **** Ejercicio: 2 stars (list_funs) *)\n(** Complete las definiciones de [nonzeros], [oddmembers] y\n    [countoddmembers] de mas abajo.  Echele un vistazo a los tests\n    para entender que deberian hacer estas funciones. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\nExample test_nonzeros:            nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\nExample test_oddmembers:            oddmembers [0;1;0;2;3;0;0] = [1;3].\n (* FILL IN HERE *) Admitted.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  (* FILL IN HERE *) admit.\n\nExample test_countoddmembers1:    countoddmembers [1;0;3;1;4;5] = 4.\n (* FILL IN HERE *) Admitted.\nExample test_countoddmembers2:    countoddmembers [0;2;4] = 0.\n (* FILL IN HERE *) Admitted.\nExample test_countoddmembers3:    countoddmembers nil = 0.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, advanced (alternate) *)\n(** Complete la definicion de [alternate], que \"zippea\" dos listas en\n    una, alternando entre los elementos tomados de la primera lista y\n    los de la segunda.  Mire a los tests abajo para entenderlo con\n    ejemplos especificos.\n\n    Nota: una forma natural y elegante de escribir [alternate] puede\n    no satisfacer el requerimiento de Coq de que toda definicion\n    [Fixpoint] debe ser \"obviamente terminante\".  Si se encuentra con\n    este problema, considere una solucion mas verbosa que considera a\n    los elementos de ambas listas a la vez.  (Otra solucion podria ser\n    utilizar un tipo diferente de pares, pero esta no es la unica\n    forma).  *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  (* FILL IN HERE *) admit.\n\n\nExample test_alternate1:        alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate2:        alternate [1] [4;5;6] = [1;4;5;6].\n (* FILL IN HERE *) Admitted.\nExample test_alternate3:        alternate [1;2;3] [4] = [1;4;2;3].\n (* FILL IN HERE *) Admitted.\nExample test_alternate4:        alternate [] [20;30] = [20;30].\n (* FILL IN HERE *) Admitted. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Bolsas (\"Bags\") via Listas *)\n\n(** Una bolsa \"[bag]\" (o multiconjunto \"[multiset]\") es como un\n    conjunto, pero cada elemento puede aparecer muchas veces en vez de\n    solamente una.  Una forma razonable de implementar bags es\n    representandolas como listas de numeros naturales. *)\n\nDefinition bag := natlist.  \n\n(** **** Ejercicio: 3 stars (bag_functions) *)\n(** Complete las siguientes definiciones para las funciones [count],\n    [sum], [add], y [member] para bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := \n  (* FILL IN HERE *) admit.\n\n(** Todas estas pruebas deben solucionarse con [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** La operacion [sum] de multiset es similar a la [union] de sets:\n    [sum a b] contiene los elementos de [a] y [b].  (Los matematicos\n    usualmente definen [union] ligeramente diferente, y por ello no\n    usamos el mismo nombre para esta operacion).  Para [sum] le damos\n    un hint: no nombre los argumentos de la funcion.  Es mas,\n    escribimos [Definition] en vez de [Fixpoint], de forma que si\n    incluso persiste en dar nombres para los argumentos, no podra\n    procesarlos recursivamente.  El punto de establecer el problema de\n    este modo es para promover otras formas de crear esta funcion, tal\n    vez utilizando funciones que ya han sido definidas.  *)\n\nDefinition sum : bag -> bag -> bag := \n  (* FILL IN HERE *) admit.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag := \n  (* FILL IN HERE *) admit.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool := \n  (* FILL IN HERE *) admit.\n\nExample test_member1:             member 1 [1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_member2:             member 2 [1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, optional (bag_more_functions) *)\n(** Aqui hay algunas otras funciones sobre bags para que practique. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  (* Cuando remove_one es aplicado a un bag sin el numero en cuestion,\n     debe retornar el mismo bag sin cambiar. *)\n  (* FILL IN HERE *) admit.\n\nExample test_remove_one1:         count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one2:         count 5 (remove_one 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one3:         count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_one4:         count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  (* FILL IN HERE *) admit.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2:          count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3:          count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4:          count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars (bag_theorem) *)\n(** Escriba un teorema interesante sobre bags involucrando las\n    funciones [count] y [add], y demuestrelo.  Note que, como el\n    problema no esta totalmente especificado, es posible que usted\n    cree un teorema que es cierto, pero cuya prueba requira tecnicas\n    que no ha aprendido todavia.  Sientase libre de preguntar por\n    ayuda si se queda estancado! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Razonando acerca de listas *)\n\n(** De igual manera que con los numeros, se pueden probar muchos hechos\n    simples acerca de funciones sobre listas con simplificacion.  Por\n    ejemplo, la simplificacion realizada por [reflexivity] es\n    suficiente para este teorema... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... porque el [[]] es sustituido en la posicion del match en la\n    definicion de [app], permitiendo que el match pueda ser\n    simplificado. *)\n\n(** Tambien, como con los numeros, a veces es util realizar un\n    analisis por caso en las posibles formas (vacia o no vacia) que\n    puede tener una lista desconocida. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\". \n    reflexivity.  Qed.\n\n(** Aqui, el caso para [nil] fuciona porque decidimos definir [tl nil\n    = nil].  Note que la anotacion [as] en la tactica [destruct]\n    introduce dos nombres, [n] y [l'], correspondiendo al hecho que el\n    operador [cons] para listas tomas dos argumentos (la cabeza y cola\n    de la lista que se esta construyendo). *)\n\n(** Usualmente, sin embargo, ciertos teoremas interesantes acerca de\n    listas requiere induccion para sus pruebas. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simplemente leer pruebas no le va a permitir llegar muy lejos!  Es\n    muy importante entender los pasos involucrados en cada prueba,\n    usando Coq y pensando en cada paso que razonamiento se esta\n    llevando a cabo.  De otra forma, esta garantizado que los\n    ejercicios no van a tener ningun sentido.  *)\n\n(* ###################################################### *)\n(** ** Induccion sobre Listas *)\n\n(** Pruebas por induccion en tipos de datos como [natlist] son quizas\n    un poco menos familiares que induccion sobre numeros naturales,\n    pero la idea basica es la misma.  Cada declaracion [Inductive]\n    define un conjunto de constructores que establecen como construir\n    un elemento del tipo: un booleano puede ser [true] o [false]; un\n    numero puede ser [O] o [S] aplicado a otro numero; una lista puede\n    ser [nil] o [cons] aplicado a un numero y una lista.\n\n    Es mas, la aplicacion de los constructores declarados en un tipo\n    inductivo a si mismos es la _unica_ forma que los valores del tipo\n    inductivo pueden tomar.  Este hecho da forma a un estilo de\n    razonamiento acerca conjuntos definidos inductivamente: un numero\n    es [O] o es [S] aplicado a otro numero _mas pequenio_; una lista\n    es [nil] o [cons] aplicado a un numero y una lista _mas pequnia_;\n    etc.  Entonces, si tenemos en mente una proposicion [P] que\n    menciona una lista [l] y queremos argumentar que [P] vale para\n    _todas_ las listas, podemos razonar de la siguiente manera:\n\n      - Primero, mostrar que [P] es verdadero para [l] cuando [l] es [nil].\n\n      - Luego mostrar que [P] es verdadero para [l] cuando [l] es\n        [cons n l'] para algun numero [n] y alguna lista mas chica [l'],\n        asumiendo que [P] es verdadero para [l'].\n\n    Como listas largas solo pueden ser construidas de listas mas\n    cortas, eventualmente llegando a [nil], estos dos principios\n    bastan para establecer la prueba de [P] para toda lista [l].  Aqui\n    hay un ejemplo concreto: *)\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(** De vuelta, esta prueba en Coq no es muy iluminadora como documento\n    estatico -- es mas facil ver que esta pasando si se esta\n    trabajando en una sesion interactiva de Coq, donde se puede ver el\n    estado del objetivo actual y su contexto en cada paso, pero este\n    estado no es visible en la prueba estatica.  Entonces, la prueba\n    en lenguaje natural -- es decir, apta para humanos -- debe incluir\n    informacion mas explicita; en particular, puede ayudar recordarle\n    al lector cual es la hipotesis inductiva en el segundo caso.  *)\n\n(** _Teorema_: Para todas listas [l1], [l2], y [l3], \n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Prueba_: Por induccion en [l1].\n\n   - Primero, suponga [l1 = []].  Debemos mostrar\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n     que se desprende directamente de la definicion de [++].\n\n   - Ahora suponga [l1 = n::l1'], con\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n     (la hipotesis inductiva). Debemos mostrar\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n  \n     Por definicion de [++], esto se sigue de\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n     que es inmediato utilizando la hipotesis inductiva.  []\n\n  Aqui hay una prueba similar: *)\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(** Para un ejemplo un poco mas complejo sobre induccion en listas,\n    suponga que definimos la funcion \"cons a la derecha\" como... *)\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(** ... y la usamos para definir la funcion [rev] para revertir una lista: *)\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(** Pasemos ahora a probar algunos teoremas sobre las nuevas funciones\n    [snoc] y [rev].  Probemos una propiedad un poco mas compleja que\n    las que hemos visto hasta ahora, que revertir una lista no cambia\n    su largo.  Nuestro primer intento se va a quedar estancado en el\n    caso [cons]... *)\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    (* Este es el caso dificil.  Empezemos por simplificar la ecuacion. *)\n    simpl. \n    (* Ahora parece que estamos estancados: el objetivo es una\n       igualdad involucrando [snoc], pero no tenemos ninguna ecuacion\n       en el contexto local o en el ambiente global que diga algo\n       sobre [snoc]!\n\n       Podemos hacer un poco de progreso si reescribimos la hipotesis inductiva... *)\n    rewrite <- IHl'.\n    (* ... pero ya no podemos hacer nada. *)\nAbort.\n\n(** Entonces tomemos la ecuacion sobre [snoc] que nos permite hacer\n    progreso y provemosla como un lema separado. *)\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(** Note que hicimos el lema lo mas _general_ posible: en particular,\n    cuantificamos sobre _toda_ [natlist], no solo aquella que resulta\n    de la aplicacion de [rev].  Esto debe resultar natural, puesto que\n    la verdad del objetivo no depende de que la lista haya sido\n    revertida.  Es mas, es mucho mas facil provar la propiedad mas\n    general.  *)\n    \n(** Ahora podemos completar la prueba original. *)\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(** Para comparar, aqui estan las pruebas informales de estos dos teoremas: \n\n    _Teorema_: Para todo numero [n] y lista [l],\n       [length (snoc l n) = S (length l)].\n \n    _Prueba_: Por induccion en [l].\n\n    - Primero, suponga [l = []].  Debemos probar\n        length (snoc [] n) = S (length []),\n      que resulta inmediato de las definiciones de\n      [length] y [snoc].\n\n    - Luego, suponga [l = n'::l'], con\n        length (snoc l' n) = S (length l').\n      Tenemos que mostrar\n        length (snoc (n' :: l') n) = S (length (n' :: l')).\n      Por la definicion de [length] y [snoc], esto es equivalente a\n        S (length (snoc l' n)) = S (S (length l')),\n      que es inmediato por la hipotesis inductiva. [] *)\n                        \n(** _Teorema_: Para toda lista [l], [length (rev l) = length l].\n    \n    _Prueba_: Por induccion en [l].  \n\n      - Primero, suponga [l = []].  Debemos mostrar\n          length (rev []) = length [],\n        que resulta inmediato de considerar las definiciones de [length] \n        y [rev].\n    \n      - Luego, suponga [l = n::l'], con\n          length (rev l') = length l'.\n        Tenemos que mostrar que\n          length (rev (n :: l')) = length (n :: l').\n        Porla definicion de [rev], esto es equivalente a\n          length (snoc (rev l') n) = S (length l')\n        que, por el lema anterior, es lo mismo que\n          S (length (rev l')) = S (length l').\n        Concluimos gracias a la hipotesis inductiva. [] *)\n\n(** Obviamente, el estilo de estas pruebas es mas bien verborragica y\n    pedante.  Luego de un par, podemos encontrar mas facil de seguir\n    pruebas que no muestran tanto detalle (puesto que podemos\n    entenderlas en nuestras mentes o en un papel borrador si es\n    necesario) y simplemente resaltar los pasos no obvios.  En este\n    estilo mas comprimido, la prueba de arriba puede verse mas como:\n    *)\n\n(** _Teorema_:\n     Para toda lista [l], [length (rev l) = length l].\n\n    _Prueba_: Primero, observe que length (snoc l n) = S (length l)\n       para cualquier [l].  Esto se desprende de una simple induccion\n       en [l].  La propiedad principal se desprende tambien por otra\n       simple induccion en [l], usando la observacion junto con la\n       hipotesis inductiva en el caso donde [l = n'::l']. [] *)\n\n(** Que estilo es preferible en una determinada situacion depende en\n    la sofisticacion de la audencia y en que tan similar la prueba en\n    cuestion sea a otras a las que la audencia se haya ya\n    expuesto.  El estilo mas pedante es un buen default por ahora. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** Hemos visto que las pruebas pueden hacer uso de otros teoremas que\n    ya se han provado, usando [rewrite], y mas tarde vamos a ver otras\n    formas de reusar teoremas.  Pero para referirse a un teorema, es\n    necesario saber su nombre, y recordar los nombres de todos los\n    posibles teoremas que podamos querer usar puede ser una tarea muy\n    dificil!  Usualmente es imposible recordar los teoremas que se han\n    demostrado; mucho menos sus nombres.\n\n    El comando de Coq [SearchAbout] es bastante util para esto.\n    Escribiendo [SearchAbout foo] hace que Coq muestre una lista de\n    teoremas involucrando a [foo].  Por ejemplo, observe la lista que\n    muestra el siguiente comando, mostrando los teoremas que demostramos\n    sobre [rev]: *)\n\nSearchAbout rev.\n\n(** Mantenga [SearchAbout] en mente cuando haga los siguientes\n    ejercicios, y durante el resto del curso; puede salvarle mucho\n    tiempo!  *)\n    \n\n\n(* ###################################################### *)\n(** ** Ejercicios Sobre Listas, Parte 1 *)\n\n(** **** Ejercicio: 3 stars (list_exercises) *)\n(** Mas practica sobre listas. *)\n\nTheorem app_nil_end : forall l : natlist, \n  l ++ [] = l.   \nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hay una solucion corta al siguiente ejercicio.  Si usted se\n    encuentra en un embrollo, vuelva atras y busque una solucion mas\n    facil. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Un ejercicio acerca de su implementacion de [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Ejercicios Sobre Listas, Part 2 *)\n\n(** **** Ejercicio: 2 stars (list_design) *)\n(** Ejercicio de disenio: \n     - Escriba un teorema no trivial involucrando [cons]\n       ([::]), [snoc], y [app] ([++]).  \n     - Demuestrelo. *) \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Ejercicio: 3 stars, advanced (bag_proofs) *)\n(** Aqui hay un par de pequenios teoremas para demostrar acerca de su\n    definicion de bags. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** El siguiente lema acerca [ble_nat] puede ayudarle en la siguiente prueba. *)\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intros n. induction n as [| n'].\n  Case \"0\".  \n    simpl.  reflexivity.\n  Case \"S n'\".\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 3 stars, optional (bag_count_sum) *)  \n(** Escriba un teorema interesante acerca de bags involucrando las\n    funciones [count] y [sum], y demuestrelo.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Ejercicio: 4 stars, advanced (rev_injective) *)\n(** Demuestre que la funcion [rev] es injectiva, es decir,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nHay una forma dificil y otra facil de resolver este ejercicio.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Opciones (Options) *)\n\n(** Aqui hay otra definicion de tipo que es usada comunmente en\n    programacion: *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.  \n\n(** El uso de [natoption] es una forma de retornar \"error\" en\n    funciones.  Por ejemplo, suponga que queremos escribir una funcion\n    que retorne el elemento [n]-ario de una lista.  Si le damos tipo\n    [nat -> natlist -> nat], entonces vamos a tener que retornar un\n    numero arbitrario cuando la lista es muy corta! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n  match l with\n  | nil => 42  (* arbitrario! *)\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(** Por otro lado, si le damos el tipo [nat -> natlist -> natoption],\n    entonces podemos retornar [None] cuando la lista es muy corta y\n    [Some a] cuando la lista tiene suficientes elementos y [a] aparece\n    en la posicion [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(** Este ejemplo es una buena oportunidad para traer a colacion otra\n    pequenia caracteristica del lenguaje de programacion de Coq: las\n    expresiones condicionales... *)\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(** Los condicionales de Coq son como aquellos encontrados en\n    cualquier otro lenguaje, con una pequenia generalizacion.  Como el\n    tipo booleano no esta insertado en la logica subyacente, Coq\n    permite expresiones condicionales de _cualquier_ tipo inductivo\n    definido con exactamente dos constructores.  La guarda es\n    considerada [true] si evalua al primer constructor en la\n    definicion [Inductive] y [false] si evalua al segundo. *)\n\n(** La funcion de abajo extrae el [nat] de un [natoption], retornando\n    un default especificado en el caso [None]. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Ejercicio: 2 stars (hd_opt) *)\n(** Usando la misma idea, modifique la funcion [hd] definida\n   anteriormente de forma que no tengamos que pasar un elemento por\n   default en el caso [nil].  *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n  (* FILL IN HERE *) admit.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 1 star, optional (option_elim_hd) *)\n(** Este ejercicio relaciona [hd_opt] con el viejo [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars (beq_natlist) *)\n(** Complete la definicion de [beq_natlist], que compara dos listas de\n    numeros por igualdad.  Demuestre que [beq_natlist l l] retorna [true]\n    para toda lista [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  (* FILL IN HERE *) admit.\n\nExample test_beq_natlist1 :   (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Diccionarios *)\n\n(** Como ejemplo final sobre como se pueden definir tipos de datos\n    fundamentales, aqui hay una declaracion de un simple tipo de datos\n    [dictionary], usando numeros para tanto las claves como los\n    valores guardados en esas claves.  (Es decir, un diccionario\n    representa un mapeo finito de numeros a numeros).  *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n  | empty  : dictionary \n  | record : nat -> nat -> dictionary -> dictionary. \n\n(** Esta declaracion puede ser leida como: \"Hay dos formas de\n    construir un [dictionary]: mediante el constructor [empty], para\n    representar el diccionario vacio, o mediante el constructor\n    [record] aplicado a una clave, un valor, y un [dictionary] ya\n    existente, para construir un diccionario con el mapeo clave-valor\n    nuevo\".  *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n  (record key value d).\n\n(** Aqui hay una funcion [find] que busca un [dictionary] por una\n    determinada clave.  Evalua a [None] si la clave no se encontro, y\n    a [Some val] si la clave [key] esta mapeada a [val] en el\n    diccionario.  Si la misma clave esta mapeada a multiples valores, [find]\n    retorna la primera que encuentra. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption := \n  match d with \n  | empty         => None\n  | record k v d' => if (beq_nat key k) \n                       then (Some v) \n                       else (find key d')\n  end.\n\n\n(** **** Ejercicio: 1 star (dictionary_invariant1) *)\n(** Complete la siguiente prueba. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 1 star (dictionary_invariant2) *)\n(** Complete la siguiente prueba. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n  beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\nEnd Dictionary.\n\nEnd NatList.\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418272911436, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8384851683814012}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\nSection section_for_chapter_7.\n\n(* 7.1 p186 *)\n\nDefinition divides (n m:nat) := exists (p:nat), p*n=m.\n\nTheorem divides_0 : forall n, divides n 0.\nProof.\nintros.\nunfold divides.\nexists 0.\ntrivial.\nQed.\n\nPrint divides_0.\n\nCheck ex_intro (fun p : nat => p * 1 = 0) 0 eq_refl.\n\nTheorem divides_plus : forall n m, divides n m -> divides n (n + m).\nProof.\nintros.\nelim H.\nintros.\nelim H0.\nexists (S x).\nsimpl.\ntrivial.\nQed.\n\nTheorem not_divides_plus : forall n m:nat, ~ divides n m -> ~ divides n (n+m).\nProof. \nintros n m H; red; intro H'; elim H'; intro y.\ncase y; simpl.\nintro H2; apply H.\ncut (m=0).\nintro H3; rewrite H3; apply divides_0.\nomega.\nintros n0 Hn0.\napply H.\nexists n0.\nomega.\nQed.\n\nTheorem not_divides_lt : forall n m:nat, 0 < m ->  m < n -> ~ divides n m.\nProof.\nintros n m H H0 H1.\nelim H1; intros q Hq.\nrewrite <- Hq in H.\nrewrite <- Hq in H0.\ngeneralize H H0. case q.\nsimpl.  \nintros; absurd (0 < 0); auto with arith.\nclear H H0; intros y Hy Hy'.\nsimpl in Hy'. \nabsurd (n <= n + y * n); auto with arith. \nQed.\n\n\nTheorem not_lt_2_divides : forall n m:nat, n <> 1 -> n < 2 -> 0 < m -> ~ divides n m.\nProof.\nintros n m H H0; cut (n=0).\nintro e;rewrite e.   \ncase m.\nintro; absurd (0 < 0); auto with arith.\nintros n0 Hn0 H1.\nelim H1; intros q Hq.\nrewrite mult_0_r in Hq; discriminate Hq.\nomega.\nQed.\n\nTheorem le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\nProof.\nintros; omega.\nQed.\n\nTheorem lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/ n=m.\nProof.\nintros; omega.\nQed.\n\nEnd section_for_chapter_7.\n", "meta": {"author": "FiveEyes", "repo": "Notes", "sha": "5b5dfdddd4cb6eb05179ae3c58e2f33b7c88e2f9", "save_path": "github-repos/coq/FiveEyes-Notes", "path": "github-repos/coq/FiveEyes-Notes/Notes-5b5dfdddd4cb6eb05179ae3c58e2f33b7c88e2f9/PL/Coq/coq_art_exercise_chapter7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.891811053345418, "lm_q1q2_score": 0.8382251160627665}}
{"text": "Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq.\n\n(* Coq Faust Demo for LAC 2015 *)\n\n(* Basic syntax\n\n- Functions:\n\n  fun x => x + x\n\n  - takes a parameter named x, return x + x\n\n- Application is just juxtaposition:\n\n  f g\n\n *)\n\nEval compute in ([fun x => x + x] 2).\n\n(* Datatypes and pattern matching\n\nInductive nat : Type :=\n| 0    : nat\n| n.+1 : nat -> nat\n\n*)\n\nFixpoint is_even n :=\n  match n with\n  | 0    => true\n  | n.+1 => ~~ (is_even n)\n  end.\n\nEval compute in (is_even 3, is_even 2).\n\nLemma is_even4 : is_even 4 = true.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nLemma is_even_mult2 : forall n, is_even (n.*2) = true.\nProof.\n  elim=> [|n ihn].\n  + done.\n  + rewrite /=.\n    rewrite negbK.\n    rewrite ihn.\n    done.\nQed.\n\n(* Types:\n\nTypes are the most important part of Coq.\n\nThe key type is the function type, A \u2192 B,\nwhich represents programs with input A and\noutput B.\n\nThe main typing or reasoning rule is:\n\n\u0393 \u22a2 f : A \u2192 B         \u0393 \u22a2 x : A\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         \u0393 \u22a2 f x : B\n\nThis codifies the rule of \"modus ponens\".\n\nAnother important rule is:\n\n    \u0393, x : A \u22a2 e : B\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n \u0393 \u22a2 fun x => e : A \u2192 B\n\nThis captures the act of\n\"reasoning under a hypothesis\"\n\n*)\n\n(***********************************************)\n(* Proof idioms                                *)\n\nDefinition trivial_1 P : P -> P :=\n  fun x => x.\n\nDefinition trivial_2 P Q : P -> Q -> P :=\n  fun x y => x.\n\n(* Replace by y *)\n\n(* We can build programs interactively *)\nLemma trivial_3 P Q : P -> Q -> P.\nProof.\n  move=> p q.\n  exact: p.\nQed.\n\nLemma trivial_4 P Q : P -> Q -> P.\nProof. exact: trivial_2. Qed.\n\n(* Proof by Shuffling: move/apply\nBookeping a significant cost in formal proof.\n*)\n\n(* Proof by inspection: case/elim *)\nLemma OrC P Q : P \\/ Q -> Q \\/ P.\nProof.\n  case.\n  + right. done.\n  + left. done.\nQed.\n\n(* Naming: add naturals Commutative *)\nPrint plus.\n(*\nplus (n m : nat) :=\n  match n with\n  | 0 => m\n  | p.+1 => (plus p m).+1\n  end\n\nOr\n - 0 + m    => m\n - n.+1 + m => (n+m).+1\n\nNote no rule for m + 0!\n\n*)\n\nLemma addn0 n : n + 0 = n.\n(* Welcome to equality\n\n   equality is a type, such that the only\n   constructor is when programs are the same.\n\n   erefl x : x = x\n\n   When we know A = B, we can use rewrite to\n   replace A by B!\n *)\nProof.\n  elim: n => [ | n ihn] /=.\n  - compute. done.\n  - Check addSn.\n    rewrite addSn.\n    rewrite ihn. done.\nQed.\n\n(* Equality works for more complicated things *)\nRequire Import ssralg.\nOpen Scope ring_scope.\nImport GRing.Theory.\n\nLemma roots (N : fieldType) (x : N) :\n  (x - 1) * (x - 1) = x ^+ 2 - x *+ 2 + 1.\nProof.\n  rewrite !(mulrDl, mulrDr).\n  Search _ (_ * -1).\n  rewrite !(mulrN1, mulN1r).\n  rewrite opprK mulr2n !addrA.\n  rewrite opprD addrA.\n  done.\nQed.\n\n", "meta": {"author": "ejgallego", "repo": "mini-faust-coq", "sha": "a8dea492ceba48ac7f7977bcf87638e1ceea3d51", "save_path": "github-repos/coq/ejgallego-mini-faust-coq", "path": "github-repos/coq/ejgallego-mini-faust-coq/mini-faust-coq-a8dea492ceba48ac7f7977bcf87638e1ceea3d51/faust-demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.8382058600423125}}
{"text": "\nRequire Import Arith.\n\nInductive BinaryTree : Type :=\n| Leaf : BinaryTree\n| Node : BinaryTree->BinaryTree->BinaryTree.\n\nCheck Node (Node Leaf Leaf) Leaf.\n\nCheck Leaf.\n\nCheck Node Leaf Leaf.\n\nDefinition max (a:nat) (b:nat) : nat := \n    if a <=? b then b else a.\n\nFixpoint TreeDepth (tree : BinaryTree) : nat := \n    match tree with \n    | Leaf => 0\n    | Node leftc rightc => (max (TreeDepth rightc) (TreeDepth leftc)) + 1\n    end.\n\nCompute TreeDepth Leaf.\nCompute TreeDepth (Node Leaf Leaf).\nCompute TreeDepth (Node Leaf (Node Leaf (Node Leaf Leaf))).\n\nInductive bin : Type :=\n    L : bin\n    | N : bin -> bin -> bin.\n\nFixpoint flatten_aux (t1 t2:bin) : bin :=\n    match t1 with\n    | L => N L t2\n    | N t'1 t'2 => flatten_aux t'1 (flatten_aux t'2 t2)\n    end.\n\nFixpoint flatten (t:bin) : bin :=\n    match t with\n    | L => L \n    | N t1 t2 => flatten_aux t1 (flatten t2)\n    end.\n\nFixpoint size (t:bin) : nat :=\n    match t with\n    | L => 1 \n    | N t1 t2 => 1 + size t1 + size t2\n    end.\n\nCompute flatten (N (N L L) (N (N L L) L)).\n\nDefinition example7 (t : bin): bool :=\nmatch t with N L L => false | _ => true end.\n\n(*My Proof*)\nLemma example7_size : forall t, example7 t = false -> size t = 3.\nProof.\n    induction t.\n    simpl example7.\n    discriminate.\n    case t1.\n    case t2.\n    simpl.\n    intros h; reflexivity.\n    intros b0 b1.\n    simpl.\n    discriminate.\n    intros b0 b1.\n    simpl.\n    discriminate.\nQed.\n    \n(*Book Proof*)\nLemma example7_size_book : forall t, example7 t = false -> size t = 3.\nProof.\n    intros t.\n    destruct t.\n    simpl.\n    discriminate.\n    destruct t1.\n    destruct t2.\n    simpl.\n    auto.\n    simpl; discriminate.\n    simpl; discriminate.\nQed.\n\n(*My Proof*)\nLemma flatten_aux_size :\nforall t1 t2, size (flatten_aux t1 t2) = size t1 + size t2 + 1.\nProof.\n    induction t1.\n    intros t2.\n    simpl.\n    ring.\n\n    intros t2.\n    simpl.\n    rewrite IHt1_1.\n    rewrite IHt1_2.\n    ring.\nQed.\n\n(*Book Proof*)\nLemma flatten_aux_size_book :\nforall t1 t2, size (flatten_aux t1 t2) = size t1 + size t2 + 1.\nProof.\n    induction t1.\n    intros t2.\n    simpl.\n    ring. (*Same as my base case nice*)\n\n    intros t2; simpl.\n    rewrite IHt1_1.\n    rewrite IHt1_2.\n    ring. (*Wow same proof I used!*)\nQed.\n\n(*Exersize, My proof*)\nLemma flatten_size : forall t, size (flatten t) = size t.\nProof.\n    induction t.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite flatten_aux_size.\n    rewrite IHt2.\n    ring.\nQed.\n\nLemma not_subterm_self_l : forall x y, ~ x = N x y.\nProof.\n    induction x.\n    intros y.\n    discriminate. (*Unsure why this works since*)\n\n    intros y.\n    intros abs.\n    injection abs.\n    intros H1 H2.\n\n    assert (IHx1' : x1 <> N x1 x2).\n    apply IHx1.\n    case IHx1'.\n    exact H2.\nQed.\n\n\n\n", "meta": {"author": "James-Oswald", "repo": "Coq-In-A-Hurry", "sha": "d9ba73090affe7d7c8a324bf726f709a7b949a15", "save_path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry", "path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry/Coq-In-A-Hurry-d9ba73090affe7d7c8a324bf726f709a7b949a15/Chapter7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9005297894548548, "lm_q1q2_score": 0.8379053803898251}}
{"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\n(** This declaration can be read: \"The one and only way to\n    construct a pair of numbers is by applying the constructor [pair]\n    to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Functions for extracting the first and second components of a pair\n    can then be defined by pattern matching. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily in what follows, it is nice\n    to be able to write them with the standard mathematical notation\n    [(x,y)] instead of [pair x y].  We can tell Coq to allow this with\n    a [Notation] declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in pattern\n    matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n    is not to be confused with the \"multiple pattern\" syntax (with no\n    parentheses: [x, y]) that we have seen previously.  The above\n    examples illustrate pattern matching on a pair with elements [x]\n    and [y], whereas, for example, the definition of [minus] in\n    [Basics] performs pattern matching on the values [n] and [m]:\n\n       Fixpoint minus (n m : nat) : nat :=\n         match n, m with\n         | O   , _    => O\n         | S _ , O    => n\n         | S n', S m' => minus n' m'\n         end.\n\n    The distinction is minor, but it is worth knowing that they\n    are not the same. For instance, the following definitions are\n    ill-formed:\n\n        (* Can't match on a pair with multiple patterns: *)\n        Definition bad_fst (p : natprod) : nat :=\n          match p with\n          | x, y => x\n          end.\n\n        (* Can't match on multiple values with pair patterns: *)\n        Definition bad_minus (n m : nat) : nat :=\n          match n, m with\n          | (O   , _   ) => O\n          | (S _ , O   ) => n\n          | (S n', S m') => bad_minus n' m'\n          end.\n*)\n\n(** Now let's try to prove a few simple facts about pairs.\n\n    If we state properties of pairs in a slightly peculiar way, we can\n    sometimes complete their proofs with just reflexivity (and its\n    built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\n(** But just [reflexivity] is not enough if we state the lemma in the\n    most natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** Instead, we need to expose the structure of [p] so that\n    [simpl] can perform the pattern match in [fst] and [snd].  We can\n    do this with [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n    generates two subgoals, [destruct] generates just one subgoal\n    here.  That's because [natprod]s can only be constructed in one\n    way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but here is roughly what's going on in case you are\n    interested.  The \"[right associativity]\" annotation tells Coq how to\n    parenthesize expressions involving multiple uses of [::] so that,\n    for example, the next three declarations mean exactly the same\n    thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The \"[at level 60]\" part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n    [1 + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** Next let's look at several functions for constructing and\n    manipulating lists.  First, the [repeat] function takes a number\n    [n] and a [count] and returns a list of length [count] in which\n    every element is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Since [app] will be used extensively, it is again convenient\n    to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first element (the\n    \"tail\").  Since the empty list has no first element, we pass\n    a default value to be returned in that case.  *)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs)\n\n    Complete the definitions of [nonzeros], [oddmembers], and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist\n  := match l with\n     | nil    => nil\n     | O :: t => nonzeros t\n     | n :: t => n :: nonzeros t\n     end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist\n  := match l with\n     | nil    => nil\n     | n :: t => match odd n with\n                | false => oddmembers t\n                | true  => n :: oddmembers t\n                end\n     end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\n(** For [countoddmembers], we're giving you a header that uses keyword\n    [Definition] instead of [Fixpoint].  The point of stating the\n    question this way is to encourage you to implement the function by\n    using already-defined functions, rather than writing your own\n    recursive definition. *)\n\nDefinition countoddmembers (l:natlist) : nat\n  := length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)\n\n    Complete the following definition of [alternate], which\n    interleaves two lists into one, alternating between elements taken\n    from the first list and elements from the second.  See the tests\n    below for more specific examples.\n\n    Hint: there is an elegant way of writing [alternate] that fails to\n    satisfy Coq's requirement that all [Fixpoint] definitions be\n    _structurally recursing_, as mentioned in [Basics]. If you\n    encounter that difficulty, consider pattern matching against both\n    lists at the same time with the \"multiple pattern\" syntax we've\n    seen before. *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n  := match l1, l2 with\n     | x1 :: l1', x2 :: l2' => x1 :: x2 :: alternate l1' l2'\n     | l1, nil              => l1\n     | nil, l2              => l2\n     end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions)\n\n    Complete the following definitions for the functions [count],\n    [sum], [add], and [member] for bags. *)\n\nFixpoint count (v : nat) (s : bag) : nat\n  := match s with\n     | n :: s' => if v =? n then S (count v s') else count v s'\n     | nil     => O\n     end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't call this operation [union].)\n\n    We've deliberately given you a header that does not give explicit\n    names to the arguments.  Implement [sum] with an already-defined\n    function without changing the header. *)\n\nDefinition sum : bag -> bag -> bag\n  := app.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v : nat) (s : bag) : bag\n  := cons v s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint member (v : nat) (s : bag) : bool\n  := match s with\n     | n :: s' => if n =? v then true else member v s'\n     | nil    => false\n     end.\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions)\n\n    Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n    remove, it should return the same bag unchanged.  (This exercise\n    is optional, but students following the advanced track will need\n    to fill in the definition of [remove_one] for a later\n    exercise.) *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag\n  := match s with\n     | n :: s' => if n =? v then s' else n :: remove_one v s'\n     | nil     => nil\n     end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n  := match s with\n     | n :: s' => if n =? v then remove_all v s' else n :: remove_all v s'\n     | nil     => nil\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     | n :: s1' => if member n s2 then included s1' (remove_one n s2) else false\n     | nil      => true\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(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count)\n\n    Adding a value to a bag should increase the value's count by one.\n    State this as a theorem and prove it. *)\n(*\nTheorem add_inc_count : ...\nProof.\n  ...\nQed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_add_inc_count : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, just the simplification performed by [reflexivity] is\n    enough for this theorem... *)\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs.  We'll see how to do this next. *)\n\n(** (Micro-Sermon: As we get deeper into this material, simply\n    _reading_ proof scripts will not get you very far!  It is\n    important to step through the details of each one using Coq and\n    think about what each step achieves.  Otherwise it is more or less\n    guaranteed that the exercises will make no sense when you get to\n    them.  'Nuff said.) *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors.  For example, a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to another\n    number; and a list can be either [nil] or [cons] applied to a\n    number and a list.   Moreover, applications of the declared\n    constructors to one another are the _only_ possible shapes\n    that elements of an inductively defined set can have.\n\n    This last fact directly gives rise to a way of reasoning about\n    inductively defined sets: a number is either [O] or else it is [S]\n    applied to some _smaller_ number; a list is either [nil] or else\n    it is [cons] applied to some number and some _smaller_ list;\n    etc. So, if we have in mind some proposition [P] that mentions a\n    list [l] and we want to argue that [P] holds for _all_ lists, we\n    can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can always be broken down into smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case.\n\n    Once again, this Coq proof is not especially illuminating as a\n    static document -- it is easy to see what's going on if you are\n    reading the proof in an interactive Coq session and you can see\n    the current goal and context at each point, but this state is not\n    visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n               [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing\n    function [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** For something a bit more challenging than the proofs\n    we've seen so far, let's prove that reversing a list does not\n    change its length.  Our first attempt gets stuck in the successor\n    case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress at the point where we got\n    stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length.\n    simpl. rewrite -> IHl'. rewrite add_comm.\n    reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length], [++], and [plus].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2.\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After reading a couple like this, we might find it easier to\n    follow proofs that give fewer details (which we can easily work\n    out in our own minds or on scratch paper if necessary) and just\n    highlight the non-obvious steps.  In this more compressed style,\n    the above proof might look like this: *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l], by a straightforward induction on [l].  The main\n     property again follows by induction on [l], using the observation\n     together with the induction hypothesis in the case where [l =\n     n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that they will already be familiar with.\n    The more pedantic style is a good default for our present\n    purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Let's say\n    you've forgotten the name of a theorem about [rev].  The command\n    [Search rev] will cause Coq to display a list of all theorems\n    involving [rev]. *)\n\nSearch rev.\n\n(** Or say you've forgotten the name of the theorem showing that plus\n    is commutative.  You can use a pattern to search for all theorems\n    involving the equality of two additions. *)\n\nSearch (_ + _ = _ + _).\n\n(** You'll see a lot of results there, nearly all of them from the\n    standard library.  To restrict the results, you can search inside\n    a particular module: *)\n\nSearch (_ + _ = _ + _) inside Induction.\n\n(** You can also make the search more precise by using variables in\n    the search pattern instead of wildcards: *)\n\nSearch (?x + ?y = ?y + ?x).\n\n(** The question mark in front of the variable is needed to indicate\n    that it is a variable in the search pattern, rather than a\n    variable that is expected to be in scope currently. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    Your IDE likely has its own functionality to help with searching.\n    For example, in ProofGeneral, you can run [Search] with [C-c C-a\n    C-a], and paste its response into your buffer with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises)\n\n    More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1.\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1. rewrite -> app_assoc. reflexivity.\nQed.\n\n(** An _involution_ is a function that is its own inverse. That is,\n    applying the function twice yield the original input. *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr. rewrite -> IHl. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| n1 l1'].\n  - simpl. reflexivity.\n  - destruct n1 as [|n1'].\n    + simpl.\n      rewrite <- IHl1'.\n      reflexivity.\n    + simpl.\n      rewrite <- IHl1'.\n      reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist)\n\n    Fill in the definition of [eqblist], which compares\n    lists of numbers for equality.  Prove that [eqblist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool\n  := match l1, l2 with\n     | n1 :: l1', n2 :: l2' => if n1 =? n2 then eqblist l1' l2' else false\n     | nil, nil => true\n     | _, _ => false\n     end.\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> eqb_refl. rewrite <- IHl'. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  reflexivity. Qed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next\n    exercise (it will also be useful in later chapters). *)\n\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n   definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  induction s as [| n s'].\n  - simpl. reflexivity.\n  - simpl.\n    destruct n as [|n'].\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum)\n\n    Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!  Hint: If you defined [count] using\n    [=?] you may find it useful to know that [destruct] works on\n    arbitrary expressions, not just simple identifiers.)\n*)\n\nTheorem bag_count_sum : forall (s1 s2 : bag), forall n : nat,\n  count n (sum s1 s2) = (count n s1) + (count n s2).\n  intros s1 s2 n.\n  induction s1 as [| n' s1'].\n  - reflexivity.\n  - simpl.\n    destruct (n =? n').\n    + simpl. rewrite <- IHs1'. reflexivity.\n    + rewrite <- IHs1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (involution_injective) *)\n\n(** Prove that every involution is injective. Involutions were defined\n    above in [rev_involutive]. An _injective_ function is one-to-one:\n    it maps distinct inputs to distinct outputs, without any\n    collisions. *)\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 I n1 n2 H.\n  rewrite -> I.\n  rewrite <- H.\n  rewrite <- I.\n  reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (rev_injective)\n\n    Prove that [rev] is injective. Do not prove this by induction --\n    that would be hard. Instead, re-use the same proof technique that\n    you used for [involution_injective]. Do not try to use that\n    exercise directly as a lemma: the types are not the same. *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2. intros H.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' n'\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. As we see here, constructors of inductive definitions can\n    be capitalized. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n*)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars, standard (hd_error)\n\n    Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  := match l with\n     | nil    => None\n     | h :: _ => Some h\n     end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd)\n\n    This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default.\n  destruct l.\n  reflexivity. reflexivity.  Qed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id (n : nat).\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us flexibility to change representations later\n    if we want to. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, eqb_id x x = true.\nProof.\n  intros x.\n  destruct x.\n  simpl. rewrite -> eqb_refl. reflexivity. Qed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.  (* make the definitions from NatList available here *)\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map by shadowing it with a new one (or simply adds a new\n    entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if eqb_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros d k v.\n  simpl. rewrite -> eqb_id_refl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d m n o.\n  intros H.\n  simpl. rewrite -> H.\n  reflexivity. Qed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard, optional (baz_num_elts)\n\n    Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n    in a comment.) *)\n\n(** no elements *)\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.9273632956467157, "lm_q1q2_score": 0.8376818876389999}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\n(*\n    You are only allowed to use these tactics:\n\n    simpl, reflexivity, intros, rewrite, destruct, induction, apply, assert\n\n    You are not allowed to use theorems outside this file *unless*\n    explicitly recommended.\n*)\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nShow that 5 equals 5.\n\n *)\nTheorem ex1:\n  5 = 5.\nProof.\nreflexivity.\nQed.\n\n(**\n\nShow that equality for natural numbers is reflexive.\n\n *)\nTheorem ex2:\n  forall (x:nat), x = x.\nProof.\nintros.\nreflexivity.\nQed.\n\n(**\n\nShow that [1 + n] equals the successor of [n].\n\n *)\nTheorem ex3:\n  forall n, 1 + n = S n.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n(**\n\nShow that if [x = y], then [y = x].\n\n *)\nTheorem ex4:\n  forall x (y:nat), x = y -> y = x.\nProof.\nintros.\nrewrite H.\nreflexivity.\nQed.\n\n(**\n\nShow that if the result of the conjunction and the disjunction equal,\nthen both boolean values are equal.\n\n\n *)\nTheorem ex5:\n  forall (b c : bool), (andb b c = orb b c) -> b = c.\nProof.\nintros b.\nintros c.\ndestruct b.\n- simpl.\n  intros H.\n  rewrite H.\n  reflexivity.\n- simpl.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\n(**\n\nIn an addition, we can move the successor of the left-hand side to\nthe outer most.\n\n\n *)\nTheorem ex6:\n  forall n m, n + S m = S (n + m).\nProof.\nintros.\ninduction n.\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite <- IHn.\n  reflexivity.\nQed.\n\n(**\n\nIf two additions are equal, and the numbers to the left of each addition\nare equal, then the numbers to the right of each addition must be equal.\nTo complete this exercise you will need to use the auxiliary\ntheorem: eq_add_S\n\n\n *)\nTheorem ex7:\n  forall x y n, n + x = n + y -> x = y.\nProof.\nintros.\ninduction n.\n- simpl in H.\n  apply H.\n- simpl in H.\n  Check eq_add_S.\n  apply eq_add_S in H.\n  apply IHn.\n  apply H.\n\nQed.\n\n(**\n\nShow that addition is commutative.\nHint: You might need to prove `x + 0 = x` and `S (y + x) = y + S x`\nseparately.\n\n\n *)\n\nLemma X0 : forall x, x + 0 = x.\nProof.\nintros x.\ninduction x.\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHx.\n  reflexivity.\nQed.\n\n\nLemma SYX : forall x y, x + S y = S (x + y).\nProof.\nintros x y.\ninduction x.\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHx.\n  reflexivity.\nQed.\n\nTheorem ex8:\n  forall x y, x + y = y + x.\nProof.\nintros.\ninduction x.\n- simpl.\n  rewrite X0.\n  reflexivity.\n- simpl.\n  rewrite IHx.\n  rewrite SYX.\n  reflexivity.\nQed.\n\n(**\n\nIf two additions are equal, and the numbers to the right of each addition\nare equal, then the numbers to the left of each addition must be equal.\n\nHint: Do not try to prove this theorem directly. You should be using\nauxiliary results. You can use Admitted theorems.\n\n\n *)\nTheorem ex9:\n  forall x y n, x + n = y + n -> x = y.\nProof.\nintros.\ninduction n.\n- simpl.\n  rewrite X0 in H.\n  rewrite H.\n  rewrite X0.\n  reflexivity.\n- simpl.\n  apply IHn.\n  Check eq_add_S.\n  apply eq_add_S.\n  rewrite <- ex6.\n  rewrite H.\n  apply ex6.\nQed.\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/hw1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8374529630889634}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\n\nInductive even : nat -> Prop := \n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S n)).\n\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\n(*standard (ev_double)*)\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  intro n. induction n as [|n' IHn'].\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. apply IHn'.\nQed.\n(* /standard (ev_double)*)\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  -\n    left. reflexivity.\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  - simpl. apply ev_0.\n  - 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  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\n(*standard (inversion_practice)*)\nTheorem SSSSev__even : forall n,\n  even (S (S (S (S n)))) -> even n.\nProof.\n  intros n H. inversion H. inversion H1. apply H3. \nQed.\n(*/standard (inversion_practice)*)\n\n(* standard (even5_nonsense)*)\nTheorem even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  intro H. inversion H. inversion H1. inversion H3. Qed.\n(* /standard (even5_nonsense)*)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nLemma ev_even : forall n, \n  even n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH]. \n  -\n    exists 0. reflexivity.\n  -\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\n(*standard (ev_sum)*)\nTheorem ev_sum : forall n m, even n -> even m -> even (n + m).\nProof.\n  intros n m En Em. induction En as [|n' E' IH].\n  - simpl. apply Em.\n  - simpl. apply ev_SS. apply IH.\nQed. \n(*/standard (ev_sum)*)\n\n(*advanced, recommended (ev_ev__ev)*)\nTheorem ev_ev__ev : forall n m,\n  even (n+m) -> even n -> even m.\nProof.\n  intros n m Eplus En. induction En as [|n' IHn'].\n  - simpl in Eplus. apply Eplus.\n  - simpl in Eplus. inversion Eplus. apply IHIHn'. apply H0.\nQed.\n(* /advanced, recommended (ev_ev__ev)*)\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n n : le n n\n  | le_S n m (H : le n m) : le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2. Qed.\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 n : even (S n) -> next_even n (S n)\n  | ne_2 n (H : even (S (S n))) : next_even n (S (S n)).\n\nInductive 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\n(* standard (exp_match_ex1)*)\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros T s H. inversion H. Qed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s rel1 rel2. intros [H|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. induction ss as [|h t].\n  - simpl. apply MStar0.\n  - simpl. apply MStarApp.\n    + apply H. simpl. left. trivial.\n    + apply IHt. intros s H'.\n      apply H. simpl. right. apply H'.\nQed.\n(* /standard (exp_match_ex1)*)\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  -\n    apply Hin.\n  -\n    apply Hin.\n  - simpl. rewrite In_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    +\n      left. apply (IH1 Hin).\n    +\n      right. apply (IH2 Hin).\n  -\n    simpl. rewrite In_app_iff.\n    left. apply (IH Hin).\n  -\n    simpl. rewrite In_app_iff.\n    right. apply (IH Hin).\n  -\n    destruct Hin.\n -\n    simpl. rewrite In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    +\n      apply (IH1 Hin).\n    +\n      apply (IH2 Hin).\nQed.\n\n(*standard (re_not_empty)*)\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool :=\n  match re with\n    | EmptySet => false\n    | EmptyStr => true\n    | Char _ => true\n    | App re1 re2 => andb (re_not_empty re1) (re_not_empty re2)\n    | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n    | Star re1 => true\n  end.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\nintros T re.  split.\n  - (* -> *)\n    intros [s Hmatch].\n    induction Hmatch\n    as [\n        |x'\n        |s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n        |re|s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n    + (* EmptyStr *)\n      trivial.\n    + (* Char *)\n      trivial.\n    + (* App *)\n      simpl. rewrite IH1. rewrite IH2. trivial.\n    + (* Union *)\n      simpl. rewrite IH. trivial.\n    + (* Union *)\n      simpl. rewrite IH. \n      destruct (re_not_empty re1);trivial.\n    + (* Star *)\n      trivial.\n    + (* Star *)\n      trivial.\n  - (* <- *)\n    intros H. \n    induction re.\n    + (* EmptySet *)\n      inversion H.\n    + (* EmptyStr *)\n      exists []. apply MEmpty.\n    + (* Char *)\n      exists [t]. apply MChar.\n    + (* App *)\n      simpl in H. \n      rewrite andb_true_iff in H.\n      destruct H as [L R].\n      destruct (IHre1 L) as [s1 H1].\n      destruct (IHre2 R) as [s2 H2].\n      exists (s1++s2). apply MApp; assumption.\n    + (* union *)\n      simpl in H. rewrite orb_true_iff in H.\n      destruct H as [H | H].\n      * destruct (IHre1 H) as [s1 M].\n        exists s1. apply MUnionL. assumption.\n      * destruct (IHre2 H) as [s2 M].\n        exists s2. apply MUnionR. assumption.\n    + (* Star *)\n      exists []. apply MStar0.\nQed.\n\n(*/standard (re_not_empty)*)\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   - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n   -\n    injection Heqre'. intros Heqre'' s H. apply H.\n\n  -\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\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\n  end.\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\n  napp (n + m) l = napp n l ++ napp m l.\nProof.\n  intros T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\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\nImport Coq.omega.Omega.\n\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  -\n    simpl. omega.\n  Abort.\n\nEnd Pumping.\n\nRequire Import PeanoNat.\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  -\n    simpl. intros H. apply H. reflexivity.\n  -\n    simpl. destruct (n =? m) eqn:H.\n    +\n      intros _. rewrite eqb_eq in H. rewrite H.\n      left. reflexivity.\n    +\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H : P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros 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. destruct H as [H1 |H2]. \n  - split. intro H. reflexivity. intro H. apply H1.\n  - split. intro H. elim (H2 H). intro H.  inversion H.\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  -\n    simpl. intros H. apply H. reflexivity.\n  -\n    simpl. destruct (eqbP n m) as [H | H].\n    +\n      intros _. rewrite H. left. reflexivity.\n    +\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(*standard, recommended (eqbP_practice)*)\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.\n  induction l as [| a t IH].\n  - simpl. intros _ f. destruct f.\n  - simpl. destruct (eqbP n a) as [H | H].\n    + intros H'. discriminate.\n    + simpl. intros H1 [H2 | H3].\n      * apply H. rewrite H2. reflexivity.\n      * apply IH. apply H1. apply H3.\nQed.\n(*/standard, recommended (eqbP_practice)*)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n| ns1 : nostutter []\n| ns2 : forall n, nostutter [n]\n| ns3 : forall (n m : X) (l : list X), n <> m -> nostutter l -> nostutter (m :: l) -> nostutter (n :: m :: l).\n\nExample test_nostutter_2:  nostutter (@nil nat).\nProof. repeat constructor; apply beq_nat_false_iff; auto.\nQed.\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]).\n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H2; auto. Qed.\ns\n\n\n\n\n\n\n", "meta": {"author": "unisuke82", "repo": "SoftwareFoundation", "sha": "1911ed60b7dff597eac434734cb26d67162b6805", "save_path": "github-repos/coq/unisuke82-SoftwareFoundation", "path": "github-repos/coq/unisuke82-SoftwareFoundation/SoftwareFoundation-1911ed60b7dff597eac434734cb26d67162b6805/volume1/Indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8933094159957174, "lm_q1q2_score": 0.8372192184664183}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export Recdef.\n \nFixpoint exp2 (n : nat) : nat :=\n match n with 0 => 1 | S p => 2 * exp2 p end.\n\nLemma exp2_positive : forall n, exp2 n <> 0.\nProof. \n induction n as [ | n IHn].\n - discriminate.  \n - simpl;  destruct (exp2 n).\n   + now destruct IHn.   \n   + discriminate.\nQed.\n\n\nFixpoint div2 (n:nat) : nat :=\nmatch n with 0 | 1 => 0\n            | S (S p) => S (div2 p)\nend.\n\nLemma div2_double : forall n, div2 (2 * n) = n.\nProof.   \n  induction n as [ | n IHn].\n -   simpl;auto.\n -  replace (2 * S n) with (S (S (2 * n))) by omega.\n    simpl in *; now rewrite IHn.\nQed.\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.\n  intros P H0 H1 Hrec n; assert (P n * P (S n))%type.\n  - elim n; intuition.\n  - intuition.\nQed.\n\n\n\nLemma div2_le : forall n,  div2 n <= n.\nProof.\n  induction n using  div2_rect; auto.\n  - simpl;auto with arith.\nQed.\n\nLemma div2_lt : forall n,  n <> 0 -> div2 n < n.\nProof.\n  induction n as [| | n IHn] using div2_rect; auto.\n  - now destruct 1.\n  - simpl;intros.\n    apply le_lt_trans with (S n);auto.\n    generalize (div2_le n);auto with arith.\nQed.\n\n \nFunction log2 (n:nat) {measure (fun n:nat => n)} :=\nmatch n with 0 | 1 => 0\n           | n => S (log2 (div2 n))\nend.\n intros; apply div2_lt; discriminate.\nQed.\n\n\n\n(** Tests :\n\nAbout log2_rect.\n*)\n\nLemma log_of_exp2_0  : forall n p, n = exp2 p -> log2  n = p. \nProof.\n intro n; functional induction (log2 n).\n - induction p;simpl; try discriminate.\n   intro H; case_eq (exp2 p).\n     intro H0;  destruct (exp2_positive p);auto.      \n     intros n H0;rewrite H0 in H;discriminate.\n -  destruct p.\n    + auto.\n    + simpl.\n      intro H.\n      case_eq (exp2 p).\n      * intro H0; destruct (exp2_positive p);auto.\n      * intros n H0;  rewrite H0 in H; elimtype False; omega.   \n - intros p H;  destruct p. \n   +  simpl in H;  subst n;    contradiction. \n   +  simpl in H; rewrite (IHn0 p); auto. \n    rewrite H;   generalize (div2_double (exp2 p));auto.\nQed.\n\nLemma log_of_exp2 : forall n:nat, log2 (exp2 n) = n.\nProof.\n intro n; now apply log_of_exp2_0.\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/ch15_general_recursion/SRC/log2_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8976952948443462, "lm_q1q2_score": 0.8370589513960769}}
{"text": "Check True.\n\nCheck False.\n\nCheck 3.\n\nCheck (3+4).\n\nCheck (3=5).\n\nCheck (3,4).\n\nCheck ((3=5) /\\ True).\n\nCheck nat -> Prop.\n\nCheck (3,3=5).\n\nCheck (fun x:nat => x = 3).\n\nCheck (forall x:nat, x < 3 \\/ (exists y:nat, x=y+3)).\n\nCheck (let f := fun x => (x*3,x) in f 3).\n\nLocate \"_ <= _\".\n\nCheck and.\n\nCheck (and True False).\n\nLocate \"_ /\\ _\".\n\nEval compute in\n  let f := fun x => (x*3,x) in f 3.\n\nCheck (fun a b c d e => a+b+c+d+e).\n\nEval compute in\n  let f := (fun a b c d e => a+b+c+d+e) in f 1 2 3 4 5.\n\nDefinition example1 := fun x:nat => x*x+2*x+1.\n\nDefinition example1' (x:nat) := x*x+2*x+1.\n\nCheck example1.\n\nEval compute in example1 1.\n\nPrint example1.\n\nRequire Import Bool.\n\nEval compute in if true then 3 else 5.\n\nSearch bool.\n\nRequire Import Arith.\n\nDefinition is_zero (n:nat) :=\n  match n with\n  | 0 => True\n  |S p => False\n  end.\n\nPrint pred.\n\nFixpoint sum_n n:=\n  match n with\n  | 0 => 0\n  | S p => p + sum_n p\n  end.\n\nFixpoint sum_n2 n s :=\n  match n with\n  | 0 => s\n  | S p => sum_n2 p (p + s)\n  end.\n  \nFixpoint evenb n :=\n  match n with\n  | 0 => true\n  | 1 => false\n  | S (S p) => evenb p\n  end.\n\nRequire Import List.\n\nCheck 1::2::3::nil.\n\nCheck (nil : list nat).\n\nEval compute in map (fun x => x+3) (1::3::2::nil).\n\nEval compute in map S (1::22::3::nil).\n\nEval compute in let l := (1::2::3::nil) in l ++ map (fun x => x+3) l.\n\nDefinition head_evb l :=\n  match l with \n  | nil => false \n  | a :: tl => evenb a \n  end.\n\nFixpoint sum_list l :=\n  match l with\n  | nil => 0\n  | n::tl => n + sum_list tl \n  end.\n\nFixpoint insert n l:=\n  match l with\n  | nil => n::nil\n  | a::tl => if leb n a then n::l else a::insert n tl\n  end.\n  \nCheck 1::2::3::nil.\n\nEval compute in insert 7 (5::9::nil).\n\nFixpoint sort l :=\n  match l with\n  | nil => nil\n  | a::tl => insert a (sort tl)\n  end.\n  \nEval compute in sort (1::4::3::22::5::16::7::nil).\n\nSearch True.\n\nSearchPattern (_ + _ <= _ + _).\n\nSearchRewrite (_ + (_-_)).\n\nSearchAbout leb.\n\nLemma example2 : forall a b:Prop, a /\\ b -> b /\\ a.\nProof. intros a b H. split.\n  destruct H as [H1 H2].\n  exact H2.\n  intuition.\nQed.\n\nLemma example3 : forall a b: Prop, a \\/ b -> b \\/ a.\nProof. intros a b H.\n  destruct H as [H1 | H1].\n  right; assumption.\n  left; assumption.\nQed.\n\n\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/hurry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.9161096204605946, "lm_q1q2_score": 0.8370278530883075}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export SF.Tactics.\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions ([forall\n    x, P]).  In this chapter, we will see how Coq can be used to carry\n    out other familiar forms of logical reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** Note that all well-formed propositions have type [Prop] in Coq,\n    regardless of whether they are true or not. Simply _being_ a\n    proposition is one thing; being _provable_ is something else! *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** Indeed, propositions don't just have types: they are _first-class\n    objects_ that can be manipulated in the same ways as the other\n    entities in Coq's world.  So far, we've seen one primary place\n    that propositions can appear: in [Theorem] (and [Lemma] and\n    [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** We can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments.  For instance, here's a\n    polymorphic property defining the familiar notion of an _injective\n    function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** The equality operator [=] that we have been using so far is also\n    just a function that returns a [Prop]. The expression [n = m] is\n    just syntactic sugar for [eq n m], defined using Coq's [Notation]\n    mechanism. Because [=] can be used with elements of any type, it\n    is also polymorphic: *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type argument [A]\n    to [eq] is declared as implicit, so we need to turn off implicit\n    arguments to see the full type of [eq].) *)\n\n(* #################################################################### *)\n(** * Logical Connectives *)\n\n(** ** Conjunction *)\n\n(** The _conjunction_ or _logical and_ of propositions [A] and [B] is\n    written [A /\\ B], denoting the claim that both [A] and [B] are\n    true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  Its effect is to\n    generate two subgoals, one for each part of the statement: *)\n\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** More generally, the following principle works for any two\n    propositions [A] and [B]: *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** A logical statement with multiple arrows is just a theorem that\n    has several hypotheses.  Here, [and_intro] says that, for any\n    propositions [A] and [B], if we assume that [A] is true and we\n    assume that [B] is true, then [A /\\ B] is also true.\n\n    Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can, apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** So much for proving conjunctive statements.  To go in the other\n    direction -- i.e., to _use_ a conjunctive hypothesis to prove\n    something else -- we employ the [destruct] tactic.\n\n    If the proof context contains a hypothesis [H] of the form [A /\\\n    B], writing [destruct H as [HA HB]] will remove [H] from the\n    context and add two new hypotheses: [HA], stating that [A] is\n    true, and [HB], stating that [B] is true.  For instance: *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] when we introduce it instead of\n    introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** In this case, there is not much difference between the two\n    theorems.  But it is often necessary to explicitly decompose\n    conjunctions that arise from intermediate steps in proofs,\n    especially in bigger developments.  Here's a simplified\n    example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know [A /\\\n    B] but in some context we need just [A] (or just [B]).  The\n    following lemmas are useful in such cases: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of conjuncts in multi-way conjunctions.  The\n    following commutativity and associativity theorems come in handy\n    in such cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n  \n(** **** Exercise: 2 stars (and_assoc)  *)\n(** (In the following proof of associativity, notice how the _nested_\n    intro pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (Alternatively, we can write [or A B], where [or : Prop ->\n    Prop -> Prop].)\n\n    To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis, which, as for [nat] or other data types, can be done\n    with [destruct] or [intros].  Here is an example: *)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     [n = 0 \\/ m = 0] *)\n  intros n m [Hn | Hm].\n  - (* Here, [n = 0] *)\n    rewrite Hn. reflexivity.\n  - (* Here, [m = 0] *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n(** We can see in this example that, when we perform case analysis on\n    a disjunction [A \\/ B], we must satisfy two proof obligations,\n    each showing that the conclusion holds under a different\n    assumption -- [A] in the first subgoal and [B] in the second.\n    Note that the case analysis pattern ([Hn | Hm]) allows us to name\n    the hypothesis that is generated in each subgoal.\n\n    Conversely, to show that a disjunction holds, we need to show that\n    one of its sides does. This is done via two tactics, [left] and\n    [right].  As their names imply, the first one requires proving the\n    left side of the disjunction, while the second requires proving\n    its right side.  Here is a trivial use... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and a slightly more interesting example requiring the use of\n    both [left] and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** ** Falsehood and Negation *)\n\n(** So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    _negative_ results, showing that certain propositions are _not_\n    true. In Coq, such negative statements are expressed with the\n    negation operator [~].\n\n    To see how negation works, recall the discussion of the _principle\n    of explosion_ from the [Tactics] chapter; it asserts that, if we\n    assume a contradiction, then any other proposition can be derived.\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].  Coq actually makes a slightly different\n    choice, defining [~ P] as [P -> False], where [False] is a\n    _particular_ contradictory proposition defined in the standard\n    library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can [destruct] it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\n(** Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** This is how we use [not] to state that [0] and [1] are different\n    elements of [nat]: *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** Such inequality statements are frequent enough to warrant a\n    special notation, [x <> y]: *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    get things into the right configuration so that Coq can understand\n    it!  Here are proofs of a few familiar facts to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** Similarly, since inequality involves a negation, it requires a\n    little practice to be able to work with it fluently.  Here is one\n    useful trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see some examples such uses of [True] later on. *)\n\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB.  Qed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we need\n    to import a special Coq library that allows rewriting with other\n    formulas besides equality: *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences: *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\n(** We can now use these facts with [rewrite] and [reflexivity] to\n    give smooth proofs of statements involving equivalences.  Here is\n    a ternary version of the previous [mult_0] result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which side of\n    the equivalence to use. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n(* ############################################################ *)\n(** ** Existential Quantification *)\n\n(** Another important logical connective is _existential\n    quantification_.  To say that there is some [x] of type [T] such\n    that some property [P] holds of [x], we write [exists x : T,\n    P]. As with [forall], the type annotation [: T] can be omitted if\n    Coq is able to infer from the context what the type of [x] should\n    be.\n\n    To prove a statement of the form [exists x, P], we must show that\n    [P] holds for some specific choice of value for [x], known as the\n    _witness_ of the existential.  This is done in two steps: First,\n    we explicitly tell Coq which witness [t] we have in mind by\n    invoking the tactic [exists t]; then we prove that [P] holds after\n    all occurrences of [x] are replaced by [t].  Here is an example: *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n    the context, we can destruct it to obtain a witness [x] and a\n    hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.  Qed.\n\n(** **** Exercise: 1 star (dist_not_exists)  *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* #################################################################### *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure:\n\n    - If [l] is the empty list, then [x] cannot occur on it, so the\n      property \"[x] appears in [l]\" is simply false.\n\n    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n      occurs in [l] if either it is equal to [x'] or it occurs in\n      [l']. *)\n\n(** We can translate this directly into a straightforward Coq\n    function, [In].  (It can also be found in the Coq standard\n    library.) *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested conjunctions. *)\n\nExample In_example_1 : In 4 [3; 4; 5].\nProof.\n  simpl. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions, though convenient in some\n    cases, also has some drawbacks.  In particular, it is subject to\n    Coq's usual restrictions regarding the definition of recursive\n    functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n  (* FILL IN HERE *) admit.\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, prove the following facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* #################################################################### *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from many other proof\n    assistants is that it treats _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it in detail in order to use Coq.  This\n    section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [SF.ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use the [Check] command to ask Coq to\n    print the type of an expression.  We can also use [Check] to ask\n    what theorem a particular identifier refers to. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** Coq prints the _statement_ of the [plus_comm] theorem in the same\n    way that it prints the _type_ of any term that we ask it to\n    [Check].  Why?\n\n    The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_ -- a data structure that represents a logical\n    derivation establishing of the truth of the statement [forall n m\n    : nat, n + m = m + n].  The type of this object _is_ the statement\n    of the theorem that it is a proof of.\n\n    Intuitively, this makes sense because the statement of a theorem\n    tells us what we can use that theorem for, just as the type of a\n    computational object tells us what we can do with that object --\n    e.g., if we have a term of type [nat -> nat -> nat], we can give\n    it two [nat]s as arguments and get a [nat] back.  Similarly, if we\n    have an object of type [n = m -> n + n = m + m] and we provide it\n    an \"argument\" of type [n = m], we can derive [n + n = m + m].\n\n    Operationally, this analogy goes even further: by applying a\n    theorem, as if it were a function, to hypotheses with matching\n    types, we can specialize its result without having to resort to\n    intermediate assertions.  For example, suppose we wanted to prove\n    the following result: *)\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\n\n(** One simple way of fixing this problem, using only tools that we\n    already know, is to use [assert] to derive a specialized version\n    of [plus_comm] that can be used to rewrite exactly where we\n    want. *)\n\n  rewrite plus_comm.\n  assert (H : m + p = p + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n(** A more elegant alternative is to apply [plus_comm] directly to the\n    arguments we want to instantiate it with, in much the same way as\n    we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take2 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples of the idioms from this section in\n    later chapters. *)\n\n(* #################################################################### *)\n(** * Coq vs. Set Theory *)\n\n(** Coq's logical core, the _Calculus of Inductive Constructions_,\n    differs in some important ways from other formal systems that are\n    used by mathematicians for writing down precise and rigorous\n    proofs.  For example, in the most popular foundation for\n    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set\n    Theory (ZFC), a mathematical object can potentially be a member of\n    many different sets; a term in Coq's logic, on the other hand, is\n    a member of at most one type.  This difference often leads to\n    slightly different ways of capturing informal mathematical\n    concepts, though these are by and large quite natural and easy to\n    work with.  For example, instead of saying that a natural number\n    [n] belongs to the set of even numbers, we would say in Coq that\n    [ev n] holds, where [ev : nat -> Prop] is a property describing\n    even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be either cumbersome or\n    sometimes even impossible, unless we enrich the core logic with\n    additional axioms.  We conclude this chapter with a brief\n    discussion of some of the most significant differences between the\n    two worlds. *)\n\n(** ** Functional Extensionality\n\n    The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But\n    since Coq's equality operator is polymorphic, these are not the\n    only possibilities -- in particular, we can write propositions\n    claiming that two _functions_ are equal to each other: *)\n\nExample function_equality_ex : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same outputs:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_.\n\n    Informally speaking, an \"extensional property\" is one that\n    pertains to an object's observable behavior.  Thus, functional\n    extensionality simply means that a function's identity is\n    completely determined by what we can observe from it -- i.e., in\n    Coq terms, the results we obtain after applying it.\n\n    Functional extensionality is not part of Coq's basic axioms: the\n    only way to show that two functions are equal is by\n    simplification (as we did in the proof of [function_equality_ex]).\n    But we can add it to Coq's core logic using the [Axiom]\n    command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Using [Axiom] has the same effect as stating a theorem and\n    skipping its proof using [Admitted], but it alerts the reader that\n    this isn't just something we're going to come back and fill in\n    later!\n\n    We can now invoke functional extensionality in proofs: *)\n\nLemma plus_comm_ext : plus = fun n m => m + n.\nProof.\n  apply functional_extensionality. intros n.\n  apply functional_extensionality. intros m.\n  apply plus_comm.\nQed.\n\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as they may render it inconsistent -- that is, it may\n    become possible to prove every proposition, including [False]!\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe: hard work is generally required to establish the\n    consistency of any particular combination of axioms.  Fortunately,\n    it is known that adding functional extensionality, in particular,\n    _is_ consistent.\n\n    Note that it is possible to check whether a particular proof\n    relies on any additional axioms, using the [Print Assumptions]\n    command. For instance, if we run it on [plus_comm_ext], we see\n    that it uses [functional_extensionality]: *)\n\nPrint Assumptions plus_comm_ext.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 5 stars (tr_rev)  *)\n(** One problem with the definition of the list-reversing function\n    [rev] that we have is that it performs a call to [app] on each\n    step; running [app] takes time asymptotically linear in the size\n    of the list, which means that [rev] has quadratic running time.\n    We can improve this with the following definition: *)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(** This version is said to be _tail-recursive_, because the recursive\n    call to the function is the last operation that needs to be\n    performed (i.e., we don't have to execute [++] after the recursive\n    call); a decent compiler will generate very efficient code in this\n    case.  Prove that both definitions are indeed equivalent. *)\n\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** ** Propositions and Booleans *)\n\n(** We've seen that Coq has two different ways of encoding logical\n    facts: with _booleans_ (of type [bool]), and with\n    _propositions_ (of type [Prop]). For instance, to claim that a\n    number [n] is even, we can say either (1) that [evenb n] returns\n    [true] or (2) that there exists some [k] such that [n = double k].\n    Indeed, these two notions of evenness are equivalent, as can\n    easily be shown with a couple of auxiliary lemmas (one of which is\n    left as an exercise).\n\n    We often say that the boolean [evenb n] _reflects_ the proposition\n    [exists k, n = double k].  *)\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(** **** Exercise: 3 stars (evenb_double_conv)  *)\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either (1) that [beq_nat n m] returns [true] or (2) that [n =\n    m].  These two notions are equivalent. *)\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** However, while the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, we have\n    also seen that they need not be equivalent _operationally_.\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little help in the middle of a proof\n    involving [n] and [m]; however, if we convert the statement to the\n    equivalent form [n = m], we can rewrite with it.\n\n    The case of even numbers is also interesting.  Recall that, when\n    proving the backwards direction of\n    [even_bool_prop] ([evenb_double], going from the propositional to\n    the boolean claim), we used a simple induction on [k]).  On the\n    other hand, the converse (the [evenb_double_conv] exercise)\n    required a clever generalization, since we can't directly prove\n    [(exists k, n = double k) -> evenb n = true].\n\n    For these examples, the propositional claims were more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects an\n    elements of [bool] (or some other inductive type with two\n    elements).  The reason for this error message has to do with the\n    _computational_ nature of Coq's core language, which is designed\n    so that every function that it can express is computable and\n    total.  One reason for this is to allow the extraction of\n    executable programs from Coq developments.  As a consequence,\n    [Prop] in Coq does _not_ have a universal case analysis operation\n    telling whether any given proposition is true or false, since such\n    an operation would allow us to write non-computable functions.\n\n    Although general non-computable properties cannot be phrased as\n    boolean computations, it is worth noting that even many\n    _computable_ properties are easier to express using [Prop] than\n    [bool], since recursive function definitions are subject to\n    significant restrictions in Coq.  For instance, the next chapter\n    shows how to define the property that a regular expression matches\n    a given string using [Prop].  Doing the same with [bool] would\n    amount to writing a regular expression matcher, which would be\n    more complicated, harder to understand, and harder to reason\n    about.\n\n    Conversely, an important side benefit of stating facts using\n    booleans is enabling some proof automation through computation\n    with Coq terms, a technique known as _proof by\n    reflection_. Consider the following statement: *)\n\nExample even_1000 : exists k, 1000 = double k.\n\n(** The most direct proof of this fact is to give the value of [k]\n    explicitly. *)\n\n Proof. exists 500. reflexivity. Qed.\n\n(** On the other hand, the proof of the corresponding boolean\n    statement is even simpler: *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** What is interesting is that, since the two notions are equivalent,\n    we can use the boolean formulation to prove the other one without\n    mentioning 500 explicitly: *)\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** Although we haven't gained much in terms of proof size in this\n    case, larger proofs can often be made considerably simpler by the\n    use of reflection.  As an extreme example, the Coq proof of the\n    famous _4-color theorem_ uses reflection to reduce the analysis of\n    hundreds of different cases to a boolean computation.  We won't\n    cover reflection in great detail, but it serves as a good example\n    showing the complementary strengths of booleans and general\n    propositions. *)\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  (* FILL IN HERE *) admit.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** ** Classical vs. Constructive Logic *)\n\n(** We have seen that it is not possible to test whether or not a\n    proposition [P] holds while defining a Coq function.  You may be\n    surprised to learn that a similar restriction applies to _proofs_!\n    In other words, the following intuitive reasoning principle is not\n    derivable in Coq: *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\n(** To understand operationally why this is the case, recall that, to\n    prove a statement of the form [P \\/ Q], we use the [left] and\n    [right] tactics, which effectively require knowing which side of\n    the disjunction holds.  However, the universally quantified [P] in\n    [excluded_middle] is an _arbitrary_ proposition, which we know\n    nothing about.  We don't have enough information to choose which\n    of [left] or [right] to apply, just as Coq doesn't have enough\n    information to mechanically decide whether [P] holds or not inside\n    a function.  On the other hand, if we happen to know that [P] is\n    reflected in some boolean term [b], then knowing whether it holds\n    or not is trivial: we just have to check the value of [b].  This\n    leads to the following theorem: *)\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m].\n\n    You may find it strange that the general excluded middle is not\n    available by default in Coq; after all, any given claim must be\n    either true or false.  Nonetheless, there is an advantage in not\n    assuming the excluded middle: statements in Coq can make stronger\n    claims than the analogous statements in standard mathematics.\n    Notably, if there is a Coq proof of [exists x, P x], it is\n    possible to explicitly exhibit a value of [x] for which we can\n    prove [P x] -- in other words, every proof of existence is\n    necessarily _constructive_.  Because of this, logics like Coq's,\n    which do not assume the excluded middle, are referred to as\n    _constructive logics_.  More conventional logical systems such as\n    ZFC, in which the excluded middle does hold for arbitrary\n    propositions, are referred to as _classical_.\n\n    The following example illustrates why assuming the excluded middle\n    may lead to non-constructive proofs: *)\n\n(** _Claim_: There exist irrational numbers [a] and [b] such that [a ^\n    b] is rational.\n\n    _Proof_: It is not difficult to show that [sqrt 2] is irrational.\n    If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =\n    sqrt 2] and we are done.  Otherwise, [sqrt 2 ^ sqrt 2] is\n    irrational.  In this case, we can take [a = sqrt 2 ^ sqrt 2] and\n    [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^\n    2 = 2].  []\n\n    Do you see what happened here?  We used the excluded middle to\n    consider separately the cases where [sqrt 2 ^ sqrt 2] is rational\n    and where it is not, without knowing which one actually holds!\n    Because of that, we wind up knowing that such [a] and [b] exist\n    but we cannot determine what their actual values are (at least,\n    using this line of argument).\n\n    As useful as constructive logic is, it does have its limitations:\n    There are many statements that can easily be proven in classical\n    logic but that have much more complicated constructive proofs, and\n    there are some that are known to have no constructive proof at\n    all!  Fortunately, like functional extensionality, the excluded\n    middle is known to be compatible with Coq's logic, allowing us to\n    add it safely as an axiom.  However, we will not need to do so in\n    this book: the results that we cover can be developed entirely\n    within constructive logic at negligible extra cost.\n\n    It takes some practice to understand which proof techniques must\n    be avoided in constructive reasoning, but arguments by\n    contradiction, in particular, are infamous for leading to\n    non-constructive proofs.  Here's a typical example: suppose that\n    we want to show that there exists [x] with some property [P],\n    i.e., such that [P x].  We start by assuming that our conclusion\n    is false; that is, [~ exists x, P x]. From this premise, it is not\n    hard to derive [forall x, ~ P x].  If we manage to show that this\n    intermediate fact results in a contradiction, we arrive at an\n    existence proof without ever exhibiting a value of [x] for which\n    [P x] holds!\n\n    The technical flaw here, from a constructive standpoint, is that\n    we claimed to prove [exists x, P x] using a proof of [~ ~ exists\n    x, P x]. However, allowing ourselves to remove double negations\n    from arbitrary statements is equivalent to assuming the excluded\n    middle, as shown in one of the exercises below.  Thus, this line\n    of reasoning cannot be encoded in Coq without assuming additional\n    axioms. *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** The consistency of Coq with the general excluded middle axiom\n    requires complicated reasoning that cannot be carried out within\n    Coq itself.  However, the following theorem implies that it is\n    always safe to assume a decidability axiom (i.e., an instance of\n    excluded middle) for any _particular_ Prop [P].  Why? Because we\n    cannot prove the negation of such an axiom; if we could, we would\n    have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist)  *)\n(** It is a theorem of classical logic that the following two\n    assertions are equivalent:\n\n    ~ (exists x, ~ P x)\n    forall x, P x\n\n    The [dist_not_exists] theorem above proves one side of this\n    equivalence. Interestingly, the other direction cannot be proved\n    in constructive logic. Your job is to show that it is implied by\n    the excluded middle. *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n  \nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "erikmd", "repo": "tryjscoq", "sha": "b5636d1b7bc6616fe7f136678e30bc4030484f22", "save_path": "github-repos/coq/erikmd-tryjscoq", "path": "github-repos/coq/erikmd-tryjscoq/tryjscoq-b5636d1b7bc6616fe7f136678e30bc4030484f22/jscoq/examples/sf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8902942290328345, "lm_q1q2_score": 0.8367994341379505}}
{"text": "Fixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nFixpoint eqb (n m : nat) : bool :=\nmatch n with\n| O => match m with\n        | O => true\n        | S m' => false\n        end\n| S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\nend.\n\n\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n\nTheorem leb_refl : forall n : nat, \n    (n <=? n) = true. \nProof. \n    intros n. induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\n    Qed. \n\nTheorem zero_neqb_S : forall n : nat, \n    0 =? (S n) = false. \nProof. \n    intros n. destruct n.\n    - reflexivity.\n    - reflexivity.\n    Qed. \n\nTheorem andb_false_r : forall b : bool, \n    andb b false = false. \nProof. \n    intros b. destruct b. \n    - reflexivity.\n    - reflexivity.\n    Qed. \n\nTheorem S_neqb_0 : forall n : nat, \n    (S n) =? 0 = false. \nProof. \n    intros n. destruct n. \n    - reflexivity.\n    - reflexivity. Qed.\n\nLemma add_0_r : forall n : nat, \n    n + 0 = n.\nProof. Admitted. \n\nTheorem mult_1_1 : forall n : nat, \n    1 * n = n. \nProof. \n    intros n. induction n as [| n' IHn']. \n    - reflexivity.\n    - simpl. rewrite -> add_0_r. reflexivity.\n    Qed. \n\nTheorem all3_spec : forall b c : bool, \n    orb (andb b c)(orb (negb b)(negb c)) = true. \n    (* b&&c || (~b||~c) == true *)\nProof. \n    intros b c. destruct b. \n    - destruct c. \n     + reflexivity.\n     + reflexivity.\n    - destruct c. \n     + reflexivity.\n     + reflexivity.\n    Qed. \n\nLemma add_assoc : forall n m p : nat, \n    n + (m + p) = (n + m) + p. \nProof. Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat, \n    (n + m) * p = (n * p) + (m * p). \nProof. \n    intros n m p. induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn'. rewrite -> add_assoc. reflexivity.\n    Qed. \n\nTheorem mult_assoc : forall n m p : nat, \n    n * (m * p) = (n * m) * p. \nProof. \n    intros n m p. induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> mult_plus_distr_r. rewrite -> IHn'. reflexivity.\n    Qed. ", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/induction/exercises/more_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.9032942034496965, "lm_q1q2_score": 0.8367247902083574}}
{"text": "Require Import ZArith.\nRequire Import List.\n\nSet Implicit Arguments.\n\nDefinition dec (n : nat) : {p : nat | n = p + 1} + {n = 0}.\n  forall n : nat, {p : nat | n = p + 1} + {n = 0}\nrefine (fun n:nat => match n return {p : nat | n = p + 1} + {n = 0} with\n | 0 => inright _ _\n | S p => inleft _ (exist _ p _)\nend\n).\n\nOpen Scope Z_scope.\n\n(* Inductive Sorted : list Z -> Prop := *)\n(*   | sorted0 : Sorted nil *)\n(*   | sorted1 : forall z:Z, Sorted (z :: nil) *)\n(*   | sorted2 : forall (z1 z2:Z) (l:list Z), *)\n(*         z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l). *)\n\n\nFixpoint count (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat     (* %nat to force the interpretation in nat, since have we open Z_scope *)\n  | (z' :: l') =>\n      match Z.eq_dec z z' with\n      | left _ => S (count z l')\n      | right _ => count z l'\n      end\n  end.\n\nDefinition Perm (l1 l2:list Z) : Prop := forall z, count z l1 = count z l2.\n\nLemma Perm_cons : forall a l1 l2, Perm l1 l2 -> Perm (a::l1) (a::l2).\n(* FILL IN HERE *) Admitted.\n\nLemma Perm_cons_cons : forall x y l, Perm (x::y::l) (y::x::l).\n(* FILL IN HERE *) Admitted.\n\n\n\n(*Lemma strong_length : *)\n", "meta": {"author": "lrpereira", "repo": "software-verification", "sha": "d732c6341c6fa581a367b839820f43e0488db5c2", "save_path": "github-repos/coq/lrpereira-software-verification", "path": "github-repos/coq/lrpereira-software-verification/software-verification-d732c6341c6fa581a367b839820f43e0488db5c2/coq/tpc3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.8366779809867512}}
{"text": "\nRequire Import Arith.\nRequire Import List.\n\n\n(*-----------------------------------------------------------*)\n\n(**  * Fonctions calculables vs. relations logiques *)\n\nFixpoint sum_fun (n:nat) : nat :=\n  match n with\n    | 0 => 0\n    | S m => n + sum_fun m\n  end.\n\nExample sum_fun_5:\n  sum_fun 5 = 15.\nProof.\n  compute. reflexivity.\nQed.\n\nExample sum_fun_10:\n  sum_fun 10 = 55.\nProof.\n  compute. reflexivity.\nQed.\n\nLemma two_times:\n  forall n : nat, 2 * n = n + n.\nProof.\n  intro n. ring.\nQed.\n\nTheorem sum_fun_Gauss:\n  forall n : nat, 2 * (sum_fun n) = n * (n + 1).\nProof.\n  intro n.\n  rewrite two_times.\n  induction n as [| n'].\n  - (* cas n=0 *)\n    simpl.\n    reflexivity.\n  - (* cas n=S n' *)\n    simpl.    \n    (* SearchPattern (S _ = S _).\n       eq_S: forall x y : nat, x = y -> S x = S y *)\n    apply eq_S.\n    assert (H:  n' + sum_fun n' + S (n' + sum_fun n')\n                = sum_fun n' + sum_fun n' + n' + S n').\n    { ring. }\n    rewrite H. clear H.\n    rewrite IHn'.\n    ring.\nQed.\n\n\n(*  R\u00e8gles : \n\n                             n s : nat   sum_rel n s\n   ============= (sum_O)    ============================ (sum_S)\n    sum_rel 0 0              sum_rel (S n) ( (S n) + s)\n\n*)\n\nInductive sum_rel : nat -> nat -> Set :=\n| sum_O: sum_rel 0 0\n| sum_S: forall n s:nat,\n           sum_rel n s -> sum_rel (S n) ( (S n) + s).\n\nExample sum_rel_3:\n  sum_rel 3 6.\nProof.\n  change (sum_rel 3 (3 + 3)).\n  apply sum_S.\n  change (sum_rel 2 (2 + 1)).\n  apply sum_S.\n  change (sum_rel 1 (1 + 0)).\n  apply sum_S.\n  apply sum_O.\nQed.\n\nTheorem sum_rel_Gauss:\n  forall n s : nat, (sum_rel n s) -> 2 * s = n * (n + 1).\nProof.\n  induction n as [|n'].\n  - (* cas n=0 *)\n    intros s Hsum.\n    inversion Hsum.\n    simpl.\n    reflexivity.\n  - (* cas n=S n' *)\n    intros s Hsum.\n    inversion Hsum. clear Hsum n H H1.\n    apply IHn' in H0. clear IHn'.\n    rewrite two_times in *.\n    assert (H1: S n' + s0 + (S n' + s0) = s0 + s0 + S n' + S n').\n    { ring. }\n    rewrite H1. clear H1.\n    rewrite H0.\n    ring.\nQed.\n\nTheorem sum_rel_Gauss':\n  forall n s : nat, (sum_rel n s) -> 2 * s = n * (n + 1).\nProof.\n  intros n s H.\n  induction H.  (* rule induction *)\n  - (* cas sum_O *)\n    simpl.\n    reflexivity.\n  - (* cas sum_S *)\n    rewrite two_times in *.\n    assert (H1: S n + s + (S n + s) = s + s + S n + S n).\n    { ring. }\n    rewrite H1. clear H1.\n    rewrite IHsum_rel.\n    ring.\nQed.\n\n\n(** ** Exercice 1 *)\n\n(** *** Question 1 *)\n\nFixpoint concat_fun {A : Type} (l1 l2 : list A) : list A :=\n  match l1 with\n    | nil => l2\n    | a :: l1 => a :: concat_fun l1 l2\n  end.\n\n(** *** Question 2 *)\n\nInductive concat_rel (A : Set) : list A -> list A -> list A -> Prop :=\n| concat_nil: forall l : list A, concat_rel A nil l l\n| concat_cons: forall e1 : A,\n               forall l1 l2 l3 : list A,\n                 concat_rel A l1 l2 l3\n                 -> concat_rel A (e1::l1) l2 (e1::l3).\n\nArguments concat_nil [A] _.\nArguments concat_cons [A] _ _ _ _ _.\n\nPrint concat_rel.\n\nCheck concat_rel_ind.\n\n(** *** Question 3 *)\n\nLemma concat_fun_cons:\n  forall A : Set, forall e : A, forall l1 l2 : list A,\n    concat_fun (e::l1) l2 = e::(concat_fun l1 l2).\nProof.\nintros A e l1 l2.\ndestruct l1.\n-simpl.\n reflexivity.\n-simpl.\n reflexivity.\nQed.\n\n(** *** Question 5 *)\n\nLemma concat_fun_length:\n  forall A : Set, forall l1 l2 : list A,\n    length (concat_fun l1 l2) = (length l1) + (length l2).\nProof.\n  intros A l1 l2.\n  induction l1 as [|l' ll'].\n  -simpl.\n   reflexivity.\n  -simpl.\n   rewrite IHll'.\n   reflexivity.\nQed.\n\n  (** *** Question 4 *)\n\nLemma concat_rel_cons:\n  forall A : Set, forall e : A, forall l1 l2 l3 : list A,\n    concat_rel A l1 l2 l3 -> concat_rel A (e::l1) l2 (e::l3).\nProof.\n  intros A e l1 l2 l3 Hrel.\n  induction Hrel.\n  - apply concat_cons.\n    apply concat_nil.\n  - apply concat_cons.\n    apply concat_cons.\n    exact Hrel.\nQed.\n    (** *** Question 6 *)\n\nLemma concat_rel_length:\n  forall A : Set, forall l1 l2 l3 : list A,\n    concat_rel A l1 l2 l3 \n    -> length l3 = (length l1) + (length l2).\nProof.\n  intros A l1 l2 l3 Hrel.\n  induction Hrel.  (* rule induction *)\n  - simpl.\n    reflexivity.\n  - (* cas concat_cons *)\n    simpl.\n    SearchPattern (S (_) = S (_)).\n    apply eq_S.\n    exact IHHrel.\nQed.\n(** ** Exercice 2 : appartenance \u00e0 une liste *)\n\nSection is_in.\n\nVariable A : Set.\nVariable A_eq_dec : forall a b : A, {a = b} + {a <> b}.\n\nFixpoint is_in_fun (e : A) (l : list A) : bool :=\n  match l with\n    | nil => false\n    | e'::l' => match A_eq_dec e e' with\n                  | left _ => true\n                  | right _ => is_in_fun e l'\n                end\n  end.\n\nEnd is_in.\n\nCheck is_in_fun.\n\nExample is_in_fun_ex1:\n  is_in_fun nat (eq_nat_dec) 3 (1::2::3::4::5::nil) = true.\nProof.\n  compute. reflexivity.\nQed.\n\n(** *** Question 1 *)\n\nInductive is_in_rel (A:Set) : A -> list A -> Prop :=\n  is_in_head: forall a : A, forall l : list A, is_in_rel A a (a::l)\n| is_in_tail: forall a b : A, forall l : list A, a <> b -> is_in_rel A a l -> is_in_rel A a (b::l).\n\n(** *** Question 2 *)\n    \nExample is_in_rel_ex1:\n  is_in_rel nat 3 (1::2::3::4::5::nil).\nProof.\n  apply is_in_tail.\n  discriminate.\n  apply is_in_tail.\n  discriminate.\n  apply is_in_head.\nQed.\n(** ** Exercice 3 : liste pr\u00e9fixe *)\n\nSection is_prefix.\n\nVariable A : Set.\nVariable A_eq_dec : forall a b : A, {a = b} + {a <> b}.\n\nFixpoint is_prefix_fun (l1 l2 : list A) : bool :=\n  match l1 with\n    | nil => true\n    | e1::l1' => match l2 with\n                   | nil => false\n                   | e2::l2' => match A_eq_dec e1 e2 with\n                                  | left _ => is_prefix_fun l1' l2'\n                                  | right _ => false\n                                end\n                 end\n  end.\n\nEnd is_prefix.\n\n\n(** *** Question 1 *)\n\nInductive is_prefix_rel (A : Set) : list A -> list A -> bool -> Prop :=\n| is_prefix_nil: forall l : list A, is_prefix_rel A nil l l\n| is_prefix_cons: forall e1 : A,\n               forall l1 l2 l3 : list A,\n                 is_prefix_rel A l1 l2 l3\n                 -> is_prefix_rel A (e1::l1) l2 (e1::l3).\n\n(** *** Question 2 *)\n\n[[\nLemma is_prefix_is_in_fun: \n  forall A : Set, forall A_eq_dec : forall a b : A, {a = b} + {a <> b},\n    forall l2 l1 : list A,\n      (is_prefix_fun A A_eq_dec l1 l2) = true \n      -> (forall e :  A, is_in_fun A A_eq_dec e l1 = true -> is_in_fun A A_eq_dec e l2 = true).\nProof.\n  intros A A_eq_dec.\n  induction l2 as [| e2 l2'].\n  - (* cas l2 = nil *)\n    (* <<< A COMPLETER >>>> *)\n  - (* cas l2=e2::l2' *)\n    intros l1 H1 e H2.\n    simpl.\n    destruct (A_eq_dec e e2).\n    + (* cas e=e2 *)\n      reflexivity.\n    + (* cas e<>e2 *)\n      { destruct l1 as [| e1 l1'].\n        - (* cas l1=nil *)\n          (* <<< A COMPLETER >>> *)\n        - (* cas l1=e1::l1' *)\n          { apply IHl2' with (l1:=l1').\n              (* <<< A COMPLETER >>> *)\n          }\n      }\nQed.\n\n(** *** Question 3 *)\n\nLemma is_prefix_is_in_rel: \n  forall A : Set,\n  forall l1 l2 : list A,\n    (is_prefix_rel A l1 l2)\n    -> (forall e :  A, is_in_rel A e l1 -> is_in_rel A e l2).\nProof.\n  intros A l1 l2 Hprefix.\n  induction Hprefix.\n  (* <<<A COMPLETER>>> *)\n\n\n", "meta": {"author": "ebtaleb", "repo": "SVP", "sha": "cac36c82a07248ccfc078207e43678b5f5b19e3d", "save_path": "github-repos/coq/ebtaleb-SVP", "path": "github-repos/coq/ebtaleb-SVP/SVP-cac36c82a07248ccfc078207e43678b5f5b19e3d/TP08/theme8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.9073122276263202, "lm_q1q2_score": 0.8364709595188584}}
{"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\n(** This declaration can be read: \"The one and only way to\n    construct a pair of numbers is by applying the constructor [pair]\n    to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Here are simple functions for extracting the first and\n    second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily in what follows, it is nice\n    to be able to write them with the standard mathematical notation\n    [(x,y)] instead of [pair x y].  We can tell Coq to allow this with\n    a [Notation] declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n\n(** The new notation can be used both in expressions and in pattern\n    matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n    is not to be confused with the \"multiple pattern\" syntax (with no\n    parentheses: [x, y]) that we have seen previously.  The above\n    examples illustrate pattern matching on a pair with elements [x]\n    and [y], whereas, for example, the definition of [minus] in\n    [Basics] performs pattern matching on the values [n] and [m]:\n\n       Fixpoint minus (n m : nat) : nat :=\n         match n, m with\n         | O   , _    => O\n         | S _ , O    => n\n         | S n', S m' => minus n' m'\n         end.\n\n    The distinction is minor, but it is worth knowing that they\n    are not the same. For instance, the following definitions are\n    ill-formed:\n\n        (* Can't match on a pair with multiple patterns: *)\n        Definition bad_fst (p : natprod) : nat :=\n          match p with\n          | x, y => x\n          end.\n\n        (* Can't match on multiple values with pair patterns: *)\n        Definition bad_minus (n m : nat) : nat :=\n          match n, m with\n          | (O   , _   ) => O\n          | (S _ , O   ) => n\n          | (S n', S m') => bad_minus n' m'\n          end.\n*)\n\n(** Now let's try to prove a few simple facts about pairs.\n\n    If we state properties of pairs in a slightly peculiar way, we can\n    sometimes complete their proofs with just reflexivity (and its\n    built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** Instead, we need to expose the structure of [p] so that\n    [simpl] can perform the pattern match in [fst] and [snd].  We can\n    do this with [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n    generates two subgoals, [destruct] generates just one subgoal\n    here.  That's because [natprod]s can only be constructed in one\n    way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but here is roughly what's going on in case you are\n    interested.  The \"[right associativity]\" annotation tells Coq how to\n    parenthesize expressions involving multiple uses of [::] so that,\n    for example, the next three declarations mean exactly the same\n    thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The \"[at level 60]\" part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n    [1 + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** Next let's look at several functions for constructing and\n    manipulating lists.  First, the [repeat] function takes a number\n    [n] and a [count] and returns a list of length [count] in which\n    every element is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Since [app] will be used extensively, it is again convenient\n    to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first element (the\n    \"tail\").  Since the empty list has no first element, we pass\n    a default value to be returned in that case.  *)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs) \n\n    Complete the definitions of [nonzeros], [oddmembers], and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist:=\n    match l with\n  | nil  => nil\n  | h::t  => match h with\n            | 0  => nonzeros (t)\n            | _  => h:: nonzeros (t)\n            end        \n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n   Proof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil  => nil\n  | h::t  => match (oddb h) with\n            | false  => oddmembers t\n            | true  => h:: oddmembers (t)\n            end        \n  end.\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n   Proof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n Proof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  Proof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n Proof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate) \n\n    Complete the following definition of [alternate], which\n    interleaves two lists into one, alternating between elements taken\n    from the first list and elements from the second.  See the tests\n    below for more specific examples.\n\n    (Note: one natural and elegant way of writing [alternate] will\n    fail to satisfy Coq's requirement that all [Fixpoint] definitions\n    be \"obviously terminating.\"  If you find yourself in this rut,\n    look for a slightly more verbose solution that considers elements\n    of both lists at the same time.  One possible solution involves\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1, l2 with\n  | nil,_ => l2\n  | _ , nil => l1 \n  | h1 :: t1, h2:: t2 => h1 :: h2 :: alternate t1 t2\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  Proof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  Proof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  Proof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  Proof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions) \n\n    Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v : nat) (s : bag) : nat :=\n     match s with\n  | nil => 0\n  | h :: t => if h =? v then ( S (count v t)) else (count v t)\n  end.\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n Proof. reflexivity.  Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n Proof. reflexivity.  Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't call this operation [union].)  For\n    [sum], we're giving you a header that does not give explicit names\n    to the arguments.  Moreover, it uses the keyword [Definition]\n    instead of [Fixpoint], so even if you had names for the arguments,\n    you wouldn't be able to process them recursively.  The point of\n    stating the question this way is to encourage you to think about\n    whether [sum] can be implemented in another way -- perhaps by\n    using one or more functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag :=\n   app.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n Proof. reflexivity.  Qed.\n\nDefinition add (v : nat) (s : bag) : bag :=\n  v :: s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n Proof. reflexivity.  Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n Proof. reflexivity.  Qed.\n\nDefinition member (v : nat) (s : bag) : bool :=\n   negb ((count v s) =? 0).\n\nExample test_member1:             member 1 [1;4;1] = true.\n Proof. reflexivity.  Qed.\n\nExample test_member2:             member 2 [1;4;1] = false.\n Proof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions) \n\n    Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n    remove, it should return the same bag unchanged.  (This exercise\n    is optional, but students following the advanced track will need\n    to fill in the definition of [remove_one] for a later\n    exercise.) *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n     match s with\n  | nil => nil\n  | h :: t =>  if (h =? v) then (t) else (h :: (remove_one v t))\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity.  Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  Proof. reflexivity.  Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity.  Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  Proof. reflexivity.  Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => if h =? v\n                 then (remove_all v t)\n              else (h :: (remove_all v t))\n  end.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity.  Qed.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\n  Proof. reflexivity.  Qed.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity.  Qed.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n  Proof. reflexivity.  Qed.\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool :=\n   match s1 with \n  | nil => true\n  | hd1 :: tl1 => \n      andb (member hd1 s2)\n           (subset tl1 (remove_one hd1 s2))\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n Proof. reflexivity.  Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n Proof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count) \n\n    Adding a value to a bag should increase the value's count by one.\n    State that as a theorem and prove it. *)\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_add_inc_count : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, just the simplification performed by [reflexivity] is\n    enough for this theorem... *)\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs.  We'll see how to do this next. *)\n\n(** (Micro-Sermon: As we get deeper into this material, simply\n    _reading_ proof scripts will not get you very far!  It is\n    important to step through the details of each one using Coq and\n    think about what each step achieves.  Otherwise it is more or less\n    guaranteed that the exercises will make no sense when you get to\n    them.  'Nuff said.) *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors.  For example, a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to another\n    number; and a list can be either [nil] or [cons] applied to a\n    number and a list.   Moreover, applications of the declared\n    constructors to one another are the _only_ possible shapes\n    that elements of an inductively defined set can have.\n\n    This last fact directly gives rise to a way of reasoning about\n    inductively defined sets: a number is either [O] or else it is [S]\n    applied to some _smaller_ number; a list is either [nil] or else\n    it is [cons] applied to some number and some _smaller_ list;\n    etc. So, if we have in mind some proposition [P] that mentions a\n    list [l] and we want to argue that [P] holds for _all_ lists, we\n    can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can always be broken down into smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case.\n\n    Once again, this Coq proof is not especially illuminating as a\n    static document -- it is easy to see what's going on if you are\n    reading the proof in an interactive Coq session and you can see\n    the current goal and context at each point, but this state is not\n    visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing\n    function [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** For something a bit more challenging than the proofs\n    we've seen so far, let's prove that reversing a list does not\n    change its length.  Our first attempt gets stuck in the successor\n    case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress at the point where we got\n    stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length.\n    simpl. rewrite -> IHl'. rewrite plus_comm.\n    reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length], [++], and [plus].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2.\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After reading a couple like this, we might find it easier to\n    follow proofs that give fewer details (which we can easily work\n    out in our own minds or on scratch paper if necessary) and just\n    highlight the non-obvious steps.  In this more compressed style,\n    the above proof might look like this: *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l], by a straightforward induction on [l].  The main\n     property again follows by induction on [l], using the observation\n     together with the induction hypothesis in the case where [l =\n     n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that they will already be familiar with.\n    The more pedantic style is a good default for our present\n    purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Let's say\n    you've forgotten the name of a theorem about [rev].  The command\n    [Search rev] will cause Coq to display a list of all theorems\n    involving [rev]. *)\n\nSearch rev.\n\n(** Or say you've forgotten the name of the theorem showing that plus\n    is commutative.  You can use a pattern to search for all theorems\n    involving the equality of two additions. *)\n\nSearch (_ + _ = _ + _).\n\n(** You'll see a lot of results there, nearly all of them from the\n    standard library.  To restrict the results, you can search inside\n    a particular module: *)\n\nSearch (_ + _ = _ + _) inside Induction.\n\n(** You can also make the search more precise by using variables in\n    the search pattern instead of wildcards: *)\n\nSearch (?x + ?y = ?y + ?x).\n\n(** The question mark in front of the variable is needed to indicate\n    that it is a variable in the search pattern, rather than a\n    variable that is expected to be in scope currently. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    Your IDE likely has its own functionality to help with searching.\n    For example, in ProofGeneral, you can run [Search] with [C-c C-a\n    C-a], and paste its response into your buffer with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises) \n\n    More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. induction l1 as [| n1 l1'].\n  - simpl. rewrite -> app_nil_r. reflexivity. \n  - simpl. rewrite -> IHl1'. \n    simpl. rewrite -> app_assoc.\n    reflexivity. Qed.\n\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l' IHl' ].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. \n           rewrite -> IHl'.  \n           reflexivity. Qed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4. induction l1 as [| n l1' IHl' ].\n  - simpl. rewrite <- app_assoc. reflexivity.\n  - simpl. rewrite <- IHl'.\n           reflexivity. Qed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n1 l1' IHl'].\n  - reflexivity.\n  - induction n1 as [| n1' IHn'].\n    + simpl. rewrite -> IHl'. reflexivity.\n    + simpl. rewrite -> IHl'. reflexivity. Qed.\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist) \n\n    Fill in the definition of [eqblist], which compares\n    lists of numbers for equality.  Prove that [eqblist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | _ , nil => false\n  | nil, _  => false\n  | h1 :: t1, h2:: t2 => if h1 =? h2 then \n                            andb true (eqblist t1 t2)\n                         else\n                            false\n  end.\n   \n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\n  Proof. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\n  Proof. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\n  Proof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\n  intros l. induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite <- IHl'. simpl. \n           rewrite <- eqb_refl. \n           reflexivity. Qed.\nSearch (_=?_).\n\n(** \nTH\u00e9or\u00e8me : Pour tous listes de types nat [l], [true = eqbList l l].\n\npreuve  : Par induction sur [l].\n\n  - premi\u00e8rement, on suppose que [l = []]. Et on doit montre que\n\n      true = eqblist [ ] [ ]\n\n      Ce qui est vraie de la definition de [eqblist]\n  \n  - Secondement, on suppose que [l = n::l'], avec\n\n      l'hypoth\u00e8se [true = eqblist l' l']\n\n      et on doit montre que [true = eqblist (n :: l') (n :: l')]\n    \n      Par la definition d'eqblist \u00e7a equivaut \u00e0\n\n        [true = eqblist (l' l') si n = n, sinon\n        [false]\n\n      Ce que  par l'effet d'hypoth\u00e8se d'induction est \u00e9gale \u00e0\n         [true = true si n = n, sinon\n        [false]\n\n      Et qui est vraie par l'application du th\u00e9or\u00e8me eqb_refl .\n     \n*)\n\n\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero)  *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n   simpl. reflexivity. Qed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n   definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count)  *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  intros s. induction s as [| n s' IHs ].\n  - reflexivity.\n  - destruct n as [| n'].\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs. reflexivity. Qed.\n\n   \n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum) \n\n    Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!) *)\n\n(*Le th\u00e9or\u00e8me ici verifie que le compte d'un nombre (zero) dans le bag qui contient la somme de deux bags est egale\n  \u00e0 la somme des comptes d'un nombre (zero) dans chaque bag *)\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 as [| h1 t1 IHb].\n  - simpl. reflexivity.\n  - destruct h1 as [| h1'].\n    + simpl. rewrite -> IHb. reflexivity.\n    + simpl. rewrite -> IHb. reflexivity.\nQed.\n\n\n(** **** Exercise: 4 stars, advanced (rev_injective) \n\n    Prove that the [rev] function is injective. There is a hard way\n    and an easy way to do this. *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n    rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 Hl.\n  rewrite <- rev_involutive.\n  rewrite <- Hl.\n  rewrite -> rev_involutive.\n  reflexivity. Qed.\n  \n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' n'\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. As we see here, constructors of inductive definitions can\n    be capitalized. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if n =? O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the [bool] type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars, standard (hd_error) \n\n    Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption := \n  match l with\n  | nil => None\n  | h :: t => Some h\n  end.\n   \n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd) \n\n    This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default. destruct l as [| n l'].\n  - reflexivity.\n  - simpl. reflexivity. Qed.\n  \n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id (n : nat).\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us more flexibility. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl)  *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof. intros x . destruct x. \n       simpl. rewrite<-eqb_refl.\n       reflexivity. Qed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map by shadowing it with a new one (or simply adds a new\n    entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if eqb_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n(** **** Exercise: 1 star, standard (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard, optional (baz_num_elts) \n\n    Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n    in a comment.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* 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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.9219218391455084, "lm_q1q2_score": 0.836470954106576}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* ** Binomial theorem *)\n\nRequire Import Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac gcd.\n\nSet Implicit Arguments.\n\nSection factorial.\n\n  Fixpoint fact n := match n with 0 => 1 | S n => (S n) * fact n end.\n\n  Fact fact_0 : fact 0 = 1.\n  Proof. trivial. Qed.\n\n  Fact fact_S n : fact (S n) = (S n)*fact n.\n  Proof. trivial. Qed.\n\n  Fact fact_gt_0 n : 0 < fact n.\n  Proof.\n    unfold lt; simpl.\n    induction n as [ | n IHn ]; simpl; auto.\n    generalize (n*fact n); intros; lia.\n  Qed.\n\n  Fact divides_n_fact_n n : 0 < n -> divides n (fact n).\n  Proof.\n    destruct n as [ | n ]; try lia; intros _.\n    apply divides_mult_r, divides_refl.\n  Qed.\n\n  Fact divides_fact_S n : divides (fact n) (fact (S n)).\n  Proof. apply divides_mult, divides_refl. Qed.\n\n  Fact divides_fact n i : 0 < i <= n -> divides i (fact n).\n  Proof.\n    intros (H1 & H2); revert H2.\n    induction 1 as [ | n H2 IH2 ].\n    + apply divides_n_fact_n; auto.\n    + apply divides_trans with (1 := IH2), divides_fact_S.\n  Qed.   \n\nEnd factorial.\n\nSection binomial.\n\n  Infix \"<d\" := divides (at level 70, no associativity).\n\n  Hint Resolve divides_refl : core.\n\n  Let fact_neq_0 n : fact n <> 0.\n  Proof. generalize (fact_gt_0 n); lia. Qed.\n\n  Fixpoint binomial n p :=\n    match n, p with\n      | _, 0     => 1\n      | 0, S _   => 0\n      | S n, S p => binomial n p + binomial n (S p)\n    end.\n\n  Fact binomial_n0 n : binomial n 0 = 1.\n  Proof. destruct n; auto. Qed.\n\n  Fact binomial_SS n p : binomial (S n) (S p) = binomial n p + binomial n (S p).\n  Proof. auto. Qed.\n\n  Fact binomial_n1 n : 1 <= n -> binomial n 1 = n.\n  Proof.\n    destruct n as [ | n ]; try lia; intros _.\n    induction n as [ | n IHn ]; auto.\n    rewrite binomial_SS, IHn, binomial_n0; lia.\n  Qed.\n\n  Fact binomial_gt n : forall p, n < p -> binomial n p = 0.\n  Proof.\n    induction n as [ | n IHn ]; intros [|] ?; simpl; auto; try lia.\n    do 2 (rewrite IHn; try lia).\n  Qed.\n\n  Fact binomial_nn n : binomial n n = 1.\n  Proof.\n    induction n; auto; rewrite binomial_SS, binomial_gt with (p := S _); lia.\n  Qed.\n\n  Theorem binomial_thm n p : p <= n -> fact n = binomial n p * fact p * fact (n-p).\n  Proof.\n    intros H.\n    replace n with (n-p+p) at 1 2 by lia.\n    generalize (n-p); clear n H; intros n.\n    induction on n p as IH with measure (n+p).\n    revert n p IH; intros [ | n ] [ | p ] IH; simpl plus; auto.\n    + rewrite binomial_nn; simpl; lia.\n    + rewrite Nat.add_0_r, binomial_n0; simpl; lia.\n    + rewrite fact_S, binomial_SS.\n      replace (S (n+S p)) with (S p+S n) by lia.\n      do 3 rewrite Nat.mul_add_distr_r; f_equal.\n      * replace (n+S p) with (S n+p) by lia.\n        rewrite fact_S, IH; try lia; ring.\n      * rewrite (fact_S n), IH; try lia; ring.\n  Qed.\n\n  Fact binomial_le n p : p <= n -> binomial n p = div (fact n) (fact p * fact (n-p)).\n  Proof.\n    intros H.\n    symmetry; apply div_prop with (r := 0).\n    + rewrite binomial_thm with (p := p); auto; ring.\n    + red; change 1 with (1*1); apply Nat.mul_le_mono; apply fact_gt_0.\n  Qed.\n\n  Fact binomial_sym n p : p <= n -> binomial n p = binomial n (n-p).\n  Proof.\n    intros H; do 2 (rewrite binomial_le; try lia).\n    rewrite Nat.mul_comm; do 3 f_equal; lia.\n  Qed.\n\n  Fact binomial_spec n p : p <= n -> fact n = binomial n p * fact p * fact (n-p).\n  Proof. apply binomial_thm. Qed.\n\n  Fact binomial_0n n : 0 < n -> binomial 0 n = 0.\n  Proof. intros; rewrite binomial_gt; auto; simpl. Qed.\n\n  Theorem binomial_pascal n p : binomial (S n) (S p) = binomial n p + binomial n (S p).\n  Proof. auto. Qed.\n\nEnd binomial.\n", "meta": {"author": "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/binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.8887588023318195, "lm_q1q2_score": 0.8361351752235671}}
{"text": "Module NatList.\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nDefinition bag := natlist.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nFixpoint eq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n\t  | O => true\n  \t| S m' => false\n\t  end\n    | S n' => match m with\n\t    | O => false\n\t    | S m' => eq_nat n' m'\n\t    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\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 :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\n  | h :: t => match (eq_nat h v) with\n              | true => S (count v t)\n              | false => count v t\n              end\n  end.\n\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 eq_nat h v with\n              | true => t\n              | false => h :: (remove_one v t)\n              end\n  end.\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intro n.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\n(**** NEW ****)\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  intros s.\n  induction s.\n  - simpl. reflexivity.\n  - simpl. destruct n.\n    -- simpl. rewrite ble_n_Sn. reflexivity.\n    -- simpl. rewrite IHs. reflexivity.\n  Qed.\n", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter3/remove_does_not_increase_count.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8902942355821459, "lm_q1q2_score": 0.8360083865828811}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined 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\nExample e1: even 7.\nProof. unfold even. simpl. Abort.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  \n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\nintros.\ninduction n.\nsimpl.\napply ev_0.\nsimpl.\napply ev_SS.\napply IHn.\nQed.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\nintros.\nsimpl.\napply b_sum with (n:=n) (m:=(n+0)).\napply H.\napply b_sum with (n:=n) (m:=0).\napply H.\napply b_0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\nintros.\ninduction m.\nCase \"m=0\".\n   simpl.\n   apply b_0.\nCase \"m=m'\".\n    simpl.\n    apply b_sum with (n:=n) (m:=m*n).\n    apply H.\n    apply IHm.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\nintros.\nrepeat (apply g_plus5).\napply g_plus3.\napply H.\nQed.\n\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\n\n(** **** Exercise: 2 stars (gorgeous_sum)  *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\nintros.\ninduction H.\nsimpl.\napply H0.\napply g_plus3 with (n:=n+m).\nassumption.\napply g_plus5 with (n:=n+m).\nassumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous)  *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\nintros.\ninduction H.\napply g_0.\napply g_plus3 with (n:=0).\napply g_0.\napply g_plus5 with (n:=0).\napply g_0.\napply gorgeous_sum.\napply IHbeautiful1.\napply IHbeautiful2.\nQed.\n\n(** [] *)\n\n\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\nintros.\nrewrite -> plus_swap. \napply plus_assoc.  \nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   destruct H.\n   simpl.\n   apply g_0.\n   apply g_plus3 with (n:= n+(3+n+0)).\n   apply gorgeous_sum.\n   apply H.\n   apply g_plus3 with (n:= n+0).\n   apply gorgeous_sum.\n   apply H.\n   apply g_0.\n   apply g_plus5 with (n:= n+(5+n+0)).\n   apply gorgeous_sum.\n   apply H.\n   apply g_plus5 with (n:= n+0).\n   apply gorgeous_sum.\n   apply H.\n   apply g_0.\nQed.\n   \n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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. simpl. apply IHE'.  \nQed.\n\n(** **** Exercise: 1 star (ev__even)  *) \n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\nTheorem ev__even' : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction n.\n  Case \"E = ev_0\". \n  unfold even.\n  reflexivity.\n  unfold even.\nAdmitted.\n\n(** We cannot do it with induction on n because according to the induction hypothesis,\nn is even, while we need to prove that S n is even in the second part of the proof,\nwhich is a contradiction to the hypothesis. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \nintros.\ninduction H.\nCase \"ev0\".\n   induction H0.\n   SCase \"ev0'\".\n      simpl.\n      apply ev_0.\n   SCase \"ev(SSm)\".\n      simpl.\n      apply ev_SS.\n      apply H0.\nCase \"evSSn\".\n    simpl.\n    apply ev_SS.\n    assumption.\nQed.\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we \n   can _look_ at that evidence for more information. For example, consider \n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead \n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  (*induction E.*)\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice)  *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\nintros.\ninversion H.\ninversion H1.\napply 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.\nintros.\ninversion H.\ninversion H1.\ninversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\nintros.\ninduction H0.\nCase \"ev0\".\n   simpl in H.\n   apply H.\nCase \"evSS\".\n   inversion H.\n   apply IHev in H2.\n   apply H2.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nSearchAbout plus.\n\nTheorem ev_ev__ev' : forall n m,\n  ev n -> ev m -> ev (n+m).\nProof.\nAdmitted.\n \nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\nintros.\ninversion H.\n\napply ev_ev__ev with (n:=n) in H.\napply ev_sum.\napply H.\napply ev_ev__ev with (n:=n) (m:=p) in H0.\napply H0.\napply ev_ev__ev with (n:=n) (m:=p) in H0.\nAdmitted.\n(*apply ev_sum.\napply H.\napply H0.\napply ev_sum.\ninduction m.\nsimpl.\napply H0.\n.\nsimpl.*)\n\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However, \n   we can define inductive predicates about any type of data. For example, \n   suppose we would like to characterize lists of _even_ length. We can \n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof. \n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H. \n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil. \n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l. \n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n    \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 [pal_app_rev] that \n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that \n       forall l, pal l -> l = rev l.\n\nInductive pal {X:Type} : (list X) -> Prop :=\n| p0 : pal []\n| p1 : forall (x:X), pal [x]\n| p : forall l, l=rev l -> pal l.\n*)\n\nInductive pal {X:Type} : (list X) -> Prop :=\n| p0 : pal []\n| p1 : forall (x:X), pal [x]\n| p : forall l x, pal l -> pal (x :: snoc l x).\n\nTheorem pal_app_rev: forall (X: Type) (l: list X), pal (l ++ rev l).\nProof.\nintros.\ninduction l.\nsimpl.\napply p0.\nsimpl.\nSearchAbout snoc.\nrewrite <- snoc_with_append.\napply p.\nassumption.\nQed.\n\nTheorem pal_rev: forall (X:Type) (l: list X), pal l -> l = rev l.\nProof.\nintros.\ninduction H.\nreflexivity.\nreflexivity.\nsimpl.\nSearchAbout snoc.\nrewrite -> rev_snoc.\nsimpl.\napply f_equal.\nrewrite <-IHpal.\nreflexivity.\nQed.\n\n\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\nTheorem palindrome_converse: forall (X:Type) (l: list X), l = rev l -> pal l.\nProof.\nintros.\nAdmitted.\n(* FILL IN HERE *)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n| tr : forall n m, total_relation n m.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop :=\n| er : forall n, ev n -> ev (S n) -> empty_relation n (S n).\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\nintros.\nrewrite -> H0 in H.\napply H.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\nintros.\ninduction n.\napply le_n.\napply le_S with (n:=0) (m:=n).\napply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \nintros.\ninduction H.\nreflexivity.\napply le_S.\napply IHle.\nQed.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \nintros.\ninversion H.\nsubst.\nreflexivity.\nrewrite <- H1.\napply le_S.\nreflexivity.\nQed.\n\nLemma plus_help : forall a b, a + S b = S (a+b).\nProof.\nintros.\ninduction a.\nsimpl.\nreflexivity.\nsimpl.\napply f_equal.\napply IHa.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \nintros.\ninduction b.\nrewrite -> plus_0_r.\nreflexivity.\nrewrite -> plus_help.\napply le_S.\nassumption.\nQed.\n\nLemma plus_help' : forall a b, S a + b = S (a+b).\nProof.\nintros.\ninduction a.\nsimpl.\nreflexivity.\nsimpl.\napply f_equal.\napply IHa.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \nunfold lt. \nintros.\nsplit.\napply le_trans with (n:=S (n1 + n2)).\nrewrite <- plus_help'.\napply le_plus_l.\napply H.\napply le_trans with (n:=S (n1 + n2)).\nrewrite <- plus_help.\nrewrite <- plus_comm.\napply le_plus_l.\napply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\nunfold lt.\nintros.\ndestruct m.\ninversion H.\napply le_S.\napply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \nintros.\ngeneralize dependent m.\ninduction n.\nintros.\napply O_le_n.\nintros.\ndestruct m.\ninversion H.\napply IHn in H.\napply n_le_m__Sn_le_Sm.\napply H.\nQed.\n\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\nintros.\ngeneralize dependent n.\ninduction m.\nintros.\ninversion H.\nreflexivity.\nintros.\ndestruct n.\nreflexivity.\nsimpl.\napply IHm.\napply Sn_le_Sm__n_le_m.\napply H.\nQed.\n\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\nintros.\napply ble_nat_true in H.\napply ble_nat_true in H0.\napply le_ble_nat.\napply le_trans with (n:=m) (m:=n).\napply H.\napply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\nintros.\nunfold not.\nintros.\napply le_ble_nat in H0.\nrewrite -> H in H0.\ninversion H0.\nQed.\n\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   (*| c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o*).\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\nExample rprov1: R 1 1 2.\nProof. apply c2. apply c3. apply c1. Qed.\n\nTheorem r': forall m n o, R m n o -> o = m+n.\nProof.\nintros.\ninduction H.\nsimpl.\nreflexivity.\nsimpl.\napply f_equal.\napply IHR.\nrewrite plus_comm.\nsimpl.\napply f_equal.\nrewrite plus_comm.\nassumption.\nQed.\n\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is, \n      any list is a subsequence of itself.  \n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3], \n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is \n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2] \n      is a subsequence of [l3], then [l1] is a subsequence of [l3].  \n      Hint: choose your induction carefully!\n*)\n\nInductive subseq: list nat -> list nat -> Prop :=\n| s1 : forall (l2: list nat), subseq [] l2\n| s2 : forall (l1 l2:list nat) (x:nat), subseq l1 l2 -> subseq (x::l1) (x::l2)\n| s3 : forall (l1 l2:list nat) (x:nat), subseq l1 l2 -> subseq (l1) (x::l2).\n\nExample sub1: subseq [1;2] [1;1;2;3].\nProof. apply s2. apply s3. apply s2. apply s1. Qed.\n\nTheorem subseq_refl: forall (l: list nat), subseq l l.\nProof.\nintros.\ninduction l.\nCase \"l=nil\".\n   apply s1.\nCase \"l=l'\".\n   apply s2.\n   apply IHl.\nQed.\n\nTheorem subseq_app: forall (l1 l2 l3: list nat),\nsubseq l1 l2 -> subseq l1 (l2++l3).\nProof.\nintros.\ninduction H.\nCase \"s1\".\n    apply s1.\nCase \"s2\".\n    simpl.\n    apply s2.\n    apply IHsubseq.\nCase \"s3\".\n    simpl.\n    apply s3.\n    apply IHsubseq.\nQed. \n\n(**Theorem sub_help: forall l1 l2 x,\nsubseq l1 l2 -> subseq l1 (x::l2) .\nProof.\nintros.\napply s3.\napply H.\nQed.*)\n    \nTheorem subseq_trans: forall (l1 l2 l3: list nat),\nsubseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\nintros.\ngeneralize dependent l1.\ninduction H0.\nCase \"s1\".\n    intros.\n    inversion H.\n    apply s1.\nCase \"s2\".\n    intros.\n    inversion H.\n    apply s1. subst.\n    apply s2.\n    apply IHsubseq.\n    apply H3.\n    apply s3. subst.\n    apply IHsubseq.\n    apply H3.\nCase \"s3\".\n    intros.\n    apply s3.\n    apply IHsubseq.\n    apply H.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability)  *)\n(* Suppose we give Coq the following definition:*)\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n\n(*\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\nExample r2: R 1 [1;2;1;0].\nProof. apply c3. apply c2. apply c3. apply c3. apply c2. apply c2. apply c2. apply c1. Qed.\n\n(*Inductive fib: list nat -> Prop:=\n|f0 : fib [0]\n|f1 : fib [0;1]\n|fxy : forall x y z l, fib l -> z = last l + last1 l -> fib (snoc l z). \n\nExample f11: fib [0;1;1;2;3;5;8].\nProof. apply fxy.\nreflexivity.\n*)\n\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\nfun (n:nat) => if (oddb n) then Podd n else Peven n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\nintros.\nunfold combine_odd_even.\ndestruct (oddb n) eqn:O.\napply H.\nreflexivity.\napply H0.\nreflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\nintros.\nunfold combine_odd_even in H.\ndestruct (oddb n) eqn:O.\napply H.\ninversion H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\nintros.\nunfold combine_odd_even in H.\ndestruct (oddb n) eqn:O.\ninversion H0.\napply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n\n", "meta": {"author": "SumithraSriram", "repo": "Software-Foundations", "sha": "e3d8739ca9f399266450c8a859e6f615e3eb352b", "save_path": "github-repos/coq/SumithraSriram-Software-Foundations", "path": "github-repos/coq/SumithraSriram-Software-Foundations/Software-Foundations-e3d8739ca9f399266450c8a859e6f615e3eb352b/sf/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.9124361658344132, "lm_q1q2_score": 0.8358915370380677}}
{"text": "\n(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\n\nTheorem beq_nat_refl : forall n : nat, n =? n = true.\nProof.\n  induction n as [|n'].\n  - simpl. reflexivity.\n  - rewrite <- IHn'. simpl. reflexivity.\nQed.\n\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are simple functions for extracting the first and\n    second components of a pair. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n    is not to be confused with the \"multiple pattern\" syntax\n    (with no parentheses: [x, y]) that we have seen previously.\n\n    The above examples illustrate pattern matching on a pair with\n    elements [x] and [y], whereas [minus] below (taken from\n    [Basics]) performs pattern matching on the values [n]\n    and [m].\n\n       Fixpoint minus (n m : nat) : nat :=\n         match n, m with\n         | O   , _    => O\n         | S _ , O    => n\n         | S n', S m' => minus n' m'\n         end.\n\n    The distinction is minor, but it is worth knowing that they\n    are not the same. For instance, the following definitions are\n    ill-formed:\n\n        (* Can't match on a pair with multiple patterns: *)\n        Definition bad_fst (p : natprod) : nat :=\n          match p with\n          | x, y => x\n          end.\n\n        (* Can't match on multiple values with pair patterns: *)\n        Definition bad_minus (n m : nat) : nat :=\n          match n, m with\n          | (O   , _   ) => O\n          | (S _ , O   ) => n\n          | (S n', S m') => bad_minus n' m'\n          end.\n*)\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a slightly peculiar way, we can complete\n    proofs with just reflexivity (and its built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n    generates two subgoals, [destruct] generates just one subgoal\n    here.  That's because [natprod]s can only be constructed in one\n    way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but here is roughly what's going on in case you are\n    interested.  The [right associativity] annotation tells Coq how to\n    parenthesize expressions involving multiple uses of [::] so that,\n    for example, the next three declarations mean exactly the same\n    thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n    [1 + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Since [app] will be used extensively in what follows, it is\n    again convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (With Default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first element (the\n    \"tail\").  Since the empty list has no first element, we must pass\n    a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, recommended (list_funs)  \n\n    Complete the definitions of [nonzeros], [oddmembers], and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match h with\n             | O => nonzeros t\n             | _ => h :: (nonzeros t)\n             end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. 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             | _ => 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\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)\n\n    Complete the definition of [alternate], which interleaves two\n    lists into one, alternating between elements taken from the first\n    list and elements from the second.  See the tests below for more\n    specific examples.\n\n    (Note: one natural and elegant way of writing [alternate] will\n    fail to satisfy Coq's requirement that all [Fixpoint] definitions\n    be \"obviously terminating.\"  If you find yourself in this rut,\n    look for a slightly more verbose solution that considers elements\n    of both lists at the same time.  One possible solution involves\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, nil => nil\n  | l,   nil => l\n  | nil, l   => l\n  | h1 :: t1, h2 :: t2 => h1 :: (h2 :: (alternate t1 t2))\n  end.\n\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, recommended (bag_functions)\n\n    Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\n  | h :: t => match eqb v h with\n             | true => S (count v t)\n             | _    => count v t\n             end\n  end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := app.\n\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := ltb O (count v s).\n\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions)\n\n    Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n    remove, it should return the same bag unchanged.  (This exercise\n    is optional, but students following the advanced track will need\n    to fill in the definition of [remove_one] for a later\n    exercise.) *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match eqb v h with\n             | true => t\n             | _    => h :: (remove_one 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\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match eqb v h with\n             | true => remove_all v t\n             | _    => h :: (remove_all v t)\n             end\n  end.\n\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h :: t => match count h s2 with\n             | 0 => false\n             | _ => subset t (remove_one h s2)\n             end\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (bag_theorem)  \n\n    Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\nTheorem bag_theorem : forall s : bag, forall n : nat,\n    count n (add n s) = S (count n s).\nProof.\n  intros s n.\n  simpl. rewrite -> beq_nat_refl. reflexivity.\nQed.\n\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bag_theorem : option (nat*string) := None.\n(* Note to instructors: For silly technical reasons, in this\n   file (only) you will need to write [Some (Datatypes.pair 3 \"\"%string)]\n   rather than [Some (3,\"\"%string)] to enter your grade and comments. \n\n    [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As for numbers, simple facts about list-processing functions\n    can sometimes be proved entirely by simplification.  For example,\n    the simplification performed by [reflexivity] is enough for this\n    theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply _reading_ proof scripts will not get you very far!  It is\n    important to step through the details of each one using Coq and\n    think about what each step achieves.  Otherwise it is more or less\n    guaranteed that the exercises will make no sense when you get to\n    them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static document -- it is easy to see what's\n    going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now, for something a bit more challenging than the proofs\n    we've seen so far, let's prove that reversing a list does not\n    change its length.  Our first attempt gets stuck in the successor\n    case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and state it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which we can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing [Search\n    foo] into your .v file and evaluating this line will cause Coq to\n    display a list of all theorems involving [foo].  For example, try\n    uncommenting the following line to see a list of theorems that we\n    have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with\n    [C-c C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises)  \n\n    More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [|h t].\n  - reflexivity.\n  - simpl. rewrite -> IHt. 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 [|h1 t1].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHt1. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [|h t].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHt.\n    simpl. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite -> app_assoc. rewrite -> app_assoc.\n  reflexivity.\nQed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [|h1 t1].\n  - simpl. reflexivity.\n  - simpl. destruct h1 as [|h1'].\n    + rewrite <- IHt1. reflexivity.\n    + simpl. rewrite <- IHt1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist)\n\n    Fill in the definition of [eqblist], which compares\n    lists of numbers for equality.  Prove that [eqblist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, 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\n                     end\n  end.\n\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  induction l as [|h t].\n  - reflexivity.\n  - simpl. rewrite -> beq_nat_refl. rewrite <- IHt. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero)  *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s. simpl. reflexivity.\nQed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n   definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count)  *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  induction s as [|h t].\n  - simpl. reflexivity.\n  - simpl. destruct h as [|h'].\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IHt. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum)\n\n    Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!) *)\nTheorem bag_count_sum : forall v : nat, forall (s1 s2 : bag),\n    (count v s1) + (count v s2) = count v (sum s1 s2).\nProof.\n  intros v s1 s2. induction s1 as [|h1 t1]. destruct s2 as [|h2 t2].\n  - simpl. reflexivity.\n  - simpl. destruct (v =? h2).\n    + reflexivity.\n    + reflexivity.\n  - simpl. destruct (v =? h1).\n    + simpl. rewrite -> IHt1. reflexivity.\n    + rewrite -> IHt1. reflexivity.\nQed.\n\n(** **** Exercise: 4 stars, advanced (rev_injective)\n\n    Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n    (There is a hard way and an easy way to do this.) *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n    rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  destruct l1 as [|h1 t1]. destruct l2 as [|h2 t2].\n  - reflexivity.\n  - rewrite <- rev_involutive. rewrite <- H. simpl. reflexivity.\n  - rewrite <- rev_involutive. rewrite <- H. rewrite -> rev_involutive.\n    reflexivity.\nQed.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_rev_injective : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match n =? O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n =? O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if n =? O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars, standard (hd_error)\n\n    Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | h::_ => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd)  \n\n    This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default. destruct l as [|h t].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id (n : nat).\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl)  *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  destruct x as [n].\n  simpl. rewrite -> beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map by shadowing it with a new one (or simply adds a new\n    entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if eqb_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n(** **** Exercise: 1 star, standard (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros d x v. destruct d as [|x' v' d'].\n  - simpl. rewrite <- eqb_id_refl. reflexivity.\n  - simpl. rewrite <- eqb_id_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o H.\n  simpl. rewrite -> H. reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard (baz_num_elts)\n\n    Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n    in a comment.) *)\n\n(* The type [baz] has no element, because there is no base baz constructor *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n(** [] *)\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n", "meta": {"author": "taigua", "repo": "software-foundations", "sha": "67e8a87e5ffa68d5c780258d51f5c6654038a173", "save_path": "github-repos/coq/taigua-software-foundations", "path": "github-repos/coq/taigua-software-foundations/software-foundations-67e8a87e5ffa68d5c780258d51f5c6654038a173/lf/coq/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.9161096107264306, "lm_q1q2_score": 0.8358915357872496}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export ProofObjects.\n\n(** * Basics *)\n(*\u5f53\u7528inductive\u5b9a\u4e49\u6570\u636e\u7c7b\u578b\u65f6\uff0cCoq\u4f1a\u81ea\u52a8\u4e3a\u8be5\u7c7b\u578b\u751f\u6210'\u5f52\u7eb3\u6cd5\u5219'\uff0c\u5982\u679ct\u662f\u5f52\u7eb3\u5b9a\u4e49\u7684\uff0c\n\u90a3\u4e48\u5bf9\u5e94\u7684\u5f52\u7eb3\u6cd5\u5219\u88ab\u79f0\u4f5ct_ind*)\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(*\u8bc1\u660eP n \u5bf9\u6240\u6709\u7684n\u90fd\u6210\u7acb\uff0c\u4e00\u4e2a\u5145\u5206\u6761\u4ef6\u65f6\u8bc1\u660e\uff0cP 0\u6210\u7acb;\u5bf9\u4efb\u610fn,\u82e5P n\u6210\u7acb\uff0c\u90a3\u4e48P (S n)\u6210\u7acb*)\n\nTheorem mult_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  -  reflexivity.\n  -  simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, standard, optional (plus_one_r')  \n\n    Complete this proof without using the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros n' IHn'. rewrite<-IHn'.  rewrite plus_comm. simpl. \n    reflexivity.\nQed.\n(** [] *)\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\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nCheck rgb_ind.\n(* ===> rgb_ind : forall P : rgb -> Prop,\n                  P red ->\n                  P green ->\n                  P blue ->\n                  forall y:rgb, P y*)\n(** [] *)\n\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\nCheck natlist1_ind.\n(** Now what will the induction principle look like? \n  natlist1_ind:\n    forall P: natlist1 -> Prop,\n      P nnil ->\n      (forall (l:natlist1)\n        P l -> forall n: nat,P (nsnocl l n)) ->\n      forall n : natlist1, P n\n[] *)\n\n(** **** Exercise: 1 star, standard, optional (byntree_ind)  *)\nInductive byntree : Type :=\n | bempty\n | bleaf (yn : yesno)\n | nbranch (yn : yesno) (t1 t2 : byntree).\nCheck byntree_ind.\n(**\n  byntree_ind:\n    forall P: byntree -> Prop,\n      P bempty ->\n      (forall (yn: yesno), P(bleaf yn)) ->\n      (forall (yn: yesno), (t1: byntree),\n       P t1 -> forall Pt2 -> P(nbranch yn t1 t2))->\n      forall b: byntree P b\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]: *)\nInductive ExSet : Type :=\n  |conl (b:bool)\n  |con2 (n:nat) (e:ExSet).\n(** [] *)\n\n(* ################################################################# *)\n(** * Polymorphism *)\nInductive list (X:Type) : Type :=\n  |nil: list X\n  |cons: X-> list X -> list X.\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*) \nInductive mytype (X:Type) : Type :=\n  |constr1 (x: X)\n  |constr2 (n:nat)\n  |constr3 (m: mytype X) (n:nat).\nCheck mytype_ind.\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.\nCheck foo'_ind.\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    P f->\n                    P( C1 l f) ) ->\n             foo' C2 ->\n             forall f : foo' X,  P f.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?*)\n\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  - reflexivity.\n  - intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nTheorem plus_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - intros m. rewrite <- plus_n_O. reflexivity.\n  - intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\nTheorem plus_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction m as [| m'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (plus_explicit_prop) *)\nTheorem plus_assoc'' : forall n m o : nat,\n  n+(m+o)=(n+m)+o.\nProof.\n  intros.\n  induction n as [| n'].\n  -rewrite plus_O_n. rewrite plus_O_n. reflexivity.\n  -simpl. rewrite IHn'. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Induction Principles in [Prop] *)\n\nCheck even_ind.\n\nTheorem ev_ev' : forall n, even n -> even' n.\nProof.\n  apply even_ind.\n  - apply even'_0.\n  - intros m Hm IH.\n    apply (even'_sum 2 m).\n    + apply even'_2.\n    + apply IH.\nQed.\nInductive le1 :nat-> nat -> Prop :=\n  |le1_n (n:nat): le1 n n\n  |le1_S (n m:nat)(H: le1 n m): le1 n (S m).\n(*\u89c2\u5bdf\u53ef\u4ee5\u53d1\u73b0\uff0c\u4e24\u4e2a\u6784\u9020\u5b50\u4e2d\u5de6\u4fa7\u7684\u53c2\u6570n\u59cb\u7ec8\u662f\u76f8\u540c\u7684\uff0c\u4e8e\u662f\u53ef\u5c06\u5176\u6574\u4f53\u5b9a\u4e49\u4e3a\u4e00\u4e2a\n\"\u4e00\u822c\u53c2\u6570\",\u4e8e\u662f\u6709\u5982\u4e0b\u7684\u5b9a\u4e49*)\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).\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 *)\nCheck nat_ind.\nPrint nat_ind.\nLemma evenb_ev : forall (n:nat),\n  evenb n= true -> even n.\nProof.\n  induction n; intros.\n  - apply ev_0.\n  - destruct n.\n    +simpl in H. inversion H.\n    +simpl in H. apply ev_SS.\nAbort.\n(*\u5728\u4e0a\u8fb9\u5173\u4e8e\u81ea\u7136\u6570\u7684\u5f52\u7eb3\u8bc1\u660e\u4e2d\uff0c\u6b65\u957f\u4e3a1\uff0c\u7136\u800c\u6211\u4eec\u5e76\u4e0d\u80fd\u7528even S n' \u63a8\u51faeven n'\n\u6545\u6211\u4eec\u9700\u8981\u4fee\u6539\u81ea\u7136\u6570\u7684\u5f52\u7eb3\u6cd5\u5219\uff0c\u5c06\u6b65\u957f\u4fee\u6539\u4e3a2*)\nDefinition nat_ind2:forall (P :nat-> Prop),\n  P 0 -> \n  P 1 ->\n  (forall (n:nat), P n-> P(S(S n))) ->\n  forall n:nat, P n:=\n     fun P => fun P0 => fun P1 => fun PSS =>\n      fix f (n:nat) :=match n with\n        |0 =>P0\n        |1 => P1\n        |S (S n') => PSS n' (f n')\n         end.\nLemma evenb_ev: forall (n:nat), evenb n =true -> even n.\nProof.\n  intros.\n  induction n as [| | n'] using nat_ind2.\n  -apply ev_0.\n  -simpl in H. inversion H.\n  -simpl in H.\n    apply ev_SS.\n    apply IHn'.\n    apply H.\nQed.", "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/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.9099070060380482, "lm_q1q2_score": 0.835731604885356}}
{"text": "Require Export P07.\n\n\n\n(** The postcondition does not hold at the beginning of the loop,\n    since [m = parity m] does not hold for an arbitrary [m], so we\n    cannot use that as an invariant.  To find an invariant that works,\n    let's think a bit about what this loop does.  On each iteration it\n    decrements [X] by [2], which preserves the parity of [X].  So the\n    parity of [X] does not change, i.e. it is invariant.  The initial\n    value of [X] is [m], so the parity of [X] is always equal to the\n    parity of [m]. Using [parity X = parity m] as an invariant we\n    obtain the following decorated program:\n    {{ X = m }} ->>                              (a - OK)\n    {{ parity X = parity m }}\n  WHILE 2 <= X DO\n      {{ parity X = parity m /\\ 2 <= X }}  ->>    (c - OK)\n      {{ parity (X-2) = parity m }}\n    X ::= X - 2\n      {{ parity X = parity m }}\n  END\n    {{ parity X = parity m /\\ X < 2 }}  ->>       (b - OK)\n    {{ X = parity m }}\n\n    With this invariant, conditions (a), (b), and (c) are all\n    satisfied. For verifying (b), we observe that, when [X < 2], we\n    have [parity X = X] (we can easily see this in the definition of\n    [parity]).  For verifying (c), we observe that, when [2 <= X], we\n    have [parity X = parity (X-2)]. *)\n\n\n(** **** Exercise: 3 stars, optional (parity_formal)  *)\n(** Translate this proof to Coq. Refer to the reduce-to-zero example\n    for ideas. You may find the following two lemmas useful: *)\n\nLemma parity_ge_2 : forall x,\n  2 <= x ->\n  parity (x - 2) = parity x.\nProof.\n  induction x; intro. reflexivity.\n  destruct x. inversion H. inversion H1.\n  simpl. rewrite <- minus_n_O. reflexivity.\nQed.\n\nLemma parity_ge_2_big : forall x,\n  parity x = parity (x + 2).\nintros. \n  destruct x. reflexivity.\n  destruct x. reflexivity.\n  replace (S (S x)) with (S (S x) + 2 - 2).\n  replace (S (S x) + 2 - 2 + 2) with (S (S x) + 2).\n  apply parity_ge_2. omega. omega. omega. Qed.\n\nLemma parity_lt_2 : forall x,\n  ~ 2 <= x ->\n  parity (x) = x.\nProof.\n  intros. induction x. reflexivity. destruct x. reflexivity.\n    apply ex_falso_quodlibet. apply H. omega.\nQed.\n\nTheorem parity_correct : forall m,\n    {{ fun st => st X = m }}\n  WHILE BLe (ANum 2) (AId X) DO\n    X ::= AMinus (AId X) (ANum 2)\n  END\n    {{ fun st => st X = parity m }}.\nProof.\n  intros m.\n  apply hoare_consequence_pre with (P':= (fun st => (parity (st X) = parity m))).\n  Case \"{{I}} while {{Q}}\".\n    eapply hoare_consequence_post. apply hoare_while.\n    SCase \"{{I /\\ b}} c {{I}}\".\n      unfold hoare_triple. intros.\n      assert (Hle : 2 <= st X).\n        destruct H0. \n        simpl in H1. destruct (st X) eqn:Hx. inversion H1.\n        destruct n eqn:Hn. inversion H1. omega.\n      inversion H; subst. simpl. unfold update. \n      rewrite eq_id. rewrite parity_ge_2. apply H0. assumption.\n      \n    SCase \"I/\\~b ->> Q\".\n      unfold hoare_triple, assert_implies. intros.\n      destruct H. rewrite<-H. symmetry.\n      apply parity_lt_2.\n      unfold not. intros.\n      simpl in H0. destruct (st X). inversion H1.\n      destruct n. inversion H1. inversion H3.\n      inversion H0.\n  Case \"P ->> I\".\n    unfold assert_implies. intros. rewrite H. 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/P08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.9263037323284109, "lm_q1q2_score": 0.8354524791653952}}
{"text": "(** * Proposi\u00e7\u00f5es definidas indutivamente *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export aula09_logica.\nRequire Coq.omega.Omega.\n\n(* ############################################### *)\n(** * Proposi\u00e7\u00f5es definidas indutivamente *)\n\n(** Veremos agora que tamb\u00e9m \u00e9 poss\u00edvel definir\n    proposi\u00e7\u00f5es de forma indutiva (i.e.,\n    usando [Indutive].\n    \n    Por exemplo, podemos dizer que [n] \u00e9 par\n    escrevendo [evenb n = true] ou\n    [exists k, n = double k]. Outra possibilidade\n    \u00e9 dizer que [n] \u00e9 par se este fato pode ser\n    deduzido a partir das seguintes regras:\n    \n    - Regra [ev_0]: o n\u00famero [0] \u00e9 par;\n    - Regra [ev_SS]: se [n] \u00e9 par,\n                     ent\u00e3o [S (S n)] \u00e9 par.\n                     \n    Para provar, por exemplo, que [4] \u00e9 par, pela\n    regra [ev_SS], \u00e9 suficiente provar que [2] \u00e9 par.\n    De novo pela mesma regra, \u00e9 suficente provar\n    que [0] \u00e9 par. Por sua vez, a regra [ev_0]\n    garante que 0 \u00e9 par.\n    \n    Estas regras s\u00e3o vistas como regras de infer\u00eancia.\n\n        ------------                        (ev_0)\n           ev 0\n\n            ev n\n       --------------                      (ev_SS)\n        ev (S (S n))\n\n    Se as premissas da regra foram satisfeitas\n    (listadas acima da linha), podemos concluir\n    a afirma\u00e7\u00e3o listada abaixo da linha.\n    \n    A prova que [4] \u00e9 par poderia ser escrita\n    da seguinte forma:\n\n\n               ------  (ev_0)\n                ev 0\n               ------ (ev_SS)\n                ev 2\n               ------ (ev_SS)\n                ev 4\n\n    Em Coq, podemos, ent\u00e3o, definir a propriedade\n    de ser par da seguinte forma indutiva. Cada\n    construtor corresponde a uma regra de infer\u00eancia. *)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nCheck ev_0.\nCheck ev.\nCheck ev_SS.\n\n(** Observe que esta defini\u00e7\u00e3o n\u00e3o resulta em um\n    [Type], mas uma fun\u00e7\u00e3o de [nat] para [Prop];\n    ou seja, uma propriedade sobre n\u00fameros.\n    \n    Al\u00e9m disto, observe que na defini\u00e7\u00e3o de ev\n    (linha 58), o argumento natural aparece sem\n    nome (i.e., \u00e0 direita do [:]). Na defini\u00e7\u00e3o\n    de listas, por exemplo, temos:\n    \n    Inductive list (X:Type) : Type :=\n    \n    Observe que aqui o X aparece antes do [: Type].\n    Isto permite [ev] receber valores diferentes\n    nos diferentes construtores. Veja que a\n    defini\u00e7\u00e3o abaixo gera um erro. *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n(** Podemos, portanto, pensar na defini\u00e7\u00e3o de [ev]\n    como a fun\u00e7\u00e3o [ev : nat -> Prop], em conjunto\n    com os teoremas primitivos [ev_0 : ev 0] e\n    [ev_SS : forall n, ev n -> ev (S (S n))].\n    \n    Tais \"teoremas-construtores\" possuem o mesmo\n    status de outros teoremas em Coq. Em particular,\n    podemos usar [apply] com o nome destes\n    \"teoremas-construtores\". *)\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** ... ou ainda por uma perspectiva funcional. *)\n\nPrint ev_SS.\nCompute (ev_SS).\nCompute (ev_SS 0 ev_0).\n\nTheorem ev_4' : ev 4.\nProof.\n  Compute (ev_SS 2 (ev_SS 0 ev_0)).\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(** Outro exemplo. *)\n\nTheorem ev_plus4 :\n  forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(** **** Exercise: (ev_double)  *)\nTheorem ev_double :\n  forall n, ev (double n).\nProof.\n  intros n. induction n as [|n'].\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. apply IHn'.\nQed.\n\n(* ############################################### *)\n(** * Usando evid\u00eancia em provas *)\n\n(** Definir [ev] como uma declara\u00e7\u00e3o [Inductive],\n    n\u00e3o s\u00f3 diz que [ev_0] e [ev_SS] s\u00e3o formas\n    v\u00e1lidas de criar evid\u00eancia sobre n\u00fameros\n    serem pares, mas tamb\u00e9m que estes dois\n    construtores s\u00e3o as _\u00fanicas_ formas de criar\n    evid\u00eancia que n\u00fameros s\u00e3o pares (no contexto,\n    da defini\u00e7\u00e3o de [ev]).\n    \n    Logo, se tivermos uma evid\u00eancia que [E]\n    para a afirma\u00e7\u00e3o [ev n], [E] precisa ter uma\n    das seguintes formas:\n\n    - [E] \u00e9 [ev_0] (e [n] \u00e9 [O]), ou\n    - [E] \u00e9 [ev_SS n' E'] (e [n] \u00e9 [S (S n')],\n      onde [E'] \u00e9 a evid\u00eancia para [ev n']).\n      \n    Portanto, \u00e9 poss\u00edvel usar t\u00e1ticas como [inversion],\n    [induction] e [destruct] em evid\u00eancias criadas\n    indutivamente. *)\n\n(** ** Inversion em evid\u00eancias *)\n\n(** Neste contexto, [inversion] realiza uma an\u00e1lise\n    de casos, e sua sintaxe \u00e9 similar \u00e0 do\n    [destruct]. Veja o exemplo abaixo. *)\n    \nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E. \n  inversion E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n(** Neste caso, poder\u00edamos ter usado [destruct]. *)\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n(** Nem sempre o uso de [inversion] e\n    [destruct] produz o mesmo resultado. *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n\n(** Como aqui temos o [ev] aplicado a um\n    elemento diferente de 0, esta evid\u00eancia\n    precisa ter sido constru\u00edda a partir de\n    ev_SS. No entanto, a t\u00e1tica [destruct]\n    n\u00e3o faz este tipo de an\u00e1lise, e gera\n    dois objetivos de prova. *)  \n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* N\u00e3o \u00e9 poss\u00edvel provar que [n] \u00e9 par a partir\n       de nenhuma premissa. *)\nAbort.\n\n(** Veja a prova com [inversion]. A t\u00e1tica [inversion]\n    detectou que (1) o caso ev_0 n\u00e3o se aplica, pois\n    0 n\u00e3o pode ser igual a [S (S n)] e que (2) em\n    [ev_SS n' E'], E = ev n' = ev n, pois n = n',\n    uma vez que [S (S n')] = [S (S n)]. *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* Caso que [E = ev_SS n' E']. *)\n  apply E'.\nQed.\n\n(** Tamb\u00e9m podemos usar [inversion] como\n    princ\u00edpio da explica\u00e7\u00e3o em hip\u00f3teses\n    envolvendo propriedades indutivas\n    que s\u00e3o claramente contradi\u00e7\u00f5es. *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  unfold not. intros H. inversion H.\nQed.\n\n(** **** Exercise: (SSSSev__even)  *)\n(** Prove o seguinte resultado usando [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E'].\n  inversion E' as [| n'' E''].\n  apply E''.\nQed.\n\n(** **** Exercise: (even5_nonsense)  *)\n(** Prove o seguinte resultado usando [inversion]. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros E. inversion E. inversion H0. inversion H2.\nQed.\n\n(** ** Indu\u00e7\u00e3o sobre evid\u00eancias *)\n\n(** Veja o exemplo a seguir. *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       com IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k').\n    simpl. reflexivity.\nQed.\n\n(** Com este resultado, podemos provar\n    que a propriedade de ser par definida\n    por [ev n] e [exists k, n = double k]\n    s\u00e3o equivalentes. *)\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk].\n             rewrite Hk. apply ev_double.\nQed.\n\n(** **** Exercise: (ev_sum)  *)\nTheorem ev_sum :\n  forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m.\n  intros En Em.\n  Print Nat.add.\n  induction En as [| n' En' IHn].\n  - simpl. apply Em.\n  - simpl. apply ev_SS. apply IHn.\nQed.\n\n(** **** Exercise: (ev_ev__ev)  *)\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m. intros Enm En. induction En as [| n' En' IHn].\n  - simpl in Enm. apply Enm.\n    (** Search (_ + _ = 0 -> _ = 0 /\\ _ = 0).\n    symmetry in H0. apply Plus.plus_is_O in H0.\n    apply proj2 in H0. rewrite H0. apply ev_0.\n    **)\n  - simpl in Enm. inversion Enm. apply IHn in H0.\n    apply H0.\nQed.\n\n(* ############################################### *)\n(** * Rela\u00e7\u00f5es indutivas *)\n\n(** Uma proposi\u00e7\u00e3o parametrizada por um n\u00famero\n    (como [ev]), pode ser vista como uma propriedade\n    sobre n\u00fameros: define um subconjunto de [nat]\n    para os quais a propriedade pode ser provada.\n    \n    De forma similar, uma proposi\u00e7\u00e3o com dois\n    argumentos pode ser vista como uma rela\u00e7\u00e3o:\n    define um conjunto de pares para os quais\n    a propriedade em quest\u00e3o pode ser provada. *)\n\nModule Playground.\n\n(** A pr\u00f3xima defini\u00e7\u00e3o afirma que existem duas\n    maneiras de produzir evid\u00eancia de que um n\u00famero\n    \u00e9 <= a outro: ou estes n\u00fameros s\u00e3o os mesmos,\n    ou ent\u00e3o o primeiro \u00e9 <= ao predecessor\n    do primeiro. *)\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(** A seguir, alguns testes para demonstrar\n    que a defini\u00e7\u00e3o de [le] \u00e9 correta. Aqui,\n    n\u00e3o \u00e9 suficiente usar [simpl] e [reflexivity],\n    uma vez que a prova n\u00e3o consiste em simplificar\n    computa\u00e7\u00f5es. *)\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.\n  apply le_S. apply le_n.\nQed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H.\n  inversion H2.\nQed.\n\n(** O operador [<] pode ser definido\n    em termos de [le]. *)\n\nEnd Playground.\n\nPrint le.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Outros exemplos de rela\u00e7\u00f5es sobre n\u00fameros. *)\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n\n(** **** Exercise: (le_exercises)  *)\n(** A seguir, v\u00e1rios exerc\u00edcios sobre as rela\u00e7\u00f5es\n    [<=] e [<], que constituem uma boa pr\u00e1tica. *)\n\nLemma le_Sm_n :\n  forall m n, S m <= n -> m <= n.\nProof.\n  intros m n H. induction H as [|m' H IHm'].\n  - apply le_S. apply le_n.\n  - apply le_S. apply IHm'.\nQed.\n\nLemma le_trans :\n  forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H. induction H as [| m' H IHm'].\n  - intros H1. apply H1.\n  - intros H2. apply le_Sm_n in H2. apply IHm'. apply H2.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n as [| n' IH'].\n  - apply le_n.\n  - apply le_S. apply IH'.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m le_n_m. induction le_n_m.\n  - apply le_n.\n  - apply le_S. apply IHle_n_m.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m. intros H. inversion H.\n  - apply le_n.\n  - apply le_Sm_n in H1. apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b. induction a as [| a' IHa'].\n  - simpl. apply O_le_n.\n  - simpl. apply n_le_m__Sn_le_Sm. apply IHa'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n  intros n1 n2 m. intros H. induction H.\n  - unfold lt. split.\n    + apply n_le_m__Sn_le_Sm. apply le_plus_l.\n    + apply n_le_m__Sn_le_Sm. rewrite plus_comm.\n      apply le_plus_l.\n  - split.\n    + apply proj1 in IHle. unfold lt.\n      unfold lt in IHle. apply le_S. apply IHle.\n    + apply proj2 in IHle. unfold lt.\n      unfold lt in IHle. apply le_S. apply IHle.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m -> n < S m.\nProof.\n  intros n m. unfold lt. intros H.\n  apply le_S. apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. intros m. intros H. apply O_le_n.\n  - simpl. intros m. intros H. destruct m as [|m'].\n    + inversion H.\n    + apply IHn' in H. apply n_le_m__Sn_le_Sm. apply H.  \nQed.\n\n(** O pr\u00f3ximo teorema \u00e9 mais f\u00e1cil de provar\n    com uma indu\u00e7\u00e3o sobre [m]. *)\n    \nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  intros n m. generalize dependent n.\n  induction m as [| m' IHm'].\n  - intros n. intros H. inversion H.\n    reflexivity.\n  - intros n. intros H. destruct n as [| n'].\n    + simpl. reflexivity.\n    + simpl. apply Sn_le_Sm__n_le_m in H.\n      apply IHm' in H. apply H.\nQed.\n\n(** O pr\u00f3ximo teorema pode ser provado\n    facilmente sem [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true ->\n  leb m o = true -> leb n o = true.\nProof.\n  intros n m o. intros Hnm Hmo.\n  apply leb_complete in Hnm.\n  apply leb_complete in Hmo.\n  Search \"le_trans\".\n  apply leb_correct.\n  apply le_trans with (n := m).\n  - apply Hnm.\n  - apply Hmo.\nQed.\n\n(* ############################################### *)\n(** * Estudo de caso: express\u00f5es regulares *)\n\n(** Primeiro, a sintaxe. *)\n\nInductive reg_exp {T : Type} : Type :=\n| EmptySet  : reg_exp\n| EmptyStr  : reg_exp\n| Char      : T -> reg_exp\n| App       : reg_exp -> reg_exp -> reg_exp\n| Union     : reg_exp -> reg_exp -> reg_exp\n| Star      : reg_exp -> reg_exp.\n\n(** Agora, a sem\u00e2ntica (como uma rela\u00e7\u00e3o indutiva). *)\n\nInductive exp_match {T} : list T -> reg_exp -> Prop :=\n| MEmpty    : exp_match [] EmptyStr\n| MChar     : forall x, exp_match [x] (Char x)\n| MApp      : forall s1 re1 s2 re2,\n                exp_match s1 re1 ->\n                exp_match s2 re2 ->\n                exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL   : forall s1 re1 re2,\n                exp_match s1 re1 ->\n                exp_match s1 (Union re1 re2)\n| MUnionR   : forall re1 s2 re2,\n                exp_match s2 re2 ->\n                exp_match s2 (Union re1 re2)\n| MStar0    : forall re, exp_match [] (Star re)\n| MStarApp  : forall s1 s2 re,\n                exp_match s1 re ->\n                exp_match s2 (Star re) ->\n                exp_match (s1 ++ s2) (Star re).\n\n(** A\u00e7\u00facar sint\u00e1tico. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(** A rela\u00e7\u00e3o anterior define as seguintes regras.\n\n      ----------------                    (MEmpty)\n       [] =~ EmptyStr\n\n      ---------------                      (MChar)\n       [x] =~ Char x\n\n   s1 =~ re1    s2 =~ re2\n  -------------------------                 (MApp)\n   s1 ++ s2 =~ App re1 re2\n\n          s1 =~ re1\n    ---------------------                (MUnionL)\n     s1 =~ Union re1 re2\n\n          s2 =~ re2\n    ---------------------                (MUnionR)\n     s2 =~ Union re1 re2\n\n      ---------------                     (MStar0)\n       [] =~ Star re\n\n  s1 =~ re    s2 =~ Star re\n ---------------------------            (MStarApp)\n    s1 ++ s2 =~ Star re\n*)\n\n(** Alguns exemplos. *)\n\nExample reg_exp_ex1 :\n  [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 :\n  [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  Compute (MApp [1] _ [2] _).\n  apply (MApp [1] _ [2] _).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** Observe que no caso anterior \u00e9 preciso\n    manualmente informar como dividir a\n    string [1;2] em [1] e [2]. Se o objetivo\n    fosse [1] ++ [2], Coq conseguiria inferir. *)\n\nExample reg_exp_ex3 :\n  ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** Provando que toda string [s] que\n    casa com o padr\u00e3o [re], casa tamb\u00e9m\n    com o padr\u00e3o [Star re]. *)\n\nLemma MStar1 :\n  forall T s (re : @reg_exp T) ,\n    s =~ re -> s =~ Star re.\nProof.\n  intros T s re H.\n  rewrite <- (app_nil_r _ s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Inductively defined propositions\n  https://softwarefoundations.cis.upenn.edu/lf-current/IndProp.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/aula11_prop_indutivas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.9207896720870642, "lm_q1q2_score": 0.8354437274027455}}
{"text": "(** Exercise 1 (andb_true_elim2) *)\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H. destruct c.\n  Case \"c = true\".\n    reflexivity.\n  Case \"c = false\".\n    rewrite <- H. destruct b.\n    SCase \"b = true\".\n      reflexivity.\n    SCase \"b = false\".\n      reflexivity.  Qed.\n      \n(** Exercise 2 (basic_induction) *)\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. 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. rewrite -> IHn'. reflexivity.  Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = 0\".\n    rewrite -> plus_0_r. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.  Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n    \n\n(** Exercise 3 (double_plus) *)\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.  Qed.\n\n\n(** Exercise 4 (destruct_induction) *)\n(** Induction does a destruct but also adds the induction hypothesis. \n      Destruct only destructurizes, but does not add any Induction hypothesis. *)\n\n\n(** Exercise 5 (evenb_n__oddb_Sn) *)\nTheorem evenb_n__oddb_Sn : forall n : nat,\n  evenb n = negb (evenb (S n)).\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    assert (H: evenb (S (S n')) = evenb n').\n    SCase \"Proof of assertion\".\n      reflexivity.\n    rewrite -> H. rewrite -> IHn'.\n    rewrite -> negb_involutive. reflexivity.  Qed.\n    \n\n(** Exercise 6 (more_exercises) *)\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof. \n(* prediction: need induction *)\n  intros n. induction n. reflexivity. simpl. rewrite <- IHn. reflexivity. Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n(* prediction: do not need induction, just reflexivity *)\nProof. reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n(* prediction: need destruct because b comes first in andb *)\nProof. intros b. destruct b. Case \"b=true\". reflexivity. Case \"b=false\". reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n(* prediction: need induction in p, because p comes first in the goal. *)\n  Proof. intros n m p. intros H.  (* note: important to introduce H before starting the induction. *)\ninduction p.\nCase \"p=0\". simpl. rewrite <- H. reflexivity.\nCase \"S p\". simpl. rewrite <- IHp. reflexivity. Qed.\n\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n(* prediction: do not need induction *)\n  reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n(* prediction: do not need induction because 1 comes first in mult? Actually, we would need induction if we didn't use plus_0_r: mult is more difficult than plus to prove things about. *)\n  intros n. simpl. rewrite -> plus_0_r. reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n               (negb c))\n  = true.\nProof.\n(* prediction: need to destructure b since it comes first in andb. \nActually, also need to destructure c, because can't compute negb c in general. \nOtherwise would have to prove many lemmas about orb x (negb x)= true etc. *)\n intros b c. destruct b.\nCase \"b=true\". destruct c. \nSCase \"c=true\". reflexivity.\nSCase \"c=false\". reflexivity.\nCase \"b=false\". destruct c.\nSCase \"c=true\". reflexivity.\nSCase \"c=false\". reflexivity. Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n(* prediction: need induction in n because it comes first in goals. *)\n\n  (n + m) * p = (n * p) + (m * p).\nProof. intros n m p. \ninduction n. Case \"n=0\". reflexivity.\nCase \"S n\". simpl. rewrite <- plus_assoc. rewrite <- IHn. reflexivity. Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\n(* prediction: do not need induction, just rewriting.\nThis is wrong: we don't have any rewriting rules for this yet, only for plus with mult. \nSo we have to use induction in n, at least. *)\nProof.\n  intros n m p. induction n.\nCase \"n=0\". reflexivity.\nCase \"S n\".  simpl. rewrite -> mult_plus_distr_r. rewrite -> IHn. reflexivity. Qed.\n\n(** Exercise 7 (beq_nat_refl) *)\nTheorem beq_nat_refl : forall n : nat, \n  true = beq_nat n n.\nProof.\n(* prediction: need induction in n *)\n\nintros n. induction n. Case \"n=0\". reflexivity.\nCase \"S n\". simpl. rewrite <- IHn. reflexivity. Qed.\n\n\n(** Exercise 8 (plus_swap') *)\nTheorem plus_swap' : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.\n intros n m p. rewrite -> plus_comm. replace (n+p) with (p+n).\nrewrite <- plus_assoc. reflexivity.\nCase \"p+n=n+p\". rewrite -> plus_comm. reflexivity. Qed.\n\n", "meta": {"author": "surenz20", "repo": "CS6463", "sha": "2325abfb1d5c18104c05d4d29bf9fe1bd7de0558", "save_path": "github-repos/coq/surenz20-CS6463", "path": "github-repos/coq/surenz20-CS6463/CS6463-2325abfb1d5c18104c05d4d29bf9fe1bd7de0558/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8354437200806198}}
{"text": "(** * Multiset:  Insertion Sort Verified With Multisets *)\n\n(** Our specification of [sorted] in [Sort] was based in\n    part on permutations, which enabled us to express the idea that\n    sorting rearranges list elements but does not add or remove any.\n\n    Another way to express that idea is to use multisets, aka bags.  A\n    _set_ is like a list in which element order is irrelevant, and in\n    which no duplicate elements are permitted. That is, an element can\n    either be _in_ the set or not in the set, but it can't be in the\n    set multiple times.  A _multiset_ relaxes that restriction: an\n    element can be in the multiset multiple times.  The number of\n    times the element occurs in the multiset is the element's\n    _multiplicity_. *)\n\n(** For example:\n\n    - [{1, 2}] is a set, and is the same as set [{2, 1}].\n\n    - [[1; 1; 2]] is a list, and is different than list [[2; 1; 1]].\n\n    - [{1, 1, 2}] is a multiset and the same as multiset [{2, 1, 1}].\n\n    In this chapter we'll explore using multisets to specify\n    sortedness. *)\n\nFrom Coq Require Import Strings.String.  (* for manual grading *)\nFrom Coq Require Import FunctionalExtensionality.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Sort.\n\n(* ################################################################# *)\n(** * Multisets *)\n\n(** We will represent multisets as functions: if [m] is a\n    multiset, then [m n] will be the multiplicity of [n] in [m].\n    Since we are sorting lists of natural numbers, the type of\n    multisets would be [nat -> nat]. The input is the value, the output is\n    its multiplicity.  To help avoid confusion between those two uses\n    of [nat], we'll introduce a synonym, [value]. *)\n\nDefinition value := nat.\n\nDefinition multiset := value -> nat.\n\n(** The [empty] multiset has multiplicity [0] for every value. *)\n\nDefinition empty : multiset :=\n  fun x => 0.\n\n(** Multiset [singleton v] contains only [v], and exactly once. *)\n\nDefinition singleton (v: value) : multiset :=\n  fun x => if x =? v then 1 else 0.\n\n(** The union of two multisets is their _pointwise_ sum. *)\n\nDefinition union (a b : multiset) : multiset :=\n  fun x => a x + b x.\n\n(** **** Exercise: 1 star, standard (union_assoc)  *)\n\n(** Prove that multiset union is associative.\n\n    To prove that one multiset equals another we use the axiom of\n    functional extensionality, which was introduced in\n    [Logic]. We begin the proof below by using Coq's tactic\n    [extensionality], which applies that axiom.*)\n\nLemma union_assoc: forall a b c : multiset,\n   union a (union b c) = union (union a b) c.\nProof.\n  intros.\n  extensionality x.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (union_comm)  *)\n\n(** Prove that multiset union is commutative. *)\n\nLemma union_comm: forall a b : multiset,\n   union a b = union b a.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (union_swap)  *)\n\n(** Prove that the multisets in a nested union can be swapped.\n    You do not need [extensionality] if you use the previous\n    two lemmas. *)\n\nLemma union_swap : forall a b c : multiset,\n    union a (union b c) = union b (union a c).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Note that this is not an efficient implementation of multisets.\n    We wouldn't want to use it for programs with high performance\n    requirements.  But we are using multisets for specifications, not\n    for programs.  We don't intend to build large multisets, only to\n    use them in verifying algorithms such as insertion sort.  So this\n    inefficiency is not a problem. *)\n\n(* ################################################################# *)\n(** * Specification of Sorting *)\n\n(** A sorting algorithm must rearrange the elements into a list\n    that is totally ordered.  Using multisets, we can restate that as:\n    the algorithm must produce a list _with the same multiset of\n    values_, and this list must be totally ordered. Let's formalize\n    that idea. *)\n\n(** The _contents_ of a list are the elements it contains, without\n    any notion of order. Function [contents] extracts the contents\n    of a list as a multiset. *)\n\nFixpoint contents (al: list value) : multiset :=\n  match al with\n  | [] => empty\n  | a :: bl => union (singleton a) (contents bl)\n  end.\n\n(** The insertion-sort program [sort] from [Sort] preserves\n    the contents of a list.  Here's an example of that: *)\n\nExample sort_pi_same_contents:\n  contents (sort [3;1;4;1;5;9;2;6;5;3;5]) = contents [3;1;4;1;5;9;2;6;5;3;5].\nProof.\n  extensionality x.\n  repeat (destruct x; try reflexivity).\n  (* Why does this work? Try it step by step, without [repeat]. *)\nQed.\n\n(** A sorting algorithm must preserve contents and totally order the\n    list. *)\n\nDefinition is_a_sorting_algorithm' (f: list nat -> list nat) := forall al,\n    contents al = contents (f al) /\\ sorted (f al).\n\n(** That definition is similar to [is_a_sorting_algorithm] from [Sort],\n    except that we're now using [contents] instead of [Permutation]. *)\n\n(* ################################################################# *)\n(** * Verification of Insertion Sort *)\n\n(** The following series of exercises will take you through a\n    verification of insertion sort using multisets. *)\n\n(** **** Exercise: 3 stars, standard (insert_contents)  *)\n\n(** Prove that insertion sort's [insert] function produces the same\n    contents as merely prepending the inserted element to the front of\n    the list.\n\n    Proceed by induction.  You do not need [extensionality] if you\n    make use of the above lemmas about [union]. *)\n\nLemma insert_contents: forall x l,\n     contents (insert x l) = contents (x :: l).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (sort_contents)  *)\n\n(** Prove that insertion sort preserves contents. Proceed by\n    induction.  Make use of [insert_contents]. *)\n\nTheorem sort_contents: forall l,\n    contents l = contents (sort l).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (insertion_sort_correct)  *)\n\n(** Finish the proof of correctness! *)\n\nTheorem insertion_sort_correct :\n  is_a_sorting_algorithm' sort.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (permutations_vs_multiset) \n\n    Compare your proofs of [insert_perm, sort_perm] with your proofs\n    of [insert_contents, sort_contents].  Which proofs are simpler?\n\n      - [ ] easier with permutations\n      - [ ] easier with multisets\n      - [ ] about the same\n\n   Regardless of \"difficulty\", which do you prefer or find easier to\n   think about?\n      - [ ] permutations\n      - [ ] multisets\n\n   Put an X in one box in each list. *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_permutations_vs_multiset : option (nat*string) := None.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Equivalence of Permutation and Multiset Specifications *)\n\n(** We have developed two specifications of sorting, one based\n    on permutations ([is_a_sorting_algorithm]) and one based on\n    multisets ([is_a_sorting_algorithm']).  These two specifications\n    are actually equivalent, which will be the final theorem in this\n    chapter.\n\n    One reason for that equivalence is that permutations and multisets\n    are closely related.  We'll begin by proving:\n\n        Permutation al bl <-> contents al = contents bl\n\n    The forward direction is relatively easy, but the backward\n    direction is surprisingly difficult.\n *)\n\n(* ================================================================= *)\n(** ** The Forward Direction *)\n\n(** **** Exercise: 3 stars, standard (perm_contents)  *)\n\n(** The forward direction is the easier one. Proceed by induction on\n    the evidence for [Permutation al bl]: *)\n\nLemma perm_contents: forall al bl : list nat,\n    Permutation al bl -> contents al = contents bl.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** The Backward Direction (Advanced) *)\n\n(** The backward direction is surprisingly difficult.  This proof\n    approach is due to Zhong Sheng Hu.  The first three lemmas are\n    used to prove the fourth one.  Don't forget that [union],\n    [singleton], and [empty] must be explicitly unfolded to access\n    their definitions. *)\n\n(** **** Exercise: 2 stars, advanced (contents_nil_inv)  *)\nLemma contents_nil_inv : forall l, (forall x, 0 = contents l x) -> l = nil.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (contents_cons_inv)  *)\nLemma contents_cons_inv : forall l x n,\n    S n = contents l x ->\n    exists l1 l2,\n      l = l1 ++ x :: l2\n      /\\ contents (l1 ++ l2) x = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (contents_insert_other)  *)\nLemma contents_insert_other : forall l1 l2 x y,\n    y <> x -> contents (l1 ++ x :: l2) y = contents (l1 ++ l2) y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (contents_perm)  *)\nLemma contents_perm: forall al bl,\n    contents al = contents bl -> Permutation al bl.\nProof.\n  intros al bl H0.\n  assert (H: forall x, contents al x = contents bl x).\n  { rewrite H0. auto. }\n  clear H0.\n  generalize dependent bl.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The Main Theorem *)\n\n(** With both directions proved, we can establish the correspondence\n    between multisets and permutations. *)\n\n(** **** Exercise: 1 star, standard (same_contents_iff_perm)  *)\n\n(** Use [contents_perm] (even if you haven't proved it) and\n    [perm_contents] to quickly prove the next theorem. *)\n\nTheorem same_contents_iff_perm: forall al bl,\n    contents al = contents bl <-> Permutation al bl.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Therefore the two specifications are equivalent. *)\n\n(** **** Exercise: 2 stars, standard (sort_specifications_equivalent)  *)\n\nTheorem sort_specifications_equivalent: forall sort,\n    is_a_sorting_algorithm sort <-> is_a_sorting_algorithm' sort.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** That means we can verify sorting algorithms using either\n    permutations or multisets, whichever we find more convenient. *)\n\n(* 2020-08-07 17:08 *)\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/vfa/Multiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.927363301167348, "lm_q1q2_score": 0.8351182703024933}}
{"text": "(*\n * \u305d\u306e7: https://www.fos.kuis.kyoto-u.ac.jp/~igarashi/class/cal/handout7.pdf\n * \u5e30\u7d0d\u547d\u984c\n *)\n\nRequire Import Arith List Omega ZArith.\nFrom mathcomp Require Import all_ssreflect.\nImport ListNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*\n\u5e30\u7d0d\u578b\u306e\u5ba3\u8a00\n*)\nInductive ev : nat -> Prop :=\n| ev_O : ev 0\n| ev_SS n (H : ev n) : ev n.+2.\n\nCheck (ev 0).\nCheck ev_O.  (* ev 0 *)\nCheck (ev_SS ev_O).  (* ev 2 *)\nCheck (ev_SS (ev_SS ev_O)).  (* ev 4 *)\n\n(*\n\u5e30\u7d0d\u69cb\u9020\u306b\u95a2\u3059\u308b\u8a3c\u660e\n*)\n\nTheorem four_is_even : ev 4.\nProof.\n  apply ev_SS.\n  apply ev_SS.\n  by apply ev_O.\nQed.\n\n(*\n\u9006\u8ee2\u306e\u5b9a\u7406\n*)\nTheorem ev_inversion :\n  forall n, ev n -> n = 0 \\/ (exists m, n = m.+2 /\\ ev m).\nProof.\n  intros n Hn.\n  destruct Hn as [|m Hm].\n  - by left.\n  - right.\n    exists m.\n    done.\nQed.\n\n(*\ninversion \u30bf\u30af\u30c6\u30a3\u30af\u30b9\n*)\nTheorem evSS_ev : forall n, ev n.+2 -> ev n.\nProof.\n  intros n E.\n  inversion E as [|m H1 H2].\n  exact.\nQed.\n\nTheorem evSSSS_ev : forall n, ev n.+4 -> ev n.\nProof.\n  intros n E.\n  inversion E as [|m H1 H2].\n  inversion H1 as [|k H3 H4].\n  exact.\nQed.\n\nTheorem inversion_ex1 : forall n m o : nat, [n;m] = [o;o] -> [n] = [m].\nProof.\n  intros n m o H.\n  inversion H. (* works as injection *)\n  done.\nQed.\n\nTheorem inversion_ex2 : forall n : nat, n.+1 = 0 -> 2 + 2 = 5.\nProof.\n  intros n H.\n  inversion H.  (* works as discriminate *)\nQed.\n\nTheorem inversion_ex_S_injective : forall n m, S n = S m -> n = m.\nProof.\n  intros n m H.\n  inversion H.\n  exact.\nQed.\n\n(*\n  ev \u306e\u69cb\u9020\u306b\u95a2\u3059\u308b\u5e30\u7d0d\u6cd5\n *)\nLemma even_is_double_of_something : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E.\n  - by exists 0.\n  - destruct IHE.\n    exists (x.+1).\n    rewrite -muln2.\n    rewrite mulSn.\n    rewrite muln2.\n    rewrite -H.\n    done.\nQed.\n", "meta": {"author": "cympfh", "repo": "coq-etude", "sha": "83deac7d6931ad48540b999e3c1649cf93b0a41e", "save_path": "github-repos/coq/cympfh-coq-etude", "path": "github-repos/coq/cympfh-coq-etude/coq-etude-83deac7d6931ad48540b999e3c1649cf93b0a41e/igarashi/class07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.891811038968166, "lm_q1q2_score": 0.8349892989898996}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\n\nImport ListNotations.\n\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\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X) * (list Y) :=\n  match l with\n  | [] => ([],[])\n  | (x,y) :: ls => let rest := split ls in (x :: fst rest, y :: snd rest)\n  end.\n\nFixpoint filter {X : Type} (f : X -> bool) (l : list X) : list X :=\n  match l with\n  | [] => []\n  | x :: xs => if f x then x :: filter f xs else filter f xs\n  end.\n\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. auto. Qed.\n\n\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (NPeano.leb 7 n) (NPeano.even n)) l.\n\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. auto. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. auto. Qed.\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X)\n  : list X * list X :=\n  (filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition NPeano.odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. auto. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. auto. Qed.\n\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n    List.map f (List.rev l) = List.rev (List.map f l).\nProof.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite map_app, IHl.\n    reflexivity.\nQed.\n\nFixpoint foldr {X Y : Type} (f : X -> Y -> Y) (y : Y) (l : list X) : Y :=\n  match l with\n  | [] => y\n  | x :: xs => f x (foldr f y xs)\n  end.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  foldr (fun _ n => S n) 0 l.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. auto. Qed.\nTheorem fold_length_correct : forall X (l : list X),\n    fold_length l = length l.\nProof.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl.\n    unfold fold_length. simpl. reflexivity.\nQed.\n\nModule Church.\n  Definition nat := forall X : Type, (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 :=\n    fun X f (x : X) => f (f (f x)).\n  \n  Definition zero : nat :=\n    fun (X : Type) (f : X -> X) (x : X) => x.\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. auto. Qed.\n  \n  Example succ_2 : succ one = two.\n  Proof. auto. Qed.\n\n\n  Definition plus (n m : nat) : nat :=\n    fun X (f : X -> X) (x : X) => n X f (m X f x).\n  \n  Example plus_1 : plus zero one = one.\n  Proof. auto. Qed.\n  \n  \n  Definition mult (n m : nat) : nat :=\n    fun X f => n X (m X f).\n  \n  Example mult_1 : mult one one = one.\n  Proof. auto. Qed.\n\n  Example mult_2 : mult zero (plus three three) = zero.\n  Proof. auto. Qed.\n  \n  Example mult_3 : mult two three = plus three three.\n  Proof. auto. Qed.\n  \n  Definition exp (n m : nat) : nat :=\n    (*n nat (mult m) one.*)\n    fun X => m ((X -> X) -> X -> X) ((fun n' m' f => n' (m' f)) (n X)) (one X).\n                                 \n  Example exp_1 : exp two two = plus two two.\n  Proof. auto. Qed.\n  Example exp_2 : exp three two = plus (mult two (mult two two)) one.\n  Proof. auto. Qed.\n  Example exp_3 : exp three zero = one.\n  Proof. auto. Qed.\n  \nEnd Church.", "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/sf/polymorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8347039818050326}}
{"text": "Require Import Arith Omega.\n\nDefinition divides (n m:nat) := exists p:nat, p*n = m.\n\n\nLemma divides_O : forall n:nat, divides n 0.\nProof.\n  intro n; exists 0; simpl; trivial.\nQed.\n\nLemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).\nProof.\n intros n m H; elim H; intros q Hq.  \n exists (S q) ; simpl; auto.\nQed.\n\nLemma not_divides_plus : forall n m:nat, ~ divides n m -> ~ divides n (n+m).\nProof.\n intros n m H; red; intro H'; elim H'; intro y.\n case y; simpl.\n intro H2; apply H.\n cut (m=0).\n intro H3; rewrite H3; apply divides_O.\n Require Omega.\n omega.\n intros n0 Hn0.\n apply H.\n exists n0.\n omega.\nQed.\n\nLemma not_divides_lt : forall n m:nat, 0<m ->  m<n -> ~ divides n m.\nProof.\n intros n m H H0 H1.\n elim H1; intros q Hq.\n rewrite <- Hq in H.\n rewrite <- Hq in H0.\n generalize H H0; case q.\n simpl.  \n intros; absurd (0 < 0); auto with arith.\n clear H H0; intros y Hy Hy'.\n simpl in Hy'. \n absurd (n <= n + y * n); auto with arith. \nQed.\n\nLemma not_lt_2_divides : forall n m:nat, n <> 1 -> n < 2 -> 0 < m -> \n                        ~ divides n m.\nProof.\n intros n m H H0; cut (n=0).\n intro e;rewrite e.   \n case m.\n intro; absurd (0 < 0); auto with arith.\n intros n0 Hn0 H1.\n elim H1; intros q Hq.\n rewrite mult_0_r in Hq; discriminate Hq.\nRequire Import Omega.  \n omega.\nQed.\n  \nLemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\nProof.\n intros; omega.\nQed.\n\nLemma lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/  n=m.\nProof.\n intros; omega. \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/primes_hyps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.8346013928878092}}
{"text": "(* @todo  add as an exercise *)\n\n(** Returns smallest value of x less or equal than b such that (P b x). \n    Otherwise returns b  *)\n\n\nFrom hydras Require Import  primRec extEqualNat.\nFrom Coq Require Import Min ArithRing Lia Compare_dec Arith Lia.\n\n\n\n(** Please consider the following specification of the integer square root *)\n\nDefinition isqrt_spec n r := r * r <= n < S r * S r.\n\n(** Prove the following function [isqrt] is a primitive recursive \n    (inefficient) implementation of this specification *)\n\nSection sqrtIsPR.\n  \nLet P (n r: nat) :=  Nat.ltb n (S r * S r).\nDefinition isqrt  := boundedSearch P . \n\nLemma sqrt_correct (n: nat) : isqrt_spec n (isqrt n).\nAdmitted.\n\nLemma issqrtIsPR : isPR 1 isqrt.\nAdmitted.\n\nEnd sqrtIsPR.\n\n(** Extra work :\n   Define a faster implementation of [sqrt_spec], and prove your function is \n   extensionnaly equal to [isqrt] (hence PR!)\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/exercises/primrec/isqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.888758801595206, "lm_q1q2_score": 0.834566575955761}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Logic.\nRequire Coq.omega.Omega.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n  | wrong_ev_0 : wrong_ev 0\n  | wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros n. induction n.\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. apply IHn.\nQed.\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  - simpl. apply ev_0.\n  - simpl. apply E'. Qed.\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - simpl. apply ev_0.\n  - simpl. apply E'.\nQed.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  destruct E as [| n' E'].\nAbort.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'.\nQed.\n\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H. \n  inversion H as [| n' E' g].\n  inversion E'.\n  apply H1.\nQed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros H. simpl. inversion H.\n  inversion H1. inversion H3.\nQed.\n\nLemma ev_even_firsttry : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E. inversion E as [| n' E'].\n  - exists 0. reflexivity.\n  - 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').\n      reflexivity. }\n    apply I.\nAdmitted.\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [| n' E' IH].\n  - exists 0. reflexivity.\n  - destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - apply ev_even.\n  - intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\nSearch plus.\n\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m H1 H2.\n  induction H1.\n  - simpl. apply H2.\n  - induction H2.\n    + rewrite plus_comm. simpl.\n      apply ev_SS. apply H1.\n    + simpl. apply ev_SS. apply IHev.\nQed.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n + m) -> ev n -> ev m.\nProof.\n  intros n m H1 H2. induction H2.\n  - simpl in H1. apply H1.\n  - apply IHev. simpl in H1. apply evSS_ev in H1.\n    apply H1.\nQed.\n\nSearch plus.\n\nTheorem add_0_is_0 : forall (n m : nat),\n  n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H. induction n.\n  - split.\n    + reflexivity.\n    + simpl in H. apply H.\n  - split.\n    + inversion H.\n    + inversion H.\nQed.\n\nTheorem ev_evSS : forall n,\n  ev n -> ev (S (S n)).\nProof.\n  intros n H.\n  apply ev_SS.\n  apply H.\nQed.\n\nTheorem add_0_is_Z : forall n,\n  n = 0 -> n + n = 0.\nProof.\n  intros n H. induction n.\n  - reflexivity.\n  - inversion H.\nQed.\n\nSearch double.\n\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 : 3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 : 3 <= 6.\nProof.\n  apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 : (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2. Qed.\n\nEnd Playground.\n\nDefinition lt (n m : nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq : forall n: nat, square_of n (n * n).\n\nTheorem test_square_of : square_of 4 16.\nProof.\n apply sq. Qed.\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n : nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\nInductive total_relation : nat -> nat -> Prop :=\n  | tr : forall n m, total_relation n m.\n\nTheorem test_total_relation : total_relation 1 1.\nProof.\n  apply tr. Qed.\n\nInductive empty_relation : nat -> nat -> Prop :=\n  | er : forall n, lt n n -> empty_relation n n.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hno.\n  induction Hno.\n  - apply Hmn.\n  - apply le_S in IHHno. apply IHHno.\nQed.\n\nTheorem le_n_0 : forall n,\n  n <= 0 -> n = 0.\nProof.\n  intros n H. induction n.\n  - reflexivity.\n  - inversion H.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n. induction n.\n  - apply le_n.\n  - inversion IHn.\n    + apply le_S. apply le_n.\n    + apply le_S. apply le_S. apply H.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m Hsnsm. inversion Hsnsm.\n  - apply le_n.\n  - apply (le_trans n (S n)).\n    + apply le_S. apply le_n.\n    + apply H0.\nQed.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b. induction b.\n  - rewrite plus_comm. simpl. apply le_n.\n  - inversion IHb.\n    + rewrite <- H. rewrite <- plus_n_Sm.\n      rewrite <- H. apply le_S. apply le_n.\n    + rewrite <- plus_n_Sm. rewrite <- H.\n      apply le_S. apply le_S. apply H0.\nQed.\n\nTheorem lt_1 : forall n m,\n  S n < m -> n < m.\nProof.\n  intros n m H. inversion H.\n  - apply le_S. apply le_n.\n  - apply le_S. apply le_S in H0. \n    apply Sn_le_Sm__n_le_m in H0.\n    apply H0.\nQed.\n\n\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n  intros n1 n2 m H.\n  split.\n  - induction n2.\n    + rewrite plus_comm in H. simpl in H. apply H.\n    + apply IHn2. rewrite <- plus_n_Sm in H.\n      apply lt_1 in H. apply H.\n  - induction n1.\n    + simpl in H. apply H.\n    + apply IHn1. \n      rewrite plus_comm in H. \n      rewrite <- plus_n_Sm in H.\n      apply lt_1 in H. rewrite plus_comm in H.\n      apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m -> n < S m.\nProof.\n  intros n m H. inversion H.\n  - apply le_S. apply le_n.\n  - apply le_S. apply le_S in H0. \n    rewrite -> H1 in H0. rewrite -> H1.\n    apply H0.\nQed.\n\nSearch leb.\n\nTheorem leb_n_0 : forall n,\n  leb n 0 = true <-> n = 0.\nProof.\n  intros n.\n  split.\n  - intro H. induction n.\n    + reflexivity.\n    + inversion H.\n  - intro H. induction n.\n    + reflexivity.\n    + simpl. inversion H.\nQed.\n\nTheorem n_0 : forall n,\n  n <= 0 <-> n = 0.\nProof.\n  intros n. split.\n  - intro H. induction n.\n    + reflexivity.\n    + inversion H.\n  - intro H. induction n.\n    + reflexivity.\n    + inversion H.\nQed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  intros n m H. induction m.\n  - rewrite n_0. apply leb_n_0. apply H.\n  -  apply le_S. apply IHm. inversion H.\nAdmitted.\n\nTheorem leb_refl : forall n,\n  leb n n = true.\nProof.\n  intro n. induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m -> leb n m = true.\nProof.\n  intros n m H. induction m.\n  - rewrite leb_n_0. inversion H. reflexivity.\n  - inversion H.\n    + apply leb_refl.\n    + Admitted.\n\nInductive reg_exp {T : Type} : Type :=\n| EmptySet : reg_exp\n| EmptyStr : reg_exp\n| Char : T -> reg_exp\n| App : reg_exp -> reg_exp -> reg_exp\n| Union : reg_exp -> reg_exp -> reg_exp\n| Star : reg_exp -> reg_exp.\n\n\nInductive exp_match {T} : list T -> reg_exp -> Prop :=\n  | MEmpty : exp_match [] EmptyStr\n  | MChar : forall x, exp_match [x] (Char x)\n  | MApp : forall s1 re1 s2 re2,\n            exp_match s1 re1 ->\n            exp_match s2 re2 ->\n            exp_match (s1 ++ s2) (App re1 re2)\n  | MUnionL : forall s1 re1 re2,\n                exp_match s1 re1 ->\n                exp_match s1 (Union re1 re2)\n  | MUnionR : forall re1 s2 re2,\n                exp_match s2 re2 ->\n                exp_match s2 (Union re1 re2)\n  | MStar0 : forall re, exp_match [] (Star re)\n  | MStarApp : forall s1 s2 re,\n                exp_match s1 re ->\n                exp_match s2 (Star re) ->\n                exp_match (s1 ++ s2) (Star re).\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\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')\nend.\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 : forall T s (re : @reg_exp T),\n  s =~ re -> 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 H. induction s.\n  - inversion H.\n  - inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 -> s =~ Union re1 re2.\nProof.\n  intros T s re1 re2 H.\n  inversion H.\n  - apply MUnionL. apply H0.\n  - apply MUnionR. apply H0.\nQed.\n\nSearch In.\n\nLemma head_same_concat : forall T (x : T) (xs : list T),\n  x :: xs = [x] ++ xs.\nProof.\n  intros T x xs. induction xs.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n  (forall s, In s ss -> s =~ re) -> fold app ss [] =~ Star re.\nProof.\n  intros T ss re H. induction ss.\n  - apply MStar0.\n  - rewrite -> head_same_concat. simpl. apply MStarApp.\n    + apply H. simpl. left. reflexivity.\n    + apply IHss. intros s H1. apply H. simpl. right. apply H1.\nQed.\n\nLemma reg_exp_of_list_match_itself : forall T (l : list T),\n  l =~ reg_exp_of_list l.\nProof.\n  intros T l. induction l.\n  - simpl. apply MEmpty.\n  - simpl. apply (MApp [x] _ l).\n    + apply MChar.\n    + apply IHl.\nQed.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 = s2 <-> s1 =~ reg_exp_of_list s2.\nProof.\n  split.\n  - intro H. induction s2.\n    + simpl. rewrite -> H. apply MEmpty.\n    + simpl. induction s1.\n      * rewrite -> H. apply (MApp [x] _ s2).\n        apply MChar.\n        apply reg_exp_of_list_match_itself.\n      * rewrite -> H.\n        apply (MApp [x] _ s2).\n        apply MChar.\n        apply reg_exp_of_list_match_itself.\n  - generalize dependent s1. induction s2;\n    intros.\n    + inversion H. simpl. reflexivity.\n    + inversion H. inversion H3. subst. simpl.\n      simpl in H.  apply f_equal. apply IHs2.\n      apply H4.\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 : \n  forall T (s : list T) (re : reg_exp) (x : T),\n  s =~ re -> In x s -> In x (re_chars re).\nProof.\n  intros T s re x Hmatch Hin.\n  induction Hmatch\n    as [| x'\n        | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n        | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  - apply Hin.\n  - apply Hin.\n  - simpl. rewrite In_app_iff in *. \n    destruct Hin as [Hin | Hin].\n    + left. apply (IH1 Hin).\n    + right. apply (IH2 Hin).\n  - simpl. rewrite In_app_iff.\n    left. apply (IH Hin).\n  - simpl. rewrite In_app_iff.\n    right. apply (IH Hin).\n  - destruct Hin.\n  - simpl. rewrite In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    + apply (IH1 Hin).\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 => andb (re_not_empty re1) (re_not_empty re2)\n  | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n  | Star re => true\n  end.\n\nSearch orb.\n\nLemma list_eq_concat_empty : forall T (l : list T),\n  l = [] ++ l.\nProof.\n  intros T l. reflexivity.\nQed.\n\nSearch andb.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros T re. split.\n  - intro H. induction re.\n    + inversion H. simpl. inversion H0.\n    + reflexivity.\n    + reflexivity.\n    + simpl. apply andb_true_intro. split.\n      * apply IHre1. inversion H. inversion H0. exists s1.\n        apply H4.\n      * apply IHre2. inversion H. inversion H0. exists s2.\n        apply H5.\n    + simpl. apply Bool.orb_true_intro. inversion H. inversion H0.\n      * left. apply IHre1. exists x. apply H3.\n      * right. apply IHre2. exists x. apply H3.\n    + reflexivity.\n  - intro H. induction re.\n    + simpl. inversion H.\n    + exists []. apply MEmpty.\n    + exists [t]. apply MChar.\n    + simpl in H. apply andb_true_iff in H. inversion H.\n      apply IHre1 in H0. inversion H0.\n      apply IHre2 in H1. inversion H1.\n      exists (x ++ x0). apply (MApp x _ x0).\n      * apply H2.\n      * apply H3.\n    + simpl in H. apply orb_true_iff in H. inversion H.\n      * apply IHre1 in H0. inversion H0.\n        exists x. apply MUnionL. apply H1.\n      * apply IHre2 in H0. inversion H0.\n        exists x. apply MUnionR. apply H1.\n    + exists []. apply MStar0.\nQed.\n\nLemma star_app : forall T (s1 s2 : list T) (re : @reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  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  - simpl. intros H. apply H.\n  Abort.\n\nLemma star_app : forall T (s1 s2 : list T) (re re' : reg_exp),\n  re' = Star re -> s1 =~ re' -> s2 =~ Star re -> s1 ++ s2 =~ Star re.\nAbort.\n\nLemma star_app : forall T (s1 s2 : list T) (re : reg_exp),\n  s1 =~ Star re -> s2 =~ Star re -> s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  remember (Star re) as re'.\n  generalize dependent s2.\n  induction H1\n    as [| x' | s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        | s1 re1 re2 Hmatch IH | re1 s2' re2 Hmatch IH\n        | re'' | s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'. intros s H. apply H.\n  - inversion Heqre'. rewrite H0 in IH2, Hmatch1.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * reflexivity.\n      * apply H1.\nQed.\n\nSearch app.\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 [] /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  intros T s re H. remember (Star re). remember [s]. remember (App re re).\n  induction H.\n  - inversion Heqr.\n  - inversion Heqr.\n  - inversion Heqr.\n  - inversion Heqr.\n  - inversion Heqr.\n  - inversion Heqr. exists []. split.\n    + simpl. reflexivity.\n    + intros s' H1. simpl in H1.\n      inversion H1.\n  - exists l. split.\n    + rewrite -> Heql. simpl. simpl. \n      rewrite <- app_assoc. rewrite -> app_nil_r.\n      reflexivity.\n    + intros. rewrite -> Heql in H1. simpl in H1.\n      inversion H1.\n      * inversion Heqr. inversion H0.\n        rewrite <- H2. rewrite <- H3. rewrite -> app_nil_r.\n        rewrite -> H4 in H. apply H.\n        rewrite <- H2.\nAbort.\n\nModule Pumping.\nImport Coq.omega.Omega.\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2 \n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\n  end.\n\nLemma napp_plus : forall T (n m : nat) (l : list T),\n  napp (n + m) l = napp n l ++ napp m l.\nProof.\n  intros T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\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    not (s2 = []) /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - simpl. omega.\n  - simpl. omega.\n  - remember (App re1 re2). simpl. intro H. inversion H.\n    +\nAbort.\n\nTheorem filter_not_empty_in : forall n l,\n  filter (beq_nat n) l <> [] -> In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - simpl. intros H. apply H. reflexivity.\n  - simpl. destruct (beq_nat n m) eqn:H.\n    + intros _. rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + intros H'. right. apply IHl'. apply H'.\nQed.\n\nInductive reflect (P : Prop) : bool -> Prop :=\n  | ReflectT : P -> reflect P true\n  | ReflectF : ~ P -> reflect P false.\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros P b H. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  intros P b H. split.\n  - intro P'. destruct b.\n    + reflexivity.\n    + inversion H. apply H0 in P'. inversion P'.\n  - intros H'. inversion H.\n    + apply H0.\n    + symmetry in H1. rewrite -> H1 in H'. inversion H'.\nQed.\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m. apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (beq_nat n) l <> [] -> In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - simpl. intros H. apply H. reflexivity.\n  - simpl. destruct (beq_natP n m) as [H | H].\n    + intros _. rewrite H. left. reflexivity.\n    + intros H'. right. apply IHl'. apply H'.\nQed.\n\nFixpoint count n l :=\n  match l with\n  | [] => 0\n  | m :: l' => (if beq_nat n m then 1 else 0) + count n l'\n  end.\n\nSearch beq_nat.\n\nLemma is_in_rest : forall T (l : list T) (n x : T),\n  In n (x :: l) -> n <> x -> In n l.\nProof.\n  intros T l n x H1 H2.\n  inversion H1.\n  - rewrite -> H in H2. unfold not in H2.\n    rewrite -> H in H1. simpl in H1.\n    inversion H1.\n    + apply H2 in H0. inversion H0.\n    + apply H0.\n  - apply H.\nQed.\n\nTheorem beq_natP_practice : forall n l,\n  count n l = 0 -> ~ ( In n l ).\nProof.\n  intros n l H H'. induction l.\n  - simpl in H. simpl in H'. apply H'.\n  - destruct (beq_natP n x).\n    + rewrite <- H0 in H'. simpl in H'. \n      rewrite <- H0 in H.\n      simpl in H.\n      rewrite Nat.eqb_refl in H. simpl in H.\n      inversion H.\n    + simpl in H.\n      apply IHl.\n      * rewrite <- Nat.eqb_neq in H0. \n        rewrite H0 in H.\n        simpl in H. apply H.\n      * apply is_in_rest in H'.\n        apply H'. apply H0.\nQed.\n\nInductive nostutter {X:Type} : list X -> Prop :=\n  | NoStutterNil : nostutter []\n  | NoStutterSingleton : forall x, nostutter [x]\n  | NoStutterCons : forall (x y : X) (l : list X),\n      nostutter (y :: l) -> x <> y -> nostutter (x :: y :: l).\n\nExample test_nostutter_1 : nostutter [3;1;4;1;5;6].\nProof.\n  repeat apply NoStutterCons.\n  apply NoStutterSingleton.\n  apply beq_nat_false_iff;  auto.\n  apply beq_nat_false_iff;  auto.\n  apply beq_nat_false_iff;  auto.\n  apply beq_nat_false_iff;  auto.\n  apply beq_nat_false_iff;  auto.\nQed.\n\nExample test_nostutter_2 : nostutter (@nil nat).\nProof.\n  apply NoStutterNil. Qed.\n\nExample test_nostutter_3 : nostutter [5].\nProof.\n  apply NoStutterSingleton. Qed.\n\nExample test_nostutter_4 : not (nostutter [3;1;1;4]).\nProof.\n  intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H5. auto.\nQed.\n\nEnd Pumping.\n\n\n\n", "meta": {"author": "yanhick", "repo": "coq-exercises", "sha": "75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d", "save_path": "github-repos/coq/yanhick-coq-exercises", "path": "github-repos/coq/yanhick-coq-exercises/coq-exercises-75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d/LF/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.9019206811430764, "lm_q1q2_score": 0.8344840368334272}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    [Basics] chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p as [n m]. 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 [n m]. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n   you read them in a .v file.  The inner brackets, around 3, indicate\n   a list, but the outer brackets, which are invisible in the HTML\n   rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match h with\n              | 0 => nonzeros(t)\n              | _ => h :: nonzeros(t)\n              end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: NatList.test_nonzeros *)\n\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:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: NatList.test_oddmembers *)\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length(oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity.  Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h1 :: t1 => match l2 with\n              | nil => h1 :: t1\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(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nDefinition count_head (h v: nat) : nat :=\n  match (beq_nat h v) with\n  | true => 1\n  | false => 0\n  end.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => (count_head v h) + (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(* GRADE_THEOREM 0.5: NatList.test_count2 *)\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := app.\n(*Definition sum := app.*)\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: NatList.test_sum1 *)\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity.  Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: NatList.test_add1 *)\n(* GRADE_THEOREM 0.5: NatList.test_add2 *)\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match (count v s) with\n  | 0 => false\n  | _ => true\n  end.\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: NatList.test_member1 *)\n(* GRADE_THEOREM 0.5: NatList.test_member2 *)\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match (beq_nat h v) with\n              | true => t\n              | false => h :: (remove_one v t)\n              end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity.  Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity.  Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity.  Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity.  Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match (beq_nat h v) with\n              | true => remove_all v t\n              | false => h :: (remove_all v t)\n              end\n  end.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity.  Qed.\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  | h1 :: t1 => match s2 with\n                | nil => false\n                | h2 :: t2 => match (count h1 (h2::t2)) with\n                              | 0 => false\n                              | _ => subset t1 (remove_one h1 (h2::t2))\n                              end\n                end\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity.  Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\nTheorem count_head_eq : forall v: nat,\n  count_head v v = 1.\nProof.\n  induction v as [| v1 Hv1].\n  { reflexivity. }\n  { assert (H1: count_head (S v1) (S v1) = count_head v1 v1).\n    { reflexivity. }\n    rewrite -> H1.\n    rewrite -> Hv1.\n    reflexivity. }\nQed.\n\nTheorem count_bag_head : forall v h: nat, forall s: bag,\n  count v (h :: s) = (count_head v h) + (count v s).\nProof.\n  intros v h s. reflexivity.\nQed.\n\nTheorem bag_theorem : forall s: bag, forall v: nat,\n  count v (add v s) = 1 + (count v s).\nProof.\n  intros s v.\n  destruct s as [| h t2].\n  { simpl. rewrite -> count_head_eq. reflexivity. }\n  { assert (H2: add v (h :: t2) = (v :: h :: t2)).\n    { reflexivity. }\n    rewrite -> H2.\n    rewrite -> count_bag_head.\n    rewrite -> count_head_eq.\n    reflexivity. }\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n(*Qed.*)\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [| h l1 Hl1].\n  - reflexivity.\n  - simpl. rewrite -> Hl1. reflexivity.\nQed.\n(* GRADE_THEOREM 0.5: NatList.app_nil_r *)\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1 as [| h l11 Hl11].\n  { induction l2 as [| h1 l21 Hl21].\n    { reflexivity. }\n    { simpl. rewrite -> app_nil_r. reflexivity. } }\n  { induction l2 as [| h2 l21 Hl21].\n    { simpl. rewrite -> app_nil_r. reflexivity. }\n    { simpl. rewrite -> Hl11. rewrite -> app_assoc. reflexivity. } }\nQed.\n(* GRADE_THEOREM 0.5: NatList.rev_app_distr *)\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| h1 t1 Ht1].\n  { reflexivity. }\n  { simpl. rewrite -> rev_app_distr. rewrite -> Ht1. reflexivity. }\nQed.\n(* GRADE_THEOREM 0.5: NatList.rev_involutive *)\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  reflexivity.\nQed.\n(* GRADE_THEOREM 0.5: NatList.app_assoc4 *)\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| h l11 Hl11].\n  { induction l2 as [| h1 l21 Hl21].\n    { reflexivity. }\n    { reflexivity. } }\n  { induction l2 as [| h2 l21 Hl21].\n    { rewrite -> app_nil_r.\n      assert (H2: nonzeros [ ] = [ ]).\n      { reflexivity. }\n      rewrite -> H2.\n      rewrite -> app_nil_r.\n      reflexivity. }\n    { destruct h as [|h_].\n      { destruct h2 as [|h2_].\n        { simpl. rewrite -> Hl11. reflexivity. }\n        { simpl. rewrite -> Hl11. reflexivity. } }\n      { destruct h2 as [|h2_].\n        { simpl. rewrite -> Hl11. reflexivity. }\n        { simpl. rewrite -> Hl11. reflexivity. } } } }\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | nil => match l2 with\n          | nil => true\n          | _ => false\n          end\n  | h1::t1 => match l2 with\n              | nil => false\n              | h2::t2 => match (beq_nat h1 h2) with\n                          | true => beq_natlist t1 t2\n                          | false => false\n                          end\n              end\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. simpl. reflexivity.  Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity.  Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity.  Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l.\n  induction l as [| h1 t1 Ht1].\n  { reflexivity. }\n  { destruct h1 as [| h2].\n    { simpl. rewrite -> Ht1. reflexivity. }\n    { simpl.\n      rewrite <- beq_nat_refl.\n      rewrite -> Ht1.\n      reflexivity. } }\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star (count_member_nonzero)  *)\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  reflexivity.\nQed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** **** Exercise: 3 stars, advanced (remove_decreases_count)  *)\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s.\n  induction s as [| h t Ht].\n  { reflexivity. }\n  { simpl.\n    destruct h as [| h1].\n    { simpl.\n      rewrite -> ble_n_Sn.\n      reflexivity. }\n    { simpl.\n      rewrite -> Ht.\n      reflexivity. } }\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!) *)\nTheorem bag_count_sum : forall s1 s2 : bag, forall v: nat,\n  count v (sum s1 s2) = (count v s1) + (count v s2).\nProof.\n  intros s1 s2 v.\n  induction s1 as [| h1 t1 Ht1].\n  { reflexivity. }\n  { simpl.\n    rewrite -> Ht1.\n    rewrite -> plus_assoc.\n    reflexivity. }\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\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.\n  intros H.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | h :: t => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity.  Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity.  Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  induction l as [| h t Ht].\n  { reflexivity. }\n  { reflexivity. }\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  destruct x.\n  { simpl.\n    rewrite <- beq_nat_refl.\n    reflexivity. }\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros id v.\n  simpl.\n  rewrite <- beq_id_refl.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros x y d o.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n    (Explain your answer in words, preferrably English.)\n\nZero. All inductive statement need provide a baz type value first. We cannot\nprovide a baz from nothing.\n*)\n(** [] *)\n\n\n", "meta": {"author": "zhouzheMegvii", "repo": "SoftwareFoundation", "sha": "cd866c01c1ec6efdcdda66790a125d69bbd9e432", "save_path": "github-repos/coq/zhouzheMegvii-SoftwareFoundation", "path": "github-repos/coq/zhouzheMegvii-SoftwareFoundation/SoftwareFoundation-cd866c01c1ec6efdcdda66790a125d69bbd9e432/Lists/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.9196425377849806, "lm_q1q2_score": 0.8344029207300533}}
{"text": "(** * Lists: Working with Structured Data *)\n\nFrom LF Require Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one (as with [nybble], and here): *)\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat)\n.\n\nCheck pair 0 0.\nCheck pair 1 2.\nCheck pair 3 2.\n\n(** This declaration can be read: \"The one and only way to\n    construct a pair of numbers is by applying the constructor [pair]\n    to two arguments of type [nat].\" *)\n\nCheck (pair 3 5) : natprod.\n\n(** Functions for extracting the first and second components of a pair\n    can then be defined by pattern matching. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs will be used heavily in what follows, it is nice\n    to be able to write them with the standard mathematical notation\n    [(x,y)] instead of [pair x y].  We can tell Coq to allow this with\n    a [Notation] declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in pattern\n    matches. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Note that pattern-matching on a pair (with parentheses: [(x, y)])\n    is not to be confused with the \"multiple pattern\" syntax (with no\n    parentheses: [x, y]) that we have seen previously.  The above\n    examples illustrate pattern matching on a pair with elements [x]\n    and [y], whereas, for example, the definition of [minus] in\n    [Basics] performs pattern matching on the values [n] and [m]:\n\n       Fixpoint minus (n m : nat) : nat :=\n         match n, m with\n         | O   , _    => O\n         | S _ , O    => n\n         | S n', S m' => minus n' m'\n         end.\n\n    The distinction is minor, but it is worth knowing that they\n    are not the same. For instance, the following definitions are\n    ill-formed:\n\n        (* Can't match on a pair with multiple patterns: *)\n        Definition bad_fst (p : natprod) : nat :=\n          match p with\n          | x, y => x\n          end.\n\n        (* Can't match on multiple values with pair patterns: *)\n        Definition bad_minus (n m : nat) : nat :=\n          match n, m with\n          | (O   , _   ) => O\n          | (S _ , O   ) => n\n          | (S n', S m') => bad_minus n' m'\n          end.\n*)\n\n(** Now let's try to prove a few simple facts about pairs.\n\n    If we state properties of pairs in a slightly peculiar way, we can\n    sometimes complete their proofs with just reflexivity (and its\n    built-in simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\n(** But just [reflexivity] is not enough if we state the lemma in the\n    most natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** Instead, we need to expose the structure of [p] so that\n    [simpl] can perform the pattern match in [fst] and [snd].  We can\n    do this with [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** Notice that, unlike its behavior with [nat]s, where it\n    generates two subgoals, [destruct] generates just one subgoal\n    here.  That's because [natprod]s can only be constructed in one\n    way. *)\n\n(** **** Exercise: 1 star, standard (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n| nil\n| cons (n : nat) (l : natlist)\n.\n\nCheck nil.\nCheck cons 0 nil.\nCheck cons 1 (cons 0 nil).\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nCheck [0; 3; 4; 1; 7].\nCheck [0; 3; 4; 1; 7].\n\n(** It is not necessary to understand the details of these\n    declarations, but here is roughly what's going on in case you are\n    interested.  The \"[right associativity]\" annotation tells Coq how to\n    parenthesize expressions involving multiple uses of [::] so that,\n    for example, the next three declarations mean exactly the same\n    thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The \"[at level 60]\" part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than\n    [1 + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** Next let's look at several functions for constructing and\n    manipulating lists.  First, the [repeat] function takes a number\n    [n] and a [count] and returns a list of length [count] in which\n    every element is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => []\n  | S count' => n :: (repeat n count')\n  end.\n\nCompute repeat 1 10.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + (length t)\n  end.\n\nCompute length [1;2;3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nCompute app [1;2;3] [4;5;6].\n\n(** Since [app] will be used extensively, it is again convenient\n    to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nCompute [1;2] ++ [3;4].\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first element (the\n    \"tail\").  Since the empty list has no first element, we pass\n    a default value to be returned in that case.  *)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nCompute tl [1;2;3].\nCompute hd 0 [1;2;3].\nCompute hd 0 [].\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs)\n\n    Complete the definitions of [nonzeros], [oddmembers], and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  (* FILL IN HERE *) Admitted.\n\n(** For [countoddmembers], we're giving you a header that uses keyword\n    [Definition] instead of [Fixpoint].  The point of stating the\n    question this way is to encourage you to implement the function by\n    using already-defined functions, rather than writing your own\n    recursive definition. *)\n\nDefinition countoddmembers (l:natlist) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)\n\n    Complete the following definition of [alternate], which\n    interleaves two lists into one, alternating between elements taken\n    from the first list and elements from the second.  See the tests\n    below for more specific examples.\n\n    Hint: there is an elegant way of writing [alternate] that fails to\n    satisfy Coq's requirement that all [Fixpoint] definitions be\n    _structurally recursing_, as mentioned in [Basics]. If you\n    encounter that difficulty, consider pattern matching against both\n    lists at the same time with the \"multiple pattern\" syntax we've\n    seen before. *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    representation for a bag of numbers is as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions)\n\n    Complete the following definitions for the functions [count],\n    [sum], [add], and [member] for bags. *)\n\nFixpoint count (v : nat) (s : bag) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't call this operation [union].)\n\n    We've deliberately given you a header that does not give explicit\n    names to the arguments.  Implement [sum] with an already-defined\n    function without changing the header. *)\n\nDefinition sum : bag -> bag -> bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v : nat) (s : bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint member (v : nat) (s : bag) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_member1:             member 1 [1;4;1] = true.\n (* FILL IN HERE *) Admitted.\n\nExample test_member2:             member 2 [1;4;1] = false.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_more_functions)\n\n    Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to\n    remove, it should return the same bag unchanged.  (This exercise\n    is optional, but students following the advanced track will need\n    to fill in the definition of [remove_one] for a later\n    exercise.) *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint included (s1 : bag) (s2 : bag) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_included1:              included [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_included2:              included [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count)\n\n    Adding a value to a bag should increase the value's count by one.\n    State this as a theorem and prove it. *)\n(*\nTheorem add_inc_count : ...\nProof.\n  ...\nQed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_add_inc_count : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, just the simplification performed by [reflexivity] is\n    enough for this theorem... *)\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof.\n  intros. simpl.\n  reflexivity.\nQed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [ | n l'].\n  - (* l = nil *)\n    simpl. reflexivity.\n  - (* l = cons n l' *)\n    simpl.\n    reflexivity.\nQed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs.  We'll see how to do this next. *)\n\n(** (Micro-Sermon: As we get deeper into this material, simply\n    _reading_ proof scripts will not get you very far!  It is\n    important to step through the details of each one using Coq and\n    think about what each step achieves.  Otherwise it is more or less\n    guaranteed that the exercises will make no sense when you get to\n    them.  'Nuff said.) *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(* nat_ind: forall P: nat->Prop, *)\n(*          P 0 -> (forall n, P n -> P (S n)) -> forall n, P n. *)\n\nLemma natlist_ind': forall P: natlist -> Prop,\n  P [] -> (forall (n:nat) (l:natlist), P l -> P (n::l)) -> forall l, P l.\nProof.\n  intros P HB HI.\n  fix self 1.\n  intros l.\n  destruct l.\n  - exact HB.\n  - apply HI.\n    exact (self l).\nQed.\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors.  For example, a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to another\n    number; and a list can be either [nil] or [cons] applied to a\n    number and a list.   Moreover, applications of the declared\n    constructors to one another are the _only_ possible shapes\n    that elements of an inductively defined set can have.\n\n    This last fact directly gives rise to a way of reasoning about\n    inductively defined sets: a number is either [O] or else it is [S]\n    applied to some _smaller_ number; a list is either [nil] or else\n    it is [cons] applied to some number and some _smaller_ list;\n    etc. So, if we have in mind some proposition [P] that mentions a\n    list [l] and we want to argue that [P] holds for _all_ lists, we\n    can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can always be broken down into smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case.\n\n    Once again, this Coq proof is not especially illuminating as a\n    static document -- it is easy to see what's going on if you are\n    reading the proof in an interactive Coq session and you can see\n    the current goal and context at each point, but this state is not\n    visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n               [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing\n    function [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nCompute rev [1;2;3;4].\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** For something a bit more challenging than the proofs\n    we've seen so far, let's prove that reversing a list does not\n    change its length.  Our first attempt gets stuck in the successor\n    case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    simpl.\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress at the point where we got\n    stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nRequire Import Lia.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite <- IHl'.\n    rewrite -> app_length.\n    simpl. (* nia. *)\n    rewrite add_comm. simpl.\n    reflexivity.\nQed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length], [++], and [plus].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2.\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After reading a couple like this, we might find it easier to\n    follow proofs that give fewer details (which we can easily work\n    out in our own minds or on scratch paper if necessary) and just\n    highlight the non-obvious steps.  In this more compressed style,\n    the above proof might look like this: *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l], by a straightforward induction on [l].  The main\n     property again follows by induction on [l], using the observation\n     together with the induction hypothesis in the case where [l =\n     n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that they will already be familiar with.\n    The more pedantic style is a good default for our present\n    purposes. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Let's say\n    you've forgotten the name of a theorem about [rev].  The command\n    [Search rev] will cause Coq to display a list of all theorems\n    involving [rev]. *)\n\nSearch rev.\n\n(** Or say you've forgotten the name of the theorem showing that plus\n    is commutative.  You can use a pattern to search for all theorems\n    involving the equality of two additions. *)\n\nSearch (_ + _ = _ + _).\n\n(** You'll see a lot of results there, nearly all of them from the\n    standard library.  To restrict the results, you can search inside\n    a particular module: *)\n\nSearch (_ + _ = _ + _) inside Induction.\n\n(** You can also make the search more precise by using variables in\n    the search pattern instead of wildcards: *)\n\nSearch (?x + ?y = ?y + ?x).\n\n(** The question mark in front of the variable is needed to indicate\n    that it is a variable in the search pattern, rather than a\n    variable that is expected to be in scope currently. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    Your IDE likely has its own functionality to help with searching.\n    For example, in ProofGeneral, you can run [Search] with [C-c C-a\n    C-a], and paste its response into your buffer with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, standard (list_exercises)\n\n    More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** An _involution_ is a function that is its own inverse. That is,\n    applying the function twice yield the original input. *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next 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  (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (eqblist)\n\n    Fill in the definition of [eqblist], which compares\n    lists of numbers for equality.  Prove that [eqblist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\n (* FILL IN HERE *) Admitted.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\n(* FILL IN HERE *) Admitted.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\n(** **** Exercise: 1 star, standard (count_member_nonzero) *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next\n    exercise (it will also be useful in later chapters). *)\n\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** Before doing the next exercise, make sure you've filled in the\n   definition of [remove_one] above. *)\n(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum)\n\n    Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!  Hint: If you defined [count] using\n    [=?] you may find it useful to know that [destruct] works on\n    arbitrary expressions, not just simple identifiers.)\n*)\n(* FILL IN HERE\n\n    [] *)\n\n(** **** Exercise: 3 stars, advanced (involution_injective) *)\n\n(** Prove that every involution is injective. Involutions were defined\n    above in [rev_involutive]. An _injective_ function is one-to-one:\n    it maps distinct inputs to distinct outputs, without any\n    collisions. *)\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  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (rev_injective)\n\n    Prove that [rev] is injective. Do not prove this by induction --\n    that would be hard. Instead, re-use the same proof technique that\n    you used for [involution_injective]. Do not try to use that\n    exercise directly as a lemma: the types are not the same. *)\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' n'\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. As we see here, constructors of inductive definitions can\n    be capitalized. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\n\nCompute nth_error [1;2;3;4] 10.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n*)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars, standard (hd_error)\n\n    Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (option_elim_hd)\n\n    This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id (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 flexibility to change representations later\n    if we want to. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\n(** **** Exercise: 1 star, standard (eqb_id_refl) *)\nTheorem eqb_id_refl : forall x, eqb_id x x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.  (* make the definitions from NatList available here *)\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map by shadowing it with a new one (or simply adds a new\n    entry if the given key is not already present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if eqb_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n(** **** Exercise: 1 star, standard (update_eq) *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (update_neq) *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars, standard, optional (baz_num_elts)\n\n    Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n(** How _many_ elements does the type [baz] have? (Explain in words,\n    in a comment.) *)\n\n(* FILL IN HERE *)\n\n(** [] *)\n\n(* 2022-08-08 17:13 *)\n", "meta": {"author": "snu-sf-class", "repo": "sf202301", "sha": "6378c120704e36a193e82db888cee8ad1b1cafa3", "save_path": "github-repos/coq/snu-sf-class-sf202301", "path": "github-repos/coq/snu-sf-class-sf202301/sf202301-6378c120704e36a193e82db888cee8ad1b1cafa3/lecture/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.9196425284247979, "lm_q1q2_score": 0.8344029099325647}}
{"text": "Require Import Arith.\n\n(** [sum_cubes_to n] is [0*0*0 + 1*1*1 + ... + n*n*n]. **)\nFixpoint sum_cubes_to (n: nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' => n * n * n + sum_cubes_to (n')\n  end.\n\n(** [sum_to n] is [0 + 1 + ... + n]. **)\nFixpoint sum_to (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S n' => n + sum_to (n')\n  end.\n\n(* Other lemmas and theorems. *)\nLemma add_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n. induction n as [ | n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nLemma plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nLemma add_comm : forall n p : nat,\n  n + p = p + n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - simpl. rewrite -> add_0_r. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n\nLemma 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  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed. \n\nLemma add_0_l: forall n: nat, 0 + n = n.\nProof.\n  intro n.\n  rewrite add_comm. rewrite add_0_r. reflexivity.\nQed.\n\nLemma add_assoc2: forall n m p: nat,\n    n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - rewrite -> add_comm. rewrite -> add_0_r. rewrite -> add_0_l. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite IHn'. reflexivity.\nQed.\n\nLemma add_assoc3: forall n m p q: nat,\n    n + m + (p + q) = n + p + (m + q).\nProof.\n  intros n m p q.\n  induction n as [| n' IHn'].\n  - rewrite add_0_l. rewrite add_0_l. rewrite add_assoc2. reflexivity.\n  - simpl. inversion IHn'. reflexivity.\nQed.\n\nLemma mul_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nLemma break_bracket_r: forall n m p: nat,\n    n * (m + p) = n * m + n * p.\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite add_assoc3. reflexivity.\nQed.\n\nLemma nat_construct: forall n m: nat,\n    n + n * m = n * S m.\nProof.\n  intros n m.\n  induction n as [| n' IHn' ].\n  - rewrite add_0_l. reflexivity.\n  - simpl. rewrite add_assoc2. rewrite IHn'. reflexivity.\nQed.\n\nLemma break_bracket_l: forall n m p: nat,\n    n * (m + p) = m * n + p * n.\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - rewrite mul_0_r. rewrite mul_0_r. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite add_assoc3.\n    rewrite nat_construct. rewrite nat_construct.\n    reflexivity.\nQed.\n\nLemma plus_n_Sn'': forall n: nat,\n    n + 1 = S n.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. inversion IHn'. reflexivity.\nQed.\n\nLemma foil: forall n m p q: nat,\n    (n + m) * (p + q) = n * p + n * q + m * p + m * q.\nProof.\n  intros. ring. (* Better take an Abstract Algebra class after this. *)\nQed.\n(* I need to finish second_equality to finish this thing. *)\n\nLemma assocForFour: forall n m p q: nat,\n    n + m + p + q = n + p + m + q.\nProof.\n  intros n m p q.\n  ring.\nQed.\n\n\n(** The most important parts. **)\n\nLemma gauss_sum_integers: forall n: nat,\n    2 * sum_to n = n * (n + 1).\nProof.\n  (* IHn': Induction hypothesis n = k. *)\n  induction n as [| n' IHn'].\n  - (* Base case: n = 0 *) simpl. reflexivity.\n  - (* Recursive case: n = k + 1 *)\n    unfold sum_to. fold sum_to.\n    rewrite break_bracket_r.\n    assert (H: S n' = n' + 1).\n    {rewrite plus_n_Sn''. reflexivity.}\n    rewrite H.\n    assert(H': n' + 1 + 1 = n' + 2).\n    {ring.}\n    rewrite H'.\n    rewrite foil.\n    rewrite assocForFour.\n    rewrite <- break_bracket_l.\n    assert(H'': 2 * (n' + 1) = n' * 2 + 1 * 2).\n    {rewrite <- break_bracket_l. reflexivity.}\n    rewrite H''.\n    rewrite IHn'.\n    rewrite add_comm.\n    ring.\nQed.\n\nTheorem sum_cubes: forall n: nat, \n    sum_cubes_to n = sum_to n * sum_to n.\nProof.\n    (* IHn': Induction hypothesis n = k. *)\n    induction n as [|n' IHn'].\n    - (* Base case: n = 0 *) simpl. reflexivity.\n    - (* Recursive case: n = k + 1 *)\n    unfold sum_cubes_to. unfold sum_to. \n    fold sum_cubes_to. fold sum_to.\n    rewrite IHn'. rewrite foil.\n    assert(H: S n' * S n' +  S n' * sum_to n' + sum_to n' * S n'\n              = S n' * S n' + S n' * (sum_to n' + sum_to n')).\n    {ring.}\n    rewrite H.\n    assert(H': sum_to n' + sum_to n' = 2 * sum_to n').\n    {simpl. rewrite add_0_r. reflexivity.}\n    rewrite H'.\n    rewrite gauss_sum_integers.\n    rewrite plus_n_Sn''.\n    assert (mult_comm: S n' * (n' * S n') = S n' * S n' * n').\n    {ring.}\n    rewrite mult_comm.\n    assert (mult_iden: S n' * S n' + S n' * S n' * n' = S n' * S n' * (n' + 1)).\n    {simpl. ring.}\n    rewrite mult_iden.\n    rewrite plus_n_Sn''.\n    reflexivity.\nQed.\n", "meta": {"author": "SilverArmKnight", "repo": "PLP", "sha": "6a0b1fa3815f70ed4546f1291bd13fa892bd761b", "save_path": "github-repos/coq/SilverArmKnight-PLP", "path": "github-repos/coq/SilverArmKnight-PLP/PLP-6a0b1fa3815f70ed4546f1291bd13fa892bd761b/Final Project/finalProject.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.9073122163480667, "lm_q1q2_score": 0.8344029092056514}}
{"text": "(** -> \u3092\u542b\u3080\u8a3c\u660e *)\nModule Section4.\n\nSection imp_sample.\nVariables P Q R:Prop.\nTheorem imp_sample : (P -> (Q -> R)) -> (P -> Q) -> P -> R.\nProof.\n  (* \u6700\u521d\u306f intro(s) \u3057\u3066\u30b4\u30fc\u30eb\u306e -> \u3092\u7121\u304f\u3059 *)\n  intros pqr pq p.\n  (* \u30b4\u30fc\u30eb\u306e R \u3092\u5f97\u3089\u308c\u305d\u3046\u306a\u306e\u306f pqr *)\n  apply pqr.\n    (* \u30b4\u30fc\u30eb = P. \u305d\u306e\u307e\u307e\u306e\u4eee\u5b9a\u304c\u3042\u308c\u3070 assumption *)\n    assumption.\n    (* \u30b4\u30fc\u30eb = Q. pq \u3092\u4f7f\u3048\u3070 Q \u304c\u5f97\u3089\u308c\u305d\u3046 *)\n    apply pq.  assumption.\nQed.\n\n(** 4.2 /\\ \u3092\u542b\u3080\u8a3c\u660e *)\nTheorem and_assoc : (P/\\Q)/\\R -> P/\\(Q/\\R).\nProof.\n  intro pqr.\n  (* (P/\\Q)/\\R \u3092\u5206\u89e3\u3059\u308b *)\n  destruct pqr as [[p q] r].\n  (* \u30b4\u30fc\u30eb\u306e P/\\(Q/\\R) \u3092 P \u3068 Q/\\R \u306b\u5206\u89e3 *)\n  split.\n    (* \u30b4\u30fc\u30eb P *)\n    assumption.\n    (* \u30b4\u30fc\u30eb Q /\\ R\u3002 split. assumption. assumption. \u3067\u3082 OK *)\n    split; assumption.\nQed.\n\n(** 4.3 \\/ \u3092\u542b\u3080\u8a3c\u660e *)\nTheorem or_assoc : (P\\/Q)\\/R -> P\\/(Q\\/R).\nProof.\n  intro pqr.\n  (* (P\\/Q)\\/R \u3092\u5206\u89e3\u3059\u308b *)\n  destruct pqr as [[p|q]|r].\n    (* \u4eee\u5b9a p:P *)\n    left. assumption.\n    (* \u4eee\u5b9a q:Q *)\n    right. left. assumption.\n    (* \u4eee\u5b9a r:R *)\n    right; right.  assumption.\nQed.\n\n(** 4.4 ~\u3092\u542b\u3080\u8a3c\u660e *)\nPrint False.\n\nTheorem neg_sample : ~(P /\\ ~P).\nProof.\n  (* ~\u3067\u59cb\u307e\u308b\u30b4\u30fc\u30eb\u306f intro *)\n  intro.\n  destruct H as [p np].\n  (* \u30b4\u30fc\u30eb\u304c False \u306a\u3089 ~\u3067\u59cb\u307e\u308b\u4eee\u5b9a\u3092 elim *)\n  elim np.\n  assumption.\nQed.\n\nEnd imp_sample.\n(** \u8ab2\u984c\uff14\uff1a\u547d\u984c\u8ad6\u7406\u306e\u8a3c\u660e *)\n(* \u8a3c\u660e\u305b\u3088 *)\nSection Ex4.\nVariable A B C D:Prop. \nTheorem ex4_1 : (A -> C) /\\ (B -> D) /\\ A /\\ B -> C /\\ D. \nProof.\n  intro H.\n  destruct H as [ac [bd [a b]]].\n  split.\n    apply ac. assumption.\n    apply bd. assumption.\nQed.\n\nTheorem ex4_2 : ~~~A -> ~A. \nProof.\n  intro nnna.\n  intro a.\n  elim nnna.\n  intro na.\n  elim na.\n  assumption.\nQed.\n\nTheorem ex4_3 : (A -> B) -> ~B -> ~A. \nProof.\n  intros ab nb.\n  intro a.\n  elim nb.\n  apply ab.\n  assumption.\nQed.\n\nTheorem ex4_4 : ((((A -> B) -> A) -> A) -> B) -> B. \nProof.\n  intro H.\n  apply H.\n  intro H1.\n  apply H1.\n  intro a.\n  apply H.\n  intro H2.\n  assumption.\nQed.\n\nTheorem ex4_5 : ~~(A\\/~A).\nProof.\n  intro H.\n  elim H.\n  right.\n  intro a.\n  elim H.\n  left.\n  assumption.\nQed.\n\nEnd Ex4.\nEnd Section4.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120202/tutorial3_ans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.9207896693699845, "lm_q1q2_score": 0.8342260741752356}}
{"text": "Require Import Arith.\n\nFixpoint div3 (n:nat): nat :=\n  match n with 0 => 0 | 1 => 0 | 2 => 0 |\n               (S (S (S p))) => (S (div3 p))\n          end.\n\nSection div3_proof.\n Let P (n:nat) := div3 n <= n.\n\n Remark P_ok : forall n : nat, P n /\\ P (S n) /\\ P (S (S n)).\n Proof.\n  simple induction n.\n  unfold P; simpl ; auto.\n  intros n0 [H1 [H2 H3]].\n  repeat split; auto.\n  unfold P; simpl; auto with arith.\nQed.\n\n Lemma div3_le : forall n : nat, div3 n <= n.\n Proof.\n  intro n; case (P_ok n); auto.\n Qed.\n\nEnd div3_proof.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/progav/SRC/div3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8339635708994494}}
{"text": "Theorem mul_0_r :\n  forall (n : nat), n * 0 = 0.\nintros.\ninduction n as [| n' IHn'].\n- reflexivity.\n- simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem plus_n_Sm :\n  forall (n m : nat), S (n + m) = n + S m.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.  (* TODO: what happened here?! *)\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem plus_n_0 :\n  forall (n : nat), n + 0 = n.\nintros.\ninduction n as [|n' IHn'].\n- unfold \"+\".\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nLemma plus_S :\n  forall (m n : nat), S (m + n) = m + S n.\nintros.\ninduction m as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nTheorem add_comm :\n  forall (n m : nat), n + m = m + n.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  rewrite -> plus_n_0.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  rewrite <- plus_S.\n  reflexivity.\nQed.\n\nTheorem add_assoc :\n  forall (n m p : nat),\n  (n + m) + p = n + (m + p).\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nFixpoint double (n : nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall (n : nat), double n = n + n.\nintros.\ninduction n as [|n' IHn'].\n- (* n = 0 *)\n  reflexivity.\n- (* n = S n' *)\n  simpl.\n  rewrite IHn'.\n  rewrite -> plus_S.\n  reflexivity.\nQed.\n\nFixpoint even (n : nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => even n'\n  end.\n\nTheorem even_S :\n  forall (n : nat), even (S n) = negb (even n).\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\nAdmitted.\n\n(*\nTheorem: For any natural n and m,\n  n + m = m + n.\nProof: By unduction on n.\n* First suppose n = 0. We must show that\n    0 + m = m + 0.\nThis follows directly from definition of + (?!).\n* Next, suppose n = S n' and\n  n' + m = m + n'.\nWe must show that\n  S n' + m = m + S n'.\nFollowing definition of +, we can rewrite LHS as\n  S (n' + m)\nwhich, according to inductive hypothesis, is the same as\n  S (m + n')\nwhich, as prooved in preceeding lemma, can be rewritten as\n  m + S n'.\nWe thus have a trivial equality.\nQed.\n*)\n\nTheorem add_shuffle3 :\n  forall (n m p : nat), n + (m + p) = m + (n + p).\nProof.\nintros.\nassert (n + (m + p) = (m + p) + n) as H.\n- rewrite add_comm.\n  reflexivity.\n- rewrite H.\n  rewrite add_assoc.\n  assert (H1: n + p = p + n).\n  + rewrite add_comm. reflexivity.\n  + rewrite H1. reflexivity.\nQed.\n\nLemma mult_0:\n  forall (n : nat), n * 0 = 0.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nLemma add_0:\n  forall (n : nat), n + 0 = n.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nLemma mult_S_lhs:\n  forall (n m : nat), S n * m = n * m + m.\nProof.\nintros.\ndestruct n.\n- simpl.\n  rewrite -> add_0.\n  reflexivity.\n- simpl.\n  rewrite add_assoc.\n  assert (H: m + n * m = n * m + m).\n  + rewrite add_comm.\n    reflexivity.\n  + rewrite H.\n    reflexivity.\nQed.\n\nLemma mult_S_rhs:\n  forall (n m : nat), n * S m = n + n * m.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  rewrite add_shuffle3.\n  reflexivity.\nQed.\n\nTheorem mul_comm:\n  forall (n m : nat), n * m = m * n.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  rewrite -> mult_0.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  rewrite mult_S_rhs.\n  reflexivity.\nQed.\n\nFixpoint leb (n m : nat) : bool :=\n  match n, m with\n  | O, _       => true\n  | _, O       => false\n  | S n', S m' => leb n' m'\n  end.\n\nCheck leb.\n\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nTheorem leb_refl :\n  forall (n : nat), n <=? n = true.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | O, O       => true\n  | S n', S m' => eqb n' m'\n  | _, _       => false\n  end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n\nTheorem zero_negb_S :\n  forall (n : nat),\n  0 =? (S n) = false.\nProof.\nintros.\nunfold \"=?\".\nreflexivity.\nQed.\n\nDefinition andb (a b : bool) : bool :=\n  match a, b with\n  | false, _ => false\n  | _, false => false\n  | _, _     => true\n  end.\n\nTheorem andb_false_r :\n  forall (b : bool), andb b false = false.\nProof.\nintros.\ndestruct b; unfold andb; reflexivity.\nQed.\n\nTheorem plus_leb_compat_l :\n  forall (n m p : nat), n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\nintros.\ninduction p as [|p' IHp']; simpl; assumption.\nQed.\n\nTheorem S_neqb_0 :\n  forall (n : nat), S n =? 0 = false.\nProof.\nintros.\nunfold \"=?\".\nreflexivity.\nQed.\n\nTheorem mult_1_1 :\n  forall (n : nat), 1 * n = n.\nProof.\nintros.\nunfold \"*\".\nrewrite plus_n_0.\nreflexivity.\nQed.\n\nTheorem all3_spec :\n  forall (b c : bool),\n  orb\n    (andb b c)\n    (orb (negb b)\n         (negb c))\n  = true.\nProof.\nintros.\ndestruct c; destruct b; unfold andb; unfold negb; unfold orb; reflexivity.\nQed.\n\nTheorem mult_plus_distr_r :\n  forall (n m p : nat),\n  (n + m) * p = n * p + m * p.\nProof.\nintros.\ninduction p as [|p' IHp'].\nAdmitted. (* Too boring ... *)\n\nTheorem mult_assoc :\n  forall (n m p : nat), n * (m * p) = (n * m) * p.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- rewrite mult_S_lhs.\n  rewrite mult_S_lhs.\n  rewrite IHn'.\n  rewrite -> mult_plus_distr_r.\n  reflexivity.\nQed.\n\nTheorem eqb_refl :\n  forall (n : nat), n =? n = true.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- unfold \"=?\".\n  reflexivity.\n- simpl. (* TODO: what happens here ?! *)\n  assumption.\nQed.\n\nTheorem add_shuffle3' :\n  forall (n m p : nat), n + (m + p) = m + (n + p).\nProof.\nintros.\nreplace (n + (m + p)) with ((m + p) + n).\n- rewrite add_assoc.\n  replace (p + n) with (n + p); rewrite add_comm; reflexivity.\n- rewrite add_comm.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | Z\n  | B_0 (n : bin)\n  | B_1 (n : bin).\n\nFixpoint incr (m : bin) : bin :=\n  match m with\n  | Z      => B_1 Z\n  | B_0 m' => B_1 m'\n  | B_1 m' => B_0 (incr m')\n  end.\n\nFixpoint bin2nat (m : bin) : nat :=\n  match m with\n  | Z      => O\n  | B_0 m' => 2 * bin2nat m'\n  | B_1 m' => 2 * bin2nat m' + 1\n  end.\n\nLemma plus_1_is_S :\n  forall (n : nat),\n  n + 1 = S n.\nProof.\nintros.\nrewrite add_comm.\nunfold \"+\".\nreflexivity.\nQed.\n\nTheorem binary_commute :\n  forall (b : bin), bin2nat (incr b) = S (bin2nat b).\nProof.\nintros.\ninduction b.\n- simpl.\n  reflexivity.\n- unfold incr.\n  simpl.\n  rewrite plus_1_is_S.\n  reflexivity.\n- simpl.\n  rewrite IHb.\n  simpl.\n  rewrite add_0.\n  replace (S (bin2nat b)) with (bin2nat b + 1).\n  + rewrite add_assoc.\n    reflexivity.\n  + rewrite plus_1_is_S.\n    reflexivity.\nQed.\n\n(* TODO: binary inverse *)", "meta": {"author": "yugr", "repo": "Lalambda", "sha": "0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7", "save_path": "github-repos/coq/yugr-Lalambda", "path": "github-repos/coq/yugr-Lalambda/Lalambda-0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7/21/Coq/LF/02_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8962513807543222, "lm_q1q2_score": 0.8339244996775356}}
{"text": "Require Import Arith fib_ind.\n\n\n(* A generalisation of the fibonacci sequence, parameterized by\n   its two first items *)\n\nFixpoint general_fib (a0 a1 n:nat) {struct n} : nat :=\n  match n with\n  | O => a0\n  | S p => general_fib a1 (a0 + a1) p\n  end.\n\nDefinition fib_tail (n:nat) := general_fib 1 1 n.\n\n\n(** Test : should return 89\n\nCompute fib_tail 10.\n\n*)\n\n\nLemma general_fib_1 : forall a b:nat, general_fib a b 1 = b.\nProof. reflexivity. Qed.\n\n\nLemma general_fib_S :\n forall a b n:nat, general_fib a b (S n) = general_fib b (a + b) n.\nProof. reflexivity. Qed. \n\n\nLemma general_fib_2 :\n forall a b n:nat,\n   general_fib a b (S (S n)) = general_fib a b n + general_fib a b (S n).\nProof.\n intros a b n; generalize a b; induction n as [ | n IHn].\n - reflexivity.\n - clear a b; intros a b.\n   rewrite (general_fib_S _ _ (S (S n))), IHn.\n   now rewrite (general_fib_S _ _  (S n)).\nQed.\n\nLemma linear_fibo_equiv : forall n:nat, fib_tail n = fib n.\nProof.\n intro n; induction n as [| | n IHn IHSn] using fib_ind.\n - reflexivity.  \n - reflexivity.  \n -  unfold fib_tail in *; rewrite general_fib_2.\n    rewrite IHn, IHSn; reflexivity.  \nQed.\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/ch9_function_specification/SRC/fib_tail.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.8338954414782987}}
{"text": "Require Import Recdef PeanoNat Lia.\n\n(* [Z] to 0, [L n] to 2n + 1, a [R n] to 2n + 2. *)\nInductive Nat : Type :=\n| Z : Nat\n| L : Nat -> Nat\n| R : Nat -> Nat.\n\nFunction succ (n : Nat) : Nat :=\nmatch n with\n| Z => L Z\n| L n' => R n'\n| R n' => L (succ n')\nend.\n\nFunction pred (n : Nat) : Nat :=\nmatch n with\n| Z => Z\n| L Z => Z\n| L n' => R (pred n')\n| R n' => L n'\nend.\n\nFunction add (n m : Nat) : Nat :=\nmatch n, m with\n| Z   , _    => m\n| _   , Z    => n\n| L n', L m' => R (add n' m')\n| L n', R m' => succ (R (add n' m'))\n| R n', L m' => succ (R (add n' m'))\n| R n', R m' => R (succ (add n' m'))\nend.\n\nFunction div2 (n : Nat) : Nat :=\nmatch n with\n| Z => Z\n| L n' => n'\n| R n' => succ n'\nend.\n\nFunction mul2 (n : Nat) : Nat :=\n  pred (L n).\n\nFunction mul (n m : Nat) : Nat :=\nmatch n with\n| Z    => Z\n| L n' => add (mul2 (mul n' m)) m\n| R n' => mul2 (add (mul n' m) m)\nend.\n\nFunction sub (n m : Nat) : Nat :=\nmatch n, m with\n| Z   , _    => Z\n| _   , Z    => n\n| L n', L m' => mul2 (sub n' m')\n| L n', R m' => pred (mul2 (sub n' m'))\n| R n', L m' => succ (mul2 (sub n' m'))\n| R n', R m' => mul2 (sub n' m')\nend.\n\nFunction le (n m : Nat) : bool :=\nmatch n, m with\n| Z   , _    => true\n| _   , Z    => false\n| L n', L m' => le n' m'\n| L n', R m' => le n' m'\n| R n', L m' => false (* 2n <= 2m -1 *)\n| R n', R m' => le n' m'\nend.\n\nDefinition L' (n : nat) : nat :=\n  1 + 2 * n.\n\nDefinition R' (n : nat) : nat :=\n  2 + 2 * n.\n\nFunction fromNat (n : Nat) : nat :=\nmatch n with\n| Z => 0\n| L n' => L' (fromNat n')\n| R n' => R' (fromNat n')\nend.\n\nFunction toNat (n : nat) : Nat :=\nmatch n with\n| 0 => Z\n| S n' => succ (toNat n')\nend.\n\nCompute fromNat (L (L (L (L Z)))).\nCompute fromNat (R (R (R (R Z)))).\nCompute fromNat (R (R (L (R Z)))).\n\nCompute fromNat (succ (L (L (L (L Z))))).\nCompute fromNat (succ (R (R (R (R Z))))).\nCompute fromNat (succ (R (R (L (R Z))))).\n\nCompute fromNat (pred (L (L (L (L Z))))).\nCompute fromNat (pred (R (R (R (R Z))))).\nCompute fromNat (pred (R (R (L (R Z))))).\n\nCompute fromNat (div2 (L (L (L (L Z))))).\nCompute fromNat (div2 (R (R (R (R Z))))).\nCompute fromNat (div2 (R (R (L (R Z))))).\n\nCompute fromNat (mul2 (L (L (L (L Z))))).\nCompute fromNat (mul2 (R (R (R (R Z))))).\nCompute fromNat (mul2 (R (R (L (R Z))))).\n\nLemma pred_succ :\n  forall n : Nat,\n    pred (succ n) = n.\nProof.\n  intros n; functional induction (succ n); cbn.\n  1-2: reflexivity.\n  rewrite IHn0; clear IHn0.\n  destruct n'; cbn; reflexivity.\nQed.\n\nLemma div2_mul2 :\n  forall n : Nat,\n    div2 (mul2 n) = n.\nProof.\n  intros n; functional induction (mul2 n); cbn.\n  induction n as [| n' | n']; cbn.\n  1, 3: reflexivity.\n  rewrite <- IHn' at 2.\n  destruct n'; cbn in *; reflexivity.\nQed.\n\nLemma fromNat_succ :\n  forall n : Nat,\n    fromNat (succ n) = S (fromNat n).\nProof.\n  intros n; functional induction (fromNat n); cbn; lia.\nQed.\n\nLemma fromNat_toNat :\n  forall n : nat,\n    fromNat (toNat n) = n.\nProof.\n  intros n; functional induction (toNat n); cbn.\n  - reflexivity.\n  - rewrite fromNat_succ, IHn0. reflexivity.\nQed.\n\nLemma L'_S :\n  forall n : nat,\n    L' (S n) = 2 + L' n.\nProof.\n  intros; cbn; lia.\nQed.\n\nLemma R'_S :\n  forall n : nat,\n    R' (S n) = 3 + L' n.\nProof.\n  intros; cbn; lia.\nQed.\n\nLemma toNat_L' :\n  forall n : nat,\n    toNat (L' n) = L (toNat n).\nProof.\n  induction n as [| n'].\n  - reflexivity.\n  - rewrite L'_S.\n    change (toNat (2 + _)) with (succ (succ (toNat (L' n')))).\n    rewrite IHn'; cbn. reflexivity.\nQed.\n\nLemma toNat_R' :\n  forall n : nat,\n    toNat (R' n) = R (toNat n).\nProof.\n  induction n as [| n'].\n  - reflexivity.\n  - rewrite R'_S.\n    change (toNat (3 + _)) with (succ (succ (toNat (R' n')))).\n    rewrite IHn'; cbn. reflexivity.\nQed.\n\nLemma toNat_fromNat :\n  forall n : Nat,\n    toNat (fromNat n) = n.\nProof.\n  intros n; functional induction (fromNat n).\n  - reflexivity.\n  - rewrite toNat_L', IHn0. reflexivity.\n  - rewrite toNat_R', IHn0. reflexivity.\nQed.\n\nLemma add_Z_l :\n  forall n : Nat,\n    add Z n = n.\nProof. reflexivity. Qed.\n\nLemma add_Z_r :\n  forall n : Nat,\n    add n Z = n.\nProof.\n  intros []; reflexivity.\nQed.\n\nLemma add_succ_l :\n  forall n m : Nat,\n    add (succ n) m = succ (add n m).\nProof.\n  intros n m; functional induction (add n m)\n  ; cbn; rewrite ?IHn0.\n  3-6: reflexivity.\n  - destruct m; reflexivity.\n  - destruct n; reflexivity.\nQed.\n\nLemma add_succ_r :\n  forall n m : Nat,\n    add n (succ m) = succ (add n m).\nProof.\n  intros n m; functional induction (add n m)\n  ; cbn; rewrite ?IHn0.\n  3-6: reflexivity.\n  - destruct m; reflexivity.\n  - destruct n; cbn; rewrite ?add_Z_r; reflexivity.\nQed.\n\nLemma add_comm :\n  forall n m : Nat,\n    add n m = add m n.\nProof.\n  intros n m; functional induction (add n m)\n  ; cbn; rewrite ?add_Z_r, ?IHn0; reflexivity.\nQed.\n\nLemma add_assoc :\n  forall a b c : Nat,\n    add (add a b) c = add a (add b c).\nProof.\n  intros a b.\n  functional induction (add a b); cbn; intros.\n  1-2: reflexivity.\n  all: destruct c; cbn; rewrite ?add_succ_l, ?add_succ_r, ?IHn; reflexivity.\nQed.\n\nLemma mul_Z_l :\n  forall n : Nat,\n    mul Z n = Z.\nProof. reflexivity. Qed.\n\nLemma mul_Z_r :\n  forall n : Nat,\n    mul n Z = Z.\nProof.\n  induction n as [| n' IH | n' IH]; cbn.\n  - reflexivity.\n  - rewrite IH; cbn. reflexivity.\n  - rewrite IH; cbn. reflexivity.\nQed.\n\nLemma fromNat_add :\n  forall n m : Nat,\n    fromNat (add n m) = fromNat n + fromNat m.\nProof.\n  intros n m; functional induction (add n m)\n  ; cbn; rewrite ?fromNat_succ; lia.\nQed.\n\nLemma fromNat_pred :\n  forall n : Nat,\n    fromNat (pred n) = fromNat n - 1.\nProof.\n  intros n; functional induction (pred n); simpl.\n  1-2: reflexivity.\n  - rewrite IHn0. destruct n'; cbn; lia.\n  - unfold L'. lia.\nQed.\n\nLemma fromNat_mul2 :\n  forall n : Nat,\n    fromNat (mul2 n) = 2 * fromNat n.\nProof.\n  intros n; unfold mul2.\n  rewrite fromNat_pred.\n  cbn; lia.\nQed.\n\nLemma fromNat_mul :\n  forall n m : Nat,\n    fromNat (mul n m) = fromNat n * fromNat m.\nProof.\n  intros n m; functional induction (mul n m); simpl.\n  - reflexivity.\n  - rewrite fromNat_add, fromNat_mul2, IHn0. lia.\n  - rewrite fromNat_mul2, fromNat_add, IHn0. lia.\nQed.\n\nLemma mul_L_r :\n  forall n m : Nat,\n    mul n (L m) = add (mul2 (mul m n)) n.\nProof.\n  induction n as [| n' IH | n' IH]; simpl; intros m.\n  - rewrite mul_Z_r; cbn; reflexivity.\nAdmitted.\n\nLemma mul_R_r :\n  forall n m : Nat,\n    mul n (R m) = mul2 (add (mul m n) n).\nProof.\n  induction n as [| n' IH | n' IH]; simpl; intros m.\n  - rewrite mul_Z_r; cbn; reflexivity.\nAdmitted.\n\nLemma mul_comm :\n  forall n m : Nat,\n    mul n m = mul m n.\nProof.\n  intros n m.\n  rewrite <- toNat_fromNat, fromNat_mul, Nat.mul_comm, <- fromNat_mul, toNat_fromNat.\n  reflexivity.\nQed.\n\nLemma fromNat_L :\n  forall n : Nat,\n    fromNat (L n) = L' (fromNat n).\nProof. reflexivity. Qed.\n\nLemma fromNat_R :\n  forall n : Nat,\n    fromNat (R n) = R' (fromNat n).\nProof. reflexivity. Qed.\n\nLemma fromNat_sub :\n  forall n m : Nat,\n    fromNat (sub n m) = fromNat n - fromNat m.\nProof.\n  intros n m; functional induction (sub n m)\n  ; rewrite ?fromNat_L, ?fromNat_R, ?fromNat_succ, ?fromNat_pred, ?fromNat_mul2, ?IHn0\n  ; unfold L', R'.\n  1-4, 6: cbn; lia.\nAdmitted.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Num/WeirdBinaryNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8872045929715078, "lm_q1q2_score": 0.833895440960856}}
{"text": "Require Import Arith.\nRequire Import ZArith.\n\nParameters (prime_divisor : nat -> nat)\n           (prime : nat -> Prop)\n           (divides : nat -> nat -> Prop).\n\nOpen Scope nat_scope.\n\nCheck (prime (prime_divisor 220)).\n\nCheck (divides (prime_divisor 220) 220).\n\nCheck (divides 3).\n\n\n(* Parameterized Data Types *)\n\nParameter binary_word : nat -> Set.\n\nDefinition short : Set := binary_word 32.\n\nDefinition long : Set := binary_word 64.\n\n(* Exercise 4.1 *)\nCheck ((nat -> nat) -> Prop). (* Compare if two naturals are equal *)\nCheck ((nat -> nat) -> (nat -> nat) -> Prop). (* Compare if two functions are\nequal *)\nCheck (nat -> nat -> Set). (* Given two naturals m and n, return the type of\nan m x n matrix *)\n\nPrint not.\n\nRequire Import List.\n\nParameters (decomp : nat -> list nat) (decomp2 : nat -> nat * nat).\n\nCheck (decomp 220).\nCheck (decomp2 284).\n\nCheck @cons.\nCheck @pair.\nCheck @fst.\n\nCheck le_n.\nCheck le_S.\n\nCheck (le_n 36).\n\n\n(* Definition of Polymorphic Functions *)\n\nDefinition twice : forall A : Set, (A -> A) -> A -> A :=\n  fun A f a => f (f a).\n\nCheck (twice Z).\n\nCheck (twice Z (fun z => (z*z)%Z)).\n\nCheck (twice _ S 56).\n\nCheck (twice (nat -> nat) (fun f x => f (f x)) (mult 3)).\n\nEval compute in\n  (twice (nat -> nat) (fun f x => f (f x)) (mult 3) 1).\n\n\n(* Proofs - Curry-Howard isomorphism *)\nTheorem le_i_SSi : forall i : nat, i <= S (S i).\nProof (fun i : nat => le_S _ _ (le_S _ _ (le_n i))).\n\n\n(* Expressive power of the Dependent Product *)\n\n(* Exercise 4.3 *)\nSection A_declared.\n  Variables (A : Set) (P Q : A -> Prop) (R : A -> A -> Prop).\n\n  Theorem all_perm : (forall a b : A, R a b) -> forall a b : A, R b a.\n  Proof (fun (H : forall a b : A, R a b) (a b : A) => H b a).\n\n  Theorem all_imp_dist :\n    (forall a : A, P a -> Q a) -> (forall a : A, P a) -> forall a : A, Q a.\n  Proof (fun (H : forall a : A, P a -> Q a)\n             (H' : forall a : A, P a)\n             (a : A) => H a (H' a)).\n\n  Theorem all_delta : (forall a b : A, R a b) -> forall a : A, R a a.\n  Proof (fun (H : forall a b : A, R a b)\n             (a : A) => H a a).\n\nEnd A_declared.\n\n(* Exercise 4.4 *)\nTheorem id : forall A : Set, A -> A.\nProof (fun (A : Set) (a : A) => a).\nPrint id.\n\nTheorem diag : forall A B : Set, (A -> A -> B) -> A -> B.\nProof (fun (A B : Set) (f : A -> A -> B) (a : A) => (f a) a).\nPrint diag.\n\nTheorem permute : forall A B C : Set, (A -> B -> C) -> B -> A -> C.\nProof (fun (A B C : Set) (f : A -> B -> C) (b : B) (a : A) => f a b).\nPrint permute.\n\nTheorem f_nat_Z : forall A : Set, (nat -> A) -> Z -> A.\nProof (fun (A : Set) (f : nat -> A) (z : Z) => f (Zabs_nat z)).\nPrint f_nat_Z.\n\n(* Exercise 4.5 *)\nTheorem 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 (fun (A : Type)\n      (P : A -> A -> Prop)\n      (H : forall x y : A, P x y) (x y : A) => H y x).\nPrint all_perm'.\n\nTheorem resolution :\n  forall (A : Type) (P Q R S : A -> Prop),\n  (forall a : A, Q a -> R a -> S a) ->\n  (forall b : A, P b -> Q b) ->\n  (forall c : A, P c -> R c -> S c).\nProof.\n  intros A P Q R S H H' c HPc HRc.\n  apply H; [apply H'; assumption | assumption].\nQed.\nPrint resolution.\n\n\n(* Equality in the Coq System *)\n\nCheck @eq.\nCheck @refl_equal.\n\nTheorem ThirtySix : 9*4 = 6*6.\nProof (refl_equal 36).\n\nCheck eq_sym.\nPrint eq_sym.\n\nTheorem eq_sym' : forall (A : Type) (x y : A), x = y -> y = x.\nProof.\n  intros A x y H.\n  rewrite H. reflexivity.\nQed.\n\nPrint eq_sym'.\n\nPrint and.\nPrint or.\n", "meta": {"author": "vishallama", "repo": "interactive_theorem_proving_and_program_development", "sha": "147498230e5f2d1791f41c37b8b6c37c8ec4aa37", "save_path": "github-repos/coq/vishallama-interactive_theorem_proving_and_program_development", "path": "github-repos/coq/vishallama-interactive_theorem_proving_and_program_development/interactive_theorem_proving_and_program_development-147498230e5f2d1791f41c37b8b6c37c8ec4aa37/src/chap04-dependent-products/Chapter04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8991213772699435, "lm_q1q2_score": 0.8338121581965029}}
{"text": "(*\n   \u518d\u5e30\u95a2\u6570\u3068 CPS \u3068\u306e\u7b49\u4fa1\u6027\u306e\u8a3c\u660e\u3002\u5358\u7d14\u7248\n   \uff08\u3072\u3068\u3064\u524d\u306e\u5024\u3060\u3051\u3092\u4f7f\u3046\u518d\u5e30\u306b\u306f\u3001\u540c\u3058\u30d5\u30ec\u30fc\u30e0\u30ef\u30fc\u30af\u3067\n   \u5bfe\u5fdc\u3067\u304d\u308b\u304c\u3001fib\u306f\u4e0d\u5b8c\u5168\u3067\u3042\u308b\uff09\n   2010_10_30\n   *)\n\n\nInductive tree : Set :=\n| leaf : tree \n| node : tree->tree->tree.\nEval cbv in node (node leaf leaf) (node leaf leaf).\n\n\n(* \u518d\u5e30\u7248 *)\nFixpoint leaf_count (t : tree) : nat :=\n  match t with\n    | leaf => 1\n    | node r l => (leaf_count r) + (leaf_count l)\n  end.\nEval cbv in leaf_count (node (node leaf leaf) (node leaf leaf)). (* 4 *)\n\n\n(* CPS\u7248 *)\nFixpoint leaf_count_cps (t : tree) (cont : nat -> nat) : nat :=\n  match t with\n    | node r l =>\n      leaf_count_cps r\n      (fun n => leaf_count_cps l\n        (fun m => cont (n + m)))\n    | leaf =>\n      cont 1\n  end.\nEval cbv in leaf_count_cps (node (node leaf leaf) (node leaf leaf)) (fun n => n). (* 4 *)\nEval cbv in leaf_count_cps (node (node (node leaf leaf) (node leaf leaf))\n  (node leaf (node leaf leaf))) (fun n => n). (* 7 *)\n\n\nEval cbv in leaf_count_cps (node leaf leaf) (fun (r:nat) => r).   (* 2 *)\nEval cbv in leaf_count_cps leaf\n  (fun (n1:nat) => leaf_count_cps leaf\n    (fun (n2:nat) => n1 + n2)).             (* 2 *)\n\n\nLemma leaf_count_cps_plus :\n  forall l r f,\n    leaf_count_cps (node l r) f =\n    leaf_count_cps l (fun n1:nat => leaf_count_cps r (fun n2:nat => f (n1 + n2))).\nProof.\n  intros.\n  simpl.\n  (* \u3053\u306eGoal\u306e\u5de6\u8fba\u304c\u53f3\u8fba\u3068\u304a\u306a\u3058\u306b\u306a\u308b\u3088\u3046\u306b\u3001\u5b9a\u7406\u3092\u7528\u610f\u3059\u308b\u306e\u3060\u3002*)\n  reflexivity.\nQed.\n\n\nTheorem eq_leaf_count_leaf_count_cps :\n  forall (t : tree),\n    (forall f, f (leaf_count t) = (leaf_count_cps t f)).\nProof.\n    induction t.\n    intros.\n    simpl.\n    reflexivity.\n    \n    intro f.\n    rewrite leaf_count_cps_plus.\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    simpl.\n    reflexivity.\nQed.\n\n\n\n\n(***************)\n(* List Length *)\n(***************)\nRequire Export List.\n\n\n(* \u518d\u5e30\u7248 *)\nFixpoint len (lst : list nat) :=\n   match lst with \n     | nil => 0\n     | hd :: tl => S (len tl)\n   end.\nEval cbv in len (1::2::3::4::nil).\n\n\n(* CPS\u7248 *)\nFixpoint len_cps (lst : list nat) (cont : nat -> nat) :=\n   match lst with \n     | nil => cont 0\n     | hd :: tl => len_cps tl (fun x => cont (S x))\n   end.\nEval cbv in len_cps (1::2::3::4::nil) (fun n:nat => n).\n\n\nLemma len_cps_Sn :\n  forall n l f,\n    len_cps (n::l) f =\n    len_cps l (fun (r:nat) => f (S r)).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem eq_len_len_cps :\n  forall (t : list nat),\n    (forall f, f (len t) = (len_cps t f)).\nProof.\n    induction t.\n    intros.\n    simpl.\n    reflexivity.\n    \n    intro f.\n    rewrite len_cps_Sn.\n    rewrite <- IHt.\n    simpl.\n    reflexivity.\nQed.\n\n\n(************)\n(* \u968e\u4e57     *)\n(************)\n\n\n(* \u968e\u4e57\u306e\u518d\u5e30\u7248 *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n    | 0 => 1\n    | (S n') => n * fact n'\n  end.\nEval cbv in fact 6.                         (* 720 *)\n\n\n(* CPS \u7248 *)\nFixpoint fact_cps (n : nat) (cont : nat -> nat) : nat :=\n  match n with\n    | 0 => cont 1\n    | (S n') => fact_cps n' (fun (a : nat) => cont (n * a))\n  end.\nEval cbv in fact_cps 6 (fun a => a).        (* 720 *)\n\n\nLemma fact_cps_Sn :\n  forall n f,\n    fact_cps (S n) f =\n    fact_cps n (fun (r:nat) => (f (S n * r))).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\n\n(* fact_cps_Sn \u306e\u5b9f\u9a13 *)\nEval cbv in fact_cps 6 (fun (r:nat) => r).  (* 720 *)\nEval cbv in fact_cps 5 (fun (r:nat) => (6 * r)). (* 720 *)\n\n\nTheorem eq_fact_fact_cps :\n  forall (n:nat),\n    (forall f, f (fact n) = fact_cps n f).\nProof.\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n    \n  intro f.\n  rewrite fact_cps_Sn.\n  rewrite <- IHn.\n  simpl.\n  reflexivity.\nQed.\n\n\n(******************)\n(* \u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u6570 *)\n(******************)\n\n\n(** \u666e\u901a\u306e\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u95a2\u6570\u306e\u5b9a\u7fa9 *)\nFixpoint fib (n: nat) : nat :=\n  match n with\n    | 0 => 1\n    | 1 => 1\n    | S (S m as sm) => fib sm + fib m\n  end.\n\n\n(** CPS\u5909\u63db\u3055\u308c\u305f\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u95a2\u6570\u306e\u5b9a\u7fa9 *)\nFixpoint fib_cps (n:nat) (cont:nat -> nat) : nat :=\n  match n with\n    | 0 =>  cont 1\n    | 1 =>  cont 1\n    | S (S m as sm) =>\n      fib_cps sm (fun r1 =>\n        fib_cps m (fun r2 => cont (r1 + r2)))\n  end.\n\n\nLemma fib_SSn : forall n, fib (S (S n)) = fib (S n) + fib n.\n  reflexivity.\nQed.\n\n\nLemma fib_cps_SSn :\n  forall n f,\n    fib_cps (S (S n)) f = fib_cps (S n) (fun r1 => fib_cps n (fun r2 => f (r1+r2))).\nProof.\n  reflexivity.\nQed.\n\n\nHypothesis eq_fib_fib_cps_SSn :             (* XXXX *)\n  forall n f,\n    f (fib (S (S n))) = fib_cps n (fun r2 : nat => f (fib (S n) + r2)).\n\n\nTheorem eq_fib_fib_cps :\n  forall n f, f (fib (S n)) = fib_cps (S n) f.\nProof.\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n    \n  intro f.\n  rewrite fib_cps_SSn.\n  rewrite <- IHn.\n  apply eq_fib_fib_cps_SSn.                 (* XXXX *)\nQed.\n\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_cps_simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.903294214513915, "lm_q1q2_score": 0.8337759368855386}}
{"text": "Section Nat.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nFixpoint plus (n : nat) (m : nat) :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\nCompute plus (S (S (S O))) (S (S O)).\nCompute plus (S (S (S O))) O.\nNotation \"x + y\" := (plus x y)\n  (at level 50, left associativity): nat_scope.\nCheck ((0 + 1) + 1).\n\nFixpoint mult (n : nat) (m : nat) :=\n  match n with\n    | O => O\n    | S n' => m + (mult n' m)\n  end.\nCompute mult 4 2.\n\nFixpoint eqb (n m : nat) :=\n  match n with\n  | O =>\n    match m with\n      | O => true\n      | S m' => false\n      end\n  | S n' =>\n    match m with\n      | O => false\n      | S m' => eqb n' m'\n      end\n  end.\nNotation \"x =? y\" := (eqb x y)\n  (at level 50, left associativity): nat_scope.\n\nFixpoint leb (n m : nat) :=\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.\nNotation \"x <=? y\" := (leb x y)\n  (at level 50, left associativity): nat_scope.\n\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem plus_n_0 : forall n:nat, n + 0 = n.\nProof.\n  induction n as [| n' IH].\n  - reflexivity.\n  - simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\nTheorem plus_id : forall n m : nat,\n  n = m -> n + n = m + m.\nProof.\n  intros n m H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_transitive: forall n m: nat, n + m = m + n.\nProof.\n  induction m as [|m' ihm].\n  - apply plus_n_0.\n  - give_up.\nAdmitted.\n\nTheorem mult_0_n : forall n : nat, 0 * n = 0.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem mult_n_0 : forall n : nat, n * 0 = 0.\nProof.\n  induction n as  [| n' IH].\n  - reflexivity.\n  - simpl.\n    apply IH.\nQed.\n\nTheorem mult_n_0_m_0 : forall n m : nat,\n  (n * 0) + (m * 0) = 0.\nProof.\n    intros n m.\n    rewrite (mult_n_0 n).\n    rewrite (mult_n_0 m).\n    reflexivity.\nQed.\n\nTheorem plus_q_neq_0_firsttry: forall n:nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n    - reflexivity.\n    - reflexivity.\nQed.\n\nEnd Nat.\n", "meta": {"author": "SnO2WMaN", "repo": "hello-coq", "sha": "bf30f5886c3954ffd456f00e7c5b6c622761c8f9", "save_path": "github-repos/coq/SnO2WMaN-hello-coq", "path": "github-repos/coq/SnO2WMaN-hello-coq/hello-coq-bf30f5886c3954ffd456f00e7c5b6c622761c8f9/src/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8807970826714613, "lm_q1q2_score": 0.8337595842518698}}
{"text": "(********************)\n\n(* The final goal of the exercise is to implement a dictionary (aka map).\n   We'll do this incrementally by defining auxiliary functions and testing them. *)\n\n\nRequire Import List.\nImport ListNotations. \n\n(* The mechanism of sections allows to modularize the proof in multiple ways.\n   We'll see its applications along the way. *)\nSection NatEq.\n\n  (* Implement a function that checks the equality of two natural numbers. \n     Use pattern matching and recursion. *)\n  Fixpoint nat_eq (x y: nat): bool :=\n    match (x,y) with\n    | (S x', S y') => nat_eq x' y'\n    | (O, O) => true\n    | (_, _) => false\n    end.\n  (*Admitted.*)\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* We're not _proving_ that our implementations are correct yet,\n     but we can still test them on some inputs. *)\n  (* Do not modify these test suits. *)\n  (* Try to understand the meaning of the 'nat_eq_tests' definition. *)\n  (* To do that, you may want to investigate the 'forallb': *)\n  Print forallb. \n  Let nat_eq_tests := forallb id\n                       [ nat_eq 0 0;\n                         negb (nat_eq 0 1);\n                         negb (nat_eq 10 0);\n                         nat_eq 10 10;\n                         negb (nat_eq 10 13) ].\n\n  (* Do not modify these '*_pass' definitions and proofs.  *)\n  (* If your implementations are correct, the execution of them should proceed, *)\n  (* otherwise an error should occur.  *)\n  Let nat_eq_tests_pass: nat_eq_tests = true.\n  Proof. tauto. Qed.\n\n  (* Now try to remove one of 'negb' in 'nat_eq_tests' definitions *)\n  (* and execute nat_eq_tests_pass. *)\n  (* Don't forget to restore the initial state of 'nat_eq_tests'. *)\n  \nEnd NatEq.\n\n(* The section hides 'Let' definitions. *)\nFail Print nat_eq_tests_pass. \nPrint nat_eq.\n\n\nSection Option. \n\n  (* A value of 'option' type instantiated with an arbitrary type A\n     contains either a value of the type A or a special value None. *)\n  Print option. \n  \n  (* Implement a function that checks if an optional actually contains a value. *)\n  (* Use 'if-then-else' syntax: *)\n  (* For a value 't' of an inductive type T with exactly two constructors T1 and T2, \n     an expression 'if t then X1 else X2' is equivalent to  \n     'match t with \n      | T1 => X1\n      | T2 => X2\n      end' *)\n  Definition has_some {A: Type} (o: option A) : bool :=\n    match o with\n    | (Some _) => true\n    | (Nona) => false\n    end.\n (* Replace the previous line with ':= (your implementation) . ' *)\n    \n  Let has_some_tests := forallb id\n                       [\n                         (* here A = nat is inferred because of (1: nat) *)\n                         has_some (Some 1);\n                       (* note that without an argument we can't automatically infer the type *)\n                         negb (has_some (@None nat));\n                         has_some (Some (@None bool))\n                       ].\n  \n  Let has_some_tests_pass: has_some_tests = true.\n  Proof. tauto. Qed.\n\n  (* Implement a function that compares two optional natural numbers. *)\n  (* Reuse the nat_eq you've defined before *)\n  Definition option_nat_eq (o1 o2: option nat) : bool :=\n    match (o1,o2) with\n    | (Some n1, Some n2) => nat_eq n1 n2\n    | (None, None) => true\n    | (_, _) => false\n    end.\n\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  Let option_nat_eq_tests := forallb id\n                                     [option_nat_eq None None;\n                                     negb (option_nat_eq (Some 5) None);\n                                     option_nat_eq (Some 5) (Some 5)\n                                     ]. \n\n  Let option_nat_eq_tests_pass: option_nat_eq_tests = true.\n  Proof. tauto. Qed.\n                                     \nEnd Option.\n\nSection FunUpd.\n  \n  (* A handy primitive we'll use below is the function update. *)\n  (* Essentially, we'd like to take a function and override its value on a single input. *)\n  (* Here we'll only concentrate on functions whose input type is nat, \n     but which are still polymorphic on the output type. *)\n  (* Implement the function update using if-then-else expression and nat_eq. *)\n  Definition upd {V: Type} (f: nat -> V) (x: nat) (y: V): nat -> V :=\n      fun n : nat => if (nat_eq x n) then y else (f n).\n\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  Let upd_tests := forallb id\n                           [\n                             nat_eq ((upd id 5 3) 5) 3;\n                             nat_eq ((upd (upd id 5 3) 5 7) 5) 7;\n                             nat_eq ((upd id 5 3) 123) 123;\n                             nat_eq ((upd (upd id 5 3) 7 10) 5) 3\n                           ].\n\n  Let upd_tests_pass: upd_tests = true.\n  Proof. tauto. Qed.\n\nEnd FunUpd.  \n\nSection NatDict.\n  (* Now we're ready to provide the first implementation of a dictionary. *)\n  (* We'll work with dictionaries whose keys are natural numbers \n     and values have an arbitrary (but uniform) type. *)\n  \n  (* Remember that in previous sections we had to specify arguments like '{A: Type}' to keep the definitions polymorphic. *)\n  (* Instead of repeating them, we can specify that a particular type is a common argument for all functions in this section. *)  \n  Context {V: Type}. \n\n  (* The first implementation of dictionary is based on partial functions. *)\n  (* Remember that in Coq all functions are total, \n     that is, the function should return a value for all inputs. *)\n  (* If we're to implement a dictionary with a total function, it wont' be clear\n     how to represent a missing value. *)\n  (* But the absence of a value is naturally represented with None, \n     while a value 'v' contained in a dictionary can be wrapped in 'Some v' *)\n  Definition nat_dict_fun := nat -> option V.\n  Print nat_dict_fun. (* Note that here V is fixed *)\n  \n  (* Implement a function that creates an empty dictionary *)\n  Definition new_dict' : nat_dict_fun\n  := fun n : nat => None.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement an insertion using the 'upd' construct. *)\n  Definition insert' (d: nat_dict_fun) (k: nat) (v: V) : nat_dict_fun := \n    upd d k (Some v).\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a deletion similarly. *)\n  Definition remove' (d: nat_dict_fun) (k: nat) : nat_dict_fun \n    := upd d k None.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a function that retrieves a value by key. *)\n  (* Note that here the usage of option as a return type \n     is not due to the partial function implementation,\n     but rather due to a common sense: \n     if a dictionary (with an arbitrary implementation) doesn't contain a value,\n     a retrieval method should somehow reflect it. *)\n  Definition get' (d: nat_dict_fun) (k: nat) : option V := d k.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement a function that checks the presence of a given key. *)\n  (* You can either reuse existing dict methods or write an independent implementation. *)\n  Definition contains' (d: nat_dict_fun) (k: nat): bool :=\n   match (get' d k) with\n   | None => false\n   | Some _ => true\n   end.\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \nEnd NatDict.\n\nSection NatDictTests.\n\n  Print nat_dict_fun. (* note that now nat_dict_fun is polymorphic on value type *)\n\n  (* To save some space we'll define common terms and reuse them\n     with 'let .. in ..' syntax. *)\n  Let tests :=\n    (* Note that we must specify the value type for an empty dictionary,\n       since there are no arguments which can be used to infer it *)\n    let new := @new_dict' nat in\n    let ins5 := insert' new 5 10 in\n    let ins5ins5 := insert' ins5 5 15 in\n    let ins5rm5 := remove' ins5 5 in\n    let ins5ins5rm5 := remove' ins5ins5 5 in\n    forallb id\n                       [ \n                         negb (contains' new 5);\n                         contains' ins5 5;\n                         contains' ins5ins5 5;\n                         negb (contains' ins5rm5 5);\n                         negb (contains' ins5ins5rm5 5);\n                         option_nat_eq (get' new 5) None;\n                         option_nat_eq (get' ins5 5) (Some 10);\n                         option_nat_eq (get' ins5ins5 5) (Some 15);\n                         option_nat_eq (get' ins5ins5rm5 5) None;\n                         option_nat_eq (get' ins5 3) None\n                       ].\n\n  Let nat_dict_fun_tests_pass: tests = true.\n  Proof. tauto. Qed.\n  \nEnd NatDictTests.\n\n\nSection NatDict'.\n  Context {V: Type}.\n  (* The other implementation of a dictionary is based on a list\n     that stores pairs of keys and values. *)\n  (* If there are multiple pairs with the same key, \n     the one closer to the list head is used. *)\n  \n  (* '*' in context of types means the product (aka pair) type. *)\n  Definition nat_dict_list := list (nat * V). \n\n  (* Since the functions below operate on list which is defined inductively, \n     some of them should also be inductively defined. *)\n  \n  (* Implement a function that creates an empty dictionary. *)\n  Definition new_dict'' : nat_dict_list := nil\n  .\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  (* Implement the insertion *)\n  Definition insert'' (d: nat_dict_list) (k: nat) (v: V) : nat_dict_list :=\n    cons (pair k v) d\n  .\n (* Replace the previous line with ':= (your implementation) . ' *)\n  \n  \n  (* Implement the deletion. *)\n  (* Mind the case when the list contain multple occurences of the same key. *)\n  (* You may find useful that a pattern to be matched can be complex: *)\n  (*    '(k, v) :: d'     destructs the list into the head and tail (named d')\n     and, additionally, destructs the head into the key 'k' and value 'v' *)  \n  Fixpoint remove'' (d: nat_dict_list) (k: nat) : nat_dict_list :=\n  match d with\n  | nil => nil\n  | cons h t => \n    if (nat_eq k (fst h))\n      then remove'' t k\n      else cons h (remove'' t k)\n  end\n  . \n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* Implement the retrieval function. *)\n  Fixpoint get'' (d: nat_dict_list) (k: nat) : option V :=\n  match d with\n  | nil => None\n  | cons h t => \n    if (nat_eq k (fst h))\n      then Some (snd h)\n      else (get'' t k)\n  end\n  .\n (* Replace the previous line with ':= (your implementation) . ' *)\n\n  (* Implement the check for key presence. *)\n  Fixpoint contains'' (d: nat_dict_list) (k: nat): bool :=\n    match (get'' d k) with\n   | None => false\n   | Some _ => true\n   end\n  .\n (* Replace the previous line with ':= (your implementation) . ' *)\n     \nEnd NatDict'.\n\nSection NatDict'Tests.\n\n  (* The tests here are the same as for the previous implementation. *)\n  Let tests :=\n    let new := @new_dict'' nat in\n    let ins5 := insert'' new 5 10 in\n    let ins5ins5 := insert'' ins5 5 15 in\n    let ins5rm5 := remove'' ins5 5 in\n    let ins5ins5rm5 := remove'' ins5ins5 5 in\n    forallb id\n                       [ \n                         negb (contains'' new 5);\n                         contains'' ins5 5;\n                         contains'' ins5ins5 5;\n                         negb (contains'' ins5rm5 5);\n                         negb (contains'' ins5ins5rm5 5);\n                         option_nat_eq (get'' new 5) None;\n                         option_nat_eq (get'' ins5 5) (Some 10);\n                         option_nat_eq (get'' ins5ins5 5) (Some 15);\n                         option_nat_eq (get'' ins5ins5rm5 5) None;\n                         option_nat_eq (get'' ins5 3) None\n                       ].\n\n  Let nat_dict_list_tests_pass: tests = true.\n  Proof. tauto. Qed.\n  \nEnd NatDict'Tests.\n\n\n\n(* The tasks below are additional and not required. *)\n\n\n\n(* As you can see, these two implementations comply to the same interface. *)\n(* Yet, since their types are different, we had to write separate test suites, \n   despite they're essentially the same. *)\n(* Functional languages allow to specify a general interface with typeclasses. *)\nSection DictGeneral.\n\n  (* General interface for a dict polymorphic on value type. *)\n  (* This actually defines a type whose elements are interface implementations. *)\n  Class Dict := {\n    D: Type -> Type; \n    new_dict: forall (V: Type), D V;\n    insert: forall {V: Type}, (D V) -> nat -> V -> (D V);\n    remove: forall {V: Type}, (D V) -> nat -> (D V);\n    get: forall {V: Type}, (D V) -> nat -> option V;\n    contains: forall {V: Type}, (D V) -> nat -> bool\n  }.\n\n  (* Now we can specify expected behavior on the level of this interface. *)\n  (* The argument is an arbitrary dict implementation. *)\n  Let dict_tests (DictImpl: Dict) : bool :=\n    let new := @new_dict DictImpl nat in\n    let ins5 := insert new 5 10 in\n    let ins5ins5 := insert ins5 5 15 in\n    let ins5rm5 := remove ins5 5 in\n    let ins5ins5rm5 := remove ins5ins5 5 in\n    forallb id\n                       [\n                         negb (contains new 5);\n                         contains ins5 5;\n                         contains ins5ins5 5;\n                         negb (contains ins5rm5 5);\n                         negb (contains ins5ins5rm5 5);\n                         option_nat_eq (get new 5) None;\n                         option_nat_eq (get ins5 5) (Some 10);\n                         option_nat_eq (get ins5ins5 5) (Some 15);\n                         option_nat_eq (get ins5ins5rm5 5) None;\n                         option_nat_eq (get ins5 3) None\n                       ].\n            \n  (* Now we can state that our function-based implementation \n     complies to Dict interface. *)\n  Instance FunDict: Dict := {\n    D := @nat_dict_fun;\n    new_dict := @new_dict';\n    insert := @insert';\n    remove := @remove';\n    get := @get';\n    contains := @contains'\n  }.                       \n                       \n\n  (* Define instance of Dict class for the list-based implementation. *)\n   \n      (* place your code here *)\n  \n  (* Then, state and prove 'fun_dict_tests' and 'list_dict_tests' lemmas\n     by instantiating 'dict_tests' with instances you've just created. \n     These lemmas, as before, should be proved just by 'tauto'. *)\n\n      (* place your code here *)\n \nEnd DictGeneral.\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/b1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.9149009607937928, "lm_q1q2_score": 0.8336391921456249}}
{"text": "Require Import Arith.\nInductive tree : Type :=\n  | Leaf : tree\n  | Node : nat -> tree -> tree -> tree.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint ltb (m n : nat) : bool :=\nmatch (m, n) with\n  | (_, 0) => false\n  | (0, _) => true\n  | (S m', S n') => ltb m' n'\nend.\n\nFixpoint tinsert (t : tree) (i : nat) : tree :=\nmatch t with\n| Leaf => Node i Leaf Leaf\n| Node d l r => if ltb d i then Node d l (tinsert r i) else Node d (tinsert l i) r\nend.\n\nFixpoint tinsert_all (t : tree) (l : lst) : tree :=\nmatch l with \n| Nil => t\n| Cons n l' => tinsert (tinsert_all t l') n\nend.\n\nFixpoint tsize (t : tree) : nat :=\nmatch t with\n| Leaf => 0\n| Node d l r => 1 + (tsize l) + (tsize r)\nend.\n\nFixpoint leb (n m : nat) : bool :=\nmatch (n, m) with\n  | (0, _) => true\n  | (S n', S m') => leb n' m'\n  | _ => false\nend. \n\nLemma leb_refl : forall n, leb n n = true.\nProof.\ninduction n. reflexivity. simpl. apply IHn.\nQed.\n\nLemma leb_m_Sn : forall m n, leb m n = true -> leb m (S n) = true.\nProof.\ninduction m.\n- intros. reflexivity.\n- intros. simpl. destruct n.\n  + inversion H.\n  + apply IHm. simpl in H. apply H.\nQed.\n\nLemma helper : forall t n, (tsize (tinsert t n)) = S (tsize t).\nProof.\nintros. induction t.\n- reflexivity.\n- simpl. destruct (ltb n0 n).\n  + simpl. rewrite IHt2. rewrite <- plus_n_Sm. reflexivity.\n  + simpl. rewrite IHt1. reflexivity.\nQed.\n\n\nTheorem tree_insert_all : forall l t,  (tsize t)  <= (tsize (tinsert_all t l)).\nProof.\n  intros. induction l.\n  - simpl. auto with arith.\n  - simpl. rewrite IHl.\n    rewrite helper. 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/tree_insert_all.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8902942355821459, "lm_q1q2_score": 0.833569140313818}}
{"text": "(* Power.v *)\n(* author: Peter Urbak *)\n(* version: 2014-06-02 *)\n\n(** * Power *)\n\n(** ** Requirements *)\n\n(* Standard library *)\nRequire Import Arith.\n\n(* Own modules *)\nRequire Import Cases.\n\n(** ** Preliminary *)\n\n(*\n(* {NATS} *)\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n(* {END} *)\n*)\n\n(*\n(* {NAT_RECT} *)\nnat_rect : forall P : nat -> Type,\n  P O ->\n  (forall (n : nat), P n -> P (S n)) ->\n  (forall (n : nat), P n).\n(* {END} *)\n*)\n\n(*\n(* {EQ} *)\nInductive eq (A : Type) (x : A) : A -> Prop :=\n| eq_refl : x = x\n(* {END} *)\n*)\n\n(** ** Power\n\n  *** Definition *)\n\n(* {POWER} *)\nFixpoint power (e b : nat) : nat :=\n  match e with\n    | O => 1\n    | S e' => b * (b ^ e')\n  end\n  where \"b ^ e\" := (power e b).\n(* {END} *)\nHint Unfold power : power.\n\n(** *** Unfolding lemmas *)\n\n(* {UNFOLD_POWER_BASE_CASE} *)\nLemma unfold_power_base_case :\n  forall b : nat,\n    b ^ 0 = 1.\n(* {END} *)\nProof.\n  intro b.\n  unfold power.\n  reflexivity.\nQed.\nHint Rewrite unfold_power_base_case : power.\n\n(* {UNFOLD_POWER_INDUCTION_CASE} *)\nLemma unfold_power_induction_case :\n  forall b e' : nat,\n    b ^ (S e') = b * (b ^ e').\n(* {END} *)\nProof.\n  intros b e'.\n  unfold power.\n  reflexivity.\nQed.\nHint Rewrite unfold_power_induction_case : power.\n\n(** *** Properties *)\n\nLemma power_b_1 :\n  forall (b : nat),\n    b ^ 1 = b.\nProof.\n  intro b.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> unfold_power_base_case.\n  rewrite -> mult_1_r.\n  reflexivity.\nQed.\nHint Rewrite power_b_1 : power.\n\nLemma power_1_e :\n  forall (e : nat),\n    1 ^ e = 1.\nProof.\n  induction e as [ | e' IH_e' ].\n\n  Case \"e = 0\".\n  rewrite -> unfold_power_base_case.\n  reflexivity.\n\n  Case \"e = S e'\".\n  rewrite -> unfold_power_induction_case.\n  rewrite -> IH_e'.\n  rewrite -> mult_1_l.\n  reflexivity.\nQed.\nHint Rewrite power_1_e : power.\n\nLemma power_0_e :\n  forall (e' : nat),\n    0 ^ (S e') = 0.\nProof.\n  intro e'.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> mult_0_l.\n  reflexivity.\nQed.\nHint Rewrite power_0_e : power.\n\nLemma power_distributivity :\n  forall (b e1 e2 : nat),\n    b ^ (e1 + e2) = (b ^ e1) * (b ^ e2).\nProof.\n  intro b.\n  case e1 as [ | e1' ].\n\n  Case \"e1 = 0\".\n  case e2 as [ | e2' ].\n\n  SCase \"e2 = 0\".\n  rewrite -> plus_0_l.\n  rewrite -> unfold_power_base_case.\n  rewrite -> mult_1_r.\n  reflexivity.\n\n  SCase \"e2 = S e2'\".\n  rewrite -> plus_0_l.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> unfold_power_base_case.\n  rewrite -> mult_1_l.\n  reflexivity.\n\n  Case \"e1 = S e1'\".\n  induction e2 as [ | e2' IH_e2' ].\n\n  SCase \"e2 = 0\".\n  rewrite -> plus_0_r.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> unfold_power_base_case.\n  rewrite -> mult_1_r.\n  reflexivity.\n\n  SCase \"e2 = S e2'\".\n  rewrite <- plus_n_Sm.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> IH_e2'.\n  rewrite ->2 unfold_power_induction_case.\n  rewrite <-2 mult_assoc.\n  rewrite -> mult_comm.\n  rewrite <- mult_assoc.\n  rewrite -> (mult_comm b (b ^ e2')).\n  rewrite <- mult_assoc.\n  reflexivity.\nQed.\nHint Rewrite power_distributivity : power.\n\nLemma power_e_identity :\n  forall (b e1 e2 : nat),\n    (b ^ e1) ^ e2 = b ^ (e1 * e2).\nProof.\n  intro b.\n  case e1 as [ | e1' ].\n\n  Case \"e1 = 0\".\n  case e2 as [ | e2' ].\n\n  SCase \"e2 = 0\".\n  rewrite -> mult_0_r.\n  rewrite ->2 unfold_power_base_case.\n  reflexivity.\n\n  SCase \"e2 = S e2'\".\n  rewrite -> mult_0_l.\n  rewrite -> unfold_power_base_case.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> power_1_e.\n  rewrite -> mult_1_r.\n  reflexivity.\n\n  Case \"e1 = S e1'\".\n  induction e2 as [ | e2' IH_e2' ].\n\n  SCase \"e2 = 0\".\n  rewrite -> mult_0_r.\n  rewrite ->2 unfold_power_base_case.\n  reflexivity.\n\n  SCase \"e2 = S e2'\".\n  rewrite -> mult_succ_r.\n  rewrite -> power_distributivity.\n  rewrite <- IH_e2'.\n  rewrite <- mult_comm.\n  rewrite <- unfold_power_induction_case.\n  reflexivity.\nQed.\nHint Rewrite power_e_identity : power.\n\nLemma power_distribution_identity :\n  forall (b1 b2 e : nat),\n    (b1 * b2) ^ e = (b1 ^ e) * (b2 ^ e).\nProof.\n  intros b1 b2.\n  induction e as [ | e' IH_e' ].\n\n  Case \"e = 0\".\n  rewrite ->3 unfold_power_base_case.\n  rewrite -> mult_1_r.\n  reflexivity.\n\n  Case \"e = S e'\".\n  rewrite -> unfold_power_induction_case.\n  rewrite -> IH_e'.\n  rewrite ->2 unfold_power_induction_case.\n  rewrite <-2 mult_assoc.\n  rewrite -> (mult_comm b2 _).\n  rewrite <- mult_assoc.\n  rewrite -> (mult_comm b2 _).\n  reflexivity.\nQed.\nHint Rewrite power_distribution_identity : power.", "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/Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8335691325572278}}
{"text": "Require Import  Algebra.Utils Algebra.SetoidCat.\n\nRequire Import RelationClasses Relation_Definitions Morphisms SetoidClass.\n\nRequire Import Coq.Lists.List.\n\nOpen Scope type_scope.\nSection Monoid.\n\n  Context\n    {A : Type}\n    {SA : Setoid A}.\n\n  Class Monoid : Type :=\n    {\n      mempty : A;\n      mappend : SA ~> SA ~~> SA;\n      left_unit_monoid: forall (a : A),\n                       mappend @ mempty @ a == a;\n      right_unit_monoid: forall (a : A),\n                           mappend @ a @ mempty == a;\n      associativity_monoid : forall (a b c : A),\n                            mappend @ (mappend @ a @ b) @ c == mappend @ a @ (mappend @ b @ c)\n\n    }.\n\nEnd Monoid.\n\nClass MonoidHomomorphism {A B: Type}\n      {SA : Setoid A} {SB : Setoid B} {MA : @Monoid _ SA} {MB : @Monoid _ SB} (f : SA ~> SB) :=\n  {\n    monoid_homomorphism_mempty :  f @ mempty == mempty;\n    monoid_homomorphism_mappend : forall a a2, f @ (mappend @ a @ a2) == mappend @ (f @ a) @ ( f @ a2)\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/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.8335019983663944}}
{"text": "(*\n * This tutorial is for Shizhuo! But anyone else who likes it\n * is welcome to take a look at it. It's about pairs of unary\n * and binary natural numbers in Coq, and why unary and binary\n * numbers are equivalent, and what that means.\n *\n * Consider the unary natural numbers, which we redefine\n * from scratch inductively:\n *)\nInductive nat : Set :=\n| O : nat           (* 0 *)\n| S : nat -> nat.   (* successor (1 + n) *)\n\n(*\n * Consider also the binary natural numbers, which we also\n * redefine from scratch inductively, starting with the\n * positive binary numbers:\n *)\nInductive bin_pos : Set :=\n| O1 : bin_pos             (* 01 *)\n| xO : bin_pos -> bin_pos  (* shift left and add 0 *)\n| x1 : bin_pos -> bin_pos. (* shift left and add 1 *)\n(*\n * and continuing:\n *)\nInductive bin : Set :=\n| OO : bin                 (* 00 *)\n| pos : bin_pos -> bin.    (* positive binary numbers *)\n\n(* --- Some related terms --- *)\n\n(*\n * How are these related? Let's define corresponding points/terms.\n *)\nDefinition zeros : nat * bin :=\n  (O, OO). (* 0, 00 *)\n\nDefinition ones : nat * bin :=\n  (S O, pos O1). (* 1, 01 *)\n\nDefinition twos : nat * bin :=\n  (S (S O), pos (xO O1)). (* 2, 10 *)\n\nDefinition threes : nat * bin :=\n  (S (S (S O)), pos (x1 O1)). (* 3, 11 *)\n\nDefinition fours : nat * bin :=\n  (S (S (S (S O))), pos (xO (xO O1))). (* 4, 100 *)\n\nDefinition fives : nat * bin :=\n  (S (S (S (S (S O)))), pos (x1 (xO O1))). (* 5, 101 *)\n\nDefinition sixes : nat * bin :=\n  (S (S (S (S (S (S O))))), pos (xO (x1 O1))). (* 6, 110 *)\n\n(* --- Converting from unary to binary --- *)\n\n(*\n * In general, we can define a function that gets us from unary\n * to binary. First we define the successor function over\n * positive binary numbers:\n *)\nFixpoint S_bin_pos (b : bin_pos) : bin_pos :=\n  match b with\n  | O1 => xO O1\n  | xO bb => x1 bb\n  | x1 bb => xO (S_bin_pos bb)\n  end.\n(*\n * and then over all of binary:\n *)\nDefinition S_bin (b : bin) : bin :=\n  match b with\n  | OO => pos O1\n  | pos bb => pos (S_bin_pos bb)\n  end.\n\n(*\n * Our function f maps O to OO, and S n to S_bin (f n):\n *)\nFixpoint f (n : nat) : bin :=\n  match n with\n  | O => OO\n  | S m => S_bin (f m)\n  end.\n\n(*\n * Some tests, which correspond to the examples above:\n *)\nEval compute in (f O).\nEval compute in (f (S O)).\nEval compute in (f (S (S O))).\nEval compute in (f (S (S (S O)))).\nEval compute in (f (S (S (S (S O))))).\nEval compute in (f (S (S (S (S (S O)))))).\nEval compute in (f (S (S (S (S (S (S O))))))).\n\n(* --- Getting from binary to unary --- *)\n\n(*\n * We can also go back in the opposite direction.\n * The easiest way is to play a similar game.\n * We define what \"shift to the left and add zero\"\n * and \"shift to the left and add one\" correspond to in unary.\n * The function falls out of that by pattern matching and\n * recursion.\n *\n * First, let's define addition (since we defined\n * numbers from scratch, this isn't a primitive):\n *)\nFixpoint add (n m : nat) : nat :=\n  match n with\n  | O => m              (* O + m = m *)\n  | S p => S (add p m)  (* (1 + p) + m = 1 + (p + m) *)\n  end.\n\n(*\n * Now we can define shifting to the left and adding zero/one:\n *)\nDefinition xO_nat (n : nat) :=\n  add n n.\n\nDefinition x1_nat (n : nat) :=\n  S (add n n).\n\n(*\n * Now we can get back from binary to unary, starting with this:\n *)\nFixpoint g_pos (b : bin_pos) : nat :=\n  match b with\n  | O1 => S O\n  | xO bb => xO_nat (g_pos bb)\n  | x1 bb => x1_nat (g_pos bb)\n  end.\n(*\n * and concluding with this:\n *)\nDefinition g (b : bin) : nat :=\n  match b with\n  | OO => O\n  | pos bb => g_pos bb\n  end.\n\n(* --- This is an equivalence! --- *)\n\n(*\n * Some lemmas, first, about the auxiliary functions we defined.\n * I'm going to automate these a bit since the proofs are not\n * super important.\n *)\nLemma add_n_Sm:\n  forall (n m : nat),\n    add n (S m) = S (add n m).\nProof.\n  induction n; simpl; congruence.\nQed.\n\nLemma S_OK :\n  forall (b : bin), g (S_bin b) = S (g b).\nProof.\n  induction b as [|bb]; auto.\n  induction bb; auto.\n  simpl in *. rewrite IHbb. unfold xO_nat, x1_nat. simpl.\n  f_equal. apply add_n_Sm.\nQed.\n\nDefinition xO_bin (b : bin) :=\n  match b with\n  | OO => OO\n  | pos bb => pos (xO bb)\n  end.\n\nLemma xO_OK:\n  forall (n : nat), f (xO_nat n) = xO_bin (f n).\nProof.\n  intros n. induction n; auto.\n  simpl. unfold xO_nat in IHn.\n  rewrite add_n_Sm. simpl in *. rewrite IHn.\n  destruct (f n); auto.\nQed.\n\nDefinition x1_bin (b : bin) :=\n  match b with\n  | OO => pos O1\n  | pos bb => pos (x1 bb)\n  end.\n\nLemma x1_OK:\n  forall (n : nat), f (x1_nat n) = x1_bin (f n).\nProof.\n  intros n. induction n; auto.\n  simpl. unfold x1_nat in IHn.\n  rewrite add_n_Sm. simpl in *. rewrite IHn.\n  destruct (f n); auto.\nQed.\n\n(*\n * OK, the proofs we care about! These are worth stepping through.\n *)\nTheorem section:\n  forall (n : nat), g (f n) = n.\nProof.\n  intros n. induction n.\n  - reflexivity.\n  - simpl. rewrite S_OK. rewrite IHn. reflexivity.\nQed.\n\nTheorem retraction:\n  forall (b : bin), f (g b) = b.\nProof.\n  intros b. induction b as [|bb].\n  - reflexivity.\n  - induction bb.\n    + reflexivity.\n    + simpl in *. rewrite xO_OK. rewrite IHbb. reflexivity.\n    + unfold g. replace (g_pos (x1 bb)) with (x1_nat (g_pos bb)) by reflexivity.\n      rewrite x1_OK. simpl in IHbb. rewrite IHbb.\n      reflexivity.\nQed.\n\n\n", "meta": {"author": "tlringer", "repo": "proof-demos", "sha": "cf2ab87596c1bf10c7d00c7de396de23ba29fdcc", "save_path": "github-repos/coq/tlringer-proof-demos", "path": "github-repos/coq/tlringer-proof-demos/proof-demos-cf2ab87596c1bf10c7d00c7de396de23ba29fdcc/coq/NatBin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.9073122313857378, "lm_q1q2_score": 0.8333483657640992}}
{"text": "(* ###################################################################### *)\n(** * Proofs and Programs *)\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: Define a three-valued data type, representing ternary\n    logic.  Here something can be true, false and unknown. *)\n\nInductive trivalue : Type :=\n| one : trivalue\n| two : trivalue\n| three : trivalue.\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\nCheck negb.\nCompute (negb true).\n\nDefinition orb (b1 b2: bool) : bool :=\n  match b1, b2 with\n  | false, false => false\n  | _, _ => true\n  end.\n\nPrint orb.\n\nDefinition andb (b1 b2: bool) : bool :=\n  if b1 then b2 else false.\n\nDefinition xorb (b1 b2 : bool) : bool :=\n  match b1, b2 with\n  | true, false => true\n  | false, true => true\n  | _, _ => false\n  end.\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 : forall b, andb false b = false.\nProof.\n  intros b1.\n  simpl.\n  reflexivity.\nQed.\n\n(** Exercise: Prove this. *)\nTheorem orb_true_l :\n  forall b, orb true b = true.\nProof.\n  intros b.\n  simpl.\n  reflexivity.\nQed.\n\n(** New tactics\n    -----------\n\n    - [destruct]: Consider all possible constructors of an inductive\n      data type, generating subgoals that need to be solved\n      separately. *)\n\nLemma double_negation : forall b : bool, negb (negb b) = b.\nProof.\n  intros b.\n  simpl.\n  destruct b.\n  (* focus on: *)\n  + (* case: b is true *)\n    simpl.\n    reflexivity.\n  + (* case: b is false *)\n    simpl.\n    reflexivity.\nQed.\n\nTheorem andb_commutative : forall b1 b2 : bool, andb b1 b2 = andb b2 b1.\nProof.\n intros b1 b2.\n destruct b1.\n + simpl.\n   destruct b2.\n   - simpl.\n     reflexivity.\n   - simpl.\n     reflexivity.\n + destruct b2; simpl; reflexivity.\nQed.\n\n(* we should use `+` `-` `*` consistently *)\n\n(** Exercise: Show that false is an identity element for xor -- that\n    is, [xor false b] is equal to [b] *)\n\nTheorem xorb_false : forall b : bool, xorb false b = b.\nProof.\n intros b.\n destruct b.\n + simpl.\n   reflexivity.\n + simpl; reflexivity.\nQed.\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\nTheorem rewrite_example : forall b1 b2 b3 b4 : bool,\n  b1 = b4 ->\n  b2 = b3 ->\n  andb b1 b2 = andb b3 b4.\nProof.\n  intros b1 b2 b3 b4 E14 E23.\n  rewrite <- E14.\n  rewrite <- E23.\n  apply andb_commutative.\nQed.\n\n(** Exercise: Show that if [b1 = b2] then [xorb b1 b2] is equal to\n    [false] *)\n\nTheorem xorb_same : forall b1 b2 : bool, b1 = b2 -> xorb b1 b2 = false.\nProof.\n  intros b1 b2 E.\n  rewrite E.\n(*\n  destruct b2.\n  + simpl.\n    reflexivity.\n  + simpl.\n    reflexivity.\n*)\n  destruct b2; reflexivity.\nQed.\n\nEnd Bool.\n\nModule Nat.\n\n(* ###################################################################### *)\n(** * Numbers and induction *)\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nCheck (S (S O)). (* [C-c C-a C-c] in Proof General *)\n\nFixpoint plus (n m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n\n(** Exercise: Define exponentiation *)\n\nFixpoint expo (n m : nat) : nat :=\n  match m with\n  | O    => (S O)\n  | S m' => mult n (expo n m')\n  end.\n\n  Notation \"x + y\" := (plus x y) (at level 50, left associativity).\n\n  Notation \"x * y\" := (mult x y) (at level 40, left associativity).\n\n  Notation \"x ^ y\" := (expo x y) (at level 30, right associativity).\n\n  Compute ( (S (S O)) + (S (S O)) ).\n  Compute ( (S (S O)) * (S (S O)) ).\n  Compute ( (S (S O)) ^ (S (S O)) ).\n\nLemma plus_0_l: forall n : nat, O + n = n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\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. *)\n\nLemma plus_O_r: forall n : nat, n + O = n.\nProof.\n  intros n.\n  simpl.\n  (* instead of: destruct n. *)\n  induction n as [| n' IH].\n  (* IH ==== Inductive Hypotesis *)\n(*\n  + simpl.\n    reflexivity.\n\n  reflexivity *includes* simpl\n*)\n  + reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\nPrint plus_O_r.\n\nTheorem plus_assoc: forall m n o, m + (n + o) = (m + n) + o.\nProof. \n  intros m n o.\n  induction m.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHm.\n    reflexivity.\n Qed.\n\n(** Take-home exericse: Try to do induction on [n] and [o] in the\n    above proof, and see where it fails. *)\n\n(** Exercise: Show that [n + S m] is equal to [S (n + m)]. *)\n\nLemma plus_S_r : forall n m, n + S m = S (n + m).\nProof.\n  intros n m.\n  simpl.\n  induction n as [| n' IH].\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(** Exercise: Show that plus is commutative. *)\n(** Hint: Look at our earlier lemmas. *)\n\nLemma plus_comm : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction m.\n  + simpl.\n    apply plus_O_r.\n  + simpl.\n    rewrite <- IHm.\n   apply plus_S_r.\nQed.\n\n(*\n  To search the right lemma: SearchAbout \n\n  e.g. SearchAbout (_ + S = _).\n*)\n\n(** Additional take-home exercises: Show that mult has an identity [S\n    O], a annihilator [O] and associative, commutative and\n    distributive properties. *)\n\nFixpoint minus (m n : nat) : nat :=\n  match m, n with\n  | O, _ => m\n  | _, O => m\n  | S m', S n' => minus m' n'\n  end.\n\nNotation \"x - y\" := (minus x y) (at level 50, left associativity).\n\nFixpoint ble_nat (m n : nat) : bool :=\n  match m, n with\n  | O, _ => true\n  | _, O => false\n  | S n', S m' => ble_nat n' m'\n  end.\n\nFail Fixpoint div (m n: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => if ble_nat n m then S (div (m - n) n) else O\n  end.\n\nFixpoint div (m n: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => match m with\n            | O => O\n            | S m' => S (div (S m' - S n') (S n'))\n            end\n  end.\nFixpoint beq_nat (m n : nat) : bool :=\n  match m, n with\n  | O, O => true\n  | S m', S n' => beq_nat m' n'\n  | _, _ => false\n  end.\n\nDefinition max (m n : nat) : nat :=\n  if ble_nat m n then n else m.\n\n(** New tactic\n    ----------\n\n    - [clear]: Remove hypotheses from the context (needed here to\n      simplify our IH). *)\n\n(* revert is the opposite of intros *)\n\nLemma beq_nat_eq :\n  forall m n, m = n -> beq_nat m n = true.\nProof.\n  intros m n e. rewrite e. clear m e.\n  induction n as [|n IH].\n  - reflexivity.\n  - simpl. apply IH.\nQed.\n\n(** New tactics\n    -----------\n\n    - [discriminate]: Looks for an equation between terms starting\n      with different constructors, and solves the current goal.\n\n    - [revert]: The opposite of [intros]; removes variables and\n      hypotheses from the context, putting them back in the goal. *)\n\nLemma eq_beq_nat :\n  forall m n, beq_nat m n = true -> m = n.\nProof.\n(* 1st try\n  intros m n e.\n  induction m.\n  + destruct n.\n      - reflexivity.\n      - simpl in e.\n         discriminate.\n  + rewrite IHm\n*)\n  intros m n e.\n  revert n e.\n  induction m.\n  + intros n e.\n      destruct n.\n      - reflexivity.\n      - simpl in e.\n         discriminate.\n  + intros n H.\n      destruct n.\n      - simpl in H.\n          discriminate.\n      - simpl in H.\n        apply IHm in H.\n        rewrite H.\n        reflexivity.\nQed.\n\nLemma plus_eq_0 : forall n m,  n + m = O -> n = O.\nProof.\n(*  SearchAbout (_ + (S _) = _). \n  intros n.\n  induction n.\n  + reflexivity.\n  + intros m H.\n      destruct n.\n*)\n\n  intros n.\n  induction n.\n  + reflexivity.\n  + intros m H.\n      (* inversion H. *)\n       simpl in H.\n       discriminate.\n\nQed.\n\nEnd Nat.\n\n\n(** Useful notation... *)\n\nCompute (S (S O)).\nCompute (S (S O) + S O).\n\n(* ###################################################################### *)\n(** * 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(* Explicit polymorphism. *)\nDefinition singleton_list (T : Type) (x : T) :=\n  cons T x (nil T).\n\n(* Inferred (but still a bit explicit) *)\nDefinition singleton_list' (T : Type) (x : T) :=\n  cons _ x (nil _).\n\n(* Implicit, inferred all the time *)\nArguments nil {T}.\nArguments cons {T} _ _.\nDefinition singleton_list'' {T} (x : T) :=\n  cons x nil.\n\nCheck (singleton_list'' 3).\nCheck (@singleton_list'' nat).\n\n(* @ turn off implicit arguments *)\n\nCheck @singleton_list''.\nCheck @nil.\n\nNotation \"h :: t\" := (cons h t) (at level 60, right associativity).\nNotation \"[ ]\" := (nil).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(* Exercise: Define \"snoc\", which adds an element to the end of a list. *)\n\nFixpoint snoc {T} (l : list T) (x : T) : list T :=\n  match l with\n  | []       => [x]\n  | x' :: l' => x' :: snoc l' x\n  end.\n\nFixpoint app {T} (l1 l2 : list T) : list T :=\n  match l1 with\n  | [] => l2\n  | h :: l1' => h :: (app l1' l2)\n  end.\n\nNotation \"l1 ++ l2\" := (app l1 l2) (at level 60, right associativity).\n\nLemma app_assoc :\n  forall T (l1 l2 l3 : list T),\n    l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n(*  intros T l x.\n  induction l as [|x' l IH]; simpl.\n  - reflexivity.\n  - rewrite IH. reflexivity.\nQed.\n*)\nAdmitted.\n\nLemma snoc_app :\n  forall T (l : list T) (x : T),\n    snoc l x = l ++ [x].\nProof.\n  (* Fill in here *)\nAdmitted.\n\nEnd List.\n\n(** Lists, of course, are also defined in the standard library. *)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(** Notice that the definition of rev (list reversal) given in the\n    standard library runs in quadratic time. *)\n\nPrint rev. (* [C-c C-a C-p] in Proof General *)\n\n(** This is a tail-recursive equivalent that runs in 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(** New Tactic\n    ----------\n\n    - [unfold]: Calling [unfold foo] expands the definition of [foo]\n      in the goal.\n*)\n\nLemma tr_rev_aux_correct :\n  forall T (l1 l2 : list T),\n    tr_rev_aux l1 l2  = rev l1 ++ l2.\nProof.\n  intros T l1 l2.\n  revert l2.\n  induction l1 as [|x1 l1 IH]; simpl.\n  - intros l2. reflexivity.\n  - intros l2. rewrite IH.\n    SearchAbout (_ ++ _ ++ _).\n    rewrite <- app_assoc.\n    simpl.\n    reflexivity.\nQed.\n\nLemma tr_rev_correct :\n  forall T (l : list T),\n    tr_rev l = rev l.\nProof.\n  intros T l.\n  unfold tr_rev.\n  rewrite tr_new_aux_correct.\n  simpl.\n  SearchAbout (_ ++ [])\n(*\n  induction l as [|x l IH]. simpl.\n  - reflexivity.\n  - .\n*)\n  apply app_nil_r.\nQed.\n\n(* ###################################################################### *)\n(** * Dependently Typed Programming *)\n\nDefinition stack := list.\n\nDefinition push {T} (x:T) (s : stack T) : stack T  := x :: s.\n\n(* Definition pop {T} (s : stack T) : T * stack T := *)\n\n(* Length-Indexed Stacks *)\n\n(* Exercise: Write a snoc function to add an element to the bottom of\n   an indexed stack. Do not use the combine function (in this case, it\n   will make life difficult.) *)\n", "meta": {"author": "filippovitale", "repo": "cufp2015", "sha": "258ce9cded09a4cdd724eb3d8ac04b82c409ae70", "save_path": "github-repos/coq/filippovitale-cufp2015", "path": "github-repos/coq/filippovitale-cufp2015/cufp2015-258ce9cded09a4cdd724eb3d8ac04b82c409ae70/t12-coq/basics_short.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.9073122276263202, "lm_q1q2_score": 0.8333483582619454}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Coq.omega.Omega.\nFrom LF Require Export logic.\n\n\n(*\u5076\u6570\u306e\u5b9a\u7fa9\nev_0:0\u304c\u5076\u6570\u3067\u3042\u308b\nev_SS: n\u304c\u5076\u6570\u306e\u3068\u304dn+2\u306f\u5076\u6570\u3067\u3042\u308b*)\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S n)).\n\n(*\u76f4\u611f\u7684\u306b\u306f\u4e0b\u306e\u5b9a\u7fa9\u3060\u3051\u3069\u3053\u308c\u306f\u7121\u7406\u3002\n  \u5e30\u7d0d\u7684\u5b9a\u7fa9\u306b\u3057\u306a\u3044\u3068\u3002\n error message:\n    \"wrong_ev\" must have \"n\" as 1st argument in \"wrong_ev 0\"*)\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(*\u3053\u308c\u306a\u3089OK*)\nInductive even' : nat -> Prop := \n| ev_0' : even' 0 \n| ev_SS' : forall n, even' n -> even' (S (S n)).\n\n(*4\u304c\u5076\u6570\u3067\u3042\u308b\u8a3c\u660e*)\nTheorem ev_4 : even 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\nTheorem ev_4' : even 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\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. induction n. simpl. apply ev_0. simpl. apply ev_SS. apply IHn.\nQed.\n\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  -\n    left. reflexivity.\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  - simpl. apply ev_0.\n  - simpl. apply E'.\nQed.\n\nTheorem evSS_ev : forall n, even (S (S n)) -> even n.\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  -\n    \nAbort. (*destruct\u3058\u3083\u7121\u7406*)\n\nTheorem evSS_ev : forall n, even (S (S n)) -> even n.\nProof. intros n H. apply ev_inversion in H. destruct H.\n - discriminate H.\n - destruct H as [n' [Hnm Hev]]. injection Hnm.\n   intro Heq. rewrite Heq. apply Hev.\nQed.\n\n(*inversion\u4f7f\u3048\u3070\u7c21\u5358*)\nTheorem evSS_ev' : forall n,\n  even (S (S n)) -> even n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'.\nQed.\n\nTheorem one_not_even : ~ even 1.\nProof.\n  intros H. apply ev_inversion in H.\n  destruct H as [ | [m [Hm _]]].\n  - discriminate H.\n  - discriminate Hm.\nQed.\n\n(*inversion\u3067discriminate\u3092\u3067\u304d\u308b*)\nTheorem one_not_even' : ~ even 1.\n  intros H. inversion H. Qed.\n\n\nTheorem SSSSev__even : forall n,\n  even (S (S (S (S n)))) -> even n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n\nTheorem even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  intros. inversion H. inversion H1. inversion H3.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nLemma ev_even_firsttry : forall n,\n  even n -> exists k, n = double k.\nProof.\n intros n E. inversion E as [| n' E'].\n  -\n    exists 0. reflexivity.\n  - \n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k'). reflexivity. }\n    apply I.\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  -\n    exists 0. reflexivity.\n  -\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. destruct n. \n  - intros. apply H0.\n  - intros. induction H0 as [|n' E H1].\n       + simpl. rewrite <- plus_n_O. apply H.\n       + simpl. Search plus. rewrite PeanoNat.Nat.add_succ_r. \n         apply ev_SS. rewrite PeanoNat.Nat.add_succ_r. rewrite PeanoNat.Nat.add_succ_l in H1.\n          apply H1.\nQed.\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\nTheorem even''_ev : forall n, even'' n <-> even n.\nProof.\n  intros. induction n. split. intros. apply ev_0. intros. apply even''_0.\n  - split. intros. induction H. \n     + apply ev_0. + apply ev_SS. apply ev_0.\n     + apply ev_sum. apply IHeven''1. apply IHeven''2.\n     + intro.\n     { induction H. \n        - apply even''_0.\n        - apply even''_sum with (n:= 2) (m:= n0). \n             + apply even''_2.\n             + apply IHeven. }\nQed.\n\n\nTheorem ev_ev__ev : forall n m,\n  even (n+m) -> even n -> even m.\nProof.\n  intros n m H En.\n  induction En as [| n' IHn'].\n  simpl in H.\n  apply H.\n  simpl in H.\n  inversion H.\n  apply IHIHn'.\n  apply H1.\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 H H1 . destruct m.\n  - simpl. rewrite plus_comm in H. simpl in H. apply (ev_ev__ev n p) in H1.\n    apply H1. apply H.\n  - destruct p. + rewrite <- plus_n_O in H1. rewrite <- plus_n_O. apply (ev_ev__ev n (S m)).\n    apply H. apply H1.\n    + apply (ev_ev__ev n (S m)) in H. apply ev_sum. apply H. apply (ev_ev__ev n (S p)) in H1.\n      apply H1. destruct n. apply ev_0.\nAdmitted.\n\n\n(*------Inductive Relations--------*)\nInductive le : nat -> nat -> Prop :=\n  | le_n n : le n n\n  | le_S n m (H : le n m) : le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2. Qed.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 n : even (S n) -> next_even n (S n)\n  | ne_2 n (H : even (S (S n))) : next_even n (S (S n)).\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros. generalize dependent H.\n  induction H0. \n    - intros. apply H.\n    - intros. apply le_S. apply IHle in H. apply H.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n.\n  - apply le_n.\n  - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros. induction H. \n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\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).\n       + apply le_S. apply le_n.\n       + apply H2.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction b.\n  - rewrite plus_comm. simpl. apply le_n.\n  - rewrite plus_comm. simpl. apply le_S. rewrite plus_comm. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt. intros. split. \n   - apply le_trans with (n:= S (n1 + n2) ).\n    + Search plus S eq. rewrite <- plus_Sn_m. apply le_plus_l.\n    + apply H.\n  - apply le_trans with (n:= S (n1 + n2) ).\n    + Search plus S eq. rewrite plus_n_Sm. rewrite plus_comm. apply le_plus_l.\n    + apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply le_S. apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  n =< m = true -> n <= m.\nProof.\n  intros n m.\n  generalize dependent m.\n  induction n as [| n' IH].\n  - intros. apply O_le_n.\n  - intros. destruct m.\n    + discriminate.\n    + apply n_le_m__Sn_le_Sm.\n      apply IH.\n      apply H.\nQed.\n\n\nTheorem leb_succ : forall n m,\n  (n =< m) = true -> (n =< S m) = true.\nProof.\n  intros n m. generalize dependent m. induction n as [| n' IH].  reflexivity. intros. simpl. inversion H.\n  destruct m. discriminate. rewrite H1. apply IH. apply H1.\nQed.\n\nTheorem leb_nn : forall n,\n  n =< n = true.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n =< m = true.\nProof.\n  intros. induction m.\n  -  inversion H. simpl. reflexivity.\n  - intros. inversion H.\n     + rewrite leb_nn. reflexivity.\n     + apply leb_succ. apply IHm. apply H2.\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 H H0. apply leb_correct. apply leb_complete in H. apply leb_complete in H0.\n  generalize dependent H0. generalize dependent H. apply le_trans.\nQed.\n\nTheorem leb_iff : forall n m,\n  n =< m = true <-> n <= m.\nProof.\n  intros. split.\n  - apply leb_complete. - apply leb_correct.\nQed.\n\n\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\nTheorem R112:\n  R 1 1 2.\nProof.\n  apply c2. apply c3. apply c1.\nQed.\nTheorem R226:\n  R 2 2 6.\nProof.\n  apply c2. apply c3. apply c3. apply c2. apply c4. apply c2. apply c3.\nAbort.\n\nDefinition fR : nat -> nat -> nat :=\n  fun n m =>  n + m.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n  unfold fR. intros. split.\n  - intros. induction H. \n   + reflexivity.\n   + apply eq_S with (x:= (m+n)). apply IHR.\n   + rewrite plus_comm. simpl. rewrite plus_comm.\n     apply eq_S with (x:= (m+n)). apply IHR.\n   + simpl in IHR. apply S_injective in IHR. apply S_injective.\n     rewrite plus_n_Sm. apply IHR.\n   + rewrite plus_comm. apply IHR.\n  - intros. destruct H. induction n. \n   + rewrite plus_comm. simpl. \n    induction m. apply c1. apply c2. apply IHm.\n   + rewrite plus_comm. simpl. apply c3. rewrite plus_comm. apply IHn.\nQed.\n\nInductive subseq {X : Type} : list X -> list X -> 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. induction l. apply subseq_nil. 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. induction H.\n  - apply subseq_nil.\n  - simpl. apply subseq_inboth. apply IHsubseq.\n  - simpl. apply subseq_in2nd. apply IHsubseq.\nQed.\n\nTheorem subseq_nil_r : forall l : list nat,\n  subseq l [] -> l = [].\nProof.\n  intros. inversion H. reflexivity.\nQed.\n\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 T12 T23.\n  generalize dependent T12.\n  generalize dependent l1.\n  induction T23.\n  - intros. inversion T12. apply subseq_nil.\n  - intros. inversion T12.\n    + apply subseq_nil.\n    + apply subseq_inboth. apply IHT23. apply H1.\n    + apply subseq_in2nd. apply IHT23. apply H1.\n  - intros. apply subseq_in2nd. apply IHT23. apply T12.\nQed.\n\nInductive R' : nat -> list nat -> Prop := \n | c7 : R' 0 [] \n | c8 : forall n l, R' n l -> R' (S n) (n :: l) \n | c9 : forall n l, R' (S n) l -> R' n l.\nTheorem R'210:\n  R' 2 [1;0].\nProof.\n  apply c8. apply c8. apply c7.\nQed.\nTheorem R11210 :\n  R' 1 [1;2;1;0].\nProof.\n  apply c9. apply c8. apply c9. apply c9. apply c8. apply c8. apply c8. apply c7.\nQed.\nTheorem R'6321: \n  R' 6 [3;2;1;0].\nProof.\n  Abort.\n\n\n\n\n(*---------\u6b63\u898f\u8868\u73fe\u306e\u30e2\u30c7\u30eb\u5316--------------*)\n(*\nThe expression EmptySet does not match any string.\nThe expression EmptyStr matches the empty string [].\nThe expression Char x matches the one-character string [x].\n\nIf re1 matches s1, and re2 matches s2, then App re1 re2 matches s1 ++ s2.\nIf at least one of re1 and re2 matches s, then Union re1 re2 matches s.\nIf we can write some string s as the concatenation of a sequence of strings s = s_1 ++ ... ++ s_k,\n    and the expression re matches each one of the strings s_i, then Star re matches s.\nAs a special case, the sequence of strings may be empty,\n   so Star re always matches the empty string [] no matter what re is.*)\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).\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\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\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  unfold not. intros. inversion H. \nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros. inversion H.\n  + apply MUnionL. apply H0.\n  + apply MUnionR. apply H0.\nQed.\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros. induction ss.\n  - simpl. apply MStar0.\n  - simpl. apply MStarApp.\n     + apply H. simpl. left. reflexivity.\n     + apply IHss. intros. apply H. right. apply H0.\nQed.\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  intros T s1 s2. \n  generalize dependent s1.\n  induction s2 as [|h t].\n  - (* s2 = [] *)\n    split. \n    + intros H. simpl in H. inversion H. reflexivity.\n    + intros H. simpl. rewrite H. apply MEmpty.\n  - (* s2 = h::t *)\n    intros s1. split. \n    + intros H. simpl in H. inversion H. \n      inversion H3. simpl. \n      apply (IHt s2) in H4. rewrite H4. reflexivity.\n    + intros H. simpl. rewrite H.\n      assert ( A : forall S (x:S) y, [x]++y = x::y).\n      {  intros S x y. simpl. reflexivity.  }\n      rewrite <- A. apply MApp.\n      * apply MChar.\n      * apply IHt. reflexivity.\nQed.\n\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  -\n    apply Hin.\n  -\n    apply Hin.\n  - simpl. apply In_app_iff. apply In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    +\n      left. apply (IH1 Hin).\n    +\n      right. apply (IH2 Hin).\n  -\n    simpl. apply In_app_iff.\n    left. apply (IH Hin).\n  -\n    simpl. apply In_app_iff.\n    right. apply (IH Hin).\n  -\n    destruct Hin.\n  -\n    simpl. apply In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    +\n      apply (IH1 Hin).\n    +\n      apply (IH2 Hin).\nQed.\n\n\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool :=\n  match re with \n  | EmptySet => false\n  | EmptyStr => true\n  | Char _   => true\n  | App re1 re2 => andb (re_not_empty re1) (re_not_empty re2)\n  | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n  | Star re1 => true\n  end.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros. split.\n  - intros [s H]. induction H.\n    + reflexivity.\n    + reflexivity.\n    + simpl. rewrite IHexp_match1. rewrite IHexp_match2. reflexivity.\n    + simpl. rewrite IHexp_match. reflexivity.\n    + simpl. rewrite IHexp_match. apply orb_true_iff. right. reflexivity.\n    + reflexivity.\n    + rewrite IHexp_match2. reflexivity.\n\n   - intros. induction re.\n     + discriminate.\n     + exists []. apply MEmpty.\n     + exists [t]. apply MChar.\n     + simpl in H. apply andb_true_iff in H. inversion H. apply IHre1 in H0. apply IHre2 in H1.\n       inversion H0. inversion H1. exists (x ++ x0). apply MApp. apply H2. apply H3.\n     + simpl in H. apply orb_true_iff in H. inversion H.\n      { apply IHre1 in H0. inversion H0. exists x. apply MUnionL. apply H1. }\n      { apply IHre2 in H0. inversion H0. exists x. apply MUnionR. apply H1. }\n    + exists []. apply MStar0.\nQed.\n\n\n(*--------The remember Tactic--------*)\n\nLemma star_app: forall T (s1 s2 : list T) (re : @reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1. induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  -\n    simpl. intros H. apply H.\n  -\n  Abort.\n\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  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  -\n    injection Heqre'. intros Heqre'' s H. apply H.\n  -\n    injection Heqre'. intros H0.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * rewrite H0. reflexivity.\n      * apply H1.\nQed.\n\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp),\n  s =~ Star re ->\n  exists ss : list (list T),\n    s = fold app ss []\n    /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  intros. remember (Star re) as str.\n  induction H  as [|x'|s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n        |re''|s1 s2 re'' Hmatch1 IH1 Hmatch2 IH2].\n  - inversion Heqstr.\n  - inversion Heqstr.\n  - inversion Heqstr.\n  - inversion Heqstr.\n  - inversion Heqstr.\n  - exists []. split. reflexivity.\n    intros. inversion H.\n  - destruct (IH2 Heqstr) as [ss' [L R]].\n    exists (s1::ss'). split.\n    + simpl. rewrite <- L. reflexivity.\n    + intros s' H. destruct H.\n      { rewrite <- H. inversion Heqstr. rewrite H1 in Hmatch1. apply Hmatch1. }\n      { apply R. apply H. }\nQed.\n\n(*pumping\uff1a\u4e00\u5b9a\u4ee5\u4e0a\u306e\u9577\u3055\u306e\u6587\u5b57\u5217\u306f\u5206\u5272\u3057\u3066\u5224\u5b9a\u3059\u308b\u3002*)\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\nLemma pumping : forall T (re : @reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n  intros T re s Hmatch. unfold not.\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  -\n    simpl. intros. inversion H. \n  -\n   simpl. intros. inversion H. inversion H2.\n  -\n   simpl. intros.\nAdmitted.\n\n\n(*---Case Study: Improving Reflection---*)\n\n(*\u30d6\u30fc\u30eb\u6f14\u7b97\u3068Prop\u306e\u95a2\u9023\u4ed8\u3051\u3067\u9762\u5012\u306b\u306a\u308b\u8a3c\u660e*)\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  -\n    simpl. intros H. apply H. reflexivity.\n  -\n    simpl. destruct (n =? m) eqn:H.\n    +\n      intros _. apply eqb_eq in H. rewrite H.\n      left. reflexivity.\n    +\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n\n(*bool\u304b\u3089Prop\u3078\u76f4\u63a5\u5909\u63db\u3059\u308b\u95a2\u6570\u3092\u7528\u3044\u308b*)\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H : P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros P b H. destruct b.\n  - apply ReflectT. apply H. reflexivity.\n  - apply ReflectF. intros H'. apply H in H'. discriminate.\nQed.\n\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  intros. induction H.\n  - split. intros. reflexivity. intros. apply H.\n  - split. intros. induction H. apply H0. intros. discriminate.\nQed.\n\nLemma eqbP : forall n m, reflect (n = m) (n == m).\nProof.\n  intros n m. apply iff_reflect. split. apply eqb_eq. apply eqb_eq.\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  -\n    simpl. intros H. apply H. reflexivity.\n  -\n    simpl. destruct (eqbP n m) as [H | H].\n    +\n      intros _. rewrite H. left. reflexivity.\n    +\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 count_0_app : forall n x l,\n   count n (x :: l) = 0 ->  count n (l) = 0.\nProof.\n  intros. inversion H. destruct (n == x).\n  discriminate. simpl. reflexivity.\nQed.\n\nTheorem In_x_app : forall {X: Type}(n x: X) l,\n  In n l -> In n (x:: l).\nProof.\n  intros. simpl. right. apply H.\nQed.\n\nTheorem eqbP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  unfold not. intros. induction l.\n  - inversion H0.\n  - apply IHl. \n     + apply count_0_app in H. apply H.\n     + simpl in H0. inversion H0.\n      * rewrite H1 in H. simpl in H. rewrite eqb_nn in H. discriminate.\n      * apply H1.\nQed.\n\n\n\nInductive nostutter {X:Type} : list X -> Prop :=\n  | st_nil : nostutter []\n  | st_2nil (x: X): nostutter [x]\n  | st_nm  : forall x h t, nostutter (h :: t) -> ~(x = h) -> nostutter (x :: h :: t).\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof. apply st_nm. apply st_nm. apply st_nm. apply st_nm. apply st_nm. apply st_2nil.\n       - unfold not. intros. discriminate.\n       - unfold not. intros. discriminate.\n       - unfold not. intros. discriminate.\n       - unfold not. intros. discriminate.\n       - unfold not. intros. discriminate.\nQed.\n\nExample test_nostutter_2: nostutter (@nil nat).\nProof. apply st_nil. Qed.\n\nExample test_nostutter_3: nostutter [5].\nProof. apply st_2nil. Qed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\nProof. unfold not. intros. inversion H. inversion H2.\n       unfold not in H9. apply H9. reflexivity.\nQed.\n\nInductive pal {X: Type} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_one (x: X) : pal [x]\n  | pal_add : forall (x: X) l, pal l -> pal (x :: l ++ [x]).\n\n\nTheorem rev_pal : forall {X: Type} (l: list X),\n  pal (l ++ rev l).\nProof.\n  intros. induction l.\n  - simpl. apply pal_nil.\n  - simpl. rewrite app_assoc. apply (pal_add x (l ++ rev l)). apply IHl.\nQed.\n\n\nTheorem pal_rev : forall {X: Type} (l : list X),\n  pal l -> l = rev l.\nProof.\n  intros. induction H.\n  - simpl. reflexivity. - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. simpl. rewrite <- IHpal. reflexivity.\nQed.\n\nTheorem revpal : forall {X: Type} (l: list X),\n  l = rev l -> pal l.\nProof.\n  intros. induction l.\n  - apply pal_nil.\n  - induction IHl.\n    + apply pal_one.\n    + inversion H. assert ([x0; x0] = (x0 :: [] ++ [x0])). { reflexivity. }\n      rewrite H0. apply pal_add. apply pal_nil.\n    + simpl in H. inversion H.\nAdmitted.\n\nTheorem in_x : forall {X: Type} (x: X) (l: list X),\n  l = [x] -> In x l.\nProof.\n  intros. inversion H. simpl. left. reflexivity.\nQed.\n\nTheorem f_equal : forall {X Y : Type} (x y : X) (f: X-> Y),\n x = y -> f x = f y.\n  Proof.\n    destruct 1; trivial.\nDefined.\n\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  induction l. simpl. intro. inversion H. destruct 1.\n  subst x0; auto.\n  exists [], l; auto.\n  destruct (IHl H) as (l1, (l2, H0)).\n  exists (x::l1), l2; simpl.\nAdmitted.\n\n\n(*-------\u9ce9\u306e\u5de3\u306e\u539f\u7406\u7121\u7406\u3060\u3063\u305f---------*)\nInductive repeats {X:Type} : list X -> Prop :=\n  | repeat (x: X): repeats [x ; x]\n  | replace_many (l1 l2 l3: list X): repeats l2 -> repeats (l1 ++ l2 ++ l3).\n\nExample retest : repeats [1; 3; 4; 5; 5].\n  apply (replace_many [1; 3; 4] [5; 5] []). apply repeat.\nQed.\n\nTheorem app_one : forall {X: Type} (l: list X) x,\n  (x :: l) = [x] ++ l.\nProof. reflexivity. Qed.\n\nLemma lt_not_eq: forall n:nat , ~(n <n).\nProof.\n  unfold not. unfold lt. intros. Search le. induction n. inversion H.\n  apply IHn. apply Sn_le_Sm__n_le_m in H. apply H.\nQed.\n\nLemma le_leftS : forall n m : nat, S n <= m -> n <= m.\nProof. intros. apply le_trans with (S n).\n   apply le_S. apply le_n. apply H. \nQed.\n\nTheorem le_le_eq : forall n m, n <= m -> m <= n -> n = m.\nProof.\n  intros. inversion H. reflexivity.\n  inversion H0. rewrite H3. symmetry. apply H5.\n\n(*induction H. reflexivity. induction H0. reflexivity.*)\nAdmitted.\n\nLemma lt_nn : forall n, ~(n < n).\nProof.\n intros. unfold lt. unfold not. intros. induction n. inversion H. apply IHn. \n apply Sn_le_Sm__n_le_m in H. apply H.\nQed.\n\n\nLemma lt_not_le: forall n m : nat, n < m -> ~ m <= n.\nProof.\n intros. inversion H.\n - apply lt_not_eq.\n - apply n_le_m__Sn_le_Sm in H0. rewrite H2 in H0. rewrite H2. apply le_leftS in H0. apply le_leftS in H0.\n unfold not. intros. \n unfold not. intros. apply le_le_eq in H0. rewrite H0 in H. apply lt_nn in H. apply H. apply H3.\nQed.\n\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. inversion H1.\n - intros. apply not_exists_dist with  (X:= list X) (P:= repeats) (x:= x:: l1') in H. apply H.\n  unfold not. intros. inversion H2. apply H3.\n\n(*  rewrite <- app_nil_r. simpl. rewrite app_one. apply replace_many. apply H.\n  unfold not. intros. inversion H2. apply H3. induction x0. \n apply IHl1' with (l2:= l2).\n  apply H. intros. apply H0. simpl. right. apply H2.\n  apply not_exists_dist with  (X:= nat) (P:= lt (length l2)) (x:= length l1') in H. apply H.\n  unfold not. intros. inversion H3. induction x0. *)\nAbort.\n\n\n\n\n(*\u4ee5\u4e0b\u306e4\u3064\u306fexcluded_middle\u3092\u542b\u3081\u3066\u7b49\u4fa1\u3067\u3042\u308b\u3002\n\u3000\u8a3c\u660e\u3057\u308d\u3002*)\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\n\n", "meta": {"author": "NeM-T", "repo": "sfc", "sha": "e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e", "save_path": "github-repos/coq/NeM-T-sfc", "path": "github-repos/coq/NeM-T-sfc/sfc-e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e/practice/Coq/SF/1st/indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.9073122119620789, "lm_q1q2_score": 0.8333483378008447}}
{"text": "(* Sheffer 1913 states that any of the logical connectives\n  for Boolean algebra can be implemented with the other using not and the logical connective.*)\n\nRequire Import Bool.\n\nExample andb_orb : forall a b : bool,\n  (* a \u2227 b = \u00ac(\u00aca\u2228\u00acb) *)\n  andb a b = negb(orb (negb a) (negb b)).\nProof.\n  intros a b.\n  destruct a.\n  - simpl. rewrite -> negb_involutive. reflexivity.\n  - auto.\nQed.\n\nSearch (negb (negb _)).\n\nExample andb_implb : forall a b : bool,\n  (* a \u2227 b = \u00ac(a\u21d2\u00acb) *)\n  andb a b = negb (implb a (negb b)).\nProof.\n  intros a b.\n  destruct a.\n  - simpl. rewrite -> negb_involutive. reflexivity.\n  - auto.\nQed.\n\nExample orb_andb : forall a b: bool,\n  (* a \u2228 b\t= \u00ac(\u00aca\u2227\u00acb) *)\n  orb a b = negb (andb (negb a) (negb b)).\nProof.\n  intros a b.\n  destruct a.\n  destruct b.\n  - auto.\n  - auto.\n  - simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n\nExample orb_implb : forall a b: bool,\n  (* a \u2228 b = \u00aca\u21d2b *)\n  orb a b = implb (negb a) b.\nProof.\n  intros a b.\n  destruct a.\n  - auto.\n  - auto.\nQed.\n\nExample implb_andb : forall a b: bool,\n  (* a \u21d2 b\t\u00ac(a\u2227\u00acb) *)\n  implb a b = negb(andb a (negb b)).\nProof.\n  intros a b.\n  unfold implb.\n  destruct a.\n  - destruct b. auto. auto.\n  - auto.\nQed.\n\nExample implb_orb : forall a b : bool,\n  (* a \u21d2 b = \u00aca\u2228b *)\n  implb a b = orb (negb a) b.\nProof.\n  intros a b.\n  unfold implb.\n  destruct a.\n  - destruct b. auto. auto.\n  - auto.\nQed.\n\nDefinition nandb (a: bool) (b: bool) : bool:=\n  negb (andb a b).\n\nExample nandb_tt : nandb true  true   = false. auto. Qed.\nExample nandb_tf : nandb false true   = true. auto. Qed.\nExample nandb_ft : nandb true  false  = true. auto. Qed.\nExample nandb_ff : nandb false false  = true. auto. Qed.\n\nExample xorb_andb : forall a b : bool,\n(* (a \u2295 b) = \u00ac(\u00ac(a \u2227 \u00acb) \u2227 \u00ac(\u00aca \u2227 b)) *)\n  xorb a b = negb(andb (negb (andb a (negb b)))\n                       (negb (andb (negb a) b))).\nProof.\n  intros a b.\n  unfold negb, xorb.\n  destruct a.\n  - destruct b. auto. auto.\n  - destruct b. auto. auto.\nQed.\n\nExample xorb_orb : forall a b : bool,\n(* (a \u2295 b) = \u00ac(\u00ac(\u00aca \u2228 \u00acb)\u2228 \u00ac(a\u2228b)) *)\n  xorb a b = negb(orb (negb (orb (negb a) (negb b)))\n                      (negb (orb a b))).\nProof.\n  intros a b.\n  unfold negb, xorb.\n  destruct a.\n  - destruct b. auto. auto.\n  - destruct b. auto. auto.\nQed.\n\nExample xorb_implb : forall a b : bool,\n(* (a \u2295 b) = \u00ac((a \u21d2 \u00acb) \u21d2 \u00ac(\u00aca \u21d2 b)) *)\n  xorb a b = negb ( implb (implb a (negb b))\n                          (negb (implb (negb a) (b)))).\nProof.\n  intros a b.\n  unfold negb, implb, xorb.\n  destruct a.\n  - destruct b. auto. auto.\n  - destruct b. auto. auto.\nQed.\n\nExample nandb_negb : forall b : bool,\n(* \u00acb = b | b *)\n  negb b = nandb b b.\nProof.\n  unfold negb.\n  destruct b.\n  auto. auto.\nQed.\n\nExample nandb_andb : forall a b : bool,\n(* a \u2227 b = (a | b) | (a | b) *)\n  andb a b = nandb (nandb a b) (nandb a b).\nProof.\n  intros a b.\n  unfold nandb, andb, negb.\n  destruct a.\n  - destruct b. auto. auto.\n  - auto.\nQed.\n\nExample nandb_orb : forall a b : bool,\n(* a \u2228 b = (a | a) | (b | b) *)\n  orb a b = nandb (nandb a a) (nandb b b).\nProof.\n  intros a b.\n  unfold nandb, andb, negb, orb.\n  destruct a.\n  - auto.\n  - destruct b. auto. auto.\nQed.\n\nExample nandb_implb1 : forall a b : bool,\n(* a \u21d2 b = (a | (b | b)) *)\n  implb a b = nandb a (nandb b b).\nProof.\n  intros a b.\n  unfold nandb, implb, negb.\n  destruct a.\n  - destruct b. auto. auto.\n  - auto.\nQed.\n\nExample nandb_implb2 : forall a b : bool,\n(* a \u21d2 b = (a | (a | b)) *)\n  implb a b = nandb a (nandb a b).\nProof.\n  intros a b.\n  unfold nandb, implb, negb.\n  destruct a.\n  - destruct b. auto. auto.\n  - auto.\nQed.\n\nExample nandb_eqb : forall a b : bool,\n(*a <-> b = ((a | b) | ((a | a) | (b | b))) *)\n  eqb a b = nandb (nandb a b) (nandb (nandb a a) (nandb b b)).\nProof.\n  intros a b.\n  unfold eqb, nandb, negb, andb.\n  destruct a.\n  - destruct b. auto. auto.\n  - destruct b. auto. auto.\nQed.\n\nRequire Import ExtrHaskellBasic.\nExtraction Language Haskell.\nExtraction \"nandeqb.hs\" nandb_eqb.\n\n(* TODO write the props in set. https://stackoverflow.com/questions/27175971/generating-haskell-code-from-coq-logical-or-arity-value-used#comment42848956_27176986*)\nRequire Import ExtrHaskellBasic.\n", "meta": {"author": "adpextwindong", "repo": "coqfoundations_notes", "sha": "55324d1270ffdfa2ae911a5929d50f4e91fc5c76", "save_path": "github-repos/coq/adpextwindong-coqfoundations_notes", "path": "github-repos/coq/adpextwindong-coqfoundations_notes/coqfoundations_notes-55324d1270ffdfa2ae911a5929d50f4e91fc5c76/sheffer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.9005297921244243, "lm_q1q2_score": 0.8331971409273836}}
{"text": "(** * Indu\u00e7\u00e3o em Coq *)\n\nRequire Export aula03_provas.\n\n(* ############################################### *)\n(** * Prova por indu\u00e7\u00e3o *)\n\n(** Nem sempre \u00e9 poss\u00edvel provar somente por:\n    - simplifica\u00e7\u00e3o\n    - reescrita\n    - an\u00e1lise de casos *)\n\n(** Na aula passada, vimos o seguinte teorema *)\n\nPrint plus_O_n.\n\n(** E se quisermos provar n + 0 = n? *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n.\n  simpl. (* n\u00e3o simplifica nada *)\n  try reflexivity.\n(** [reflexivity] n\u00e3o funciona, pois [n]\n    em [n + 0] \u00e9 um n\u00famero arbitr\u00e1rio e\n    n\u00e3o caso padr\u00e3o com o [+] *)\n  Print NatPlayground2.plus.\nAbort.\n\n(** An\u00e1lise de casos tamb\u00e9m n\u00e3o ajuda. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  - (* n = 0 *)\n    reflexivity. (* quando [n] \u00e9 0, funciona *)\n  - (* n = S n' *)\n    simpl.       (* aqui [n] \u00e9 [S n'],\n                  outro n\u00famero arbitr\u00e1rio *)\nAbort.\n\n(** Chamadas sucessivas a [destruct n']\n    tamb\u00e9m n\u00e3o ajudaria. Precisamos de indu\u00e7\u00e3o. *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'.\n                   reflexivity.\nQed.\n\n(** Outro exemplo. *)\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(** Nota: [induction] move automaticamente\n    vari\u00e1veis quantificadas para o contexto. *)\n\n(** **** Exercise: (basic_induction)  *)\n(** Prove os seguintes teoremas. Ser\u00e1 necess\u00e1rio\n    buscar por resultados previamente provados. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n as [|n' IH].\n  - reflexivity.\n  - Print Nat.mul. simpl. rewrite -> IH. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m. induction n as [|n' IH].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IH. reflexivity. \nQed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IH].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite -> IH. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [|n' IH].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IH. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Provas aninhadas *)\n\n(** \u00c9 possivel/aconselh\u00e1vel quebrar provas maiores\n    em subprovas. Isto pode ser feito a partir de\n    [Lemma], como tamb\u00e9m a partir de \"sub-teoremas\". *)\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n  {\n    reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(** Outro exemplo: veja que a t\u00e1tica [rewrite]\n    n\u00e3o \u00e9 muito \"inteligente\" sobre onde aplicar\n    a reescrita no objetivo. *)\n\nTheorem plus_rearrange_firsttry :\n  forall n m p q : nat,\n    (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* S\u00f3 queremos trocar (n + m) por (m + n). *)\n  rewrite -> plus_comm.\n  (* Mas  reescrita n\u00e3o faz o que queremos. *)\nAbort.\n\n(** Veja a pr\u00f3xima prova. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Mais exerc\u00edcios *)\n\n(** **** Exercise: (mult_comm)  *)\n(** Use [assert] para ajudar na prova. N\u00e3o \u00e9\n    necess\u00e1rio usar indu\u00e7\u00e3o. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros. rewrite plus_assoc.\n  assert (H: n + m = m + n).\n  {\n    rewrite plus_comm. reflexivity.\n  }\n  rewrite -> H. rewrite plus_assoc.\n  reflexivity.\nQed.\n\n(** Agora, prove comutatividade da multiplica\u00e7\u00e3o.\n    Talvez seja necess\u00e1rio provar um teorema auxiliar.\n    O teorema [plus_swap] ser\u00e1 \u00fatil. *)\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros. induction m as [|m' IH].\n  - simpl. Search (_ * 0). rewrite <- mult_n_O.\n    reflexivity.\n  - simpl. Print Nat.mul. Search (_ * _). rewrite <- mult_n_Sm.\n    rewrite plus_comm. rewrite -> IH. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Induction\n  https://softwarefoundations.cis.upenn.edu/lf-current/Induction.html\n*)\n", "meta": {"author": "gabritto", "repo": "TAES", "sha": "68512767bd3658beae20196f34ba785d001cca9a", "save_path": "github-repos/coq/gabritto-TAES", "path": "github-repos/coq/gabritto-TAES/TAES-68512767bd3658beae20196f34ba785d001cca9a/aula04_inducao.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.925229962761739, "lm_q1q2_score": 0.833197138005729}}
{"text": "Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\n(* As with numbers, simple facts about list-processing functions can sometimes be proved entirely by simplification. For example, just the simplification performed by reflexivity is enough for this theorem... *)\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n\n(* Also, as with numbers, it is sometimes helpful to perform case analysis on the possible shapes (empty or non-empty) of an unknown list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity. Qed.\n\n(* Notice that the as annotation on the destruct tactic here introduces two names, n and l', corresponding to the fact that the cons constructor for lists takes two arguments (the head and tail of the list it is constructing). *)\n(* Usually, though, interesting theorems about lists require induction for their proofs. We'll see how to do this next. *)\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  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. \n  Qed. \n\n\n(* reversing a list *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\n\n\n\n(* For something a bit more challenging than the proofs we've seen so far, let's prove that reversing a list does not change its length. Our first attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving ++, but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(* So let's take the equation relating ++ and length that would have enabled us to make progress at the point where we got stuck and state it as a separate lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(* also be needing this *)\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof. Admitted.\n\n(* Now we can complete the original proof. *)\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length.\n    simpl. rewrite -> IHl'. rewrite add_comm.\n    reflexivity.\nQed.\n\n(* Search *)\n(* We've seen that proofs can make use of other theorems we've already proved, e.g., using rewrite. But in order to refer to a theorem, we need to know its name! Indeed, it is often hard even to remember what theorems have been proven, much less what they are called.\nCoq's Search command is quite helpful with this. Let's say you've forgotten the name of a theorem about rev. The command Search rev will cause Coq to display a list of all theorems involving rev. *)\nSearch rev.\n\n(* Or say you've forgotten the name of the theorem showing that plus is commutative. You can use a pattern to search for all theorems involving the equality of two additions *)\nSearch (_ + _ = _ + _).\n\n(* You'll see a lot of results there, nearly all of them from the standard library. To restrict the results, you can search inside a particular module: *)\n(* Search (_ + _ = _ + _) inside Induction. *)\n\n(* You can also make the search more precise by using variables in the search pattern instead of wildcards: *)\nSearch (?x + ?y = ?y + ?x).", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/lessons/reasoning_about_lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.925229954514902, "lm_q1q2_score": 0.8331971330491724}}
{"text": "(*\nThis defines the exp function by recursion on peano naturals. The \"Fixpoint\" keyword \nis required for recursive definitions (instead of \"Definition\"), and the recursive \ncalls must make one argument structurally smaller in order for termination to be \nautomatically verified (which is needed for logical soundness).\n*)\nFixpoint exp (b e : nat) : nat :=\n    match e with\n    | 0 => 1\n    | S e' => b * exp b e'\n    end.\n\n(*\nThese are two scripts for \"Ltac\", Coq's proof automation language, that are \nenough to prove anything that's provable by a combination of 1 step of beta \nreduction and induction. This includes most properties of addition, and some \nproperties of multiplication. Hooks for more complex logic are provided by the \nfirst script, which shortens some later proofs. The \"[ a | b ]; c\" syntax is used \nto run a in the first case (of a proof by cases/induction), b in the second case, \nand c afterwards.\n*)\nLtac simple_nat_induction n c1 c2 := intros; induction n as [ | n IHn ]; simpl; [ c1 | rewrite IHn; c2 ]; reflexivity.\nLtac simple_nat_induction' n := simple_nat_induction n idtac idtac.\n\n(* Right reduction properties for plus (the standard library defines it left-recursively) *)\nTheorem plus_rightzero : forall n, n + 0 = n. simple_nat_induction' n. Qed.\nTheorem plus_rightsucc : forall n m, n + (S m) = S (n + m). simple_nat_induction' n. Qed.\n\n(* Associativity/commutativity for plus are fairly routine; \"ltac:(...)\" is used to pass ltac script fragments as arguments *)\nTheorem plus_associative : forall x y z, (x + y) + z = x + (y + z). simple_nat_induction' x. Qed.\nTheorem plus_commutative : forall n m, n + m = m + n. simple_nat_induction n ltac:(rewrite plus_rightzero) ltac:(rewrite plus_rightsucc). Qed.\n\n(* Right reduction properties for mult (the standard library defines it left-recursively) *)\nTheorem mult_rightzero : forall n, n * 0 = 0. simple_nat_induction' n. Qed.\nTheorem mult_rightsucc : forall n m, n * (S m) = (n * m) + n. simple_nat_induction n idtac ltac:(rewrite plus_rightsucc, plus_associative). Qed.\n\n(*\nThe proof of associativity of multiplication is more involved than the \ncorresponding proof for addition, and requires the distributivity of \nmultiplication as a lemma. The distributivity proofs basically involve \nshuffling terms around with addition's properties in the inductive step.\n*)\nTheorem mult_leftdist : forall x y z, x * (y + z) = x * y + x * z.\n    intros; induction x.\n    - reflexivity.\n    - simpl. rewrite IHx.\n        rewrite (plus_associative y (x * y) (z + x * z)).\n        rewrite <- (plus_associative (x * y) z (x * z)).\n        rewrite (plus_commutative (x * y) z).\n        (* \"repeat rewrite\" is used here to turn the expression tree back into a linked \n        list after the rewrites have been done (association can be thought of as tree \n        rotation, and commutation as swapping left and right subtrees *)\n        repeat rewrite <- plus_associative.\n        reflexivity.\n    Qed.\n(* in the right-distributive case, \"repeat rewrite\" is used to apply right reductions until they no longer apply *)\nTheorem mult_rightdist : forall x y z, (x + y) * z = x * z + y * z.\n    intros; induction z.\n    - repeat rewrite mult_rightzero. reflexivity.\n    - repeat rewrite mult_rightsucc. rewrite IHz.\n        rewrite (plus_commutative (y * z) y).\n        rewrite (plus_associative (x * z) x (y + y * z)).\n        rewrite <- (plus_associative x y (y * z)).\n        rewrite (plus_commutative (x + y) (y * z)).\n        rewrite plus_associative.\n        reflexivity.\n    Qed.\n\n(* Associativity/commutativity for mult are straightforward once the above lemmas have been proven *)\nTheorem mult_associative : forall x y z, (x * y) * z = x * (y * z).\n    intros; induction x; [| simpl; rewrite mult_rightdist, IHx ]; reflexivity.\n    Qed.\n\nTheorem mult_commutative : forall n m, n * m = m * n.\n    intros n m; induction n; simpl;\n        [ rewrite mult_rightzero\n        | rewrite mult_rightsucc, (plus_commutative m (n * m)), IHn\n    ]; reflexivity.\n    Qed.\n\n(*\nThe original goal of part 1 (that exponentiation distributes over multiplication) \ninvolves term rewriting using multiplication's associativity / commutatitivity, \nwhich all of the above was building up to. The first one was written purely \ninteractively, the second one was written with the benefit of hindsight and \nincludes the intermediate contexts to make the rewrites visible in the source.\n*)\nTheorem exp_dist : forall n x y, exp (x*y) n = exp x n * exp y n.\n    intros n x y. induction n.\n    - reflexivity.\n    - simpl.\n        rewrite (mult_associative x (exp x n) (y * exp y n)).\n        rewrite <- (mult_associative (exp x n) y (exp y n)).\n        rewrite (mult_commutative (exp x n) y).\n        rewrite IHn.\n        repeat rewrite mult_associative.\n        reflexivity.\n    Qed.\n\nTheorem exp_dist' : forall n x y, exp (x*y) n = exp x n * exp y n.\n    intros n x y. induction n as [| n IHn].\n    - reflexivity.\n    - simpl. repeat match goal with\n    | |- (x * y) * exp (x * y) n = (x * exp x n) * (y * exp y n) => rewrite (mult_associative x (exp x n) (y * exp y n))\n    | |- (x * y) * exp (x * y) n = x * (exp x n * (y * exp y n)) => rewrite <- (mult_associative (exp x n) y (exp y n))\n    | |- (x * y) * exp (x * y) n = x * ((exp x n * y) * exp y n) => rewrite (mult_commutative (exp x n) y)\n    | |- (x * y) * exp (x * y) n = x * ((y * exp x n) * exp y n) => rewrite IHn\n    | |- (x * y) * (exp x n * exp y n) = x * ((y * exp x n) * exp y n) => repeat rewrite mult_associative\n    end. reflexivity.\n    Qed.\n\n(*\nThe third proof of distributivity (exp_dist'') makes use of Coq's library for \nreasoning about algebraic [semi-]rings. It handles associative/commutative \nrewrites by abstracting terms into variables in a polynomial and putting the \npolynomial into canonical form. This results in an extremely short/robust \nproof. The bulk of the work of proving that Peano naturals form a semiring is \n{associativity,commutativity} of {addition,multiplication}; the remainder is \nstraightforward reductions involving 0/1.\n*)\n\nRequire Export Ring.\nDefinition nat_semiring : Ring_theory.semi_ring_theory 0 1 plus mult eq := {|\n    SRadd_0_l := fun _ => eq_refl;\n    SRadd_comm := plus_commutative;\n    SRadd_assoc := (fun x y z => eq_sym (@ plus_associative x y z));\n    SRmul_1_l := plus_rightzero;\n    SRmul_0_l := fun _ => eq_refl;\n    SRmul_comm := mult_commutative;\n    SRmul_assoc := (fun x y z => eq_sym (@ mult_associative x y z));\n    SRdistr_l := mult_rightdist;\n    |}.\nAdd Ring nat_semiring : nat_semiring.\nTheorem exp_dist'' : forall n x y, exp (x*y) n = exp x n * exp y n.\n    intros n x y; induction n as [| n IHn]; simpl; [| rewrite IHn; ring_simplify ]; reflexivity.\n    Qed.\n\n(*\nFor part 2, I did each proof both with explicit term manipulation, and then \nwith ltac (under the same name suffixed with a prime). The term manipulation \nproofs are longer in the source, but the ltac proofs expand into longer terms.\n\nAccording to the Coq manual, \"tauto\" implements a decision procedure for \ntautologies in intuitionistic logic from a 1992 paper in the Journal of Symbolic \nLogic. It's sufficient to completely solve 4.4 a on it's own, and sufficient to \nsolve 4.4 b once the Law of the Excluded Middle has been brought into scope.\n*)\n\n(* 4.4 a is basically currying, with (conj/proj1/proj2) in Prop instead of (pair/fst/snd) in Set *)\nDefinition part2_44_a : forall (A B C : Prop), (A -> B -> C) -> (A /\\ B -> C) := fun A B C f x => f (proj1 x) (proj2 x).\nTheorem part2_44_a' : forall (A B C : Prop), (A -> B -> C) -> (A /\\ B -> C). tauto. Qed.\n\n(* 4.4 b requires the Law of the Excluded Middle, which isn't a primitive in the Calculus of Constructions, and must be asserted as an axiom. *)\nAxiom LEM : forall P, P \\/ ~P.\n(*\nThe \"match ... with ... end\" construct is used for pattern matching at the value level \n(i.e. in kind Set), and proof by cases at the proof level (i.e. in kind Prop). Proof by \ncontradiction in CoC ends up being a special case of proof by cases, with the False type \n(representing a contradiction) having 0 constructors, and a disjunction with 0 cases not \nrequiring any steps to prove the conclusion. ~E is sugar for (E -> False), so that if E \nis instantiated, the term of type ~E can be applied to it get a value of type False, \nwhich can be pattern matched on to get the principle of explosion.\n\nThe \"fun ... => ...\" construct is used for lambdas, which are typed as either \nimplications or foralls (necessarily as the latter if the type of the body \ndepends on the value of the binder, i.e. a dependent type)\n*)\nDefinition part2_44_b : forall (A B C D E : Prop), (A \\/ B -> C \\/ D -> E) -> (A -> ~E -> ~C) :=\n    fun A B C D E f a ne => match LEM C with\n    | or_introl c => match (ne (f (or_introl a) (or_introl c))) with end\n    | or_intror nc => nc\n    end.\nTheorem part2_44_b' : forall (A B C D E : Prop), (A \\/ B -> C \\/ D -> E) -> (A -> ~E -> ~C).\n    intros; destruct (LEM C); tauto.\n    Qed.\n", "meta": {"author": "aweinstock314", "repo": "coq-stuff", "sha": "a07354390b666226416ccd6809b0a7c50805c664", "save_path": "github-repos/coq/aweinstock314-coq-stuff", "path": "github-repos/coq/aweinstock314-coq-stuff/coq-stuff-a07354390b666226416ccd6809b0a7c50805c664/softwareverification_homework1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.9059898191142621, "lm_q1q2_score": 0.8331867744622474}}
{"text": "(****************************)\n(************ TP6 ***********)\n(****************************)\nRequire Import ZArith.\nOpen Scope Z_scope.\n(********** Exercice 1 **********)\n(* Question 1 *)\nInductive expr : Set :=\n| Plus : expr -> expr -> expr\n| Minus : expr -> expr -> expr\n| Mult : expr -> expr -> expr\n| Oper : Z -> expr.\n\n(* Question 2 *)\nDefinition exemple_1 := Mult (Plus (Oper 2) (Oper 5)) (Oper 3).\nDefinition exemple_2 := Minus (Plus (Minus (Oper 2) (Oper 1)) (Mult (Oper 7) (Oper 6))) (Oper 2).\n\n(* Question 3 *)\nFixpoint eval_expr (e:expr) : Z :=\nmatch e with\n| Plus a b => (eval_expr a) + (eval_expr b)\n| Minus c d => (eval_expr c) - (eval_expr d)\n| Mult e f => (eval_expr e) * (eval_expr f)\n| Oper o => o\nend.\n\nEval compute in eval_expr (Mult (Plus (Oper 2) (Oper 5)) (Oper 3)).\nEval compute in eval_expr (exemple_2).\n\n(********** Exercice 2 **********)\n(* Question 4 *)\nInductive element : Set :=\n| Plus_symb : element\n| Minus_symb : element\n| Mult_symb : element\n| Operande : Z -> element.\n\nDefinition liste_postfixe := list element.\n(* Question 5 *)\nOpen Scope list_scope.\n\nDefinition exemple_3 := (Operande 2)::(Operande 5)::Plus_symb::(Operande 3)::Mult_symb::nil.\nDefinition exemple_4 := (Operande 2)::(Operande 1)::Minus_symb::(Operande 7)::(Operande 6)::Mult_symb::Plus_symb::(Operande 2)::Minus_symb::nil.\n\n(* Question 6 *)\nDefinition pile := list Z.\nDefinition pile_nouv : pile := nil.\n\nDefinition empiler (l:pile) (e:Z) := e::l.\n\nDefinition depiler (l:pile) :=\nmatch l with\n| nil => 9999::nil\n| a::b => b\nend.\n\nDefinition sommet (l:pile) :=\nmatch l with\n| nil => (-1)\n| a::b => a\nend.\n\nFixpoint eval_postfixe2 (l:liste_postfixe) (p:pile) :=\nmatch l with\n| nil => p\n| a::b => let s1 := sommet p in\n          let p1 := depiler p in\n          let s2 := sommet p1 in\n          let p2 := depiler p1 in \n          eval_postfixe2 b (\n            match a with\n            | Plus_symb => empiler p2 (s1 + s2)\n            | Minus_symb => empiler p2 (s2 - s1)\n            | Mult_symb => empiler p2 (s1 * s2)\n            | Operande o => empiler p o\n            end\n          )\nend.\n\nDefinition eval_postfixe (l:liste_postfixe) := sommet(eval_postfixe2 l pile_nouv).\n\n(* Question 8 *)\nEval compute in eval_postfixe exemple_3.\nEval compute in eval_postfixe exemple_4.\n\n(********** Exercice 3 **********)\n(* Question 9 *)\nFixpoint translate (e:expr) :=\nmatch e with\n| Plus a b => (translate a)++(translate b)++(Plus_symb::nil)\n| Minus c d => (translate c)++(translate d)++(Minus_symb::nil)\n| Mult e f => (translate e)++(translate f)++(Mult_symb::nil)\n| Oper o => (Operande o)::nil\nend.\n\nEval compute in translate exemple_1.\nEval compute in translate exemple_2.\n\n(* Question 10 *)\nInductive well_formed : liste_postfixe -> Prop :=\n| w_seul : forall (z:Z), well_formed ((Operande z)::nil)\n| w_plus : forall (l1 l2:liste_postfixe), \n          well_formed l1 ->\n          well_formed l2 ->\n          well_formed (l1++l2++(Plus_symb::nil)) \n| w_moins : forall (l1 l2:liste_postfixe), \n          well_formed l1 ->\n          well_formed l2 ->\n          well_formed (l1++l2++(Minus_symb::nil))\n| w_fois : forall (l1 l2:liste_postfixe), \n          well_formed l1 ->\n          well_formed l2 ->\n          well_formed (l1++l2++(Mult_symb::nil)).\n\n(* Question 11 *)\nLemma wf_ok : forall (e:expr),\nwell_formed (translate e).\nProof.\nintros.\ninduction e.\nsimpl.\napply w_plus;\nassumption.\napply w_moins;\nassumption.\napply w_fois;\nassumption.\napply w_seul.\nQed.\n\n(* Question 12 *)\nLemma append_eval : forall (e f:liste_postfixe), forall (p:pile),\neval_postfixe2 (e ++ f) p = eval_postfixe2 f (eval_postfixe2 e p).\nProof.\ninduction e.\nsimpl.\nreflexivity.\nintros.\nsimpl.\napply IHe.\nQed.\n\nLemma depiler_eval : forall (f:liste_postfixe),\nwell_formed f -> forall p:pile, p=depiler(eval_postfixe2 f p).\nProof.\nintros.\ngeneralize p.\ninduction H; intros.\nsimpl.\nreflexivity.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- IHwell_formed2.\nrewrite <- IHwell_formed1.\nreflexivity.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- IHwell_formed2.\nrewrite <- IHwell_formed1.\nreflexivity.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- IHwell_formed2.\nrewrite <- IHwell_formed1.\nreflexivity.\nQed.\n\n(* Question 13 *)\nLemma lemma_plus : forall (e f:liste_postfixe), forall (p:pile),\nwell_formed e ->\nwell_formed f ->\nsommet (eval_postfixe2 e p) + sommet (eval_postfixe2 f (eval_postfixe2 e p))=\nsommet (eval_postfixe2 (e ++ (f ++ ((Plus_symb)::nil))) p).\nProof.\nintros.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- depiler_eval.\nrewrite Zplus_comm.\nreflexivity.\nassumption.\nQed.\n\n(* Question 14 *)\nLemma lemma_minus : forall (e f:liste_postfixe), forall (p:pile),\nwell_formed e ->\nwell_formed f ->\nsommet (eval_postfixe2 e p) - sommet (eval_postfixe2 f (eval_postfixe2 e p))=\nsommet (eval_postfixe2 (e ++ (f ++ ((Minus_symb)::nil))) p).\nProof.\nintros.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- depiler_eval.\nreflexivity.\nassumption.\nQed.\n\nLemma lemma_mult: forall (e f:liste_postfixe), forall (p:pile),\nwell_formed e ->\nwell_formed f ->\nsommet (eval_postfixe2 e p) * sommet (eval_postfixe2 f (eval_postfixe2 e p))=\nsommet (eval_postfixe2 (e ++ (f ++ ((Mult_symb)::nil))) p).\nProof.\nintros.\nrewrite append_eval.\nrewrite append_eval.\nsimpl.\nrewrite <- depiler_eval.\nrewrite Zmult_comm.\nreflexivity.\nassumption.\nQed.\n\n(* Question 15 *)\nLemma interp_ok' : forall e:expr, forall p:pile,\neval_expr e = sommet (eval_postfixe2 (translate e) p).\nProof.\nintros.\ngeneralize p.\ninduction e.\nintros.\nsimpl.\nrewrite <- lemma_plus.\nrewrite <- IHe1.\nrewrite <- IHe2.\nreflexivity.\napply wf_ok.\napply wf_ok.\nintros.\nsimpl.\nrewrite <- lemma_minus.\nrewrite <- IHe1.\nrewrite <- IHe2.\nreflexivity.\napply wf_ok.\napply wf_ok.\nintros.\nsimpl.\nrewrite <- lemma_mult.\nrewrite <- IHe1.\nrewrite <- IHe2.\nreflexivity.\napply wf_ok.\napply wf_ok.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nLemma interp_ok : forall e:expr,\neval_expr e = (eval_postfixe (translate e)).\nProof.\nintros.\nunfold eval_postfixe.\napply interp_ok'.\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", "meta": {"author": "Neo-Purpinc", "repo": "Preuves-Assistees-par-Ordinateur", "sha": "f285b2efa87283e3940121095a67a98b1b488357", "save_path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur", "path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur/Preuves-Assistees-par-Ordinateur-f285b2efa87283e3940121095a67a98b1b488357/TP6/TP6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8329543323933487}}
{"text": "(* Proof Objects *)\nRequire Export Logic.\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 : nat, beautiful n -> beautiful m -> beautiful (n + m).\n\n\nPrint beautiful.\n\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'''.\n\n(**************************************************\nExercise: 1 star (six_is_beautiful)\nGive a tactic proof and a proof object showing that 6 is beautiful.\n**************************************************)\n\nTheorem six_is_beautiful :\n  beautiful 6.\nProof.\n  apply b_sum with (n:=3) (m:=3).\n  apply b_3. apply b_3.\nQed.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  b_sum 3 3 b_3 b_3.\n\n\n\n(**************************************************\nExercise: 1 star (nine_is_beautiful)\nGive a tactic proof and a proof object showing that 9 is beautiful.\n**************************************************)\n\nTheorem nine_is_beautiful : beautiful 9.\nProof.\n  \n\n\nDefinition nine_is_beautiful' : beautiful 9 :=\n  (* FILL IN HERE *) admit.\n\u2610\n", "meta": {"author": "madsravn", "repo": "software_foundations", "sha": "2a7cf402b0a05430961018bd113fb4b2ec03b113", "save_path": "github-repos/coq/madsravn-software_foundations", "path": "github-repos/coq/madsravn-software_foundations/software_foundations-2a7cf402b0a05430961018bd113fb4b2ec03b113/lesson9_ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.9032941969413321, "lm_q1q2_score": 0.83276663764475}}
{"text": "(* week_38a_recap.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* Learning goals for this week:\n\n   - Using previous lemmas (with rewrite or apply)\n     without giving them all their arguments,\n     and\n     acquiring a sense of which arguments are actually needed,\n     to disambiguate.\n\n     To this end, all the proofs of this week's exercises\n     should be in two versions, separated by \"Restart.\":\n     * in the first version,\n       all the uses of previous lemmas\n       should have _complete arguments_; and\n     * in the second version,\n       all the uses of previous lemmas\n       should have _as few arguments as possible_.\n\n   - at\n\n   - The exact tactic:\n     it is like apply, requires all the arguments,\n     and is used to complete a subgoal.\n\n   - The f_equal tactic:\n     it is like f_equal_S,\n     just for any function rather than just for S.\n\n   - Proofs by case.\n\n   - Searching the libraries.\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nSearch (_ + _ = _ + _ -> _ = _).\n\nSearchAbout plus.\n\n(* ********** *)\n\nRequire Import unfold_tactic.\n\nLemma unfold_plus_bc :\n  forall y : nat,\n    0 + y = y.\n(* left-hand side in the base case of plus\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall x' y : nat,\n    (S x') + y = S (x' + y).\n(* left-hand side in the inductive case of plus\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_mult_bc :\n  forall y : nat,\n    0 * y = 0.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\nLemma unfold_mult_ic :\n  forall x' y : nat,\n    (S x') * y = y + (x' * y).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\n(* ***** *)\n\nLemma plus_1_l :\n  forall x : nat,\n    1 + x = S x.\nProof.\n  intro x.\n  rewrite -> (unfold_plus_ic 0).\n  rewrite -> (unfold_plus_bc x).\n  reflexivity.\n\n  Restart.\n\n  intro x.\n  rewrite -> unfold_plus_ic.\n  rewrite -> unfold_plus_bc.\n  reflexivity.\nQed.\n\nLemma plus_1_r :\n  forall x : nat,\n    x + 1 = S x.\nProof.\n  intro x.\n  rewrite -> (plus_comm x 1).\n  exact (plus_1_l x).\n\n  Restart.\n\n  intro x.\n  rewrite -> plus_comm.\n  apply plus_1_l.\nQed.\n\n(* ***** *)\n\nLemma f_equal_S :\n  forall x y : nat,\n    x = y -> S x = S y.\nProof.\n  intros x y.\n  intro H_xy.\n  rewrite -> H_xy.\n  reflexivity.\n\n  Restart.\n\n  Check f_equal.\n  Check (f_equal S).\n  apply (f_equal S).\n\n  Restart.\n\n  exact (f_equal S).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_1 :\n  forall x y : nat,\n    x = y -> 1 + x = 1 + y.\nProof.\n  exact (f_equal (plus 1)).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_10 :\n  forall x y : nat,\n    x = y -> 10 + x = 10 + y.\nProof.\n  exact (f_equal (plus 10)).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_20 :\n  forall x y : nat,\n    x = y -> x + 20 = 20 + y.\nProof.\n  intros x y H_xy.\n  rewrite -> (plus_comm x 20).\n  exact (f_equal (plus 20) H_xy).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> plus_comm.\n  apply f_equal.\n  exact H_xy.\nQed.\n\nLemma f_equal_plus_30 :\n  forall x y : nat,\n    x = y -> 30 + x = y + 30.\nProof.\n  intros x y H_xy.\n  rewrite -> (plus_comm y 30).\n  exact (f_equal (plus 30) H_xy).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> plus_comm.\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm y 30).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm y _).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm _ 30).\n\n  apply f_equal.\n  exact H_xy.\nQed.\n\n(* ********** *)\n\n(* Binomial expansion at rank 2: *)\n\nDefinition square (x : nat) : nat :=\n  x * x.\n\nLemma unfold_square :\n  forall x : nat,\n    square x = x * x.\nProof.\n  unfold_tactic square.\nQed.\n\nLemma binomial_2 :\n  forall x y : nat,\n    square (x + y) = square x + 2 * x * y + square y.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ********** *)\n\n(* [To be done at home, let's skip to the evenp example.] *)\n\n(* The power (i.e., exponentiation) function: *)\n\n(* A unit test: *)\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_test_for_power (candidate : nat -> nat -> nat) :=\n  (candidate 2 0 =n= 1)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 10 =n= 1024)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_power (power : nat -> nat -> nat) :=\n  (forall x : nat,\n     power x 0 = 1)\n  /\\\n  (forall x n' : nat,\n     power x (S n') = x * (power x n')).\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_power :\n  forall power1 power2 : nat -> nat -> nat,\n    specification_of_power power1 ->\n    specification_of_power power2 ->\n    forall x n : nat,\n      power1 x n = power2 x n.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* Some lemmas about power: *)\n\nLemma about_power_base_one :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall n : nat,\n      power 1 n = 1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_base_mult :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x y n : nat,\n      power (x * y) n = (power x n) * (power y n).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_exponent_plus :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x i j : nat,\n      power x (i + j) = (power x i) * (power x j).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_exponent_mult :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x i j : nat,\n      power x (i * j) = power (power x i) j.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* First implementation: *)\n\nFixpoint power_v1 (x n : nat) : nat :=\n  match n with\n    | 0 => 1\n    | S n' => x * (power_v1 x n')\n  end.\n\nCompute unit_test_for_power power_v1.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_v1_bc :\n  forall x : nat,\n    power_v1 x 0 = 1.\nProof.\n  unfold_tactic power_v1.\nQed.\n\nLemma unfold_power_v1_ic :\n  forall x n' : nat,\n    power_v1 x (S n') = x * (power_v1 x n').\nProof.\n  unfold_tactic power_v1.\nQed.\n\nProposition power_v1_satisfies_the_specification_of_power :\n  specification_of_power power_v1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* Second implementation\n   (lambda-dropped version of the first): *)\n\nDefinition power_v2 (x n_orig : nat) : nat :=\n  let fix visit (n : nat) : nat :=\n      match n with\n        | 0 => 1\n        | S n' => x * (visit n')\n      end\n  in visit n_orig.\n\nCompute unit_test_for_power power_v2.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_v2_bc :\n  forall x : nat,\n    power_v2 x 0 = 1.\nProof.\n  unfold_tactic power_v2.\nQed.\n\nLemma unfold_power_v2_ic :\n  forall x n' : nat,\n    power_v2 x (S n') = x * (power_v2 x n').\nProof.\n  unfold_tactic power_v2.\nQed.\n\nProposition power_v2_satisfies_the_specification_of_power :\n  specification_of_power power_v2.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* Third implementation (version with an accumulator): *)\n\nFixpoint power_acc (x n a : nat) : nat :=\n  match n with\n    | 0 => a\n    | S n' => power_acc x n' (x * a)\n  end.\n\nDefinition power_v3 (x n : nat) : nat :=\n  power_acc x n 1.\n\nCompute unit_test_for_power power_v3.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_acc_bc :\n  forall x a : nat,\n    power_acc x 0 a = a.\nProof.\n  unfold_tactic power_acc.\nQed.\n\nLemma unfold_power_acc_ic :\n  forall x n' a : nat,\n    power_acc x (S n') a = power_acc x n' (x * a).\nProof.\n  unfold_tactic power_acc.\nQed.\n\nProposition power_v3_satisfies_the_specification_of_power :\n  specification_of_power power_v3.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ********** *)\n\n(* The even predicate: *)\n\n(* A unit test: *)\n\nNotation \"A =b= B\" := (eqb A B) (at level 70, right associativity).\n\nDefinition unit_test_for_evenp (candidate : nat -> bool) :=\n  (candidate 0 =b= true)\n  &&\n  (candidate 1 =b= false)\n  &&\n  (candidate 2 =b= true)\n  &&\n  (candidate 3 =b= false)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_evenp (evenp : nat -> bool) :=\n  (evenp 0 = true)\n  /\\\n  (evenp 1 = false)\n  /\\\n  (forall n'' : nat,\n     evenp (S (S n'')) = evenp n'').\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_evenp :\n  forall f g : nat -> bool,\n    specification_of_evenp f ->\n    specification_of_evenp g ->\n    forall n : nat,\n      f n = g n.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* Properties: *)\n\nLemma about_evenp :\n  forall evenp : nat -> bool,\n    specification_of_evenp evenp ->\n    forall x : nat,\n      evenp (S x) = negb (evenp x).\nProof.\n  intros evenp.\n  unfold specification_of_evenp.\n  intros [H_0 [H_1 H_SS]].\n  intro x.\n  induction x as [ | x' IHx'].\n\n  rewrite -> H_1.\n  rewrite -> H_0.\n  unfold negb.\n  reflexivity.\n\n  rewrite -> H_SS.\n  rewrite -> IHx'.\n  destruct (evenp x') eqn:H_evenp_x'.\n\n    unfold negb.\n    reflexivity.\n\n  unfold negb.\n  reflexivity.\nQed.\n\nLemma about_evenp_of_a_sum :\n  forall evenp : nat -> bool,\n    specification_of_evenp evenp ->\n    forall x y : nat,\n      evenp (x + y) = eqb (evenp x) (evenp y).\nProof.\n  intros evenp.\n  unfold specification_of_evenp.\n  intros [H_0 [H_1 H_SS]].\n  intro x.\n  induction x as [ | x' IHx'].\n\n  intro y.\n  rewrite -> plus_0_l.\n  rewrite -> H_0.\n  unfold eqb.\n  destruct (evenp y) eqn:H_y.\n    reflexivity.\n  reflexivity.\n\n  intros [ | y'].\n\n  rewrite -> plus_0_r.\n  rewrite -> H_0.\n  destruct (evenp (S x')) eqn:H_evenp_Sx'.\n  unfold eqb.\n  reflexivity.\n\n  unfold eqb.\n  reflexivity.\n\n  rewrite -> unfold_plus_ic.\n  rewrite -> plus_comm.\n  rewrite -> unfold_plus_ic.\n  rewrite -> plus_comm.\n  rewrite -> H_SS.\n  rewrite -> IHx'.\n  rewrite -> about_evenp.\n  rewrite -> about_evenp.\n  destruct (evenp x') eqn:H_evenp_x'.\n    destruct (evenp y') eqn:H_evenp_y'.\n      unfold negb.\n      unfold eqb.\n      reflexivity.\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n  destruct (evenp y') eqn:H_evenp_y'.\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n  unfold negb.\n  unfold eqb.\n  reflexivity.\nQed.\n\n(* An implementation: *)\n\nFixpoint evenp_v0 (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S n' => match n' with\n                | 0 => false\n                | S n'' => evenp_v0 n''\n              end\n  end.\n\nCompute unit_test_for_evenp evenp_v0.\n(*\n     = true\n     : bool\n*)\n\n(* Or equivalently (syntactic sugar): *)\n\nFixpoint evenp_v0' (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S 0 => false\n    | S (S n'') => evenp_v0' n''\n  end.\n\nCompute unit_test_for_evenp evenp_v0'.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_evenp_v0_bc0 :\n  evenp_v0 0 = true.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nLemma unfold_evenp_v0_bc1 :\n  evenp_v0 1 = false.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nLemma unfold_evenp_v0_ic :\n  forall n'' : nat,\n    evenp_v0 (S (S n'')) = evenp_v0 n''.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nProposition evenp_satisfies_the_specification_of_evenp :\n  specification_of_evenp evenp_v0.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ********** *)\n\n(* The Fibonacci numbers: *)\n\n(* A unit test: *)\n\nDefinition unit_test_for_fib (candidate: nat -> nat) :=\n  (candidate 0 =n= 0)\n  &&\n  (candidate 1 =n= 1)\n  &&\n  (candidate 2 =n= 1)\n  &&\n  (candidate 3 =n= 2)\n  &&\n  (candidate 4 =n= 3)\n  &&\n  (candidate 5 =n= 5)\n  &&\n  (candidate 6 =n= 8)\n  &&\n  (candidate 7 =n= 13)\n  &&\n  (candidate 8 =n= 21)\n  &&\n  (candidate 9 =n= 34)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_the_fibonacci_function (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  forall n'' : nat,\n    fib (S (S n'')) = fib (S n'') + fib n''.\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_fibonacci_function :\n  forall fib1 fib2 : nat -> nat,\n    specification_of_the_fibonacci_function fib1 ->\n    specification_of_the_fibonacci_function fib2 ->\n    forall n : nat,\n      fib1 n = fib2 n.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* A first implementation: *)\n\nFixpoint fib_ds (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' => match n' with\n                | 0 => 1\n                | S n'' => fib_ds n' + fib_ds n''\n              end\n  end.\n\nDefinition fib_v0 (n : nat) : nat :=\n  fib_ds n.\n\nCompute unit_test_for_fib fib_v0.\n\nLemma unfold_fib_ds_base_case_0 :\n  fib_ds 0 = 0.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_base_case_1 :\n  fib_ds 1 = 1.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_induction_case :\n  forall n'' : nat,\n    fib_ds (S (S n'')) = fib_ds (S n'') + fib_ds n''.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nTheorem fib_ds_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_ds.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nCorollary fib_v0_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v0.\nProof.\n  unfold fib_v0.\n  apply fib_ds_fits_the_specification_of_the_fibonacci_function.\nQed.\n\n(* ***** *)\n\n(* A second implementation, with an accumulator: *)\n\nFixpoint fib_acc (n a1 a0 : nat) : nat :=\n  match n with\n    | 0 => a0\n    | S n' => fib_acc n' (a1 + a0) a1\n  end.\n\nDefinition fib_v1 (n : nat) : nat :=\n  fib_acc n 1 0.\n\nCompute unit_test_for_fib fib_v1.\n\nLemma unfold_fib_acc_base_case :\n  forall a1 a0 : nat,\n    fib_acc 0 a1 a0 = a0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\nLemma unfold_fib_acc_induction_case :\n  forall n' a1 a0 : nat,\n    fib_acc (S n') a1 a0 = fib_acc n' (a1 + a0) a1.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\nLemma unfold_fib_v1 :\n  forall n : nat,\n    fib_v1 n = fib_acc n 1 0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_acc :\n  forall fib : nat -> nat,\n    specification_of_the_fibonacci_function fib ->\n    forall k i : nat,\n      fib_acc k (fib (S i)) (fib i) = fib (k + i).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\nQed.\n\nTheorem fib_v1_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* A third implementation, with a co-accumulator: *)\n\nFixpoint fib_co_acc (n : nat) : nat * nat :=\n  match n with\n    | O => (1, 0)\n    | S n' => let (a1, a0) := fib_co_acc n'\n              in (a1 + a0, a1)\n  end.\n\nDefinition fib_v2 (n : nat) : nat :=\n  match n with\n    | O => 0\n    | S n' => let (a1, a0) := fib_co_acc n'\n              in a1\n  end.\n\nCompute unit_test_for_fib fib_v2.\n\nLemma unfold_fib_co_acc_base_case :\n  fib_co_acc 0 = (1, 0).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_co_acc_induction_case :\n  forall n' : nat,\n    fib_co_acc (S n') = let (a1, a0) := fib_co_acc n'\n                        in (a1 + a0, a1).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_v2_0 :\n  fib_v2 0 = 0.\nProof.\n  unfold_tactic fib_v2.\nQed.\n\nLemma unfold_fib_v2_Sn' :\n  forall n' : nat,\n    fib_v2 (S n') = let (a1, a0) := fib_co_acc n'\n                    in a1.\nProof.\n  unfold_tactic fib_v2.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_co_acc :\n  forall fib : nat -> nat,\n    specification_of_the_fibonacci_function fib ->\n    forall n : nat,\n      fib_co_acc n = (fib (S n), fib n).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nTheorem fib_v2_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v2.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* end of week_38a_recap.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w38/week_38a_recap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.9111797069968975, "lm_q1q2_score": 0.8325235133194161}}
{"text": "(** %\\chapter{Propositional Logic}% *)\n\nModule LogicPrimer.\n\n\n(** \n\n* Propositions and the [Prop] sort\n\nCIC as a logic is expressive enough to accommodate propositions with\nquantifications of an arbitrary order and over arbitrary values. On\none hand, it makes it an extremely powerful tool to state almost any\nproposition of interest in modern mathematics or computer science. On\nthe other hand, proving such statements (i.e., constructing their\nproof terms), will require human assistance, in the same way the\n\"paper-and-pencil\" proofs are constructed in the classical\nmathematics. However, unlike the paper-and-pencil proofs, proofs\nconstructed in Coq are a subject of immediate _automated_ check, since\nthey are just programs to be verified for well-typedness. Therefore,\nthe process of proof construction in Coq is _interactive_ and assumes\nthe constant interoperation between a human prover, who constructs a\nproof term for a proposition (i.e., writes a program), and Coq, the\nproof assistant, which carries out the task of _verifying_ the proof\n(i.e., type-checking the program). This largely defines our agenda for\nthe rest of this course: we are going to see how to _prove_ logical\nstatements by means of writing _programs_, that have the types\ncorresponding to these statements.\n\n*)\n\n(** * The truth and the falsehood in Coq *)\n\nRequire Import ssreflect.\n\nPrint True.\n\n(**\n[[\nInductive True : Prop :=  I : True\n]]\n*)\n\nTheorem true_is_true: True.\n\n(** \n[[\n1 subgoals, subgoal 1 (ID 1)\n  \n  ============================\n   True\n]]\n*)\n\nProof.\nexact: I.\n\n(** \n[[\nNo more subgoals.\n(dependent evars:)\n]]\n*)\n\nQed.\n\n(**\nSo, our first theorem is proved. As it was hinted previously, it could\nhave been stated even more concisely, formulated as a mere definition,\nand proved by means of providing a corresponding value, without the\nneed to enter a proof mode:\n*)\n\nDefinition true_is_true': True := I.\n\n(**\nThe difference between the two definitions of the truth's validity,\nwhich we have just constructed, can be demonstrated by means of the\n[Eval] command.\n*)\n\nEval compute in true_is_true. \n(**\n[ = true_is_true : True]\n*)\n\nEval compute in true_is_true'. \n(**\n[ = I : True]\n\nAs we can see now, the theorem is evaluated to itself, whereas the\ndefinition evaluates to it body, i.e., the value of the constructor\n[I].  \n\nThinking by analogy, one can now guess how the falsehood can be encoded.\n*)\n\nPrint False.\n\n(**\n[[\nInductive False : Prop :=  \n]]\n*)\n\nCheck False_ind.\n\n(**\n[[\nFalse_ind\n     : forall P : Prop, False -> P\n]]\n*)\n\nTheorem one_eq_two: False -> 1 = 2.\nProof.\n\nexact: (False_ind (1 = 2)).\n\nUndo.\n\n(**\n\nInstead of supplying the argument [(1 = 2)] to [False_ind] manually,\nwe can leave it to Coq to figure out, what it should be, by using the\nSSReflect [apply:] tactic.\n\n*)\n\napply: False_ind.\n\n(** \n\nThere are many more ways to prove this rather trivial statement, but\nat this moment we will demonstrate just yet another one, which does\nnot appeal to the [False_ind] induction principle, but instead\nproceeds by _case analysis_.\n\n*)\n\nUndo.\n\nPrint False_rect.\n\ncase.\n\n(**\n\nThe tactic [case] makes Coq to perform the case analysis. In\nparticular, it _deconstructs_ the _top assumption_ of the goal. The\ntop assumption in the goal is such that it comes first before any\narrows, and in this case it is a value of type [False]. Then, for all\nconstructors of the type, whose value is being case-analysed, the\ntactic [case] constructs _subgoals_ to be proved.  *)\n\nUndo.\n\nexact: (fun (f: False) => match f with end).\n\nQed.\n\n(** * Implication and universal quantification\n\nUnlike most of the value-level functions we have seen so far,\npropositions are usually parametrized by other propositions, which\nmakes them instances of _polymorphic_ types, as they appear in System\nF and System F_\\omega. Similarly to these systems, in Coq the\nuniversal quantifier [forall] binds a variable immediately following\nit in the scope of the subsequent type. For instance, the transitivity\nof implication in Coq can be expressed via the following proposition:\n\n%\\begin{center}%\n[forall P Q R: Prop, (P -> Q) -> (Q -> R) -> P -> R]\n%\\end{center}%\n\nThe proposition is therefore _parametrized_ over three propositional\nvariables, [P], [Q] and [R], and states that from the proof term of\ntype [P -> Q] and a proof term of type [Q -> R] one can receive a\nproof term of type [P -> R]. Let us now prove these statement in the\nform of theorem.  \n\n*)\n\nTheorem imp_trans: forall P Q R: Prop, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n\nmove=> A B C.\n(**\n[[\n  A : Prop\n  B : Prop\n  C : Prop\n  ============================\n   (A -> B) -> (B -> C) -> A -> C\n]]\n*)\n(*\nmove=> H1 H2 a.\n*)\n(**\n[[\n  H1 : A -> B\n  H2 : B -> C\n  a : A\n  ============================\n   C\n]]\n\nAgain, there are multiple ways to proceed now. For example, we can\nrecall the functional programming and get the result of type [C] just\nby two subsequent applications of [H1] and [H2] to the value [a] of type [A]:\n\n*)\n(*\nexact: (H2 (H1 a)).\n\n(**\n\nAlternatively, we can replace the direct application of the hypotheses\n[H1] and [H2] by the reversed sequence of calls to the [apply:]\ntactics.\n\n*)\n\nUndo.\n*)\n(**\nThe first use of [apply:] will replace the goal [C] by the goal [B],\nsince this is what it takes to get [C] by using [H2]:\n\n*)\nmove => H1 H2 a.\napply: H2.\n\n(** \n[[\n  H1 : A -> B\n  a : A\n  ============================\n   B\n]]\nThe second use of [apply:] reduces the proof of [B] to the proof of\n[A], demanding an appropriate argument for [H1].\n\n*)\n\napply: H1.\n(**\n[[\n  a : A\n  ============================\n   A\n]]\n*)\n\nexact: a. \nQed.\n\n(**\n\nIn the future, we will replace the use of trivial tactics, such as\n[exact:] by SSReflect's much more powerful tactics [done], which\ncombines a number of standard Coq's tactics in an attempt to finish\nthe proof of the current goal and reports an error if it fails to do\nso.  *)\n\n(** ** On forward and backward reasoning\n\nLet us check now the actual value of the proof term of theorem\n[imp_trans]. \n\n*)\n\nPrint imp_trans. \n(** \n[[\nimp_trans = \n  fun (A B C : Prop) (H1 : A -> B) (H2 : B -> C) (a : A) =>\n  (fun _evar_0_ : B => H2 _evar_0_) ((fun _evar_0_ : A => H1 _evar_0_) a)\n       : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R\n\nArgument scopes are [type_scope type_scope type_scope _ _ _]\n]]\n\nEven though the proof term looks somewhat furry, this is almost\nexactly our initial proof term from the first proof attempt: [H2 (H1\na)]. The only difference is that the hypotheses [H1] and [H2] are\n_eta-expanded_, that is instead of simply [H1] the proof terms\nfeatures its operational equivalent [fun b: B => H2 b]. Otherwise, the\nprinted program term indicates that the proof obtained by means of\ndirect application of [H1] and [H2] is the same (modulo eta-expansion)\nas the proof obtained by means of using the [apply:] tactic.\n\nThese two styles of proving: by providing a direct proof to the goal\nor some part of it, and by first reducing the goal via tactics, are\nusually referred in the mechanized proof community as _forward_ and\n_backward_ proof styles.\n\n  *)\n\n(** ** Refining and bookkeeping assumptions \n\nSuppose, we have the following theorem to prove, which is just a\nsimple reformulation of the previously proved [imp_trans]:\n\n*)\n\nTheorem imp_trans' (P Q R: Prop) : (Q -> R) -> (P -> Q) -> P -> R.\nProof.\nmove=> H1 H2.\n\nmove: (imp_trans P Q R) => H.\n(** \n[[\n  H1 : Q -> R\n  H2 : P -> Q\n  H : (P -> Q) -> (Q -> R) -> P -> R\n  ============================\n   P -> R\n]]\n*)\n\napply: H.\n(** \n[[\n  H1 : Q -> R\n  H2 : P -> Q\n  ============================\n   P -> Q\n\nsubgoal 2 (ID 142) is:\n Q -> R\n]]\n*)\n\ndone. \ndone.\n\n(**\n\nThe proof is complete, although the last step is somewhat repetitive,\nsince we know that for two generated sub-goals the proofs are the\nsame. In fact, applications of tactics can be _chained_ using the [;]\nconnective, so the following complete proof of [imp_trans'] runs\n[done] for _all_ subgoals generated by [apply: H]:\n\n*)\n\nRestart.\n\nmove: (imp_trans P Q R)=> H H1 H2.\napply: H; done.\n\n(**\n\nTo conclude this section, let us demonstrate even shorter way to prove\nthis theorem once again.\n\n*)\n\nRestart.\nmove=>H1 H2; apply: (imp_trans P Q R)=>//.\nQed.\n\n(** * Conjunction and disjunction *)\n\nModule Connectives.\nVariables P Q R: Prop.\n\nLocate \"_ /\\ _\".\n\n(** [\"A /\\ B\" := and A B  : type_scope] *)\n\nPrint and.\n\n(**\n[[\nInductive and (A B : Prop) : Prop :=  conj : A -> B -> A /\\ B\n\nFor conj: Arguments A, B are implicit\nFor and: Argument scopes are [type_scope type_scope]\nFor conj: Argument scopes are [type_scope type_scope _ _]\n]]\n*)\n\nGoal P -> R -> P /\\ R.\nmove=> p r. \n\n(** \n\nThe proof can be completed in several ways. The most familiar one is\nto apply the constructor [conj] directly. It will create two subgoals,\n[P] and [Q] (which are the constructor arguments), that can be\nimmediately discharged.\n\n*)\n\napply: conj=>//.\n\n(** \n\nAlternatively, since we now know that [and] has just one constructor,\nwe can use the generic Coq's [constructor n] tactic, where [n] is an\n(optional) number of a constructor to be applied (and in this case\nit's [1])\n\n*)\n\nUndo.\nconstructor 1=>//.\n\n(**\n\nFinally, for propositions that have exactly one constructor, Coq\nprovides a specialized tactic [split], which is a synonym for\n[constructor 1]: *)\n\nUndo. split=>//.\nQed.\n\n(** \n\nIn order to prove something out of a conjunction, one needs to\n_destruct_ it to get its constructor's arguments, and the simplest way\nto do so is by the [case]-analysis on a single constructor.\n\n*)\n\nGoal P /\\ Q -> Q.\nProof.\ncase.\n\ndone.\nQed.\n\n(**\n\nThe datatype of disjunction of [P] and [Q], denoted by [P \\/ Q], is\nisomorphic to the [sum] datatype from the provious lecture and can be\nconstructed by using one of its two constructors: [or_introl] or\n[or_intror].\n\n*)\n\nLocate \"_ \\/ _\".\n\n(** [\"A \\/ B\" := or A B   : type_scope] *)\n\nPrint or.\n\n(**\n\n[[\nInductive or (A B : Prop) : Prop :=\n    or_introl : A -> A \\/ B | or_intror : B -> A \\/ B\n\nFor or_introl, when applied to less than 1 argument:\n  Arguments A, B are implicit\n...\n]]\n\nIn order to prove disjunction of [P] and [Q], it is sufficient to\nprovide a proof of just [P] or [Q], therefore appealing to the\nappropriate constructor.\n\n*)\n\nGoal Q -> P \\/ Q \\/ R.\nmove=> q. \n\nby right; left.\nQed.\n\nGoal P \\/ Q -> Q \\/ P.\ncase=>x.\n\n(** \n[[\n  P : Prop\n  Q : Prop\n  R : Prop\n  x : P\n  ============================\n   Q \\/ P\n\nsubgoal 2 (ID 248) is:\n Q \\/ P\n]]\n*)\n\nby right.\n\n(**\n\n[[\n  P : Prop\n  Q : Prop\n  R : Prop\n  x : Q\n  ============================\n   Q \\/ P\n]]\n\nIn the second branch the type of [x] is [Q], as it accounts for the\ncase of the [or_intror] constructor.\n\n*)\n\nby left.\nQed.\n\n(** * Proofs with negation *)\n\n(**\n\nIn Coq's constructive approach proving the negation of [~P] of a\nproposition [P] literally means that one can derive\nthe falsehood from [P].\n\n*)\n\nLocate \"~ _\".\n\n(** \n[\"~ x\" := not x       : type_scope]\n*)\n\nPrint not.\n(** \n[[\n  not = fun A : Prop => A -> False\n       : Prop -> Prop\n]]\n\nTherefore, the negation [not] on propositions from [Prop] is just a\nfunction, which maps a proposition [A] to the implication [A ->\nFalse]. Calculus of Constructions lacks the axiom of double negation,\nwhich means that the proof of [~ ~A] will not deliver the proof of\n[A], as such derivation would be not constructive, as one cannot get a\nvalue of type [A] out of a function of type [(A -> B) -> B], where [B]\nis taken to be [False].\n\nHowever, reasoning out of negation helps to derive the familiar proofs\nby contradiction, given that we managed to construct [P] _and_ [~P],\nas demonstrated by the following theorem, which states that from any\n[Q] can be derived from [P] and [~P]. \n\n*)\n\nTheorem absurd: P -> ~P -> Q. \nProof. by move=>p H; move : (H p). Qed.\n\n(** \n\nOne extremely useful theorem from propositional logic involving\nnegation is _contraposition_. It states states that in an implication, the\nassumption and the goal can be flipped if inverted.\n\n*)\n\nTheorem contraP: (P -> Q) -> ~Q -> ~P.\n\n(** Let us see how it can be proved in Coq *)\n\nProof.\nmove=> H Hq. \nmove /H.\n(**\n[[\n  H : P -> Q\n  Hq : ~ Q\n  ============================\n   Q -> False\n]]\n*)\n\nmove /Hq.\ndone.\nQed.\n\n(** * Existential quantification *)\n\nLocate \"exists\".\n\n(**\n[[\n\"'exists' x .. y , p\" := ex (fun x => .. (ex (fun y => p)) ..)\n                      : type_scope\n]]\n\n*)\n\nPrint ex.\n\n(**\n[[\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> ex A P\n]]\n*)\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.\n\n(**\n\nThe parentheses are important here, otherwise, for instance, the scope\nof the first existentially-quantified variable [a] would be the whole\nsubsequent statement, not just the proposition _S a_.\n\n*)\n\nProof.\n\ncase=>a Hs Hst.\n(** \n[[\n  A : Type\n  S : A -> Prop\n  T : A -> Prop\n  a : A\n  Hs : S a\n  Hst : forall x : A, S x -> T x\n  ============================\n   exists b : A, T b\n]]\n\nNext, we apply the [ex]'s constructor by means of the [exists]\ntactic with an explicit witness value [a]: \n*)\n\nexists a.\n\n(** We finish the proof  by applying the weakening hypothesis [Hst]. *)\n\nby apply: Hst.\n\nQed.\n\n(** ** A conjunction and disjunction analogy\n\nSometimes, the universal and the existential quantifications are\nparaphrased as \"infinitary\" conjunction and disjunction\ncorrespondingly. This analogy comes in handy when understanding the\nproperties of both quantifications, so let us elabore on it for a bit.\n\n*)\n\nEnd Connectives.\n\n(** * Missing axioms from the classical logic *)\n\nRequire Import Classical_Prop.\n\n\n(**\n\nThe most often missed axiom is the axiom of _excluded middle_, which\npostulates that the disjunction of [P] and [~P] is provable. Adding\nthis axiom circumvents the fact that the reasoning out of the excluded\nmiddle principle is _non-constructive_.\n\n*)\n\nCheck classic.\n\n(** \n[[\nclassic\n     : forall P : Prop, P \\/ ~ P\n]]\n\nAnother axiom from the classical logic, which coincides with the type\nof Scheme's [call/cc] operator.\n*)\n\nDefinition peirce_law := forall P Q: Prop, ((P -> Q) -> P) -> P.\n\n(** \n\nIn Scheme-like languages, the [call/cc] operator allows one to\ninvoke the undelimited continuation, which aborts the\ncomputation. Similarly to the fact that [call/cc] cannot be\nimplemented in terms of polymorphically-typed lambda calculus as a\nfunction and should be added as an external operator, the Peirce's law\nis an axiom in the constructive logic.\n*)\n\nCheck NNPP.\n\n(** \n[[\nNNPP\n     : forall P : Prop, ~ ~P -> P\n]]\n\nFinally, the classical formulation of the implication through the\ndisjunction is again an axiom in the constructive logic, as otherwise\nfrom the function of type [P -> Q] one would be able to construct the\nproof of [~P \\/ Q], which would make the law of the excluded middle\ntrivial to derive.\n*)\n\nCheck imply_to_or.\n\n(**\n\n[[\nimply_to_or\n     : forall P Q : Prop, (P -> Q) -> ~P \\/ Q\n]]\n\nCuriously, none of these axioms, if added to Coq, makes its logic\nunsound: it has been rigorously proven (although, not within Coq, due\nto Godel's incompleteness result) that all classical logic axioms are\nconsistent with CIC, and, therefore, don't make it possible to derive\nthe falsehood.\n\n*)\n\n(** * Universes and [Prop] impredicativity\n\n_Impredicativity_ as a property of definitions allows one to define\ndomains that are _self-recursive_---a feature of [Prop] that we\nrecently observed. Unfortunately, when restated in the classical set\ntheory, impredicativity immediately leads to the famous Russel's\nparadox, which arises from the attempt to define a set of all sets\nthat do not belong to themselves. In the terms of programming, the\nRussel's paradox provides a recipe to encode a fixpoint combinator in\nthe calculus itself and write generally-recursive programs.\n\n** Exploring and debugging the universe hierarchy\n\nIn the light of Martin-Loef's stratification, the Coq' non-polymorphic\ntypes, such as [nat], [bool], [unit] or [list nat] \"live\" at the [0]th\nlevel of universe hierarchy, namely, in the sort [Set]. The\npolymorphic types, quantifying over the elements of the [Set] universe\nare, therefore located at the higher level, which in Coq is denoted as\n[Type(1)], but in the displays is usually presented simply as [Type],\nas well as all the higher universes. We can enable the explicit\nprinting of the universe levels to see how they are assigned:\n\n*)\n\nSet Printing Universes.\n\nCheck bool.\n\n(**\n[[\nbool\n     : Set\n]]\n*)\n\nCheck Set.\n\n\nCheck Prop.\n\n(**\nThe following type is polymorphic over the elements of the [Set]\nuniverse, and this is why its own universe is \"bumped up\" by one, so\nit becomes [Type(1)].\n*)\n\nDefinition S := forall T: Set, list T. \nCheck S.\n\n(**\nAt this moment, Coq provides a very limited version of _universe\npolymorphism_. For instance, the next definition [R] is polymorphic\nwith respect to the universe of its parameter [A], so its result lives\nin the universe, whose level is taken to be the level of [A].\n\n*)\n\nDefinition R (A: Type) (x: A): A := x. \nImplicit Arguments R [A].\n\nCheck R tt. \n\n(** \n[[\nR tt \n     : unit\n]]\n*)\n\n(** \n\nIf the argument of [R] is itself a universe, it means that [A]'s\nlevel is higher than [x]'s level, and so is the level of [R]'s result.\n\n*)\n\nCheck R Type. \n\n(**\nHowever, the attempt to apply [R] to itself immediately leads to an\nerror reported, as the system cannot infer the level of the result, by\nmeans of solving a system of universe level inequations, therefore,\npreventing meta-circular paradoxes.\n\n*)\n\n(**\n[[\nCheck R R.\n\nError: Universe inconsistency (cannot enforce Top.1225 < Top.1225).\n]]\n*)\n\n(*******************************************************************)\n(**                     * Exercices *                              *)\n(*******************************************************************)\n\n(**\n---------------------------------------------------------------------\nExercise [forall-distributivity]\n---------------------------------------------------------------------\n\nFormulate and prove the following theorem in Coq, which states the\ndistributivity of universal quantification with respect to implication:\n\\[\nforall P Q, \n  [(forall x, P(x) => Q(x)) => ((forall y, P(y)) => forall z, Q(z))]\n\\]\n\nBe careful with the scoping of universally-quantified variables\nand use parentheses to resolve ambiguities!\n*)\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.\nmove => H1 H2 z.\napply : H1; apply : H2.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Or-And distributivity]\n---------------------------------------------------------------------\nProve the following theorems.\n*)\n\nTheorem or_distributes_over_and P Q R: \n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nsplit.\n- case=>[p | [q r]]; split; do?[by left| by right].\n- case; case => [p _| q]; first by left.\n  by case=>p; [left | right].\nQed.\n\nTheorem or_distributes_over_and_2 P Q R :\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\nmove : (or_distributes_over_and P Q R).\nby move=> H; move/H.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Home-brewed existential quantification]\n---------------------------------------------------------------------\n\nLet us define our own version [my_ex] of the existential quantifier\nusing the SSReflect notation for constructors: *)\n\nInductive my_ex A (S: A -> Prop) : Prop := my_ex_intro x of S x.\n\n(** You invited to prove the following goal, establishing the\nequivalence of the two propositions. *)\n\nGoal forall A (S: A -> Prop), my_ex A S <-> exists y: A, S y.\nProof.\nby split; case; move => x Sx; exists x.\nQed.\n \n(** \nHint: the propositional equivalence [<->] is just a conjunction of\ntwo implications, so proving it can be reduced to two separate goals\nby means of [split] tactics.\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [Distributivity of existential quantification]\n---------------------------------------------------------------------\nProve the following theorem.\n*)\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.\nsplit.\n- by case => x; case => p; [left | right]; exists x.\n- by case; case => x p; exists x; [left | right].\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Two equals three]\n---------------------------------------------------------------------\nProve the following  theorem. Can you explain the proof?\n*)\n\nTheorem two_is_three A: (exists x : A, (forall R : A -> Prop, R x)) -> 2 = 3.\nProof.\nby case => x H; move: (H (fun _ => 2 = 3)).\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Dyslexic implication and contraposition]\n---------------------------------------------------------------------\n\nThe \"dyslexic\" implication and contrapositions are the following\npropositions. \n*)\n\nDefinition dys_imp (P Q: Prop) := (P -> Q) -> (Q -> P).\nDefinition dys_contrap (P Q: Prop) := (P -> Q) -> (~P -> ~Q).\n\n(**\nThese propositions are inhabited, as otherwise one, given a proof of\nany of them, would be able to construct a proof of [False]. You are\ninvited to deomnstrate it by proving the following statements.\n*)\n\nTheorem di_false: (forall P Q: Prop, dys_imp P Q) -> False.\nProof.\nby move/ (_ _ True) => H1; apply: H1.\nQed.\n\nTheorem dc_false: (forall P Q: Prop, dys_contrap P Q) -> False.\nProof.\nmove/ (_ False True).\nrewrite /dys_contrap.\nby move=> H1; apply: H1.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Irrefutability of the excluded middle]\n---------------------------------------------------------------------\n\nProof the following theorem that states that the assumption of the\nfalsehood of the excluded middle leads to inconsistencies, as is\nallows one to derive [False].\n*)\n\nTheorem excluded_middle_irrefutable: forall (P : Prop), ~~(P \\/ ~ P).\nProof.\nmove=> P H.\napply: (H); right.\nmove=> HP; move: H.\nby case; left.\nQed.\n\n(**\n---------------------------------------------------------------------\nExercise [Equivalence of classical logic axioms]\n---------------------------------------------------------------------\n\nProve that the following five axioms of the classical are equivalent.\n\n*)\n\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.\nrewrite /peirce /peirce_law /double_neg /not => H P HP.\nby move: (H P False)=> H'; apply: H'; move/HP.\nQed.\n\nLemma dn_em : double_neg -> excluded_middle.\nProof.\nrewrite /excluded_middle /double_neg => H P.\nsuff: ~ ~ (P \\/ ~ P); first by apply H.\nmove/ not_or_and.\nby case.\nQed.\n\nLemma em_dmnan: excluded_middle -> de_morgan_not_and_not.\nProof.\nrewrite /excluded_middle /de_morgan_not_and_not=> H P Q.\ncase (H P); case (H Q); intuition.\nQed.\n\nLemma dmnan_ito : de_morgan_not_and_not -> implies_to_or.\nProof.\nrewrite /de_morgan_not_and_not /implies_to_or => H P Q H1.\napply: (H); case => HP HQ.\nby apply: HP; move/H1.\nQed.\n\nLemma ito_peirce : implies_to_or -> peirce.\nProof.\nrewrite /implies_to_or /peirce /peirce_law => H P Q H1.\nmove: (H P P (@id P)) => HP.\nmove: (H Q Q (@id Q)) => HQ.\nmove: HP; case; move: HQ; case => //= => HQ HP; apply: H1 => //.\nQed.\n\n(**\n\nHint: Use [rewrite /d] tactics to unfold the definition of a value [d]\n and replace its name by its body. You can chain several unfoldings by\n writing [rewrite /d1 /d2 ...]  etc.\n\nHint: To facilitate the forward reasoning by contradiction, you can\n use the SSReflect tactic [suff: P], where [P] is an arbitrary\n proposition. The system will then require you to prove that [P]\n implies the goal _and_ [P] itself.\n\nHint: Stuck with a tricky proof? Use the Coq [admit] tactic as a\n \"stub\" for an unfinished proof of a goal, which, nevertheless will be\n considered completed by Coq. You can always get back to an admitted\n proof later.\n\n*)\n\n\n(**\n---------------------------------------------------------------------\nExercise [Inifinitary de Morgan laws]\n---------------------------------------------------------------------\n\nProve the following implication analogous to the Morgan law for\nconjunctions  and disjunctions.\n\n*)\n\nTheorem not_forall_exists A (P : A -> Prop): \n  (forall x: A, P x) -> ~(exists y: A, ~ P y).\nProof.\nmove=> H. case; move=> x HP.\nby move: (H x).\nQed.\n\n(**\n\nThen, prove that the assumption of the excluded middle axiom allows one to\nestablish the implication from the negation of (exists) to (forall).\n\n*)\n\nTheorem not_exists_forall :\n  excluded_middle -> forall (X: Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\nmove=> EM X P H x.\nrewrite /excluded_middle in EM.\nmove: (EM (P x)).\ncase.\n- done.\n- move=> PN.\n  suff: False=>//.\n  apply: H.\n  by exists x.\nQed.\n\nEnd LogicPrimer.\n\n", "meta": {"author": "anlun", "repo": "ssrLectures", "sha": "ee98c80b33ce6fab35d0cb0d8c0c45d98c5f73d8", "save_path": "github-repos/coq/anlun-ssrLectures", "path": "github-repos/coq/anlun-ssrLectures/ssrLectures-ee98c80b33ce6fab35d0cb0d8c0c45d98c5f73d8/LogicPrimer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.9019206712569268, "lm_q1q2_score": 0.8325081064843733}}
{"text": "Require Import bool.\nRequire Import nat.\n\nDefinition minustwo (n:nat) : nat :=\n    match n with\n        | O         => O\n        | S O       => O\n        | S (S p)   => p\n    end.\n\n(*\nCheck S (S (S (S O))).\nCompute minustwo 4.\nCheck S.\nCheck Playground1.pred.\nCheck minustwo.\n*)\n\nExample test_evenb0: evenb 0 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_evenb1: evenb 1 = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_evenb2: evenb 2 = true.\nProof. simpl. reflexivity. Qed.\n\n\nExample test_oddb0: oddb 0 = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb2: oddb 2 = false.\nProof. simpl. reflexivity. Qed.\n\n(*\nCompute plus 3 2.\nCompute plus 1540 3000. (* stack overflow pretty soon *)\n*)\n\nExample test_mult1: mult 3 3 = 9.\nProof. simpl. reflexivity. Qed.\n\n\nExample test_minus1: minus 10 3 = 7.\nProof. simpl. reflexivity. Qed.\n\n\nExample test_exp1: exp 3 4 = 81.\nProof. simpl. reflexivity. Qed.\n\nExample test_fact1: fact 5 = 120.\nProof. simpl. reflexivity. Qed.\n\n(*\nCompute 5 + 3 + 2 + 15.\n*)\n\n(* \nCompute 10 - 2 - 4.\n*)\n\n(*\nCompute 10 + 3 * 4.\nCheck plus 4 3.\n*)\n\n(*\nCompute eqb 0 0.\nCompute eqb 43 12.\nCompute eqb 56 56.\n*)\n\n(*\nCompute leb 23 24.\nCompute leb 24 24.\nCompute leb 25 24.\n*)\n\n(*\nCompute ltb 23 24.\nCompute ltb 24 24.\nCompute ltb 25 24.\n*)\n\nLemma plus_0_n' : forall n:nat, 0 + n = n.\nProof.\n    intros n. reflexivity.\nQed.\n\n\nLemma plus_id_example: forall n m:nat, \n    n = m -> n + n = m + m.\nProof.\n    intros n m H. rewrite H. reflexivity.\nQed.\n\nLemma 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. rewrite H1. rewrite <- H2. reflexivity.\nQed.\n\n(*\nTheorem plus_comm : forall n m:nat, \n    n + m = m + n.\nProof.\nAdmitted.  (* useful when writing bigger proofs *)\n*)\n\nLemma plus_1_neq_0' : forall n:nat,\n    eqb (n + 1) 0 = false.\nProof.\n    (* 'as' clause to name variables of constructors    *)\n    (*  of inductive type. 0 is a nullary constructor   *)\n    intros n. destruct n as [|n].   (* we don't need induction here *)\n    - reflexivity.          (* you can skip 'simpl' *) (* using bullet for clarity *)\n    - reflexivity.          (* you can skip 'simpl' *) (* using bullet for clarity *)\nQed.\n\nLemma plus_1_neq_0'' : forall n:nat,\n    eqb (n + 1) 0 = false.\nProof.\n    intros [|n].           (* shortcut for intros n. destruct n as [|n]. *) \n    - reflexivity.\n    - reflexivity.\nQed.\n\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/test_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.9149009619539554, "lm_q1q2_score": 0.8324748018183893}}
{"text": "Require Import Nat.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nInductive queue : Type :=\n  | Queue : lst -> lst -> queue.\n\nFixpoint len (l : lst) : nat :=\nmatch l with\n  | Nil => 0\n  | Cons a l1 => 1 + (len l1)\nend.\n\nDefinition qlen (q : queue) : nat :=\nmatch q with\n  | Queue l1 l2 => (len l1) + (len l2)\nend. \n\nFixpoint app (l : lst) (m: lst): lst :=\nmatch l with\n  | Nil => m\n  | Cons a l1 => Cons a (app l1 m)\nend.\n\nFixpoint rev (l: lst): lst :=\nmatch l with\n  | Nil => Nil\n  | Cons a l1 => app (rev l1) (Cons a Nil)\nend.\n\nFixpoint leb (n m : nat) : bool :=\nmatch (n, m) with\n  | (0, _) => true\n  | (S n', S m') => leb n' m'\n  | _ => false\nend. \n\nDefinition amortizeQueue (l1 l2 : lst) : queue :=\n  if leb (len l2)  (len l1) then Queue l1 l2\n  else Queue (app l1 (rev l2)) Nil.\n\nDefinition qpush (q : queue) (n : nat) : queue :=\nmatch q with\n  | Queue l1 l2 => amortizeQueue l1 (Cons n l2)\nend.\n\n\nLemma len_app : forall l1 l2, len (app l1 l2) = (len l1) + (len l2).\nProof.\n  intros. induction l1.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nLemma plus_comm: forall m n, m + n = n + m.\nProof.\ninduction m.\n- intros. simpl. rewrite <- plus_n_O. reflexivity.\n- intros. simpl. rewrite IHm. rewrite plus_n_Sm. reflexivity.\nQed.\n\nLemma len_rev : forall l, len (rev l) = len l.\nProof.\ninduction l.\n- reflexivity.\n- simpl. rewrite len_app. simpl. rewrite plus_comm. simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem queue_push : forall q n, qlen (qpush q n) = 1 + (qlen q).\nProof.\n  intros. simpl. destruct q. unfold qpush. unfold qlen. unfold amortizeQueue.\n  destruct (leb (len (Cons n l0)) (len l)).\n  - simpl. rewrite plus_n_Sm. reflexivity.\n  - simpl. rewrite <- plus_n_O. \n    rewrite len_app. \n    rewrite len_app. rewrite len_rev. \n    simpl. rewrite plus_n_Sm. rewrite (plus_comm (len l0)). reflexivity. \nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/adtind/queue_push.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.8321898232395533}}
{"text": "(** * More Logic *)\n\nRequire Export Propositions.\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P].\n\n*)\n\n\n(** *** *)\n(** Coq's [Notation] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** *** *)\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2).\n  reflexivity.  Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** *** *)\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n    time, we can use the convenient shorthand [exists e], which means\n    the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity.  Qed.\n\n(** *** *)\n(** Conversely, if we have an existential hypothesis in the\n    context, we can eliminate it with [inversion].  Note the use\n    of the [as...] pattern to name the variable that Coq\n    introduces to name the witness value and get evidence that\n    the hypothesis holds for the witness.  (If we don't\n    explicitly choose one, Coq will just call it [witness], which\n    makes proofs confusing.) *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n H.\n  inversion H as [m Hm].\n  exists (2 + m).\n  apply Hm.  Qed.\n\n\n(** Here is another example of how to work with existentials. *)\nLemma exists_example_3 :\n  exists (n:nat), even n /\\ beautiful n.\nProof.\n(* WORKED IN CLASS *)\n  exists 8.\n  split.\n  unfold even. simpl. reflexivity.\n  apply b_sum with (n:=3) (m:=5).\n  apply b_3. apply b_5.\nQed.\n\n(** **** Exercise: 1 star, optional (english_exists) *)\n(** In English, what does the proposition\n      ex nat (fun n => beautiful (S n))\n]]\n    mean? *)\n\n(* There is exists some Nat with a [beautiful] successor. *)\n\n(*\n*)\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros. unfold not. intros. inversion H0.\n    apply H1. apply H.\nQed.\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  unfold excluded_middle. intros ex_mid. intros.\n  unfold not in H. unfold not in ex_mid.\n\n  assert (M : P x \\/ ~ P x).\n    Case \"Proof of assertion\".\n    apply ex_mid.\n\n  Case \"Assertion application\".\n  unfold not in M.\n  inversion M.\n    apply H0.\n    destruct H.\n      exists x.\n      apply H0.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros. split. intros. inversion H. inversion H0.\n  Case \"L\".\n    left. exists witness. apply H1.\n    right. exists witness. apply H1.\n  Case \"R\".\n   intros. inversion H.\n     inversion H0. exists witness. left. apply H1.\n     inversion H0. exists witness. right. apply H1.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues.  The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests\nin _computations_.  While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious.\n*)\n\n(** *** *)\n(**\nIt turns out that we can get the benefits of both forms at once\nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" :=  (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction\nthat allows us to compute with them.) *)\n\n(** *** *)\n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  (* WORKED IN CLASS *)\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      right. intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. intros contra. inversion contra.\n    SCase \"m = S m'\".\n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply f_equal.  apply eq.\n      right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined.\n\n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either\nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right]\nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean].\n(Notice that we ended this proof with [Defined] rather than [Qed].\nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n*)\n\n(** *** *)\n(**\nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f. intros Hx1.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).   (* observe what appears as a hypothesis *)\n  Case \"k1 = k2\".\n    rewrite <- e.\n    symmetry. apply Hx1.\n  Case \"k1 <> k2\".\n    reflexivity.  Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the\n   version of [override] defined using [beq_nat], where we had to\n   use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n   to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n  intros.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).\n    reflexivity.\n    reflexivity.\nQed.\n(** [] *)\n\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all {X : Type} (P : X -> Prop) : list X -> Prop :=\n  | a_nil : all P []\n  | a_cons h t : P h -> all P t -> all P (h :: t).\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Using the property [all], write down a specification for [forallb],\n    and prove that it satisfies the specification. Try to make your\n    specification as precise as possible.\n\n    Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\nTheorem forallb_spec :\n  forall X (test : X -> bool) (l : list X),\n    forallb test l = true <-> all (fun x => test x = true) l.\nProof.\n  intros. split. intros. induction l as [|h t].\n    Case \"1\".\n      apply a_nil.\n    Case \"2\".\n      apply a_cons.\n      simpl in H.\n      destruct (test h). reflexivity. apply H.\n      apply IHt. simpl in H.\n      destruct (test h). apply H. inversion H.\n   Case \"3\".\n    intros.\n    induction H.\n      reflexivity.\n      simpl. rewrite H. simpl. apply IHall.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example,\n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\nInductive in_order_merge {X : Type} : list X -> list X -> list X -> Prop :=\n  | iom_nil : in_order_merge [] [] []\n  | iom_l   : forall (h : X) (xs ys zs : list X),\n                in_order_merge (h :: xs) ys (h :: zs)\n  | iom_r   : forall (h : X) (xs ys zs : list X),\n                in_order_merge xs (h :: ys) (h :: zs).\n\nTheorem filter_challenge : forall X (p : X -> bool) (l lt lf : list X),\n                             in_order_merge l lt lf ->\n                             forallb p lt = true ->\n                             forallb (fun x => negb (p x)) lf = true ->\n                             filter p l = lt.\nProof. Admitted.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l].\n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X),\n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma app_appears_in : forall (X:Type) (xs ys : list X) (x:X),\n     appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n    which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [appears_in] to define an inductive proposition\n    [no_repeats X l], which should be provable exactly when [l] is a\n    list (with elements of type [X]) where every member is different\n    from every other.  For example, [no_repeats nat [1,2,3,4]] and\n    [no_repeats bool []] should be provable, while [no_repeats nat\n    [1,2,1]] and [no_repeats bool [true,true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but you are free\n    to change the proof if the given one doesn't work for you.\n    Your definition might be different from mine and still correct,\n    in which case the examples might need a different proof.\n\n    The suggested proofs for the examples (in comments) use a number\n    of tactics we haven't talked about, to try to make them robust\n    with respect to different possible ways of defining [nostutter].\n    You should be able to just uncomment and use them as-is, but if\n    you prefer you can also prove each example with more basic\n    tactics.  *)\n\nExample test_nostutter_1:      nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some\n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma appears_in_app_split : forall (X:Type) (x:X) (l:list X),\n  appears_in x l ->\n  exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n   exercise above), such that [repeats X l] asserts that [l] contains\n   at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n    represents a list of pigeonhole labels, and list [l1] represents\n    the labels assigned to a list of items: if there are more items\n    than labels, at least two items must have the same label.  This\n    proof is much easier if you use the [excluded_middle] hypothesis\n    to show that [appears_in] is decidable, i.e. [forall x\n    l, (appears_in x l) \\/ ~ (appears_in x l)].  However, it is also\n    possible to make the proof go through _without_ assuming that\n    [appears_in] is decidable; if you can manage to do this, you will\n    not need the [excluded_middle] hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\n   excluded_middle ->\n   (forall x, appears_in x l1 -> appears_in x l2) ->\n   length l2 < length l1 ->\n   repeats l1.\nProof.\n   intros X l1. induction l1 as [|x l1'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* FILL IN HERE *)\n\n\n(* $Date: 2014-02-22 09:43:41 -0500 (Sat, 22 Feb 2014) $ *)\n", "meta": {"author": "dandougherty", "repo": "software-foundations", "sha": "67a136e3ec1360bd92f974c251958af5ffc83d09", "save_path": "github-repos/coq/dandougherty-software-foundations", "path": "github-repos/coq/dandougherty-software-foundations/software-foundations-67a136e3ec1360bd92f974c251958af5ffc83d09/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850084148385, "lm_q2_score": 0.8887587883361618, "lm_q1q2_score": 0.8321315296160849}}
{"text": "Require Import ZArith BinIntDef.\n\nLocal Open Scope Z_scope.\n\nTheorem poly_congruence_pg_28 : ~(exists x, x * x - 117 * x + 31 = 0).\nProof.\n  (** First establish that the constants we use (-117 and 31) are odd. *)\n  assert (Zodd (-117)) as H117IsOdd. compute. auto.\n  assert (Zodd 31) as H31IsOdd. compute. auto.\n  (** We proceed with a proof by contradiction.  Support some x exists.  Then x^2 - 117*x must be even.  Therefore the polynomial is odd, and the result can cannot be zero. *)\n  intro H.\n  destruct H as [x H].\n  (** We show a slightly different term is even because it makes the proof more straightforward. *)\n  assert (Zeven (-117 * x + x * x)) as HVariableComboIsEven.\n  (** We proceed by the case of whether x is even or odd. *)\n  destruct (Zeven_odd_dec x) as [HXIsEven | HXIsOdd].\n  (** If x is even, both x^2 and -117 * x must be even.  The sum of two evens is also even. **)\n  - assert (Zeven (x * x)) as HXSquaredIsEven. apply (Zeven_mult_Zeven_l x x HXIsEven).\n    assert (Zeven (-117 * x)) as HLinearTermIsEven. apply (Zeven_mult_Zeven_r (-117) x HXIsEven).\n    apply (Zeven_plus_Zeven _ _ HLinearTermIsEven) in HXSquaredIsEven.\n    assumption.\n  (** If x is even, both x^2 and -117 * x must be odd.  The sum of two odds is also odd. **)\n  - assert (Zodd (x * x)) as HXSquaredIsOdd. apply (Zodd_mult_Zodd x x HXIsOdd HXIsOdd).\n    assert (Zodd (-117 * x)) as HLinearTermIsOdd. apply (Zodd_mult_Zodd (-117) x H117IsOdd HXIsOdd).\n    apply (Zodd_plus_Zodd _ _ HLinearTermIsOdd) in HXSquaredIsOdd.\n    assumption.\n    (** Since the term x^2 + -117 * x) is even, the sum of it with 31 must be odd.\n        However 0 cannot be odd, so there cannot be an x that relationship x^2 - 117 * x + 31. *)\n  - apply (Zodd_plus_Zeven _ _ H31IsOdd) in HVariableComboIsEven.\n    replace (31 + (-117 * x + x * x)) with (x * x - 117 * x + 31) in HVariableComboIsEven.\n    rewrite H in HVariableComboIsEven.\n    compute in HVariableComboIsEven. contradict HVariableComboIsEven.\n    (** The replacement we used is easily proven with the ring tactic. *)\n    ring.\nQed.\n", "meta": {"author": "tildedave", "repo": "coq-playground", "sha": "860f5e68b6c0caed8a038f128ee298b504607c85", "save_path": "github-repos/coq/tildedave-coq-playground", "path": "github-repos/coq/tildedave-coq-playground/coq-playground-860f5e68b6c0caed8a038f128ee298b504607c85/congruence-poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8316299200677141}}
{"text": "Require Import Arith.\n\nInductive even : nat -> Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\n\n#[export] Hint Constructors even : core.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S (S (mult2 p))\n  end.\n\nLemma mult2_even : forall n:nat, even (mult2 n).\nProof. \n induction n; simpl; auto.\nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n + p).\nProof.\n intros n p Heven_n; induction  Heven_n; simpl; auto.\nQed.\n\n#[export] Hint Resolve sum_even : core.\n\nLemma square_even : forall n:nat, even n -> even (n * n).\nProof.\n intros n Hn; elim Hn; simpl; auto.\n intros n0 H0 H1; rewrite (mult_comm n0 (S (S n0))).\n right; simpl;apply sum_even; auto.\nQed.\n\n\nLemma even_mult2 : forall n:nat, even n -> (exists p, n = mult2 p).\nProof.\n induction 1.\n -  exists 0; reflexivity.\n -  destruct IHeven as [p Hp]; exists (S p); simpl; now rewrite Hp. \nQed.\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.8315869768354874}}
{"text": "Inductive nat : Type :=\n    | O : nat\n    | S : nat -> nat\n    .\n\nNotation \"0\" := (O).\nNotation \"1\" := (S 0).\n\nFixpoint plus (n:nat)(m:nat) : nat :=\n    match n with \n        | 0    => m\n        | S p  => S (plus p m)\n    end.\n        \n\nNotation \"x + y\" := (plus x y) (at level 50, left associativity).\n\nLemma plus_0_n : forall (n:nat), 0 + n = n. \nProof.\nintros n. simpl. reflexivity.\nQed.\n\nLemma plus_n_0 : forall (n:nat), n + 0 = n.\nProof.\nintros n. induction n as [|n IH].  \n    - simpl. reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\nLemma plus_1_n : forall (n:nat), 1 + n = S n.\nProof.\nintros n. simpl. reflexivity.\nQed.\n\n\nLemma plus_n_1 : forall (n:nat), n + 1 = S n.\nProof.\nintros n. induction n as [|n IH].\n    - simpl. reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\n\nLemma plus_n_Sm : forall (n:nat)(m:nat), n + S m = S (n + m).\nProof.\nintros n. induction n as [|n IH].\n    - intros m. reflexivity.\n    - intros m. simpl. rewrite IH. reflexivity.\nQed.\n    \n\n\n\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/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.8314553791674367}}
{"text": "Require Export P01.\n\n\n\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A} (beq : A -> A -> bool)\n         (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | [] , [] => true\n  | _  , [] => false\n  | [] , _  => false\n  | h1 :: t1 , h2 :: t2 => if(beq h1 h2) then beq_list beq t1 t2 else false\n  end.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq H l1 l2. generalize dependent l2.\n  induction l1 as [| h1 l1' IHl1']; induction l2 as [| h2 l2' IHl2'].\n  - simpl. split; auto.\n  - simpl. split; intros Hcontra; inversion Hcontra.\n  - simpl. split; intros Hcontra; inversion Hcontra.\n  - simpl. split; intros; destruct (beq h1 h2) eqn: Hbeq.\n    + apply H in Hbeq. apply IHl1' in H0. subst. reflexivity.\n    + inversion H0. \n    + apply H in Hbeq. apply IHl1'. subst. inversion H0. reflexivity.\n    + inversion H0. subst. rewrite <- Hbeq. apply H. reflexivity.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.9149009596336303, "lm_q1q2_score": 0.8312953813162378}}
{"text": "Require Import Arith Lists.List.\n\nDefinition injective {X Y} (f : X -> Y) :=\n  forall x x', f x = f x' -> x = x'.\n\nDefinition inv {X Y} (g : Y -> X) (f : X -> Y) :=\n  forall x, g (f x) = x.\n\nDefinition bijection X Y :=\n  { f : X -> Y & { g & inv g f /\\ inv f g }}.\n\nSection Bijection.\n\n  Variable code : nat * nat -> nat.\n  Variable decode : nat -> nat * nat.\n\n  Hypothesis decode_code : forall x, decode (code x) = x.\n  Hypothesis code_decode : forall x, code (decode x) = x.\n\n  Hypothesis bound : forall x1 x2 n, code (x1, x2) = n -> x2 < S n.\n  (* The above hypothesis is easily shown for the Cantor pairing *)\n\n  (* g encodes lists to numbers. We will show that it is a bijection. *)\n  Fixpoint g (L : list nat) := \n    match L with\n    | nil => 0\n    | x::l => S (code (x, g l))\n    end.\n  \n  \n  Lemma surj_g : forall N, { L & g L = N }.\n  Proof.\n    apply (well_founded_induction_type lt_wf); intros [|N] IH.\n    - exists nil. reflexivity.\n    - rewrite <- (code_decode N).\n      destruct (decode N) as [x n] eqn:H.\n      destruct (IH n) as [l <-].\n      { apply (bound x); congruence. }\n      exists (x::l). reflexivity.\n  Defined.\n\n  Definition f n := projT1 (surj_g n).  \n  (* In the above line, we extracted the candidate inverse f for the function g *)\n  (* We will now show that g is injective and verify that f is indeed a left and right-sided inverse *)\n\n  Fact inj_code : injective code.\n  Proof.\n    intros ? ? ?; rewrite <-decode_code; congruence.\n  Defined.\n    \n  Lemma inj_g : injective g.\n  Proof.\n    intros A; induction A.\n    - intros []. tauto. discriminate.\n    - intros [| b B]. discriminate.\n      cbn. intros [=H%inj_code]. injection H.\n      intros ?%IHA. congruence.\n  Defined.\n\n\n  Fact inv_gf : inv g f.\n  Proof.\n    intros ?. apply (projT2 (surj_g _)).\n  Defined.\n\n  Fact inv_fg : inv f g.\n  Proof.\n    intros ?. apply inj_g. now rewrite inv_gf.\n  Defined.\n  \n\n  Corollary Bij_Nat_listNat : bijection nat (list nat).\n  Proof.\n    exists f, g. split. apply inv_gf. apply inv_fg.\n  Defined.\n  \nEnd Bijection.", "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/Nat_listNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.8310280501943923}}
{"text": "Lemma exo1_1 : \nforall m : nat, 0 + m = m.\nProof.\nintros.\nreflexivity.\nQed.\n\nLemma exo1_2 :\nforall m n : nat, S n + m = S (n + m).\nProof.\nintros.\nsimpl.\nf_equal.\nQed.\n\nLemma plus_n_0 :\nforall n, n + 0 = n.\nProof.\nintros.\ninduction n.\n - simpl. reflexivity.\n - simpl. f_equal. apply IHn.\nQed.\n\nLemma plus_n_Sm :\nforall n m, n + S m = S (n + m).\nProof.\nintros.\ninduction n.\n - simpl. f_equal.\n - simpl. f_equal. apply IHn.\nQed.\n\nLemma exo2_1 :\nforall m : nat, 0 * m = 0.\nProof.\nintros.\nreflexivity.\nQed.\n\nLemma exo2_1_2 :\nforall m n : nat, S n * m = m + n * m.\nProof.\nintros.\nreflexivity.\nQed.\n\nLemma exo2_2 :\nforall m : nat, m * 0 = 0.\nProof.\nintros.\ninduction m; simpl.\n - reflexivity.\n - apply IHm.\nQed.\n\n\nLemma associative :\nforall n m p : nat, (n + m) + p = n + (m + p).\nProof.\nintros.\ninduction n; simpl.\n - reflexivity.\n - f_equal. apply IHn.\nQed.\n\nLemma commutativite :\nforall n m: nat, n + m = m +n.\nProof.\nintros.\ninduction m; simpl.\n - apply plus_n_0.\n - rewrite plus_n_Sm. f_equal. apply IHm.\nQed.\n\nLemma exo2_2_2 :\nforall m n : nat, n * S m = n + n * m.\nProof.\nintros.\ninduction n; simpl.\n - reflexivity.\n - f_equal. rewrite IHn. rewrite <- 2 associative. f_equal. apply commutativite.\nQed.\n\nLemma distributivite :\nforall n m p : nat, (n + m) * p = n * p + m * p.\nProof.\nintros.\ninduction n; simpl.\n - reflexivity.\n - rewrite IHn. rewrite <- associative. reflexivity.\nQed.\n\nLemma mul_commutativite :\nforall n m : nat, n * m = m * n.\nProof.\nintros.\ninduction m; simpl.\n - apply exo2_2.\n - rewrite <- IHm. apply exo2_2_2.\nQed.\n\nLemma mul_associativite :\nforall n m p : nat, n * (m * p) = (n * m) * p.\nProof.\nintros.\ninduction n; simpl.\n - reflexivity.\n - rewrite IHn. rewrite distributivite. reflexivity.\nQed.\n\nDefinition le (n m : nat) := exists p, n + p = m.\n\nLemma le_refl : forall n, le n n.\nProof.\nintros.\nexists 0.\napply plus_n_0.\nQed.\n\nLemma le_trans : forall n m p, le n m -> le m p -> le n p.\nProof.\nintros.\ndestruct H.\ndestruct H.\ndestruct H0.\nexists (x + x0).\nrewrite <- associative.\napply H.\nQed.\n\nLemma le_antisym : forall n m, le n m -> le m n -> n = m.\nProof.\nintros.\ndestruct H.\ndestruct H.\ninduction n; simpl.\n - destruct H0.", "meta": {"author": "arintaauza", "repo": "Coq", "sha": "1e69840d3ea96f54f516440f60aba759e8ac51ae", "save_path": "github-repos/coq/arintaauza-Coq", "path": "github-repos/coq/arintaauza-Coq/Coq-1e69840d3ea96f54f516440f60aba759e8ac51ae/tp5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.8309203139646312}}
{"text": "Require Import String.\n\nInductive EA : Type :=\n  |V: string -> EA \n  |N: nat -> EA \n  |Plus: EA -> EA -> EA\n  |Suc: EA -> EA.\n\nDefinition State := string -> nat.\n\nPrint EA_ind.\nPrint State.\n\nFixpoint eval (e:EA) (s:State) : nat :=\n  match e with\n  | V x => s x\n  | N n => n\n  | Plus e1 e2 => (eval e1 s)+(eval e2 s)\n  | Suc e => S (eval e s)\n  end.\n\nFixpoint cf (e:EA):EA :=\n match e with\n  | V x => V x\n  | N n => N n\n  | Plus e1 e2 => match cf e1 with\n                   |N n => match cf e2 with \n                            |N k => N (n+k)\n                            |_ => Plus (cf e1) (cf e2)\n                           end\n                   |_ => Plus (cf e1) (cf e2)\n                  end\n  | Suc e => match cf e with\n              |N n => N(S n)\n              |_ => Suc (cf e)\n             end\n end.\n\nLemma eq_suc_nat : forall (n:nat), S n = n + 1.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  trivial.\nQed.\n\n(*a*)\nTheorem eq_suc: forall (s:State) (e:EA), eval (Suc e) s = eval e s + 1.\nProof.\n  intro.\n  destruct e;simpl;apply eq_suc_nat.\nQed.\n\n(*b*)\nTheorem eval_cf: forall (s:State) (e:EA), eval e s = eval (cf e) s.\nProof.\n  intros.\n  induction e;simpl;trivial.\n  rewrite IHe1;rewrite IHe2;destruct (cf e1);destruct (cf e2);reflexivity.\n  rewrite (IHe);destruct (cf e); reflexivity.\nQed. \n\nFixpoint plus (e1 e2:EA) :EA :=\nmatch e1, e2 with\n  | N n1, N n2 => N (n1 + n2)\n  | N 0, e => e\n  | e, N 0 => e\n  | a, b => Plus a b\nend.\n\nFixpoint cfp (e:EA):EA :=\n match e with\n  | V x => V x\n  | N n => N n\n  | Plus e1 e2 => plus (cfp e1) (cfp e2)\n  | Suc e1 => Suc (cfp e1)\n end.\n\nLemma mas_cero: forall (n:nat), n + 0 = n.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  trivial.\nQed.\n\n(*c*)\nTheorem corr_cfp : forall (e:EA) (s:State), eval e s = eval (cfp e) s.\nProof.\n  intros.\n  induction e;simpl;trivial.\n  rewrite IHe1.\n  rewrite IHe2.\n  destruct (cfp e1);destruct (cfp e2);trivial;destruct n;simpl;trivial;rewrite mas_cero;trivial.\n  destruct (cfp e);rewrite IHe;trivial.\nQed.", "meta": {"author": "jaeem006", "repo": "Semantica", "sha": "fdfdf544dd2d30b2f03a82849d78879762d48811", "save_path": "github-repos/coq/jaeem006-Semantica", "path": "github-repos/coq/jaeem006-Semantica/Semantica-fdfdf544dd2d30b2f03a82849d78879762d48811/semanal5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8308321595161821}}
{"text": "(* Exercicio - IndProp.v - Lista 8\n   Nome: Geremias Corr\u00eaa      *)\nSet Warnings \"-notation-overridden,-parsing\".\n(*From LF Require Export Logic.*)\n\n(*####### IMPORTS NECESS\u00c1RIOS ########*)\n\n\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S 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\nTheorem ev_sum : forall n m, even n -> even m -> even (n + m).\nProof.\n  intros n m N M. induction N as [|n' N'].\n  - simpl. assumption.\n  - simpl. apply ev_SS. assumption.\nQed.\n\nTheorem ev_inversion :\n  forall (n : nat), even n ->\n    (n = 0) \\/ (exists n', n = S (S n') /\\ even n').\nProof.\n  intros n E.\n  destruct E as [ | n' E'].\n  - left. reflexivity.\n  - right. exists n'. split. reflexivity. 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 plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - rewrite <- plus_n_Sm. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  assert (H: n + m = m + n). rewrite -> plus_comm. reflexivity. rewrite -> H.\n  rewrite -> plus_assoc. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n. induction n as [ | n' IHn'].\n  - reflexivity.  (* caso 0 = 0 * 0*)\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  intros n. rewrite double_plus. induction n as [| n'].\n  - simpl. apply ev_0.\n  - simpl. rewrite <- plus_n_Sm. apply ev_SS. apply IHn'.\nQed.    \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(*3 dessas 4 importadas abaixo s\u00e3o do arquivo professor do Moodle*)\n(*A primeira logo abaixo \u00e9 a que j\u00e1 vinha para resolu\u00e7\u00e3o da quest\u00e3o, botei aqui para poder usar a le'_n_n*)\n\nInductive le' : nat -> nat -> Prop :=\n  | le_0' m : le' 0 m\n  | le_S' n m (H : le' n m) : le' (S n) (S m).\n\nLemma le'_n_n : forall a, le' a a.\nProof.\n  intros a. induction a as [|a' IH].\n  + apply le_0'.\n  + apply le_S'. apply IH.\nQed.\n\nLemma le'_n_Sm : forall a b, le' a b -> le' a (S b). \nProof.\n  intros a b H. induction H as [|a' b' Hab IH].\n  - apply le_0'.\n  - apply le_S'. apply IH.\nQed. \n\nTheorem n_le'_m__Sn_le'_Sm : forall a b, le' a b -> le' (S a) (S b).\nProof.\n  intros a b H. induction H as [m | n m Hnm IHnm].\n  - apply le_S'. apply le_0'.\n  - apply le_S'. apply IHnm.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall a b, le a b -> le (S a) (S b).\nProof.\n  Admitted.\n (*N\u00e3o consegui provar essa, ent\u00e3o dei um admitted para conseguir finalizar a le_le'.*)\n\n\n(*##### FIM IMPORTS NECESS\u00c1RIOS ######*)\n\n(* 1 - Prove que as defini\u00e7\u00f5es even e even' s\u00e3o equivalentes *)\nTheorem even'_ev : forall n, even' n <-> even n.\nProof.\n  intros n. split.\n  - intros E. induction E. \n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum. assumption. assumption.\n  - intros E. induction E.\n    + apply even'_0.\n    + assert (S (S n) = 2 + n) as H.\n      * induction n.\n        -- reflexivity.\n        -- reflexivity.\n      * rewrite H. apply even'_sum.\n       -- apply even'_2.\n       -- assumption.\nQed.\n\n(* 2 - Prove que se a soma de dois naturais \u00e9 um numero par e\n       o primeiro numero \u00e9 par implkca que os dois n\u00fameros s\u00e3o pares. *)\nTheorem ev_ev__ev : forall n m,\n  even (n + m) -> even n -> even m.\nProof.\n  intros n m H0 H1. induction H1.\n  - assumption.\n  - apply IHeven. assert (S (S n) + m = S (S (n + m))) as H.\n    + reflexivity.\n    + rewrite H in H0. apply evSS_ev in H0. assumption.\nQed.\n(*professor fez uso do inversion, que \u00e9 para ser utilizada sobre tipos indutivos, ela junta algumas t\u00e1ticas, como discrimante etc*)\n\n(* 3 - Prove: *)\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.\n  assert (even (n+m) -> even ((n+p)+(m+p))) as H.\n    - intros H. rewrite (plus_comm n p). rewrite (plus_comm m p). rewrite plus_swap.\n    rewrite plus_assoc. rewrite plus_assoc. rewrite <- double_plus.\n    rewrite <- (plus_assoc (double p) n m). apply ev_sum. apply ev_double. apply H1.\n    - apply H in H1. apply (ev_ev__ev (n+p)). assumption.\nQed.\n\n(* 4 - Prove que zero \u00e9 menor ou igual a qualquer n\u00famero natural *)\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n. induction n.\n  - apply le_n.\n  - apply le_S. assumption.\nQed.\n\n(* 5 - Prove que a rela\u00e7\u00e3o menor ou igual \u00e9 transitiva *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hno. induction Hno as [|n' o'].\n  - apply Hmn.\n  - apply le_S. apply IHHno. apply Hmn.\nQed.\n\n(* 6 - Prove que a rela\u00e7\u00e3o definida pelo tipo le' \u00e9 equivalente\n       a rela\u00e7\u00e3o <= *)\n\n(*Obs: Essa 6 eu n\u00e3o consegui direito, mas usei a resolu\u00e7\u00e3o da prova do professor para tentar interpretar eentender (os auxiliares), ainda sim gerando problemas no final*)\n(*Ainda sim geraram problemas, precisei dar um admitted e isso a\u00ed.*)\n\nTheorem le_le' : forall a b, le a b <-> le' a b.\nProof.\n  intros a b. split.\n  - intros H. induction H.\n    + apply le'_n_n.\n    + apply le'_n_Sm. apply IHle.\n  - intros H. induction H.\n    + apply O_le_n.\n    + apply n_le_m__Sn_le_Sm. apply IHle'. \nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "gerecorrea", "repo": "MFO_Metodos-Formais", "sha": "f65aff031fd0d87bc15d3a13c9281f6f918e2959", "save_path": "github-repos/coq/gerecorrea-MFO_Metodos-Formais", "path": "github-repos/coq/gerecorrea-MFO_Metodos-Formais/MFO_Metodos-Formais-f65aff031fd0d87bc15d3a13c9281f6f918e2959/ExeIndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.830832147840279}}
{"text": "Inductive boolean :=\n                 | true\n                 | false.\n\nDefinition negb (b : boolean) : boolean :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (a b:boolean) : boolean :=\n  match a with\n  | true => b\n  | false => false\n  end.\n\nDefinition nandb (a b:boolean): boolean :=\n  match a with\n  | true => negb(b)\n  | false => true\n  end.\n\n\nTheorem negb_negb : forall (b: boolean), negb(negb b) = b.\nProof.\nintros.\ndestruct b.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem false_nand: forall a b: boolean, nandb a b = false -> a=true /\\ b=true.\nProof.\nintros.\ndestruct a.\nsplit.\nreflexivity.\ndestruct b.\nreflexivity.\nsimpl in H.\nsymmetry.\napply H.\ndestruct b.\nsimpl in H.\nsplit.\nsymmetry.\napply H.\nreflexivity.\nsimpl in H.\nsplit.\nsymmetry.\napply H.\nsymmetry.\napply H.\nQed.\n", "meta": {"author": "isqnwtn", "repo": "coqworks", "sha": "d4d280d01da598158f22401136613795bdcd0f99", "save_path": "github-repos/coq/isqnwtn-coqworks", "path": "github-repos/coq/isqnwtn-coqworks/coqworks-d4d280d01da598158f22401136613795bdcd0f99/basic/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.8307890329137028}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** * From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** * Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Example *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n*)\n\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "gotoki-no-joe", "repo": "sfja31", "sha": "102ff05ec47daface0fccfbf2037a46c903a42d7", "save_path": "github-repos/coq/gotoki-no-joe-sfja31", "path": "github-repos/coq/gotoki-no-joe-sfja31/sfja31-102ff05ec47daface0fccfbf2037a46c903a42d7/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.9032942151647513, "lm_q1q2_score": 0.8307077704747231}}
{"text": "Require Import ZArith.\nRequire Import List.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*               Some Properties of fold_left                                *)\n(*                                                                           *)\n(*****************************************************************************)\n\nLemma fold_left_cons (A B : Type) (f : A -> B -> A) \n                     (b : B) (l : list B) (i : A) :\n  fold_left f (b :: l) i = fold_left f l (f i b).\nProof. trivial. Qed.\n\nLemma fold_right_cons (A B : Type) (f : B -> A -> A)\n                      (b : B) (l : list B) (i : A) :\n  fold_right f i (b :: l) =  f b (fold_right f i l).\nProof. trivial. Qed.\n\nLemma fold_left_comb (A B C D : Type) (f : B -> C -> D) (g : A -> D -> A)\n                        (l1 : list C) (l2 : list B) (i : A) :\n  fold_left (fun x y => \n      fold_left (fun x1 y1 => g x1 (f y y1)) l1 x) l2 i =\n  fold_left g (fold_right (fun y x => (map (f y) l1)++x) nil l2) i .\nProof.\nrevert i; elim l2; simpl; auto; clear l2.\nintros b l2 Hrec i.\nrewrite Hrec.\nrewrite fold_left_app.\napply f_equal2 with (f := fold_left g); auto.\ngeneralize i; elim l1; simpl; auto; clear l1 Hrec.\nQed.\n\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                         Permutations                                      *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nInductive perm {A : Type} : list A -> list A -> Prop :=\n  perm_id: forall l, perm l l\n| perm_swap: forall a b l, \n    perm (a :: b :: l) (b :: a :: l)\n| perm_skip: forall a l1 l2, \n    perm l1 l2 -> perm (a :: l1) (a :: l2)\n| perm_trans: forall l1 l2 l3, \n    perm l1 l2 -> perm l2 l3 -> perm l1 l3.\n\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                         Uniqueness                                        *)\n(*                                                                           *)\n(*****************************************************************************)\n\nInductive unique {A: Type} : list A -> Prop :=\n  uniqN: unique nil\n| uniqC: forall (a : A) l, \n        unique l -> ~ In a l -> unique (a :: l).\n\nLemma unique_inv (A : Type) (a : A) l : unique (a:: l) -> unique l.\nProof. intro H; inversion H; auto. Qed.\n\nLemma unique_app (A: Type) (l1 l2: list A) : unique (l1 ++ l2) -> unique l1.\nProof.\nelim l1; clear l1.\n- intros; apply uniqN.\n- intros a l1 Hrec H; inversion_clear H as [| xx yy Ha Hb].\n  apply uniqC; auto with datatypes.\nQed.\n\nLemma unique_perm (A : Type) (l1 l2 : list A) : \n  perm l1 l2 -> unique l1 -> unique l2.\nProof.\nintro H; elim H; clear l1 l2 H; auto.\n- intros a b l H; inversion_clear H as [| xx yy Ha Hb].\n  inversion_clear Ha as [| xx uu Ha1 Hb1].\n  repeat apply uniqC; auto with datatypes.\n  simpl; intros [H1 | H1]; subst; auto with datatypes.\n- intros a l1 l2 H1 H2 H3.\n  inversion_clear H3 as [| xx yy Ha Hb].\n  apply uniqC; auto with datatypes.\n  contradict Hb; generalize Hb; elim H1; clear l1 l2 H1 H2 Ha Hb;\n    auto with datatypes.\n  * simpl; intros a1 b1 l [H1 | [H1 | H1]]; auto.\n  * simpl; intros a1 l1 l2 H Hrec [H1 | H1]; auto.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                   Equality test for positive                              *)\n(*                                                                           *)\n(*****************************************************************************)\n\nFixpoint positive_eq (p1 p2 : positive) {struct p1} : bool :=\n  match p1, p2 with\n    xH, xH => true\n  | xO p3, xO p4 =>  positive_eq p3 p4\n  | xI p3, xI p4 => positive_eq p3 p4\n  | _, _ => false\n  end.\n\nLemma positive_eq_correct p1 p2 :\n  if positive_eq p1 p2 then p1 = p2 else p1 <> p2.\nProof.\nrevert p2; elim p1; [intros p3 Hrec | intros p3 Hrec|];\n  intros p2; (case p2; [intros p4 | intros p4 |]); simpl;\n  try (intros HH; discriminate HH); auto; generalize (Hrec p4);\n  case positive_eq; intros HH; try (subst p3; auto; fail);\n  intros HH1; case HH; injection HH1; auto.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*             Some modulo-3 operations for positive                         *)\n(*                                                                           *)\n(*****************************************************************************)\n\nDefinition pos_up x := \n  match x with\n  | 1%positive => 2%positive\n  | 2%positive => 3%positive\n  | _ => 1%positive\n  end.\n\nDefinition pos_down x := \n  match x with\n  | 2%positive => 1%positive\n  | 3%positive => 2%positive\n  | _ => 3%positive\n  end.\n\nLemma pos_up_less_4 s : (pos_up s < 4)%positive.\nProof.\ncase s; simpl; try (intros; red; simpl; auto; fail).\nintros p; case p; simpl; try (intros; red; simpl; auto; fail).\nQed.\n\nLemma pos_up_mod_3 s : (s < 4)%positive ->\n  (Z.pred (Zpos (pos_up s)) mod 3 =  (1 + Z.pred (Z.pos s)) mod 3)%Z.\nProof.\ncase s; simpl; auto; intros p; case p; simpl; auto;\nintros p1; case p1; unfold Pos.lt; intros; discriminate.\nQed.\n\nLemma pos_down_less_4 s : (pos_down s < 4)%positive.\nProof.\ncase s; simpl; try (intros; red; simpl; auto; fail).\n- intros p; case p; simpl; try (intros; red; simpl; auto; fail).\n- intros p; case p; simpl; try (intros; red; simpl; auto; fail).\nQed.\n\nLemma pos_down_mod_3 s : (s < 4)%positive ->\n  (Z.pred (Zpos (pos_down s)) mod 3 =  (2 + Z.pred (Zpos s)) mod 3)%Z.\nProof.\ncase s; simpl; auto; intros p; case p; simpl; auto;\nintros p1; case p1; unfold Pos.lt; intros; discriminate.\nQed.\n\nLemma pos_down_up s : (s < 4 -> pos_down (pos_up s) = s)%positive.\nProof.\ncase s; simpl; auto; intros p; case p; simpl; auto;\n  intros p1; case p1; auto; intros; discriminate.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                   The seven cubes                                         *)\n(*                                                                           *)\n(*****************************************************************************)\n\nInductive cube := C1 | C2 | C3 | C4 | C5 | C6 | C7.\n\nLemma unique7: unique (C1 :: C2 :: C3 :: C4 :: C5 :: C6 :: C7 :: nil).\nProof.\nrepeat apply uniqC; try apply uniqN; auto with datatypes;\n  simpl; intuition; discriminate.\nQed.\n\nDefinition c2N e := match e with \n  C1 => 0 | C2 => 1 | C3 => 2 | C4 => 3 | C5 => 4 | C6 => 5 | C7 => 6 \n  end.\n\nDefinition N2c n := match n with \n  0 => C1 | 1 => C2 | 2 => C3 | 3 => C4 | 4 => C5 | 5 => C6 | _ => C7\n  end.\n\nDefinition dummy {S1 : Type} (S2 :  Type) (e : S1) := S2.\n\nDefinition cube_pred_aux (c : cube) : cube.\nchange cube with (dummy cube c).\ncase c; match goal with |- dummy _ ?n  =>\n  let e := eval compute in (N2c (pred (c2N n))) in\n  exact e\nend.\nDefined.\n\nDefinition cube_pred (c : cube) :=\n  Eval lazy in cube_pred_aux c.\n\nDefinition cube_succ_aux (c : cube) : dummy cube c.\ncase c; match goal with |- dummy _ ?n  =>\n  let e := eval compute in (N2c (S (c2N n))) in\n  exact e\nend.\nDefined.\n\nDefinition cube_succ c := Eval lazy in cube_succ_aux c.\n\nDefinition cube_compare_aux (c1 c2 : cube) : dummy comparison (c1,c2).\ncase c1; case c2; match goal with |- dummy _ (?n1,?n2)  =>\n  let e := eval compute in (Nat.compare (c2N n1) (c2N n2)) in\n  exact e\nend.\nDefined.\nDefinition cube_compare (c1 c2 : cube) := Eval lazy in cube_compare_aux c1 c2.\n\nLemma cube_compare_correct c1 c2 :\n  match cube_compare c1 c2 with\n    | Eq => c1 = c2\n    | Lt => (c2N c1 < c2N c2)%nat\n    | Gt => (c2N c1 > c2N c2)%nat\n  end.\nProof. case c1; case c2; simpl; auto with arith. Qed.\n\nDefinition cube_encode_aux (c1 c2 : cube) : dummy positive (c1, c2).\ncase c1; case c2; match goal with |- dummy _ (?n1,?n2)  =>\n  let e := eval compute in (P_of_succ_nat (5 * c2N n2 + c2N n1)) in\n  exact e\nend.\nDefined.\n\nDefinition cube_encode (c1 c2 : cube) :=\n Eval lazy in cube_encode_aux c1 c2.\n\nDefinition cube_decode_aux (p: positive) : dummy (cube * cube) p.\nrevert p.\ndo 5 try (intro p; case p; clear p); try (intros p; exact (C1 , C1));\nmatch goal with |- dummy _ ?n =>\n  let z1 := eval compute in ((Zpos n - 1) mod 5)%Z in\n  let z2 := eval compute in ((Zpos n - 1) / 5)%Z in\n  let e := eval compute in (N2c (Z.abs_nat z1), N2c (Z.abs_nat z2)) in\n  exact e\nend.\nDefined.\n\nDefinition cube_decode (p: positive) :=\n  Eval lazy in cube_decode_aux p.\n\nLemma cube_encode_decode c1 c2 : \n c2N c1 - 4 = 0 -> c2N c2 - 5 = 0 -> cube_decode (cube_encode c1 c2) = (c1, c2).\nProof.\ncase c1; case c2; simpl; auto; intros; try discriminate.\nQed.\n\n\nDefinition cube_eq c1 c2 := \n  match cube_compare c1 c2 with Eq => true | _ => false end.\n\nLemma cube_eq_correct c1 c2 : if cube_eq c1 c2 then c1 = c2 else c1 <> c2.\nProof.\ncase c1; case c2; simpl; auto; intros; discriminate.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                   The 3 Orientations                                      *)\n(*                                                                           *)\n(*****************************************************************************)\n\nInductive orientation := O1 | O2 | O3.\n\nDefinition o2N e := match e with \n  O1 => 0 | O2 => 1 | O3 => 2\n  end.\n\nDefinition N2o n := match n with \n  0 => O1 | 1 => O2 | _ => O3 \n  end.\n\nDefinition oup o := match o with O1 => O2 | O2 => O3 | O3 => O1 end.\n\nDefinition odown o := match o with O1 => O3 | O2 => O1 | O3 => O2 end.\n\nDefinition oinv o := match o with O1 => O1 | O2 => O3 | O3 => O2 end.\n\nDefinition oadd o1 o2 := match o1 with O1 => o2 | O2 => oup o2 | o3 => odown o2 end.\n\nDefinition o2Z o := match o with O1 => 0%Z | O2 => 1%Z | o3 => 2%Z end.\n\nDefinition oeq o1 o2 :=\n   match o1, o2 with\n   | O1, O1 => true\n   | O2, O2 => true\n   | O3, O3 => true\n   | _, _ => false \n   end.\n\nLemma oeq_correct o1 o2 :\n  if oeq o1 o2 then o1 = o2 else o1 <> o2.\nProof.\ncase o1; case o2; simpl; auto; intros; discriminate.\nQed.\n\nLemma oup_mod_3 o : (o2Z (oup o) mod 3 = (o2Z o + 1) mod 3)%Z.\nProof.\ncase o; simpl; auto.\nQed.\n\nLemma odown_mod_3 o : (o2Z (odown o) mod 3 = (o2Z o - 1) mod 3)%Z.\nProof.\ncase o; simpl; auto.\nQed.\n\nLemma oadd_mod_3 ox oy : \n (o2Z (oadd ox oy) mod 3 =  (o2Z ox mod 3 + o2Z oy mod 3) mod 3)%Z.\nProof.\ncase ox; case oy; simpl; auto.\nQed.\n\nLemma oinv_eq ox oy : oadd ox oy = O1 -> oinv ox = oy.\nProof.\ncase ox; case oy; simpl; auto; intros; discriminate.\nQed.\n\nLemma eq_mod_3 ox oy : (o2Z ox mod 3 =  o2Z oy mod 3)%Z -> ox = oy.\nProof.\ncase ox; case oy; simpl; auto; intros; discriminate.\nQed.\n\nLemma oup_down o : oup (odown o) = o.\nProof. case o; simpl; auto. Qed.\n\nLemma odown_up o : odown (oup o) = o.\nProof. case o; simpl; auto. Qed.\n\nDefinition cube3_encode_aux (o : orientation) (c1 c2 : cube) : \n  dummy positive (o, c1, c2).\ncase o; case c1; case c2; match goal with |- dummy _ (?n0, ?n1,?n2)  =>\n  let e := eval compute in (P_of_succ_nat (21 * o2N n0 + 7 * c2N n1 + c2N n2)) in\n  exact e\nend.\nDefined.\n\nDefinition cube3_encode o c1 c2 := Eval lazy in cube3_encode_aux o c1 c2.\n\nDefinition cube3_decode_aux (p: positive) : dummy (orientation * cube * cube) p.\nrevert p.\ndo 6 try (intros p; case p; clear p); try (intros p; exact (O1, C1 , C1));\nmatch goal with |- dummy _ ?n => \n  exact (\n  let z1 := ((Zpos n - 1) mod 7)%Z in\n  let z2 := ((Zpos n - 1) / 7)%Z in\n  let z3 := (z2 mod 3)%Z in\n  let z4 := (z2 / 3)%Z in\n    (N2o (Z.abs_nat z4), N2c (Z.abs_nat z3), N2c (Z.abs_nat z1)))\nend.\nDefined.\n\nDefinition cube3_decode p := Eval lazy in cube3_decode_aux p.\n\nLemma cube3_encode_decode o c1 c2 : \no2N o - 2 = 0 -> c2N c1 - 2 = 0 -> \ncube3_decode (cube3_encode o c1 c2) = (o, c1, c2).\nProof.\ncase o; case c1; case c2; simpl; auto; intros; try discriminate.\nQed.\n\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                         State                                             *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nInductive state := \n  State (c1 c2 c3 c4 c5 c6 c7 : cube) \n        (o1 o2 o3 o4 o5 o6 o7 : orientation).\n\nDefinition init_state := State C1 C2 C3 C4 C5 C6 C7 O1 O1 O1 O1 O1 O1 O1.\n\nDefinition valid_state s := \n  match s with\n  | State c1 c2 c3 c4 c5 c6 c7 o1 o2 o3 o4 o5 o6 o7 =>\n     perm (C1 :: C2 :: C3 :: C4 :: C5 :: C6 :: C7 :: nil)\n          (c1 :: c2 :: c3 :: c4 :: c5 :: c6 :: c7 :: nil) /\\\n     fold_left oadd\n             (o1 :: o2 :: o3 :: o4 :: o5 :: o6 :: o7 :: nil) O1 = O1\n  end.\n\nLemma valid_state_init : valid_state init_state.\nProof.\nsimpl; repeat split; auto.\napply perm_id.\nQed.\n\nDefinition state_eq (s1 s2: state) :=\n  match s1, s2 with \n   State p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14, \n   State q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14  => \n   (cube_eq p1 q1 && cube_eq p2 q2 && cube_eq p3 q3 &&\n    cube_eq p4 q4 && cube_eq p5 q5 && cube_eq p6 q6 && cube_eq p7 q7 &&\n    oeq p8 q8 && oeq p9 q9 && oeq p10 q10 &&  oeq p11 q11 &&\n    oeq p12 q12 && oeq p13 q13 && oeq p14 q14)%bool\n   end.\n\nLemma state_eq_correct s1 s2 :\n  if state_eq s1 s2 then s1 = s2 else s1 <> s2.\nProof.\ncase s1; case s2; intros; unfold state_eq.\nrepeat match goal with |- context[cube_eq ?X ?Y] =>\n  generalize (cube_eq_correct X Y); case cube_eq;\n  [idtac | intros HH HH1; case HH; injection HH1; auto];\n  intros; subst Y\nend; simpl; auto.\nrepeat match goal with |- context[oeq ?X ?Y] =>\n  generalize (oeq_correct X Y); case oeq;\n  [idtac | intros HH HH1; case HH; injection HH1; auto];\n  intros; subst Y\nend; simpl; auto.\nQed.\n\nLocal Definition states := list state.\n\nFixpoint in_states s (ls : states) {struct ls} : bool :=\n  match ls with\n  | nil => false\n  | cons s1 ls1 => if state_eq s s1 then true else in_states s ls1\n  end.\n\nLemma in_states_correct s ls : \n  if in_states s ls then In s ls else ~In s ls.\nProof.\nelim ls; simpl; auto.\nintros a l1 Hrec; generalize (state_eq_correct s a); case state_eq; auto.\nintros H1; generalize Hrec; case in_states; auto.\nintros HH [HH1 | HH1]; case H1; auto; case HH; auto.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                         Rotations                                         *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\n(** Right Rotation: 1 -(-1)-> 4 -(+1)-> 5 -(-1)-> 2 -(+1)-> 1 **)\nDefinition rright s :=\n  match s with\n  | State p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 =>\n    State p2 p5 p3 p1 p4 p6 p7 (oup o2) (odown o5) o3 (odown o1) (oup o4) o6 o7\n  end.\n\nEval compute in rright init_state.\n\n(** Back Rotation: 4 -(-1)-> 7 -(+1)-> 6 -(-1)-> 5 -(+1)-> 4 **)\nDefinition rback s := \n  match s with\n  | State p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 =>\n    State p1 p2 p3 p5 p6 p7 p4 o1 o2 o3 (oup o5) (odown o6) (oup o7) (odown o4)\n  end.\n\nEval compute in rback init_state.\n\n(** Down Rotation: 2 -(+0)-> 5 -(+0)-> 6 -(+0)-> 3 -(+0)-> 2 **)\nDefinition rdown s := \n  match s with\n  | State p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 =>\n    State p1 p3 p6 p4 p2 p5 p7 o1 o3 o6 o4 o2 o5 o7\n  end.\n\nEval compute in rdown init_state.\n\nLtac Zmod_plus_tac H :=\n  match H with\n  | ((?X mod 3 + ?Y mod 3) mod 3)%Z => \n    let X1 := constr:((X mod 3)%Z) in\n    let Y1 :=  constr:((Y mod 3)%Z) in\n    Zmod_plus_tac X1 || Zmod_plus_tac Y1 || rewrite <- (Zplus_mod X Y 3)\n  | _ => idtac \n  end.\n\nLemma valid_state_right s : valid_state s -> valid_state (rright s).\nProof.\ncase s; unfold valid_state, rright, fold_left; \n  intros p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 (H1, H2).\nsplit.\n- apply perm_trans with (1 := H1).\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_skip.\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  apply perm_skip.\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  apply perm_skip.\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  apply perm_id.\n- apply trans_equal with (2 := H2).\n  apply eq_mod_3; auto; try (red; auto; fail).\n  repeat rewrite oadd_mod_3 || rewrite oup_mod_3 || rewrite odown_mod_3.\n  simpl.\n  repeat rewrite Zmod_mod.\n  do 7 match goal with |- ?X = _  => Zmod_plus_tac X end.\n  do 7 match goal with |- _ = ?X  => Zmod_plus_tac X end.\n  apply f_equal2 with (f := Zmod); auto.\n  ring.\nQed.\n\nLemma valid_state_back s : valid_state s -> valid_state (rback s).\nProof.\ncase s; unfold valid_state, rright, fold_left; \n  intros p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 (H1, H2).\nsplit.\n- apply perm_trans with (1 := H1).\n  do 3 apply perm_skip.\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_skip.\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_skip.\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_id.\n- apply trans_equal with (2 := H2).\n  apply eq_mod_3; auto; try (red; auto; fail).\n  repeat rewrite oadd_mod_3 || rewrite oup_mod_3 || rewrite odown_mod_3.\n  simpl.\n  repeat rewrite Zmod_mod.\n  do 7 match goal with |- ?X = _  => Zmod_plus_tac X end.\n  do 7 match goal with |- _ = ?X  => Zmod_plus_tac X end.\n  apply f_equal2 with (f := Zmod); auto.\n  ring.\nQed.\n\nLemma valid_state_down s : valid_state s -> valid_state (rdown s).\nProof.\ncase s; unfold valid_state, rright, fold_left; \n  intros p1 p2 p3 p4 p5 p6 p7 o1 o2 o3 o4 o5 o6 o7 (H1, H2).\nsplit.\n- apply perm_trans with (1 := H1).\n  apply perm_skip.\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_skip.\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  refine (perm_trans _ _ _ (perm_swap _ _ _) _).\n  apply perm_skip.\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  apply perm_skip.\n  refine (perm_trans _ _ _ _ (perm_swap _ _ _)).\n  apply perm_id.\n- apply trans_equal with (2 := H2).\n  apply eq_mod_3; auto; try (red; auto; fail).\n  repeat rewrite oadd_mod_3 || rewrite oup_mod_3 || rewrite odown_mod_3.\n  simpl.\n  repeat rewrite Zmod_mod.\n  do 7 match goal with |- ?X = _  => Zmod_plus_tac X end.\n  do 7 match goal with |- _ = ?X  => Zmod_plus_tac X end.\n  apply f_equal2 with (f := Zmod); auto.\n  ring.\nQed.\n\nLemma right_4 s : rright (rright (rright (rright s))) = s.\nProof.\ncase s; simpl; intros.\nrepeat rewrite oup_down; repeat rewrite odown_up; auto.\nQed.\n\nLemma back_4 s : rback (rback (rback (rback s))) = s.\nProof.\ncase s; simpl; intros.\nrepeat rewrite oup_down; repeat rewrite odown_up; auto.\nQed.\n\nLemma down_4 s : rdown (rdown (rdown (rdown s))) = s.\nProof.\ncase s; simpl; intros.\nrepeat rewrite oup_down; repeat rewrite odown_up; auto.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*                         Reachability                                      *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nInductive reachable : state -> Prop :=\n  reach0: reachable init_state\n| reachr: forall s, reachable s -> reachable (rright s)\n| reachb: forall s, reachable s -> reachable (rback s)\n| reachd: forall s, reachable s -> reachable (rdown s).\n\nLemma reachable_valid s : reachable s -> valid_state s.\nProof.\nintros H; elim H; auto.\n- apply valid_state_init.\n- intros; apply valid_state_right; auto.\n- intros; apply valid_state_back; auto.\n- intros; apply valid_state_down; auto.\nQed.\n\nDefinition move (s1 s2 : state) :=\n  s2 = rright s1  \\/\n  s2 = rright (rright s1) \\/\n  s2 = rright (rright (rright s1)) \\/\n  s2 = rback s1 \\/\n  s2 = rback (rback s1) \\/\n  s2 = rback (rback (rback s1)) \\/\n  s2 = rdown s1 \\/\n  s2 = rdown (rdown s1) \\/\n  s2 = rdown (rdown (rdown s1)).\n\nLemma move_valid s1 s2 : valid_state s1 -> move s1 s2 -> valid_state s2.\nProof.\nintros Hg [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | H1]]]]]]]];\n  subst s2; repeat (apply valid_state_right || apply valid_state_back \n                                            || apply valid_state_down; auto).\nQed.\n\nLemma move_sym s1 s2 : valid_state s1 -> move s1 s2 -> move s2 s1.\nProof.\nintros Hg [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | H1]]]]]]]];\n  subst s2;\ntry (pattern s1 at 2; rewrite <- right_4; unfold move; auto; fail);\ntry (pattern s1 at 2; rewrite <- down_4; auto; unfold move; do 6 right; auto; fail);\npattern s1 at 2; rewrite <- back_4; auto; unfold move; do 3 right; auto.\nQed.\n\nInductive nreachable: nat -> state -> Prop :=\n| nreach0: nreachable 0 init_state\n| nreachS: forall n s1 s2, \n     nreachable n s1 -> move s1 s2 -> nreachable (S n) s2.\n\nLemma nreachable_reachable n s : nreachable n s -> reachable s.\nProof.\nintros H; elim H; clear n s H; intros; auto.\napply reach0.\ngeneralize H1; clear H1; \n  intros [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | H1]]]]]]]];\n  subst s2; repeat apply reachr; repeat apply reachb;\n   repeat apply reachd; auto.\nQed.\n\nLemma reachable_nreachable s : reachable s -> exists n, nreachable n s.\nProof.\nintros H; elim H; clear s H; try (exists 0%nat; apply nreach0);\n  intros s Hs (n, Hrec); exists (S n); apply nreachS with s; auto;\n  unfold move; auto; do 6 right; auto.\nQed.\n\nLemma move_nreachable n s2 :\n  nreachable (S n) s2 -> exists s1, move s1 s2 /\\ nreachable n s1.\nProof.\nintros H; inversion_clear H as [| xx s1 yy Hs1 Hs2];\n  exists s1; auto.\nQed.\n\nLemma nreachable_valid n s : nreachable n s -> valid_state s.\nProof.\nintros H; elim H; clear n s H.\napply valid_state_init.\nintros n s1 s2 H1 H2 H3; apply move_valid with s1; auto.\nQed.\n\nDefinition nreachable_dec n s :\n   valid_state s -> {nreachable n s} + {~nreachable n s}.\nProof.\nrevert s; elim n; simpl; auto.\n- intros s; generalize (state_eq_correct s init_state); case state_eq; intros HH.\n  * left; rewrite HH; apply nreach0.\n  * right; intros HH1; case HH; inversion_clear HH1; auto.\n- intros n1 Hrec s Hg.\n  case (Hrec (rright s)); try intros H1.\n  * apply valid_state_right; auto.\n  * left; rewrite <- right_4; try apply nreachr3; auto.\n    apply nreachS with (1 := H1); unfold move; auto.\n  * case (Hrec (rright (rright s))); try intros H2.\n    + repeat apply valid_state_right; auto.\n    + left; rewrite <- right_4; try apply nreachr2; auto.\n      apply nreachS with (1 := H2); unfold move; auto.\n    + case (Hrec (rright (rright (rright s)))); try intros H3.\n    -- repeat apply valid_state_right; auto.\n    -- left; rewrite <- right_4; try apply nreachr1; auto.\n       apply nreachS with (1 := H3); unfold move; auto.\n    -- case (Hrec (rback s)); try intros H4.\n       ** apply valid_state_back; auto.\n       ** left; rewrite <- back_4; try apply nreachb3; auto.\n          apply nreachS with (1 := H4); unfold move; do 3 right; auto.\n       ** case (Hrec (rback (rback s))); try intros H5.\n          ++ repeat apply valid_state_back; auto.\n          ++ left; rewrite <- back_4; try apply nreachb2; auto.\n             apply nreachS with (1 := H5); unfold move; do 3 right; auto.\n          ++ case (Hrec (rback (rback (rback s)))); try intros H6.\n             --- repeat apply valid_state_back; auto.\n             --- left; rewrite <- back_4; try apply nreachb1; auto.\n                 apply nreachS with (1 := H6); unfold move; do 3 right; auto.\n             --- case (Hrec (rdown s)); try intros H7.\n                 *** apply valid_state_down; auto.\n                 *** left; rewrite <- down_4; try apply nreachd3; auto.\n                     apply nreachS with (1 := H7); unfold move;\n                     do 6 right; auto.\n                 *** case (Hrec (rdown (rdown s))); try intros H8.\n                     ++++ repeat apply valid_state_down; auto.\n                     ++++ left; rewrite <- down_4; try apply nreachd2; auto.\n                          apply nreachS with (1 := H8); \n                          unfold move; do 6 right; auto.\n                     ++++ case (Hrec (rdown (rdown (rdown s)))); try intros H9.\n                          ---- repeat apply valid_state_down; auto.\n                          ---- left; rewrite <- down_4; \n                                 try apply nreachd1; auto.\n                               apply nreachS with (1 := H9); \n                               unfold move; do 6 right; auto.\n                          ---- right; intros H10.\n                               case (move_nreachable _ _ H10); \n                                   intros s1 HH; case HH; clear HH.\n                               intros [HH1 | [HH1 | [HH1 | [HH1 | [HH1 | \n                                      [HH1 | [HH1 | [HH1 | HH1]]]]]]]] HH2; \n                                      subst s.\n                               **** case H3; rewrite right_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H2; rewrite right_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H1; rewrite right_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H6; rewrite back_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H5; rewrite back_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H4; rewrite back_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H9; rewrite down_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H8; rewrite down_4; auto; \n                                    apply nreachable_valid with n1; auto.\n                               **** case H7; rewrite down_4; auto; \n                                    apply nreachable_valid with n1; auto.\nQed.\n\nDefinition nreachable_le_dec n s :\n  valid_state s -> \n  {forall m, m < n -> ~ nreachable m s} + {exists m, m < n /\\ nreachable m s}.\nProof.\nintro Hs; elim n; simpl; clear n.\n- left; intros m Hm; contradict Hm; auto with arith.\n- intros n [Hrec | Hrec].\n  case (nreachable_dec n s); auto; intros H1.\n  + right; exists n; auto.\n  + left; intros m Hm; inversion Hm; auto.\n  + right; case Hrec; intros m (Hm1, Hm2); exists m; split; auto with arith.\nQed.\n\nDefinition nsreachable n s :=\n  nreachable n s /\\ forall m, m < n -> ~ nreachable m s.\n\nLemma nsreachable_unique n m s : nsreachable n s -> nsreachable m s -> n = m.\nProof.\nintros (H1, H2) (H3, H4).\ncase (le_or_lt n m); intros HH0.\n- case (le_lt_or_eq _ _ HH0); clear HH0; intros HH0; auto.\n  case (H4 n); auto.\n- case (H2 m); auto.\nQed.\n\nLemma nsreachable_bound n s :\n  nreachable n s -> exists m, m <= n /\\ nsreachable m s.\nProof.\nrevert s; pattern n; apply Wf_nat.lt_wf_ind; clear n.\nintros n; case n; clear n.\n- intros _ s H; exists 0; split; auto with arith.\n  split; auto; intros m Hm; contradict Hm; auto with arith.\n- intros n Hrec s Hs.\n  case (nreachable_le_dec  (S n) s).\n  + apply nreachable_valid with (1 := Hs).\n  + intros H1; exists (S n); split; auto; split; auto.\n  + intros (m, (Hm1, Hm2)).\n    case (Hrec _ Hm1 _ Hm2); intros s1 (Hs1, Hs2).\n    exists s1; split; auto with arith.\n    apply le_trans with (1 := Hs1); auto with arith.\nQed.\n\nLemma move_nsreachable n s2 :\n  nsreachable (S n) s2 -> exists s1, move s1 s2 /\\ nsreachable n s1.\nProof.\nintros (H1, H2).\ncase (move_nreachable _ _ H1); intros s1 (Hs1, Hs2).\nexists s1; split; auto.\ncase (nsreachable_bound _ _ Hs2); intros m (Hm, Hm1).\ncase (le_lt_or_eq _ _ Hm); clear Hm; intros Hm.\n- case (H2 (S m)); auto with arith.\n  apply nreachS with (2 := Hs1); auto.\n  case Hm1; auto.\n- subst n; auto.\nQed.\n\nLemma nsreachable_inv n m s :\n  n <= m -> nsreachable m s -> exists s1, nsreachable n s1.\nProof.\nintro H; revert s; elim H; auto; clear m H.\n- intros s H1; exists s; auto.\n- intros m _ H1 s H2.\n  case (move_nsreachable _ _ H2); intros s1 (_, Hs1); auto.\n  apply (H1 s1); auto.\nQed.\n\nDefinition nlreachable n s := exists m, m <= n /\\ nreachable m s.\n\nLemma nlreachable_reachable n s : nlreachable n s -> reachable s.\nProof.\nintros (m, (Hm, Hm1)).\napply nreachable_reachable with m; auto.\nQed.\n\nLemma nlreach_weak n m s : \n  n <= m -> nlreachable n s -> nlreachable m s.\nProof.\nintros H (m1, (Hm1, Hm2)).\nexists m1; split; auto.\napply le_trans with (1 := Hm1); auto.\nQed.\n\nLemma nlreachable_bound n s :\n  nlreachable n s -> exists m, m <= n /\\ nsreachable m s.\nProof.\nintros (m, (H1, H2)); case (nsreachable_bound m s); auto.\nintros p (Hp, Hp1); exists p; split; auto.\napply le_trans with (1 := Hp); auto.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*       Computational version of reachability                               *)\n(*                                                                           *)\n(*****************************************************************************)\n\n(* The list of all moves *)\nDefinition movel :=\n rright :: (fun s1 => rright (rright s1)) :: \n           (fun s1 => rright (rright (rright s1))) ::\n rback :: (fun s1 => rback (rback s1)) :: \n          (fun s1 => rback (rback (rback s1))) ::\n rdown:: (fun s1 => rdown (rdown s1)) :: \n         (fun s1 => rdown (rdown (rdown s1))):: nil.\n\n(* The list of candidate *)\nDefinition candidate_list l := \n  fold_right\n      (fun (y : state) (x : list state) =>\n        map (fun y1 : state -> state => y1 y) movel ++ x) nil l.\n\n(* A filter that only adds the element that were not already in the first list *)\nDefinition filters (ps : states * states) (s : state) :=\n          let (states, nstates) := ps in\n          if in_states s states then ps\n          else (s :: states, s :: nstates).\n\n(* Compute the next pair of states *)\nDefinition nexts (ps : states * states) s :=\n fold_left \n  (fun (ps : states * states) f => \n    let (states, nstates) := ps in\n    let s := f s in\n    if in_states s states then ps else\n    let states1 := s :: states in\n    let nstates1 := s :: nstates in (states1, nstates1))\n   movel ps.\n\n(* Now we just iterate *)\n\nFixpoint iters_aux n (ps : states * states) := \n  match n with \n  | O    => ps \n  | S n1 => let (m,p) := ps in \n            iters_aux n1 (fold_left nexts p (m,nil))\n  end.\n\nDefinition iters n := iters_aux n (init_state :: nil, init_state :: nil).\n\n(*****************************************************************************)\n(*              Proving iters                                                *)\n(*****************************************************************************)\n\nLemma movel_valid f s :\n   In f movel -> valid_state s -> valid_state (f s).\nProof.\nintros [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | [H1 | H1]]]]]]]]]; \n  try subst f;\n  intros; repeat apply valid_state_right; \n   repeat apply valid_state_back;\n   repeat apply valid_state_down; auto.\ncase H1; auto.\nQed.\n\nLemma candidate_list_correct l n :\n  (forall i, (nsreachable n i -> In i l) /\\ \n            (In i l -> nlreachable n i)) ->\n  (forall i, (nsreachable (S n) i -> In i (candidate_list l)) /\\\n            (In i (candidate_list l) -> nlreachable (S n) i)).\nProof.\nassert (F : forall l n i, \n     (forall j, move j i -> nsreachable n j -> In j l) ->\n      nsreachable (S n) i -> In i (candidate_list l)).\n- intros l1; elim l1; simpl; auto; clear l1.\n  + intros n1 i1 H Hi1.\n    case (move_nsreachable _ _ Hi1); intros j1 (Hj1, Hj2); auto.\n    apply (H j1); auto.\n  + intros s l1 Hrec n1 i1 Hi Hi1.\n    case (move_nsreachable _ _ Hi1); intros j1 (Hj1, Hj2); auto.\n    case (Hi _ Hj1 Hj2); intros HH.\n    * rewrite <-HH in Hj1; unfold move in Hj1; clear HH; intuition.\n    * do 9 match goal with |- context[?X = ?Y] =>\n              generalize (state_eq_correct X Y); \n              case state_eq; auto; intros; right\n           end.\n      apply Hrec with n1; auto.\n      intros j Hj3 Hj4.\n      case  (Hi _ Hj3 Hj4); auto.\n      intros HH1; rewrite <- HH1 in Hj3.\n      do 8 (case Hj3; intros HH2; contradict HH2; auto; \n            clear Hj3; intros Hj3).\n- intros H i; split.\n  + intros; apply F with n; auto.\n    intros; case (H j); auto.\n  +  assert (H1: forall i, In i l -> nlreachable n i).\n       intros i1; case (H i1); auto.\n     generalize H1; elim l; simpl; auto; clear l H H1.\n     * intros _ HH; case HH.\n     * intros a l Hrec; intros H1.\n       case (H1 a); auto; intros m (Hm, Hm1).\n       intros [HH1 | [HH1 | [HH1 | [HH1 | \n              [HH1 | [HH1 | [HH1 | [HH1 | [HH1 | HH1]]]]]]]]];\n       try (subst i; exists (S m); split; auto with arith;\n         apply nreachS with (1 := Hm1); unfold move; auto; \n         do 3 right; auto; do 3 right; auto).\n       apply Hrec; auto.\nQed.\n\nLemma candidate_valid l :\n  (forall s, In s l -> valid_state s) ->\n  (forall s, In s (candidate_list l) -> valid_state s).\nProof.\nelim l; unfold candidate_list; auto; clear l.\nintros a l Hrec Hg s; rewrite fold_right_cons; intros H1.\ncase (in_app_or _ _ _ H1); intros H2; auto with datatypes.\nassert (F0: valid_state a); auto with datatypes.\nrewrite in_map_iff in H2.\ncase H2; intros f (Hf, Hf1); subst s.\napply movel_valid; auto.\nQed.\n\nLemma candidate_app l1 l2 :\n candidate_list (l1 ++ l2) = candidate_list l1 ++ candidate_list l2.\nProof.\nrevert l2; elim l1; unfold candidate_list; clear l1.\n- simpl; auto.\n- intros a l1 Hrec l2; rewrite fold_right_cons.\n  rewrite app_ass, <- Hrec; auto.\nQed.\n\nLemma candidate_in a l :\n  In a (candidate_list l) <-> \n  exists i, exists f, a = f i /\\ In i l /\\ In f movel.\nProof.\nelim l; clear l.\n- split; intros H; case H; intros i (f, (_, (HH,_))); case HH.\n- intros b l Hrec; split.\n  + intros H; case (in_app_or (map (fun y1 : state -> state => y1 b) movel)\n                           (candidate_list l) _ H).\n    * elim movel; simpl; auto.\n      -- intros HH; case HH.\n      -- intros f lf Hrec1 [H1 | H1].\n         ++ exists b; exists f; auto.\n         ++ case (Hrec1 H1); intros f1 (b1, (Hb1, (Hb2, Hb3))).\n            exists f1; exists b1; auto.\n    * rewrite Hrec; intros (i, (f, (Hb1, (Hb2, Hb3)))).\n      exists i; exists f; auto with datatypes.\n  + intros (i, (f, (Hf, (Hf1, Hf2)))); subst a.\n    unfold candidate_list; rewrite fold_right_cons.\n    match goal with |- context[fold_right ?X ?Y ?Z] =>\n     change (fold_right X Y Z) with (candidate_list Z)\n    end.\n    apply in_or_app.\n    simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n    * subst b; left; generalize Hf2; elim movel; simpl; auto.\n      intros f1 lf Hrec1 [H1 | H1]; auto; subst f1; auto.\n    * right; rewrite Hrec.\n      exists i; exists f; auto.\nQed.\n\nDefinition lequiv {A : Type} l1 l2:= forall s : A, In s l1 <-> In s l2.\n\nDefinition pequiv {A : Type} (pl1 pl2 : list A * list A) := \n  lequiv (fst pl1) (fst pl2) /\\ lequiv (snd pl1) (snd pl2).\n\nLemma candidate_equiv l1 l2 :\n  lequiv l1 l2 -> lequiv (candidate_list l1) (candidate_list l2).\nProof.\nintros H1 a.\nrepeat rewrite candidate_in.\nsplit; intros (i, (f, (Hf, (Hf1, Hf2)))); exists i; exists f; auto.\n- repeat split; auto; unfold lequiv in H1; rewrite <- H1; auto.\n- repeat split; auto; unfold lequiv in H1; rewrite H1; auto.\nQed.\n\nDefinition valid_pair ps :=\n  (forall s, In s (fst ps) -> valid_state s) /\\\n  (forall s, In s (snd ps) -> valid_state s).\n\nLemma filters_valid ps s1 :\n  valid_pair ps -> valid_state s1 -> valid_pair (filters ps s1).\nProof.\ndestruct ps as (ss1, ss2); intros (Hg1, Hg2) Hg; split; intros s;\n   unfold filters; case in_states; simpl; auto; \n   intros [H1 | H1]; auto; subst s1; auto.\nQed.\n\nLemma filters_incl ps s :\n  incl (snd ps) (fst ps) ->\n  incl (snd (filters ps s)) (fst (filters ps s)).\nProof.\ndestruct ps as (ss1, ss2); intro H; unfold filters.\ncase in_states; simpl; auto with datatypes.\nQed.\n\nLemma filters_correct ps l :\n let ps1 := fold_left filters l ps in\n (forall i, In i (fst ps1) <-> In i (fst ps) \\/ In i l) /\\\n (forall i, In i (snd ps1) <-> In i (snd ps) \\/ (~In i (fst ps) /\\ In i l)).\nProof.\nrevert ps; elim l; clear l; simpl; auto.\n- intros ps; split; intros i; split; auto.\n  + intros [HH | HH]; auto; case HH.\n  + intros [HH | HH]; auto; case HH; intros _ HH1; case HH1.\n- intros a l Hrec ps.\n  case (Hrec (filters ps a)); intros H1 H2; split.\n  + intros i; apply iff_trans with (1:= H1 i).\n    unfold filter; case ps; simpl; intros s1 s2.\n    generalize (in_states_correct a s1); case in_states; simpl; auto.\n    * intros H5; split; intros [HH | HH]; auto.\n      case HH; auto; intros; subst i; auto.\n    * intros H5; split; intros [HH | HH]; auto.\n      -- case HH; auto.\n      -- case HH; auto.\n  + intros i; apply iff_trans with (1:= H2 i).\n    unfold filter; case ps; simpl; intros s1 s2.\n    generalize (in_states_correct a s1); case in_states; simpl; auto.\n    * intros H5; split; intros [HH | HH]; auto.\n      -- case HH; auto.\n      -- case HH; intros HH1 [HH2 | HH2]; auto.\n         case HH1; rewrite <- HH2; auto.\n    * intros H5; split; intros [HH | HH]; auto.\n      -- case HH; auto; intros; subst i; auto.\n      -- case HH; intros HH1 HH2; right; auto.\n      -- generalize (state_eq_correct a i); \n          case state_eq; auto; intros He.\n         case HH; intros HH1 [HH2 | HH2]; auto.\n         right; split; auto.\n         intros [HH3 | HH3]; auto.\nQed.\n\nLemma filters_equiv ps1 ps2 l1 l2 :\n  pequiv ps1 ps2 -> lequiv l1 l2 ->\n  pequiv (fold_left filters l1 ps1) (fold_left filters l2 ps2).\nProof.\nintros (H1, H2) H3.\ncase (filters_correct ps1 l1); intros Hr1 Hs1.\ncase (filters_correct ps2 l2); intros Hr2 Hs2.\nsplit; intros a;\n  (rewrite Hr1; rewrite Hr2) ||(rewrite Hs1; rewrite Hs2).\n- unfold lequiv in H1, H3; rewrite H1, H3; split; auto.\n- unfold lequiv in H1, H2, H3; rewrite H1, H2, H3; split; auto.\nQed.\n\nDefinition nexts_correct (ps : states * states) s :\n (forall s1, \n    In s1 (fst (nexts ps s)) <-> \n      In s1 (fst ps) \\/ exists f, In f movel /\\ s1 = f s /\\ ~ In s1 (fst ps)) /\\\n (forall s1, \n    In s1 (snd (nexts ps s)) <-> \n      In s1 (snd ps) \\/ exists f, In f movel /\\ s1 = f s /\\ ~ In s1 (fst ps)).\nProof.\nunfold nexts.\nmatch goal with |- context[fold_left ?X _ _] =>\n  change X with (fun ps f => filters ps (f s))\nend.\ngeneralize ps s; elim movel; clear ps s.\n- simpl; intros ps s; split; intros s1; split; auto; \n   intros HH; case HH; auto; intros (f, (HH1, _)); case HH1.\n- intros f lf Hrec ps s; repeat rewrite fold_left_cons.\n  split; intros s1; case (Hrec (filters ps (f s)) s);\n    intros Hr1 Hr2.\n  + apply iff_trans with (1 := Hr1 s1).\n    unfold filters; case ps.\n    intros ss1 ss2.\n    generalize (in_states_correct (f s) ss1); case in_states.\n    * simpl fst; auto.\n      intros H1; split; intros [H2 | H2]; auto.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         right; exists f1; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n         ++ left; rewrite Hf2, <- Hf1; auto.\n         ++ right; exists f1; auto with datatypes.\n    * simpl fst; auto.\n      intros H1; split; intros [H2 | H2]; auto with datatypes.\n      -- simpl in  H2; case H2; clear H2; intros H2; auto.\n         subst s1; right; exists f; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         right; exists f1; repeat split; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n         ++ subst f1; simpl; auto.\n         ++ generalize (state_eq_correct s1 (f s)); case state_eq; intros HH1.\n            ** rewrite HH1; auto with datatypes.\n            ** right; exists f1; repeat split; auto with datatypes.\n               simpl; intros [H3 | H3]; case Hf3; auto.\n               case HH1; auto.\n  + apply iff_trans with (1 := Hr2 s1).\n    unfold filters; case ps.\n    intros ss1 ss2.\n    generalize (in_states_correct (f s) ss1); case in_states.\n    * simpl fst; simpl snd; auto.\n      intros H1; split; intros [H2 | H2]; auto.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         right; exists f1; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n         ++ case Hf3; rewrite Hf2, <- Hf1; auto.\n         ++ right; exists f1; auto with datatypes.\n    * simpl fst; simpl snd; auto.\n      intros H1; split; intros [H2 | H2]; auto with datatypes.\n      -- simpl in  H2; case H2; clear H2; intros H2; auto.\n         subst s1; right; exists f; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         right; exists f1; repeat split; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, Hf3)).\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n         ++ subst f1; simpl; auto.\n         ++ generalize (state_eq_correct s1 (f s)); case state_eq; \n               intros HH1.\n            ** rewrite HH1; auto with datatypes.\n            ** right; exists f1; repeat split; auto with datatypes.\n               simpl; intros [H3 | H3]; case Hf3; auto.\n               case HH1; auto.\nQed.\n\nLemma nexts_equiv ps1 ps2 s :\n  pequiv ps1 ps2 -> pequiv (nexts ps1 s) (nexts ps2 s).\nProof.\nintros (H1, H2).\ncase (nexts_correct ps1 s); intros Hr1 Hs1.\ncase (nexts_correct ps2 s); intros Hr2 Hs2.\nsplit; intros a.\n- apply iff_trans with (1 := (Hr1 a)).\n  apply iff_sym; apply iff_trans with (1:= (Hr2 a)).\n  split; intros [H3 | H3].\n  + left; case (H1 a); auto.\n  + case H3; intros f1 (Hf1, (Hf2, Hf3)); right; exists f1;\n    repeat split; auto; unfold lequiv in H1; rewrite (H1 a); auto.\n  + left; case (H1 a); auto.\n  + case H3; intros f1 (Hf1, (Hf2, Hf3)); right; exists f1;\n    repeat split; auto; intros H4; case Hf3; case (H1 a); auto.\n- apply iff_trans with (1 := (Hs1 a)).\n  apply iff_sym; apply iff_trans with (1:= (Hs2 a)).\n  split; intros [H3 | H3].\n  + left; case (H2 a); auto.\n  + case H3; intros f1 (Hf1, (Hf2, Hf3)); right; exists f1;\n    repeat split; auto; unfold lequiv in H1; rewrite (H1 a); auto.\n  + left; case (H2 a); auto.\n  + case H3; intros f1 (Hf1, (Hf2, Hf3)); right; exists f1;\n    repeat split; auto; intros H4; case Hf3; case (H1 a); auto.\nQed.\n\nLemma nexts_valid ps s1 :\n  valid_pair ps -> valid_state s1 -> valid_pair (nexts ps s1).\nProof.\nunfold nexts;\n   match goal with |- context[fold_left ?X _ _] =>\n    change X with (fun ps f => filters ps (f s1))\n   end.\ngeneralize ps s1 (movel_valid); elim movel; auto; clear ps s1.\nintros f lf Hrec ps s1 Hf Hg1 Hg; rewrite fold_left_cons.\napply Hrec; auto with datatypes.\ngeneralize (filters_valid ps (f s1) Hg1); auto with datatypes.\nQed.\n\nLemma nexts_incl ps s :\n  incl (snd ps) (fst ps) ->\n  incl (snd (nexts ps s)) (fst (nexts ps s)).\nProof.\ndestruct ps as (ss1, ss2); unfold nexts;\n   match goal with |- context[fold_left ?X _ _] =>\n    change X with (fun ps f => filters ps (f s))\n   end.\ngeneralize ss1 ss2 s; elim movel; auto; clear ss1 ss2 s.\nintros f lf Hrec ss1 ss2 s Hs; repeat rewrite fold_left_cons.\ngeneralize (filters_incl (ss1, ss2) (f s)).\ncase filters; intros ss3 ss4 Hss3.\napply Hrec; auto with datatypes.\nQed.\n\nLemma fold_nexts_correct ps ss :\n  (forall s, In s (fst (fold_left nexts (snd ps) (fst ps, ss))) <->\n    In s (fst ps) \\/\n    (exists f, exists i, In f movel /\\ In i (snd ps) /\\ s = f i /\\ ~ In (f i) (fst ps))) /\\\n  (forall s, In s (snd (fold_left nexts (snd ps) (fst ps, ss))) <->\n    In s ss \\/\n    (exists f, exists i, In f movel /\\ In i (snd ps) /\\ s = f i /\\ ~ In (f i) (fst ps))).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\ngeneralize ss1 ss; elim ss2; clear ss ss1 ss2; auto.\n- unfold fold_left, fst, snd.\n  intros ss1 ss; split; intros ; split; auto; intros [H1 | H1]; auto;\n    case H1; intros f (i, (_, (HH, _))); case HH.\n- intros s1 ss2 Hrec ss1 ss.\n  rewrite fold_left_cons.\n  generalize (nexts_correct (ss1, ss) s1); case nexts; \n    simpl fst; simpl snd; intros ss3 ss4 (Hss3, Hss4).\n  assert (tmp: forall A B:Prop, A -> (A -> B) -> A /\\ B); auto.\n  + apply tmp; clear tmp.\n    * intros s; case (Hrec ss3 ss4); intros Hr1 Hr2; clear Hrec.\n      apply iff_trans with (1 := Hr1 s).\n      split; intros [H1 | H1].\n      -- rewrite Hss3 in H1; case H1; auto.\n         intros (f, (Hf1, (Hf2, Hf3))); subst s; \n         right; exists f; exists s1;  auto with datatypes.\n      -- case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))); \n           subst s; right; exists f; \n           exists i; repeat split; auto with datatypes.\n         intros H2; case Hf4. \n         unfold lequiv in Hss3; rewrite Hss3; auto.\n      -- left; unfold lequiv in Hss3; rewrite Hss3; auto.\n      -- case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))).\n         simpl in Hf2; case Hf2; clear Hf2; intros Hf2.\n         ++ subst; left; unfold lequiv in Hss3; rewrite Hss3; auto.\n            right; exists f; auto.\n         ++ generalize (in_states_correct s ss3); \n              case in_states; auto; intros H3.\n            right; exists f;\n              exists i; repeat split; auto with datatypes.\n           rewrite <- Hf3; auto.\n    * intros Hl s; case (Hrec ss3 ss4); intros Hr1 Hr2; clear Hrec.\n      apply iff_trans with (1 := Hr2 s); clear Hr2.\n      split; intros [H1 | H1].\n      -- rewrite Hss4 in H1; case H1; auto.\n         intros (f, (Hf1, (Hf2, Hf3))); subst s; \n           right; exists f; exists s1; auto with datatypes.\n      -- case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))); subst s; right; exists f; \n           exists i; repeat split; auto with datatypes.\n         intros H2; case Hf4.\n         unfold lequiv in Hss3; rewrite Hss3; auto.\n      -- left; unfold lequiv in Hss4; rewrite Hss4; auto.\n      -- match type of H1 with ?X =>\n           assert (F1: In s ss1 \\/ X); auto\n         end.\n         rewrite <- Hl, Hr1 in F1; clear Hl Hr1.\n         case F1; auto; clear F1; intros F1.\n         case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4))));\n           clear H1; subst s.\n         rewrite Hss3 in F1; case F1; clear F1; intros F1.\n         ++ case Hf4; auto.\n         ++ left; rewrite Hss4; auto.\nQed.\n\nLemma fold_nexts_equiv ps1 ps2 ss1 ss2 :\n  pequiv ps1 ps2 ->\n  lequiv ss1 ss2 ->\n  pequiv (fold_left nexts (snd ps1) (fst ps1, ss1)) \n         (fold_left nexts (snd ps2) (fst ps2, ss2)).\nProof.\nunfold pequiv, lequiv; intros (He1, He2) He3.\ncase (fold_nexts_correct ps1 ss1); intros Hr1 Hs1.\ncase (fold_nexts_correct ps2 ss2); intros Hr2 Hs2.\nsplit; intros s.\n- apply iff_trans with (1 := Hr1 s).\n  apply iff_sym; apply iff_trans with (1 := Hr2 s).\n  split; intros [H1 | H1]; auto.\n  + left; rewrite He1; auto.\n  + right; case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))).\n     exists f; exists i; repeat split; try rewrite He2; try rewrite He1; auto.\n  + left; rewrite <- He1; auto.\n  + right; case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))).\n    exists f; exists i; repeat split; try rewrite <- He2; \n    try rewrite <- He1; auto.\n- apply iff_trans with (1 := Hs1 s).\n  apply iff_sym; apply iff_trans with (1 := Hs2 s).\n  split; intros [H1 | H1]; auto.\n  + left; rewrite He3; auto.\n  + right; case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))).\n    exists f; exists i; repeat split; try rewrite He2; try rewrite He1; auto.\n  + left; rewrite <- He3; auto.\n  + right; case H1; intros f (i, (Hf1, (Hf2, (Hf3, Hf4)))).\n    exists f; exists i; repeat split; try rewrite <- He2;\n    try rewrite <- He1; auto.\nQed.\n\nLemma fold_nexts_valid ps ss :\n  valid_pair ps ->\n  (forall s, In s ss -> valid_state s) ->\n  valid_pair  (fold_left nexts (snd ps) (fst ps, ss)).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\nrevert ss1 ss; elim ss2; clear ss2; auto.\n- simpl; intros ss1 ss (HH, _) HH1; split; auto.\n- intros s ss2 Hrec ss1 ss Hg1 Hg; rewrite fold_left_cons.\n  generalize (nexts_valid (ss1, ss) s); case nexts.\n  intros ss3 ss4 Hg2.\n  case Hg1; simpl fst; simpl snd; intros Hg3 Hg4; \n    case Hg2; auto with datatypes.\n  + split; auto.\n  + simpl; intros Hg5 Hg6; apply Hrec; auto; split; auto.\n    case Hg1; auto with datatypes.\nQed.\n\nLemma fold_nexts_incl ps ss :\n  incl ss (fst ps) ->\n  incl (snd (fold_left nexts (snd ps) (fst ps, ss)))\n       (fst (fold_left nexts (snd ps) (fst ps, ss))).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\nrevert ss1 ss; elim ss2; clear ss2; auto.\nintros s ss2 Hrec ss1 ss H1.\nrepeat rewrite fold_left_cons.\ngeneralize (nexts_incl (ss1, ss) s); case nexts.\nsimpl fst; simpl snd.\nintros ss3 ss4 H3; apply Hrec; auto with datatypes.\nQed.\n\nLemma fold_nexts_nreach n ps :\n  (forall s, In s (fst ps) <-> nlreachable n s) /\\\n  (forall s, (nsreachable n s -> In s (snd ps)) /\\\n             (In s (snd ps) -> nlreachable n s)) ->\n  (forall s, In s (fst (fold_left nexts (snd ps) (fst ps,nil)))\n                <-> nlreachable (S n) s) /\\\n  (forall s, (nsreachable (S n) s \n                -> In s (snd (fold_left nexts (snd ps) (fst ps,nil)))) /\\\n             (In s (snd (fold_left nexts (snd ps) (fst ps,nil)))\n                 -> nlreachable (S n) s)).\nProof.\ndestruct ps as (ss1, ss2).\nunfold nexts.\nrewrite fold_left_comb with \n  (f := fun (y: state) (y1: state -> state) => y1 y)\n  (g := filters).\nmatch goal with |- context[fold_right ?X ?Y ?Z] =>\n  change (fold_right X Y Z) with (candidate_list Z)\nend; fold filters.\nsimpl fst; simpl snd.\nintros (H1, H2); generalize (filters_correct (ss1, nil) (candidate_list ss2));\n case (fold_left filters  (candidate_list ss2) (ss1, nil)).\nintros ss4 ss5; simpl; intros (H3, H4).\nassert (tmp: forall (A B: Prop), A -> (A -> B) -> A /\\ B); auto.\napply tmp; clear tmp.\n- intros s; apply iff_trans with (1:= H3 s).\n  split.\n  + intros [H5 | H5].\n    * case (H1 s); intros HH _.\n      case (HH H5); intros m (Hm1, Hm2).\n      exists m; auto with arith.\n    * assert (H6 := candidate_list_correct ss2 n).\n      case (fun x => H6 x s); auto.\n  + assert (H6 := candidate_list_correct ss2 n).\n    intros H7.\n    case (nlreachable_bound _ _ H7); intros m (Hm, Hm1).\n    case (le_lt_or_eq _ _ Hm); intros Hm2.\n    -- left.\n       assert (nlreachable n s).\n         apply nlreach_weak with m; auto with arith.\n         exists m; split; auto; case Hm1; auto.\n       case (H1 s); auto.\n    -- subst m; case (fun x => H6 x s); auto.\n- intros H5 s; split; intros H6.\n  + assert (F0 : In s ss4).\n      case (H5 s); auto.\n      intros _ H7; apply H7; clear H7.\n      exists (S n); split; auto; case H6; auto.\n    assert (F1: ~ In s ss1).\n      intros H7; case (H1 s); intros H8 _; clear H1.\n      generalize (H8 H7); clear H8 H7; intros H7.\n      case H7; intros m (Hm1, Hm2); clear H7.\n      case H6; intros _ H7.\n      case (H7 m); auto with arith.\n    case (H4 s); intros _ HH; apply HH; clear HH H4; auto.\n    right; split; auto.\n    case (H3 s); intros H7 _; auto.\n    case H7; auto.\n    intros H8; case F1; auto.\n   + case (H5 s); intros HH _; apply HH; clear H5 HH.\n     case (H3 s); intros _ HH; apply HH; clear H3 HH.\n     right; case (H4 s); clear H4.\n     intros HH _; case (HH H6); clear HH H6;\n       intros HH; case HH; auto.\nQed.\n\nLemma iters_aux_equiv n ps1 ps2 :\n  pequiv ps1 ps2 ->\n  pequiv (iters_aux n ps1) (iters_aux n ps2).\nProof.\nrevert ps1 ps2; elim n; simpl; auto; clear n.\nintros n Hrec (sl1, sr1) (sl2, sr2) H1.\napply Hrec.\napply (fold_nexts_equiv (sl1, sr1) (sl2, sr2)); auto.\nintros s; split; intros H; case H.\nQed.\n\nLemma iters_aux_valid n ps :\n   valid_pair ps -> valid_pair (iters_aux n ps).\nProof.\nrevert ps; elim n; simpl; auto; clear n.\nintros n Hrec (sl, sr) Hg.\napply Hrec; apply (fold_nexts_valid (sl, sr)); auto.\nintros s1 HH; case HH.\nQed.\n\nLemma iters_aux_incl n ps :\n  incl (snd ps) (fst ps) ->\n  incl (snd (iters_aux n ps)) (fst (iters_aux n ps)).\nProof.\nrevert ps; elim n; simpl; auto; clear n.\nintros n Hrec (ss1, ss2) Hi; apply Hrec.\napply (fold_nexts_incl (ss1, ss2)); auto with datatypes.\nintros z HH; inversion HH.\nQed.\n\nLemma iters_aux_nreach n m ps :\n  (forall s, In s (fst ps) <-> nlreachable m s) /\\\n  (forall s, (nsreachable m s -> In s (snd ps)) /\\\n             (In s (snd ps) -> nlreachable m s)) ->\n  (forall s, In s (fst (iters_aux n ps)) <-> nlreachable (n + m) s) /\\\n  (forall s, (nsreachable (n + m) s -> In s (snd (iters_aux n ps))) /\\\n             (In s (snd (iters_aux n ps)) -> nlreachable (n + m) s)).\nProof.\nrevert m ps; elim n; simpl; auto; clear n.\nintros n Hrec m (ss1, ss2); simpl fst; simpl snd.\nreplace (S (n + m)) with (n + (S m)); auto with arith.\nintros H1; apply Hrec.\napply (fold_nexts_nreach m (ss1, ss2)); auto.\nQed.\n\nLemma iters_valid n : valid_pair (iters n).\nProof.\nunfold iters; apply iters_aux_valid.\nsplit; intros s [H1 | H1]; try (case H1; fail); subst s;\n  apply valid_state_init.\nQed.\n\nLemma iters_incl n : incl (snd (iters n)) (fst (iters n)).\nProof.\nunfold iters; apply iters_aux_incl; simpl;\n auto with datatypes.\nQed.\n\nLemma iters_correct n :\n  (forall s, In s (fst (iters n)) <-> nlreachable n s) /\\\n  (forall s, (nsreachable n s -> In s (snd (iters n))) /\\\n             (In s (snd (iters n)) -> nlreachable n s)).\nProof.\nunfold iters.\npattern n at 2 3 6.\nreplace n with (n + 0); auto with arith.\napply iters_aux_nreach; simpl.\nassert (F1: forall s, nlreachable 0 s -> init_state = s).\n- intros s (m, Hm); generalize Hm; case m; clear m Hm.\n  + intros (_, HH); inversion HH; auto.\n  + intros n1 (Hn1, _); contradict Hn1; auto with arith.\n- split; intros s; split; auto.\n  + intros [H1 | H1].\n    * now subst s; exists 0; split; auto; constructor.\n    * now case H1.\n  + intros H1; left; apply F1.\n    now exists 0; split; auto; case H1; auto.\n  + intros [H1 | H1].\n    * now subst s; exists 0; split; auto; constructor.\n    * now case H1.\nQed.\n\n(* Main theorem if the second list is empty, the first list\n   contains all the reachable *)\nLemma iters_final n :\n   match iters n with \n   | (_, nil) => forall s, reachable s -> nlreachable (pred n) s\n   |    _     => True\n   end.\nProof.\ngeneralize (iters_correct n).\ncase iters; intros s1 s2.\ncase s2; auto; simpl.\ncase n; simpl; clear n.\n- intros (H1, H2).\n  case (H2 init_state); intros HH; case HH.\n  split.\n  + apply nreach0.\n  + intros m Hm; contradict Hm; auto with arith.\n- intros n (H1, H2) s Hs.\n  elim Hs.\n  + exists 0; split; auto with arith.\n    now constructor.\n  + intros s3 HH1 HH2.\n    case (nlreachable_bound (S n) (rright s3)).\n    * case HH2; intros m (Hm, Hm1).\n      exists (S m); split; auto with arith.\n      apply nreachS with s3; auto; unfold move; auto.\n    * intros m (Hm, Hm1).\n      case (le_lt_or_eq _ _ Hm); intros Hm2.\n      -- exists m; split; auto with arith.\n         case Hm1; auto.\n      -- subst m; case (H2 (rright s3)); intros HH _; case (HH Hm1).\n   + intros s3 HH1 HH2.\n     case (nlreachable_bound (S n) (rback s3)).\n     * case HH2; intros m (Hm, Hm1).\n       exists (S m); split; auto with arith.\n       apply nreachS with s3; auto; unfold move; auto.\n     * intros m (Hm, Hm1).\n       case (le_lt_or_eq _ _ Hm); intros Hm2.\n       -- exists m; split; auto with arith.\n          case Hm1; auto.\n       -- subst m; case (H2 (rback s3)); intros HH _; case (HH Hm1).\n   + intros s3 HH1 HH2.\n     case (nlreachable_bound (S n) (rdown s3)).\n     * case HH2; intros m (Hm, Hm1).\n       exists (S m); split; auto with arith.\n       apply nreachS with s3; auto; unfold move; do 3 right; auto.\n     * intros m (Hm, Hm1).\n       case (le_lt_or_eq _ _ Hm); intros Hm2.\n       exists m; split; auto with arith.\n       case Hm1; auto.\n       subst m; case (H2 (rdown s3)); intros HH _; case (HH Hm1).\nQed.  \n\n(*****************************************************************************)\n(*                                                                           *)\n(*            Building the naive solver                                      *)\n(*                                                                           *)\n(*****************************************************************************)\n\n(* odd for positive *)\nDefinition is_odd p :=\n   match p with xO _ => False | _ => True  end.\n\n(* n % 3 for positive *)\nDefinition porder n := \n  match (Z_of_nat n mod 3 + 1)%Z with \n    Zpos x => x\n  | _  => 1%positive\n  end.\n\n(* Same as filters but we split the first list in two to be able\n   to do some retrieval *)\n\nDefinition filter2s (pmod : positive) (ps : (states * states) * states) (s : state) :=\n          let (pstates, nstates) := ps in\n          let (states1, states2) := pstates in\n          if (in_states s states1 || in_states s states2)%bool\n          then ps\n          else match pmod with\n                 xH => ((s::states1,states2), s::nstates)\n               | xO _ => ((states1,s::states2), s::nstates)\n               | xI _ => ((s::states1,s::states2), s::nstates)\n               end. \n\nDefinition next2s p ps s :=\nEval lazy beta delta [filter2s] in\n fold_left (fun ps f => let s1 := f s in filter2s p ps s1)\n   movel ps.\n\nFixpoint iter2s_aux n p (ps : (states * states) * states) := \n  match n with \n   O => ps \n | S n1 => let (m,p1) := ps in \n           iter2s_aux n1 (pos_up p) (fold_left (next2s p) p1 (m,nil))\n  end.\n\nDefinition iter2s n := \n  iter2s_aux n 2%positive (init_state::nil, nil, init_state::nil).\n\n(* An explicit inductive type for moves *)\nInductive moves :=\n  Right | Right2 | Rightm1 | Back | Back2 | Backm1 | Down | Down2 | Downm1.\n\n(* Turn a move in an actual rotation *)\nDefinition m2f m := \n match m with\n  Right => rright \n| Right2 => fun s1 : state => rright (rright s1)\n| Rightm1 => fun s1 : state => rright (rright (rright s1))\n| Back => rback\n| Back2 =>  fun s1 : state => rback (rback s1)\n| Backm1  => fun s1 : state => rback (rback (rback s1))\n| Down => rdown\n| Down2 => fun s1 : state => rdown (rdown s1)           \n| Downm1 => fun s1 : state => rdown (rdown (rdown s1))\nend.\n\n(* The inverse function *)\n\nDefinition minv m := \n match m with\n  Right => Rightm1\n| Right2 => Right2\n| Rightm1 => Right\n| Back => Backm1\n| Back2 => Back2\n| Backm1  => Back\n| Down => Downm1\n| Down2 => Down2\n| Downm1 => Down\nend.\n\n(* The list of all moves *)\nDefinition Movel := \n  Right :: Right2 :: Rightm1 :: Back :: Back2 :: Backm1 :: \n  Down :: Down2 ::Downm1 :: nil.\n\n(* Compute the number (the reachability index mod 3) of a state *)\nDefinition get_number s s1 s2 :=\n  if in_states s s1 then\n    if in_states s s2 then 3%positive else 1%positive\n  else\n    if in_states s s2 then 2%positive else 4%positive.\n\n(* Find the next state by searching the first neighbour whose\n     number decrease modulo *)\nFixpoint get_next_aux n s s1 s2 l :=\n  match l with\n   nil => None\n  | a::l1 => if positive_eq n (get_number (m2f a s) s1 s2) then Some a\n             else get_next_aux n s s1 s2 l1\n  end.\n\nDefinition get_next s s1 s2 := get_next_aux (pos_down (get_number s s1 s2)) s s1 s2 Movel.\n\n(* Now, we just iterate *)\n\nFixpoint solve n s s1 s2 :=\n  match n with\n   0 => nil\n  | S n1 => match get_next s s1 s2 with\n             None => nil\n            | Some a => a:: solve n1 (m2f a s) s1 s2\n            end\n  end.\n\n(*******************************************************************)\n(*              Proving iter2s                                     *)\n(*******************************************************************)\n\nDefinition porder_inv n :\n  (porder n = 1 \\/ porder n = 2 \\/ porder n = 3)%positive.\nProof.\nunfold porder.\nassert (Ht: (0 < Z_of_nat n mod 3 + 1 < 4)%Z).\n  generalize (Z_mod_lt (Z_of_nat n) 3%Z (refl_equal Gt)); auto with zarith.\ngeneralize Ht; case Zplus; auto with zarith; \n try (intros; discriminate).\ndo 2 (intros p1; case p1; clear p1; auto);\n  intros p1; case p1; try (intros p2 (_, H2); discriminate H2);\n  intros (_, H2); discriminate H2.\nQed.\n\nDefinition porderS n : porder (S n) = pos_up (porder n).\nProof.\nunfold porder, pos_up.\nrewrite inj_S; unfold Z.succ; rewrite Zplus_mod.\nrewrite <- (Zmod_mod (Z_of_nat n)  3).\nrewrite <- Zplus_mod.\ngeneralize (Z_mod_lt (Z_of_nat n) 3%Z (refl_equal Gt)).\ncase Zmod; simpl; auto.\n2: intros p (Hp, _); contradict Hp; auto.\ndo 3 (intros p; case p; simpl; auto; clear p);\n try (intros p (_, Hp); discriminate Hp).\nQed.\n\nDefinition porder_inv1 n : porder n <> 1%positive \\/ is_odd (porder n).\nProof.\ngeneralize (porder_inv n); intros [H1 | [H1 | H1]]; rewrite H1; \n  simpl; auto; left; intros HH; discriminate.\nQed.\n\nDefinition valid_triple (ps : (states * states) * states) :=\n  ((forall s, In s (fst (fst ps)) -> valid_state s) /\\\n   (forall s, In s (snd (fst ps)) -> valid_state s)) /\\\n  (forall s, In s (snd ps) -> valid_state s).\n\nLemma filter2s_valid p ps s1 :\n  valid_triple ps -> valid_state s1 -> valid_triple (filter2s p ps s1).\nProof.\ndestruct ps as ((ss1, ss2), ss3).\nintros ((Hg1, Hg2), Hg3) Hg; repeat split;\n intros s; simpl in Hg1, Hg2, Hg3;\n   unfold filter2s; case in_states; simpl; auto;\n   case in_states; simpl; auto;\n   (case p; [intros p1 | intros p1 | idtac]); simpl; auto with datatypes;\n   intros [H1 | H1]; auto; subst s1; auto.\nQed.\n\nLemma filter2s_incl p ps s :\n  (forall s1, In s1 (snd ps) -> In s1 (fst (fst ps)) \\/ In s1 (snd (fst ps))) ->\n  (forall s1, In s1 (snd (filter2s p ps s)) ->\n    In s1  (fst (fst (filter2s p ps s))) \\/ In s1  (snd (fst (filter2s p ps s)))).\nProof.\ndestruct ps as ((ss1, ss2), ss3).\nintro H; unfold filter2s; intros s1.\ndo 2 (case in_states; simpl; auto with datatypes); \n  case p; [intros p1 | intros p1 | idtac];\n  simpl in H |- *; intros [H1 | H1]; subst; auto;\n  case (H _ H1); auto.\nQed.\n\nLemma filter2s_correct p ps l :\n let ps1 := fold_left (filter2s p) l ps in\n (forall i, In i (fst (fst ps1)) <-> \n    In i (fst (fst ps)) \\/\n   (~In i (snd (fst ps)) /\\ In i l /\\ is_odd p)) /\\\n (forall i, In i (snd (fst ps1)) <-> \n    In i (snd (fst ps)) \\/ \n   (~In i (fst (fst ps)) /\\ In i l /\\ p <> 1%positive)) /\\\n (forall i, In i (snd ps1) <-> In i (snd ps) \\/ \n           (~In i (fst (fst ps)) /\\ ~In i (snd (fst ps)) /\\ In i l)).\nProof.\nrevert ps; elim l; clear l; simpl; auto.\n- intros ps; split; [idtac | split];  intros i; split; auto.\n  + intros [HH | (_, (HH, _))]; auto; case HH.\n  + intros [HH | (_, (HH, _))]; auto; case HH.\n  + intros [HH | (_, (_, HH))]; auto; case HH.\n- intros a l Hrec ps.\n  case (Hrec (filter2s p ps a)); intros H1 (H2, H3); split; [idtac | idtac].\n  + intros i; apply iff_trans with (1 := H1 i).\n    unfold filter2s; case ps; simpl; intros ps1; case ps1; \n      intros s1 s2 s3; clear ps ps1 H1 H2 H3.\n    generalize (in_states_correct a s1); case in_states; simpl; auto.\n    * intros H5; split.\n      -- intros [HH | (HH, (HH1, HH2))]; auto.\n      -- intros [HH | (HH, ([HH1 | HH1], HH2))]; subst; auto.\n    * intros Ha.\n      generalize (in_states_correct a s2); case in_states; simpl; auto.\n      -- intros Hb; split.\n         ++ intros [HH | (HH, (HH1, HH2))]; auto.\n         ++ intros [HH | (HH, ([HH1 | HH1], HH2))]; subst; auto.\n            case HH; auto.\n      -- intros Hb; case p; simpl.\n         ++ intros _; split.\n            ** intros [[HH | HH]| (HH, (HH1, _))]; subst; auto.\n               right; auto.\n            ** intros [HH | (HH, ([HH1 | HH1], _))]; subst; auto.\n               generalize (state_eq_correct a i); case state_eq; auto.\n               intros HH2; right; auto; split; auto.\n               intros [HH3 | HH3]; subst; auto.\n         ++ intros _; split.\n            ** intros [HH | (_, (_, HH))]; auto; case HH.\n            ** intros [HH | (_, (_, HH))]; auto; case HH.\n         ++ split.\n            ** intros [[HH | HH] | (HH, (HH1, _))]; subst; auto.\n            ** intros [HH | (HH, ([HH1 | HH1], _))]; auto.\n  + split.\n    * intros i; apply iff_trans with (1:= H2 i).\n      unfold filter2s; case ps; simpl; intros ps1; case ps1; \n        intros s1 s2 s3; clear ps ps1 H1 H2 H3.\n      generalize (in_states_correct a s1); case in_states; simpl; auto.\n      -- intros H5; split.\n         ++ intros [HH | (HH, (HH1, HH2))]; auto.\n         ++ intros [HH | (HH, ([HH1 | HH1], HH2))]; subst; auto.\n            case HH; auto.\n      -- intros Ha.\n         generalize (in_states_correct a s2); case in_states; simpl; auto.\n         ++ intros Hb; split.\n            ** intros [HH | (HH, (HH1, HH2))]; auto.\n            ** intros [HH | (HH, ([HH1 | HH1], HH2))]; subst; auto.\n         ++ intros Hb; case p; simpl.\n            ** intros p1; split.\n               --- intros [[HH | HH]| (HH, (HH1, _))]; subst; auto.\n                   +++ right; repeat (split; auto); intros HH; discriminate.\n                   +++ right; split; auto; split; auto; intros HH2; discriminate.\n               --- intros [HH | (HH, ([HH1 | HH1], _))]; subst; auto.\n                   generalize (state_eq_correct a i); case state_eq; auto.\n                   intros HH2; right; auto; split; auto.\n                   +++ intros [HH3 | HH3]; subst; auto.\n                   +++ split; auto; intros HH3; discriminate.\n            ** intros p1; split.\n               --- intros [[HH | HH] | (HH, (HH1, _))]; subst; auto.\n                   +++ right; repeat (split; auto); intros HH; discriminate.\n                   +++ right; split; auto; split; auto; intros HH2;\n                       discriminate.\n               --- intros [HH | (HH, ([HH1 | HH1], _))]; auto.\n                   right; repeat (split; auto); intros HH2; discriminate.\n            ** split.\n               --- intros [HH | (_, (_, HH))]; auto; case HH; auto.\n               --- intros [HH | (_, (_, HH))]; auto; case HH; auto.\n    * intros i; apply iff_trans with (1:= H3 i).\n      unfold filter2s; case ps; simpl; intros ps1; case ps1; \n        intros s1 s2 s3; clear ps ps1 H1 H2 H3.\n      generalize (in_states_correct a s1); case in_states; simpl; auto.\n      -- intros H5; split.\n         ++ intros [HH | (HH, (HH1, HH2))]; auto.\n         ++ intros [HH | (HH, (HH1, [HH2 | HH2]))]; subst; auto; case HH; auto.\n      -- intros Ha.\n         generalize (in_states_correct a s2); case in_states; simpl; auto.\n         ++ intros Hb; split.\n            ** intros [HH | (HH, (HH1, HH2))]; auto.\n            ** intros [HH | (HH, (HH1, [HH2 | HH2]))]; subst; auto; case HH1; auto.\n         ++ intros Hb; case p; simpl.\n            ** intros _; split.\n               --- intros [[HH | HH]| (HH, (HH1, HH2))]; subst; auto.\n                   right; repeat split; auto.\n               --- intros [HH | (HH, (HH1, [HH2 | HH2]))]; auto.\n                   generalize (state_eq_correct a i); case state_eq; auto.\n                   intros HH3; right; repeat split; auto.\n                   +++ intros [HH4 | HH4]; subst; auto.\n                   +++ intros [HH4 | HH4]; subst; auto.\n            ** intros _; split.\n               --- intros [[HH | HH]| (HH, (HH1, HH2))]; subst; auto.\n                   right; repeat split; auto.\n               --- intros [HH | (HH, (HH1, [HH2 | HH2]))]; auto.\n                   generalize (state_eq_correct a i); case state_eq; auto.\n                   intros HH3; right; repeat split; auto.\n                   intros [HH4 | HH4]; subst; auto.\n            ** split.\n               --- intros [[HH | HH]| (HH, (HH1, HH2))]; subst; auto.\n                   right; repeat split; auto.\n               --- intros [HH | (HH, (HH1, [HH2 | HH2]))]; auto.\n                   generalize (state_eq_correct a i); case state_eq; auto.\n                   intros HH3; right; repeat split; auto.\n                   intros [HH4 | HH4]; subst; auto.\nQed.\n\nDefinition tequiv {A : Type} (pl1 pl2 : list A * list A * list A) := \n  lequiv (fst (fst pl1)) (fst (fst pl2)) /\\ \n  lequiv (snd (fst pl1)) (snd (fst pl2)) /\\\n  lequiv (snd pl1) (snd pl2).\n\nLemma filter2s_equiv p ps1 ps2 l1 l2 :\n  tequiv ps1 ps2 -> lequiv l1 l2 ->\n  tequiv (fold_left (filter2s p) l1 ps1) (fold_left (filter2s p) l2 ps2).\nProof.\nintros (H1, (H2, H3)) H4.\ncase (filter2s_correct p ps1 l1); intros Hr1 (Hs1, Ht1).\ncase (filter2s_correct p ps2 l2); intros Hr2 (Hs2, Ht2).\nunfold lequiv in H1, H2, H3, H4;\n  split; [idtac | split]; intros a;\n  (rewrite Hr1; rewrite Hr2) ||\n  (rewrite Hs1; rewrite Hs2) ||\n  (rewrite Ht1; rewrite Ht2).\n- split; intros [HH | HH].\n  + rewrite <- H1; auto.\n  + right; rewrite <- H2, <- H4; auto.\n  + rewrite H1; auto.\n  + right; rewrite H2, H4; auto.\n- split; intros [HH | HH].\n  + rewrite <- H2; auto.\n  + right; rewrite <- H1, <- H4; auto.\n  + rewrite H2; auto.\n  + right; rewrite H1, H4; auto.\n- split; intros [HH | HH].\n  + rewrite <- H3; auto.\n  + right; rewrite <- H1, <- H2, <- H4; auto.\n  + rewrite H3; auto.\n  + right; rewrite H1, H2, H4; auto.\nQed.\n\nDefinition next2s_correct p ps s :\n (forall i, In i (fst (fst (next2s p ps s))) <-> \n    In i (fst (fst ps)) \\/ exists f, In f movel /\\ i = f s /\\\n    ~In i (snd (fst ps)) /\\ is_odd p) /\\\n (forall i, In i (snd (fst (next2s p ps s))) <-> \n    In i (snd (fst ps)) \\/ exists f, In f movel /\\ i = f s /\\\n    ~In i (fst (fst ps)) /\\ p <> 1%positive) /\\\n (forall i, In i (snd (next2s p ps s)) <-> \n     In i (snd ps) \\/  exists f, In f movel /\\ i = f s /\\\n    ~In i (fst (fst ps)) /\\ ~In i (snd (fst ps))).\nProof.\nunfold next2s.\nmatch goal with |- context[fold_left ?X _ _] =>\n  change X with (fun ps f => let s1 := f s in filter2s p ps s1) \nend.\ngeneralize ps s; elim movel; clear ps s.\n- simpl; intros ps s; split; [idtac | split]; intros s1; split; auto; \n    intros HH; case HH; auto;\n    case HH; auto; intros (f, (HH1, _)); case HH1.\n- intros f lf Hrec ps s; repeat rewrite fold_left_cons.\n  split; [idtac | split]; intros s1; case (Hrec (filter2s p ps (f s)) s);\n    intros Hr1 (Hr2, Hr3); clear Hrec.\n  + apply iff_trans with (1 := Hr1 s1); clear Hr1 Hr2 Hr3.\n    unfold filter2s; case ps.\n    intros (ss1, ss2) ss3.\n    generalize (in_states_correct (f s) ss1); case in_states.\n    * simpl fst; auto.\n      intros H1; split; intros [H2 | H2]; auto.\n      -- case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))).\n         right; exists f1; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))).\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1.\n         ++ left; rewrite Hf2, <- Hf1; auto.\n         ++ right; exists f1; auto with datatypes.\n    * generalize (in_states_correct (f s) ss2); case in_states.\n      -- simpl fst; auto.\n         intros H1; split; intros [H2 | H2]; auto.\n         ++ case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))).\n            right; exists f1; auto with datatypes.\n         ++ case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); clear H2.\n            simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst.\n            ** case Hf3; auto.\n            ** right; exists f1; auto with datatypes.\n      -- case p.\n         ++ simpl fst; simpl snd; simpl is_odd.\n            intros _ H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** simpl in H3; case H3; clear H3; intros H3; subst; auto.\n               right; exists f; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               right; exists f1; repeat split; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n               generalize (state_eq_correct (f s) (f1 s)); case state_eq; intros He.\n               --- rewrite He; auto with datatypes.\n               --- right; exists f1; repeat split; auto with datatypes.\n                   simpl; intros [H3 | H3]; auto.\n         ++ simpl fst; simpl snd; simpl is_odd.\n            intros _ H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** case H3; intros f1 (_, (_, (_, HH))); case HH.\n            ** case H3; intros f1 (_, (_, (_, HH))); case HH.\n         ++ simpl fst; simpl snd; auto.\n            intros H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** simpl in H3; case H3; clear H3; intros H3; subst; auto.\n               right; exists f; simpl; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               right; exists f1; repeat split; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n               generalize (state_eq_correct (f s) (f1 s)); case state_eq; intros He.\n               --- rewrite He; auto with datatypes.\n               --- right; exists f1; repeat split; auto with datatypes.\n  + apply iff_trans with (1 := Hr2 s1); clear Hr1 Hr2 Hr3.\n    unfold filter2s; case ps.\n    intros (ss1, ss2) ss3.\n    generalize (in_states_correct (f s) ss1); case in_states.\n    * simpl fst; simpl snd; auto.\n      intros H1; split; intros [H2 | H2]; auto.\n      -- case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))).\n         right; exists f1; auto with datatypes.\n      -- case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H2.\n         simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst.\n         ++ case Hf3; auto.\n         ++ right; exists f1; auto with datatypes.\n    * simpl fst; simpl snd; auto.\n      generalize (in_states_correct (f s) ss2); case in_states;\n        simpl fst; simpl snd; auto.\n      -- intros H1 H2; split; intros [H3 | H3]; auto with datatypes.\n         ++ case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n            right; exists f1; repeat split; auto with datatypes.\n         ++ case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n            simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n            right; exists f1; repeat split; auto with datatypes.\n      -- case p; simpl fst; simpl snd; simpl is_odd.\n         ++ intros pp H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** simpl in H3; case H3; clear H3; intros H3; subst; auto.\n               right; exists f; repeat split; auto with datatypes; intros HH; discriminate.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               generalize (state_eq_correct (f s) (f1 s)); case state_eq; intros He.\n               --- case Hf3; simpl; auto with datatypes.\n               --- right; exists f1; repeat split; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n               generalize (state_eq_correct (f1 s) (f s)); case state_eq; intros He;\n                 auto with datatypes.\n               --- left; simpl; auto with datatypes.\n               --- right; exists f1; repeat split; auto with datatypes.\n                   simpl; intros [H3 | H3]; auto.\n         ++ intros pp H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** simpl in H3; case H3; clear H3; intros H3; subst; auto with datatypes.\n               right; exists f; repeat split; auto with datatypes; intros HH; \n               discriminate HH.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               right; exists f1; repeat split; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               generalize (state_eq_correct (f s) (f1 s)); case state_eq; intros He.\n               --- simpl; rewrite He; auto.\n               --- simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n                   right; exists f1; repeat split; auto with datatypes.\n         ++ intros H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** case H3; intros f1 (_, (_, (_, HH))); case HH; auto.\n            ** case H3; intros f1 (_, (_, (_, HH))); case HH; auto.\n  + apply iff_trans with (1 := Hr3 s1); clear Hr1 Hr2 Hr3.\n    * unfold filter2s; case ps.\n      intros (ss1, ss2) ss3.\n      generalize (in_states_correct (f s) ss1); case in_states;\n        simpl fst; simpl snd; auto.\n      -- intros H1; split; intros [H2 | H2]; auto.\n         ++ case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; auto; clear H2.\n            right; exists f1; auto with datatypes.\n         ++ case H2; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H2.\n            simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst.\n            ** case Hf3; auto.\n            ** right; exists f1; auto with datatypes.\n      -- generalize (in_states_correct (f s) ss2); case in_states;\n           simpl fst; simpl snd; auto.\n         ++ intros H1 H2; split; intros [H3 | H3]; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               right; exists f1; repeat split; auto with datatypes.\n            ** case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n               simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n               --- case Hf4; auto.\n               --- right; exists f1; repeat split; auto with datatypes.\n         ++ case p; simpl fst; simpl snd; auto.\n            ** intros _ H1 H2; split; intros [H3 | H3]; auto with datatypes.\n               --- simpl in H3; case H3; clear H3; intros H3; subst; auto.\n                   right; exists f; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   generalize (state_eq_correct (f s) (f1 s)); case state_eq; intros He.\n                   +++ case Hf3; simpl; auto with datatypes.\n                   +++ right; exists f1; repeat split; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   simpl in Hf1; case Hf1; clear Hf1; intros Hf1; subst; auto with datatypes.\n                   generalize (state_eq_correct (f1 s) (f s)); case state_eq; intros He;\n                     auto with datatypes.\n                   +++ left; simpl; auto with datatypes.\n                   +++ right; exists f1; repeat split; auto with datatypes.\n                       *** simpl; intros [H3 | H3]; auto.\n                       *** simpl; intros [H3 | H3]; auto.\n            ** intros _ H1 H2; split; intros [H3 | H3]; auto with datatypes.\n               --- simpl in H3; case H3; clear H3; intros H3; subst; auto.\n                   right; exists f; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   right; exists f1; repeat split; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   generalize (state_eq_correct (f s) (f1 s)); case state_eq; \n                   intros He.\n                   +++ simpl; rewrite He; auto.\n                   +++ simpl in Hf1; case Hf1; clear Hf1; \n                         intros Hf1; subst; auto with datatypes.\n                       right; exists f1; repeat split; auto with datatypes.\n                       simpl; intros [H3 | H3]; auto.\n            ** intros H1 H2; split; intros [H3 | H3]; auto with datatypes.\n               --- simpl in H3; case H3; clear H3; intros H3; subst; auto.\n                   right; exists f; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   right; exists f1; repeat split; auto with datatypes.\n               --- case H3; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); subst; clear H3.\n                   generalize (state_eq_correct (f s) (f1 s));\n                   case state_eq; intros He.\n                   +++ simpl; rewrite He; auto.\n                   +++ simpl in Hf1; case Hf1; clear Hf1; intros Hf1;\n                         subst; auto with datatypes.\n                       right; exists f1; repeat split; auto with datatypes.\n                       simpl; intros [H3 | H3]; auto.\nQed.\n\nLemma next2s_equiv p ps1 ps2 s :\n  tequiv ps1 ps2 -> tequiv (next2s p ps1 s) (next2s p ps2 s).\nProof.\nintros (H1, (H2, H3)).\ncase (next2s_correct p ps1 s); intros Hr1 (Hs1, Ht1).\ncase (next2s_correct p ps2 s); intros Hr2 (Hs2, Ht2).\nsplit; [idtac | split]; intros a.\n- apply iff_trans with (1:= (Hr1 a)); clear Hr1 Hs1 Ht1.\n  apply iff_sym; apply iff_trans with (1:= (Hr2 a)); clear Hr2 Hs2 Ht2.\n  split; intros [H4 | H4].\n  + left; case (H1 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H2 (f1 s)); auto.\n  + left; case (H1 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H2 (f1 s)); auto.\n- apply iff_trans with (1:= (Hs1 a)); clear Hr1 Hs1 Ht1.\n  apply iff_sym; apply iff_trans with (1:= (Hs2 a)); clear Hr2 Hs2 Ht2.\n  split; intros [H4 | H4].\n  + left; case (H2 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H1 (f1 s)); auto.\n  + left; case (H2 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H1 (f1 s)); auto.\n- apply iff_trans with (1:= (Ht1 a)); clear Hr1 Hs1 Ht1.\n  apply iff_sym; apply iff_trans with (1:= (Ht2 a)); clear Hr2 Hs2 Ht2.\n  split; intros [H4 | H4].\n  + left; case (H3 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H1 (f1 s));\n    case (H2 (f1 s)); auto.\n  + left; case (H3 a); auto.\n  + case H4; intros f1 (Hf1, (Hf2, (Hf3, Hf4))); right; exists f1;\n    repeat split; auto; subst; case (H1 (f1 s));\n    case (H2 (f1 s)); auto.\nQed.\n\nLemma next2s_valid p ps s :\n  valid_triple ps -> valid_state s -> valid_triple (next2s p ps s).\nProof.\nunfold next2s.\nmatch goal with |- context[fold_left ?X _ _] =>\n  change X with (fun ps f => let s1 := f s in filter2s p ps s1) \nend.\ngeneralize ps s (movel_valid); elim movel; auto; clear ps s.\nintros f lf Hrec ps s1 Hf Hg1 Hg; rewrite fold_left_cons.\napply Hrec; auto with datatypes.\ngeneralize (filter2s_valid p ps (f s1) Hg1); auto with datatypes.\nQed.\n\nLemma next2s_incl p ps s :\n  (forall s1, In s1 (snd ps) -> In s1 (fst (fst ps)) \\/ In s1 (snd (fst ps))) ->\n  (forall s1, In s1 (snd (next2s p ps s)) ->\n    In s1  (fst (fst (next2s p ps s))) \\/ In s1  (snd (fst (next2s p ps s)))).\nProof.\nunfold next2s.\nmatch goal with |- context[fold_left ?X _ _] =>\n  change X with (fun ps f => let s1 := f s in filter2s p ps s1) \nend.\ngeneralize ps s; elim movel; auto; clear ps s.\nintros f lf Hrec ps s Hs; repeat rewrite fold_left_cons.\ngeneralize (filter2s_incl p ps (f s)).\nlazy zeta.\ncase filter2s; intros (ss3, ss4) ss5 Hss3.\napply Hrec; auto with datatypes; clear Hrec.\nQed.\n\nLemma fold_next2s_correct p ps ss :\n (forall i, In i (fst (fst (fold_left (next2s p) (snd ps) (fst ps, ss)))) <-> \n    In i (fst (fst ps)) \\/ exists f, exists s, In f movel /\\ In s (snd ps) /\\ i = f s /\\\n    ~In i (snd (fst ps)) /\\ is_odd p) /\\\n (forall i, In i (snd (fst (fold_left (next2s p) (snd ps) (fst ps, ss)))) <-> \n    In i (snd (fst ps)) \\/ exists f, exists s, In f movel /\\ In s (snd ps) /\\ i = f s /\\\n    ~In i (fst (fst ps)) /\\ p <> 1%positive) /\\\n (forall i, In i (snd (fold_left (next2s p) (snd ps) (fst ps, ss))) <-> \n     In i ss \\/  exists f, exists s, In f movel /\\ In s (snd ps) /\\ i = f s /\\\n    ~In i (fst (fst ps)) /\\ ~In i (snd (fst ps))).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\ngeneralize ss1 ss; elim ss2; clear ss ss1 ss2; auto.\n- unfold fold_left, fst, snd.\n  intros ss1 ss; split; [idtac | split]; intros;\n     split; auto.\n  + intros [H1 | H1]; auto.\n    case H1; intros f (i1, (_, (HH, _))); case HH.\n  + intros [H1 | H1]; auto.\n    case H1; intros f (i1, (_, (HH, _))); case HH.\n  + intros [H1 | H1]; auto.\n    case H1; intros f (i1, (_, (HH, _))); case HH.\n- intros s1 ss2 Hrec ss1 ss.\n  rewrite fold_left_cons.\n  generalize (next2s_correct p (ss1, ss) s1); case next2s; \n    simpl fst; simpl snd; intros (ss3, ss4) ss5 (Hss3, (Hss4, Hss5)).\n  simpl fst in Hss3, Hss4, Hss5; simpl snd in Hss3, Hss4, Hss5.\n  split; [idtac | split].\n  + intros s; case (Hrec (ss3, ss4) ss5); intros Hr1 (Hr2, Hr3); clear Hrec.\n    apply iff_trans with (1 := Hr1 s); simpl fst; simpl snd; clear Hr1 Hr2 Hr3.\n    split; intros [H1 | H1].\n    * rewrite Hss3 in H1; case H1; auto.\n      intros (f, (Hf1, (Hf2, Hf3))); subst s; right; exists f; exists s1; \n      auto with datatypes.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst s; \n        right; exists f; \n        exists i; repeat split; auto with datatypes.\n      intros H2; case Hf4.\n      rewrite Hss4; auto.\n    * left; unfold lequiv in Hss3; rewrite Hss3; auto.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst; \n        auto; clear H1.\n      simpl in Hf2; case Hf2; clear Hf2; intros Hf2; subst; auto.\n      -- left; rewrite Hss3; auto.\n         right; exists f; auto.\n      -- generalize (in_states_correct (f i) ss3); case in_states; auto; intros H3.\n         right; exists f; exists i; repeat split; auto.\n         rewrite Hss4.\n         intros [HH | HH]; auto.\n         case H3; rewrite Hss3; auto.\n         case HH; intros f1 (Gf1, (Gf2, (Gf3, Gf4))).\n         right; exists f1; split; auto.\n  + intros s; case (Hrec (ss3, ss4) ss5); intros Hr1 (Hr2, Hr3); clear Hrec.\n    apply iff_trans with (1 := Hr2 s); simpl fst; simpl snd; clear Hr1 Hr2 Hr3.\n    split; intros [H1 | H1].\n    * rewrite Hss4 in H1; case H1; auto.\n      intros (f, (Hf1, (Hf2, Hf3))); subst s; right; exists f; exists s1; \n        auto with datatypes.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst s; right;\n        exists f; exists i; repeat split; auto with datatypes.\n      intros H2; case Hf4.\n      rewrite Hss3; auto.\n    * left; rewrite Hss4; auto.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst; \n        auto; clear H1.\n      simpl in Hf2; case Hf2; clear Hf2; intros Hf2; subst; auto.\n      -- left; rewrite Hss4; auto.\n         right; exists f; auto.\n      -- generalize (in_states_correct (f i) ss4); case in_states; \n           auto; intros H3.\n         right; exists f; exists i; repeat split; auto.\n         rewrite Hss3.\n         intros [HH | HH]; auto.\n         case H3; rewrite Hss4; auto.\n         case HH; intros f1 (Gf1, (Gf2, (Gf3, Gf4))).\n         right; exists f1; split; auto.\n  + intros s; case (Hrec (ss3, ss4) ss5); intros Hr1 (Hr2, Hr3); clear Hrec.\n    apply iff_trans with (1 := Hr3 s); simpl fst; simpl snd; clear Hr1 Hr2 Hr3.\n    split; intros [H1 | H1].\n    * rewrite Hss5 in H1; case H1; auto.\n      intros (f, (Hf1, (Hf2, Hf3))); subst s; right; exists f; exists s1; \n        auto with datatypes.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst s; \n        right; exists f; \n        exists i; repeat split; auto with datatypes.\n      -- intros H2; case Hf4.\n         rewrite Hss3; auto.\n      -- intros H2; case Hf5.\n         rewrite Hss4; auto.\n    * left; rewrite Hss5; auto.\n    * case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))); subst; \n         auto; clear H1.\n      simpl in Hf2; case Hf2; clear Hf2; intros Hf2; subst; auto.\n      -- left; rewrite Hss5; auto.\n         right; exists f; auto.\n      -- generalize (in_states_correct (f i) ss5); case in_states; \n           auto; intros H3.\n         right; exists f; exists i; repeat split; auto.\n         ++ rewrite Hss3.\n            intros [HH | HH]; auto.\n            case H3; rewrite Hss5; auto; clear H3.\n            case HH; intros f1 (Gf1, (Gf2, (Gf3, Gf4))).\n            right; exists f1; split; auto.\n         ++ rewrite Hss4; intros [HH | HH].\n            ** case Hf5; auto.\n            ** case HH; intros f1 (Gf1, (Gf2, (Gf3, Gf4))).\n               case H3; rewrite Hss5.\n               right; exists f1; auto.\nQed.\n\nLemma fold_next2s_equiv p ps1 ps2 ss1 ss2 :\n  tequiv ps1 ps2 ->\n  lequiv ss1 ss2 ->\n  tequiv (fold_left (next2s p) (snd ps1) (fst ps1, ss1)) \n         (fold_left (next2s p) (snd ps2) (fst ps2, ss2)).\nProof.\nunfold tequiv, lequiv.\n intros (He1, (He2, He3)) He4.\ncase (fold_next2s_correct p ps1 ss1); intros Hr1 (Hs1, Ht1).\ncase (fold_next2s_correct p ps2 ss2); intros Hr2 (Hs2, Ht2).\nsplit; [idtac | split]; intros s.\napply iff_trans with (1 := Hr1 s); clear Hr1 Hs1 Ht1.\napply iff_sym; apply iff_trans with (1 := Hr2 s); clear Hr2 Hs2 Ht2.\nsplit; intros [H1 | H1]; auto.\nleft; rewrite He1; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite He2; try rewrite He1; auto.\nrewrite He3; auto.\nleft; rewrite <- He1; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite <- He2; try rewrite <- He1; auto.\nrewrite <- He3; auto.\napply iff_trans with (1 := Hs1 s); clear Hr1 Hs1 Ht1.\napply iff_sym; apply iff_trans with (1 := Hs2 s); clear Hr2 Hs2 Ht2.\nsplit; intros [H1 | H1]; auto.\nleft; rewrite He2; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite He2; try rewrite He1; auto.\nrewrite He3; auto.\nleft; rewrite <- He2; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite <- He2; try rewrite <- He1; auto.\nrewrite <- He3; auto.\napply iff_trans with (1 := Ht1 s); clear Hr1 Hs1 Ht1.\napply iff_sym; apply iff_trans with (1 := Ht2 s); clear Hr2 Hs2 Ht2.\nsplit; intros [H1 | H1]; auto.\nleft; rewrite He4; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite He2; try rewrite He1; auto.\nrewrite He3; auto.\nleft; rewrite <- He4; auto.\nright; case H1; intros f (i, (Hf1, (Hf2, (Hf3, (Hf4, Hf5))))).\nexists f; exists i; repeat split; try rewrite <- He2; try rewrite <- He1; auto.\nrewrite <- He3; auto.\nQed.\n\nLemma fold_next2s_valid p ps ss :\n  valid_triple ps ->\n  (forall s, In s ss -> valid_state s) ->\n  valid_triple (fold_left (next2s p) (snd ps) (fst ps, ss)).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\nrevert ss1 ss; elim ss2; clear ss2; auto.\n- simpl; intros ss1 ss (HH, _) HH1; split; auto.\n- intros s ss2 Hrec ss1 ss Hg1 Hg; rewrite fold_left_cons.\n  generalize (next2s_valid p (ss1, ss) s); case next2s.\n  intros ss3 ss4 Hg2.\n  case Hg1; simpl fst; simpl snd; intros Hg3 Hg4; case Hg2;\n  auto with datatypes.\n  + split; auto.\n  + simpl; intros Hg5 Hg6; apply Hrec; auto; split; auto.\n    case Hg1; auto with datatypes.\nQed.\n\nLemma fold_next2s_incl p ps ss :\n  (forall s1, In s1 ss -> In s1 (fst (fst ps)) \\/ In s1 (snd (fst ps))) ->\n  (forall s1, In s1 (snd (fold_left (next2s p) (snd ps) (fst ps, ss))) ->\n    In s1  (fst (fst (fold_left (next2s p) (snd ps) (fst ps, ss)))) \\/ \n    In s1  (snd (fst (fold_left (next2s p) (snd ps) (fst ps, ss))))).\nProof.\ndestruct ps as (ss1, ss2); simpl fst; simpl snd.\nrevert ss1 ss; elim ss2; clear ss2; auto.\nintros s ss2 Hrec ss1 ss H1.\nrepeat rewrite fold_left_cons.\ngeneralize (next2s_incl p (ss1, ss) s); case next2s.\nsimpl fst; simpl snd.\nintros ss3 ss4 H3; apply Hrec; auto with datatypes.\nQed.\n\nLemma fold_next2s_nreach n p ps :\n   p = porder (S n) ->\n  (forall s, In s (fst (fst ps)) <-> \n     exists m, m <= n /\\ nsreachable m s /\\ is_odd (porder m)) /\\\n  (forall s, In s (snd (fst ps)) <-> \n     exists m, m <= n /\\  nsreachable m s /\\ porder m <> 1%positive) /\\\n  (forall s, (nsreachable n s -> In s (snd ps)) /\\\n             (In s (snd ps) -> nlreachable n s)) ->\n  (forall s, In s (fst (fst (fold_left (next2s p) (snd ps) (fst ps,nil)))) <-> \n     exists m, m <= S n /\\ nsreachable m s /\\ is_odd (porder m)) /\\\n  (forall s, In s  (snd (fst (fold_left (next2s p) (snd ps) (fst ps,nil)))) <-> \n     exists m, m <= S n /\\ nsreachable m s /\\ porder m <> 1%positive) /\\\n  (forall s, (nsreachable (S n) s \n                -> In s (snd (fold_left (next2s p) (snd ps) (fst ps,nil)))) /\\\n             (In s (snd (fold_left (next2s p) (snd ps) (fst ps,nil)))\n                 -> nlreachable (S n) s)).\nProof.\ndestruct ps as (ss1, ss2).\nunfold next2s.\nrewrite fold_left_comb with \n  (f := fun (y: state) (y1: state -> state) => y1 y)\n  (g := filter2s p).\nmatch goal with |- context[fold_right ?X ?Y ?Z] =>\n  change (fold_right X Y Z) with (candidate_list Z)\nend; fold filters.\nsimpl fst; simpl snd.\nintros Hn (H1, (H2, H3)); generalize (filter2s_correct p (ss1, nil) (candidate_list ss2));\n case (fold_left (filter2s p) (candidate_list ss2) (ss1, nil)).\nintros ss4 ss5; simpl; intros (H4, (H5, H6)).\nsplit; [idtac | split].\n- intros s; apply iff_trans with (1:= H4 s).\n  split.\n  + generalize (in_states_correct s (fst ss1)); case in_states; intros He.\n    * intros _; case (H1 s); intros HH _.\n      case (HH He); intros m (Hm1, (Hm2, Hm3)).\n      exists m; repeat (split; auto with arith).\n    * intros [H7 | (H8, (H9, H10))].\n      -- case He; auto.\n      -- assert (H11 := candidate_list_correct ss2 n).\n           case (fun x => H11 x s); auto.\n         intros _ H12; generalize (H12 H9); clear H11 H12; intros H11.\n         case (nlreachable_bound _ _ H11); intros m (Hm, Hm1).\n         case (le_lt_or_eq _ _ Hm); intros Hm2.\n         ++ case (porder_inv1 m); intros Hm3.\n            ** case H8; rewrite H2; exists m; auto with arith.\n            ** case He; rewrite H1; exists m; auto with arith.\n         ++ subst; exists (S n); repeat (split; auto).\n  + rewrite Hn; auto.\n    intros (m, (Hm1, (Hm2, Hm3))).\n    case (le_lt_or_eq _ _ Hm1); clear Hm1; intros Hm1.\n    * left.\n      rewrite H1; exists m; auto with arith.\n    * subst; right; split; auto.\n      -- rewrite H2.\n         intros (m1, (Hm4, (Hm5, Hmm6))).\n         contradict Hm4.\n         rewrite (nsreachable_unique _ _ _ Hm5 Hm2); auto with arith.\n      -- split; auto.\n         assert (H11 := candidate_list_correct ss2 n).\n         case (fun x => H11 x s); auto.\n- intros s; apply iff_trans with (1:= H5 s).\n  split.\n  + generalize (in_states_correct s (snd ss1)); case in_states; intros He.\n    * intros _; case (H2 s); intros HH _.\n      case (HH He); intros m (Hm1, (Hm2, Hm3)).\n      exists m; repeat (split; auto with arith).\n    * intros [H7 | (H8, (H9, H10))].\n      -- case He; auto.\n      -- assert (H11 := candidate_list_correct ss2 n).\n         case (fun x => H11 x s); auto.\n         intros _ H12; generalize (H12 H9); clear H11 H12; intros H11.\n         case (nlreachable_bound _ _ H11); intros m (Hm, Hm1).\n         case (le_lt_or_eq _ _ Hm); intros Hm2.\n         ++ case (porder_inv1 m); intros Hm3.\n            ** case He; rewrite H2; exists m; auto with arith.\n            ** case H8; rewrite H1; exists m; auto with arith.\n         ++ subst; exists (S n); repeat (split; auto).\n  + rewrite Hn; auto.\n    intros (m, (Hm1, (Hm2, Hm3))).\n    case (le_lt_or_eq _ _ Hm1); clear Hm1; intros Hm1.\n    * left.\n      rewrite H2; exists m; auto with arith.\n    * subst; right; split; auto.\n      -- rewrite H1.\n         intros (m1, (Hm4, (Hm5, Hmm6))).\n         contradict Hm4; rewrite (nsreachable_unique _ _ _ Hm5 Hm2); \n           auto with zarith.\n      -- split; auto.\n         assert (H11 := candidate_list_correct ss2 n).\n         case (fun x => H11 x s); auto.\n- intros s; split; rewrite H6; intros Hg.\n  + right; split; [idtac | split]; auto.\n    * rewrite H1; intros (m, (Hm, (Hm1, _))).\n      case Hg; intros _ HH; case (HH m); auto with arith.\n      case Hm1; auto.\n    * rewrite H2; intros (m, (Hm, (Hm1, _))).\n      case Hg; intros _ HH; case (HH m); auto with arith.\n      case Hm1; auto.\n    * case (fun x => candidate_list_correct ss2 n x s); auto.\n  + case Hg; [intros HH; case HH | intros (G1, (G2, G3))].\n    case (fun x => candidate_list_correct ss2 n x s); auto.\nQed.\n\nLemma iter2s_aux_equiv n p ps1 ps2 :\n  tequiv ps1 ps2 ->\n  tequiv (iter2s_aux n p ps1) (iter2s_aux n p ps2).\nProof.\nrevert p ps1 ps2; elim n; simpl; auto; clear n.\nintros n Hrec p (sl1, sr1) (sl2, sr2) H1.\napply Hrec.\napply (fold_next2s_equiv p (sl1, sr1) (sl2, sr2)); auto.\nintros s; split; intros H; case H.\nQed.\n\nLemma iter2s_aux_valid n p ps :\n   valid_triple ps -> valid_triple (iter2s_aux n p ps).\nProof.\nrevert p ps; elim n; simpl; auto; clear n.\nintros n Hrec p (sl, sr) Hg.\napply Hrec; apply (fold_next2s_valid p (sl, sr)); auto.\nintros s1 HH; case HH.\nQed.\n\nLemma iter2s_aux_incl n p ps :\n  (forall s1, In s1 (snd ps) -> In s1 (fst (fst ps)) \\/ In s1 (snd (fst ps))) ->\n  (forall s1, In s1 (snd  (iter2s_aux n p ps))  ->\n    In s1  (fst (fst (iter2s_aux n p ps))) \\/ In s1  (snd (fst (iter2s_aux n p ps)))).\nProof.\nrevert p ps; elim n; simpl; auto; clear n.\nintros n Hrec p (ss1, ss2) Hi; apply Hrec.\napply (fold_next2s_incl p (ss1, ss2)); auto with datatypes.\nintros z HH; inversion HH.\nQed.\n\nLemma iter2s_aux_nreach n p m ps :\n   p = porder (S m) ->\n  (forall s, In s (fst (fst ps)) <-> \n     exists m1, m1 <= m /\\ nsreachable m1 s /\\ is_odd (porder m1)) /\\\n  (forall s, In s (snd (fst ps)) <-> \n     exists m1, m1 <= m /\\  nsreachable m1 s /\\ porder m1 <> 1%positive) /\\\n  (forall s, (nsreachable m s -> In s (snd ps)) /\\\n             (In s (snd ps) -> nlreachable m s)) ->\n  (forall s, In s (fst (fst (iter2s_aux n p ps))) <-> \n     exists m1, m1 <= n + m /\\ nsreachable m1 s /\\ is_odd (porder m1)) /\\\n  (forall s, In s  (snd (fst (iter2s_aux n p ps))) <-> \n     exists m1, m1 <= n + m /\\ nsreachable m1 s /\\ porder m1 <> 1%positive) /\\\n  (forall s, (nsreachable (n + m) s \n                -> In s (snd (iter2s_aux n p ps))) /\\\n             (In s (snd (iter2s_aux n p ps))\n                 -> nlreachable (n + m) s)).\nProof.\nrevert p m ps; elim n; auto; clear n.\nintros n Hrec p m (ss1, ss2); simpl fst; simpl snd.\nrewrite plus_Snm_nSm.\nintros H1 (H2, (H3, H4)); apply (Hrec (pos_up p) (S m)).\nrewrite H1; repeat rewrite porderS; auto.\napply (fold_next2s_nreach m p (ss1, ss2)); auto.\nQed.\n\nLemma iter2s_valid n : valid_triple (iter2s n).\nProof.\nunfold iter2s; apply iter2s_aux_valid.\nrepeat split; simpl; try (intros s HH; case HH; fail);\n  intros s [H1 | H1]; try (case H1; fail); subst s;\n  apply valid_state_init.\nQed.\n\nLemma iter2s_incl n :\n  (forall s1, In s1 (snd  (iter2s n))  ->\n    In s1  (fst (fst (iter2s n))) \\/ In s1  (snd (fst (iter2s n)))).\nProof.\nunfold iter2s; apply iter2s_aux_incl; simpl;\n auto with datatypes.\nQed.\n\nLemma iter2s_correct n :\n  (forall s, In s (fst (fst (iter2s n))) <-> \n     exists m1, m1 <= n /\\ nsreachable m1 s /\\ is_odd (porder m1)) /\\\n  (forall s, In s  (snd (fst (iter2s n))) <-> \n     exists m1, m1 <= n /\\ nsreachable m1 s /\\ porder m1 <> 1%positive) /\\\n  (forall s, (nsreachable n s \n                -> In s (snd (iter2s n))) /\\\n             (In s (snd (iter2s n))\n                 -> nlreachable n s)).\nProof.\nunfold iters.\npattern n at 2 4 5 8.\nreplace n with (n + 0); auto with arith.\nunfold iter2s; apply iter2s_aux_nreach; simpl; auto.\nassert (F1: forall s, nsreachable 0 s -> init_state = s).\n- intros s (H1, H2); inversion H1; auto.\n- split.\n  + intros s; split; auto.\n    intros [H1 | H1].\n    * subst; exists 0; repeat split; auto; try constructor.\n      now intros m Hm; contradict Hm; auto with arith.\n    * case H1; auto.\n    * intros (m1, (Hm1, (Hm2, _))); left.\n      apply F1; generalize Hm1 Hm2; case m1; simpl; auto.\n      intros n1 Hn1; contradict Hn1; auto with arith.\n  + split.\n    * intros s; split; auto.\n      intros HH; case HH.\n      intros (m1, (Hm1, (Hm2, Hm3))).\n      generalize Hm1 Hm3; case m1; simpl; auto.\n      intros n1 Hn1; contradict Hn1; auto with arith.\n    * intros s; split; auto.\n      intros [HH | HH]; subst; try (case HH; fail).\n      exists 0; split; auto; constructor.\nQed.\n\n(* Main theorem, as before (s1,s2) contains all the reachable\n   states *)\n\nLemma iter2s_final n :\n  let (ss1, s3) := iter2s n in\n   let (s1, s2) := ss1 in\n   match s3 with \n    nil => \n  (forall s, reachable s -> In s s1 \\/ In s s2) /\\\n  (forall s, In s s1 -> \n     exists m1, m1 <= n /\\ nsreachable m1 s /\\ is_odd (porder m1)) /\\\n  (forall s, In s  s2 -> \n     exists m1, m1 <= n /\\ nsreachable m1 s /\\ porder m1 <> 1%positive)\n  | _ => True\n   end.\nProof.\ngeneralize (iter2s_correct n).\ncase iter2s; intros (s1, s2) s3.\ncase s3; auto; simpl.\nintros (H1, (H2, H3)).\nsplit; auto.\n- intros s Hs.\n  case (reachable_nreachable _ Hs).\n  intros k Hk.\n  case (nsreachable_bound _ _ Hk).\n  intros m (Hm, Hm1).\n  case (le_or_lt m n); intros Hn.\n  + case (porder_inv1 m); intros H4.\n    * right; rewrite H2; exists m; auto.\n    * left; rewrite H1; exists m; auto.\n  + case (nsreachable_inv n m s); auto with arith.\n    intros s4 Hs3; case (H3 s4).\n    intros HH; case (HH Hs3); auto.\n- split; auto.\n  + intros s; case (H1 s); auto.\n  + intros s; case (H2 s); auto.\nQed.\n\n(*****************************************************************************)\n(*              Proving the solver                                           *)\n(*****************************************************************************)\n\n\nLemma move_map: movel = map m2f Movel.\nProof. apply refl_equal. Qed.\n\nLemma moves_inv m s : valid_state s -> s = m2f (minv m) (m2f m s).\nProof.\ncase m; case s; unfold valid_state; simpl; intuition;\nrepeat rewrite oup_down; repeat rewrite odown_up; auto.\nQed.\n\nLemma get_number_correct n n1 s s1 s2 :\n  (s1, s2) = fst (iter2s n) -> n1 <= n ->\n  nsreachable n1 s ->  porder n1 = get_number s s1 s2.\nProof.\ngeneralize (iter2s_correct n); case iter2s.\nintros (s3, s4) ss; simpl; intros (H1, (H2, H3)) HH Hl Hr.\ninjection HH; intros; subst s3 s4; clear HH.\nunfold get_number.\ngeneralize (in_states_correct s s1); case in_states.\n- rewrite H1; intros (m, (Hm, (Hm1, Hm2))).\n  assert(m = n1); subst.\n    apply nsreachable_unique with s; auto.\n  generalize (in_states_correct s s2); case in_states.\n  + rewrite H2; intros (m1, (Hm3, (Hm4, Hm5))).\n    assert (m1 = n1); subst.\n      apply nsreachable_unique with s; auto.\n    generalize Hm2 Hm5; generalize (porder_inv n1); \n      intros [HH | [HH | HH]]; rewrite HH; auto.\n    * intros _ HH1; case HH1; auto.\n    * intros HH1; case HH1.\n  + intros HH; generalize (positive_eq_correct (porder n1) 1);\n      case positive_eq; auto; intros HH1.\n    case HH; rewrite H2; exists n1; auto.\n- generalize (in_states_correct s s2); case in_states.\n  + intros _ HH; generalize (porder_inv n1); \n      intros [HH1 | [HH1 | HH1]]; rewrite HH1; auto.\n    * case HH; rewrite H1; exists n1; rewrite HH1; simpl; auto.\n    * case HH; rewrite H1; exists n1; rewrite HH1; simpl; auto.\n  + intros HH HH1; generalize (porder_inv1 n1); intros [HH2 | HH2].\n    * case HH; rewrite H2; exists n1; auto.\n    * case HH1; rewrite H1; exists n1; auto.\nQed.\n\nLemma get_next_aux_correct n s s1 s2 l :\n  match get_next_aux n s s1 s2 l with \n    Some a => \n   In a l /\\ get_number (m2f a s) s1 s2 = n\n  | None => \n      forall a, In  a l -> get_number (m2f a s) s1 s2 <> n\n  end.\nProof.\nelim l; simpl; auto.\nintros a l1 Hrec; generalize (positive_eq_correct n (get_number (m2f a s) s1 s2));\n  case positive_eq; try (intros; discriminate); auto.\ngeneralize Hrec; case get_next_aux; auto.\n- intros m1 (H1, H2) H3; auto.\n- intros H1 H2 a1 [H3 | H3]; subst; auto.\nQed.\n\nLemma move_Movel s s1 :\n  move s s1 -> exists a, In a Movel /\\ s1 = m2f a s.\nProof.\nintros [H1|[H1|[H1|[H1|[H1|[H1|[H1|[H1|H1]]]]]]]]; subst.\n- exists Right; simpl; split; auto.\n- exists Right2; simpl; split; auto.\n- exists Rightm1; simpl; split; auto.\n- exists Back; simpl; split; auto.\n- exists Back2; simpl; split; auto; right; auto.\n- exists Backm1; simpl; split; auto; do 2 right; auto.\n- exists Down; simpl; split; auto; do 3 right; auto.\n- exists Down2; simpl; split; auto; do 4 right; auto.\n- exists Downm1; simpl; split; auto; do 5 right; auto.\nQed.\n\nLemma Movel_move s a : In a Movel -> move s (m2f a s).\nProof.\nsimpl; intros [H1|[H1|[H1|[H1|[H1|[H1|[H1|[H1|[H1|H1]]]]]]]]]; subst;\n  simpl; red; auto; do 3 right; auto; do 3 right; auto.\ncase H1.\nQed.\n\nLemma porder_move s1 s2 n1 n2 : \n  nsreachable n1 s1 -> nsreachable n2 s2 ->\n  move s1 s2 -> n1 = n2 \\/ n1 = S n2 \\/ S n1 = n2.\nProof.\nintros H1 H2 H3.\nassert (F1: nreachable (S n2) s1).\n  apply nreachS with s2; auto.\n  + case H2; auto.\n  + apply move_sym; auto.\n    apply nreachable_valid with n1; case H1; auto.\n  + case (nsreachable_bound _ _ F1); intros k (Hk, Hk1).\n    assert (k = n1); subst.\n      apply nsreachable_unique with s1; auto.\n    assert (F2: nreachable (S n1) s2).\n      apply nreachS with s1; auto.\n      case H1; auto.\n    case (nsreachable_bound _ _ F2); intros k1 (Hk2, Hk3).\n    assert (k1 = n2); subst.\n      apply nsreachable_unique with s2; auto.\n    case (le_lt_or_eq _ _ Hk); clear Hk; intros Hk; subst; auto.\n    case (le_lt_or_eq _ _ Hk2); clear Hk2; intros Hk2; subst; auto.\n    left; apply le_antisym; auto with arith.\nQed.\n\nLemma porder_move_down s1 s2 n1 n2 : \n  nsreachable n1 s1 -> nsreachable n2 s2 ->\n  move s1 s2 -> porder n2 = pos_down (porder n1) -> n1 = S n2.\nProof.\nintros H1 H2 H3; generalize (porder_move _ _ _ _ H1 H2 H3);\n  intros [HH | [HH | HH]]; auto.\n- intros HH1; contradict HH1; \n  generalize (porder_inv n1); intros [HH2 | [HH2 | HH2]]; subst; rewrite HH2;\n  intros HH3; discriminate.\n- intros HH1; contradict HH1; subst; rewrite porderS; \n  generalize (porder_inv n1); intros [HH2 | [HH2 | HH2]];\n  rewrite HH2;\n  intros HH3; discriminate.\nQed.\n\nLemma get_next_correct n n1 s s1 s2 :\n  (s1, s2) = fst (iter2s n) -> n1 < n ->\n  nsreachable (S n1) s -> \n  match get_next s s1 s2 with Some m => nsreachable n1 (m2f m s)\n  | None => False end.\nProof.\ngeneralize (iter2s_correct n) \n  (fun n1 s => get_number_correct n n1 s s1 s2); case iter2s.\nintros (s3, s4) ss; simpl; intros (H1, (H2, H3)) Hn HH Hl Hr.\ninjection HH; intros; subst s3 s4; clear HH.\ncase (move_nsreachable _ _ Hr); intros s3 (Hs1, Hs2).\ncase (fun x => (move_Movel _ _ (move_sym _ _ x Hs1))).\ncase Hs2; intros H4 _; apply nreachable_valid with (1 := H4).\nintros a (Ha, Ha1); subst.\nunfold get_next.\ngeneralize (get_next_aux_correct (pos_down (get_number s s1 s2)) s s1 s2 Movel);\n  case get_next_aux.\n- intros a1 (Ha2, Ha3).\n  rewrite <- (Hn (S n1) s) in Ha3; auto with arith.\n  assert (F1: nreachable (S (S n1)) (m2f a1 s)).\n    apply nreachS with s; auto.\n    + case Hr; auto.\n    + apply Movel_move; auto.\n    + case (nsreachable_bound _ _ F1); intros k1 (Hk2, Hk3).\n      assert (F2: nreachable (S k1) s).\n        apply nreachS with (m2f a1 s); auto.\n        * case Hk3; auto.\n        * apply move_sym; try apply Movel_move; auto.\n          apply nreachable_valid with (S n1); case Hr; auto.\n        * case (nsreachable_bound _ _ F2); intros k2 (Hk4, Hk5).\n          assert (k2 = (S n1)); subst.\n            apply nsreachable_unique with (2 := Hr); auto.\n          case (le_lt_or_eq n1 k1); auto with arith; clear Hk4; \n            intros Hk4; subst; auto.\n          case (le_lt_or_eq _ _ Hk2); clear Hk2; intros Hk2.\n          -- rewrite <- (Hn k1) in Ha3; auto with arith.\n             ++ rewrite porderS, pos_down_up in Ha3; auto.\n                ** case (le_lt_or_eq k1 (S n1)); auto with arith.\n                   --- intros HH; contradict HH; auto with arith.\n                   --- intros HH; subst; contradict Ha3.\n                       rewrite porderS.\n                       case (porder n1); simpl; auto;\n                         try (intros; discriminate).\n                       intros p; case p; intros; discriminate.\n                ** generalize (porder_inv n1); intros [HH1|[HH1|HH1]]; \n                     rewrite HH1; red; auto.\n             ++ apply le_trans with (S n1); auto with arith.\n          -- subst k1; clear F1 F2.\n             case (le_or_lt (S (S n1)) n); intros Hk6.\n             ++ rewrite <- (Hn (S (S n1))) in Ha3; auto with arith.\n                contradict Ha3; repeat rewrite porderS.\n                case (porder n1); simpl; auto; try (intros; discriminate).\n                intros p; case p; intros; discriminate.\n             ++ assert (F1: get_number (m2f a1 s) s1 s2 = 4%positive).\n                ** unfold get_number.\n                   generalize (in_states_correct (m2f a1 s) s1); \n                     case in_states; intros G1.\n                   --- rewrite H1 in G1.\n                       contradict Hk6; case G1; intros k (Hk, (Hk1,Hk2)).\n                       assert (k = S (S n1)); subst; auto with arith.\n                       apply nsreachable_unique with (1 := Hk1); auto.\n                   --- generalize (in_states_correct (m2f a1 s) s2); \n                         case in_states; intros G2; auto.\n                       rewrite H2 in G2.\n                       contradict Hk6; case G2; intros k (Hk, (Hk1,Hk2)).\n                       assert (k = S (S n1)); subst; auto with arith.\n                       apply nsreachable_unique with (1 := Hk1); auto.\n                ** contradict Ha3; rewrite F1.\n                   case porder; simpl; try (intros; discriminate);\n                   intros p; case p; intros; discriminate.\n- intros HH; case (HH a); auto.\n  rewrite <- (Hn n1 (m2f a s)); auto with arith.\n  rewrite <- (Hn (S n1)); auto with arith.\n  rewrite porderS, pos_down_up; auto;\n  generalize (porder_inv n1); intros [HH1|[HH1|HH1]]; rewrite HH1; red; auto.\nQed.\n\nLemma get_next_init n s1 s2 :  \n  (s1, s2) = fst (iter2s n) -> get_next init_state s1 s2  = None.\nProof.\ngeneralize (iter2s_correct n) \n  (fun n1 s => get_number_correct n n1 s s1 s2); case iter2s.\nintros (s3, s4) ss; simpl; intros (H1, (H2, H3)) Hn HH.\ninjection HH; intros; subst s3 s4; clear HH.\nunfold get_next.\nreplace (get_number init_state s1 s2) with 1%positive.\n- simpl pos_down.\n  generalize (get_next_aux_correct 3 init_state s1 s2 Movel);\n    case get_next_aux; auto.\n  intros a (Ha, Ha1).\n  generalize Ha1; unfold get_number.\n  generalize (in_states_correct (m2f a init_state) s1); case in_states;\n    intros G1.\n  rewrite H1 in G1.\n  case G1; intros k (Hk, (Hk1,Hk2)).\n  generalize (in_states_correct (m2f a init_state) s2); case in_states; \n    intros G2; auto.\n  + rewrite H2 in G2.\n    case G2; intros k1 (Hk3, (Hk4,Hk5)).\n    case (porder_move init_state (m2f a init_state) 0 k); auto.\n    * split; try apply nreach0; intros m Hm; contradict Hm; auto with arith.\n    * apply Movel_move; auto.\n    * intros HH; subst k.\n      case (porder_move init_state (m2f a init_state) 0 k1); auto.\n      -- split; try apply nreach0; intros m Hm; contradict Hm; auto with arith.\n      -- apply Movel_move; auto.\n      -- intros HH; subst k1.\n         case Hk5; simpl; auto.\n      -- intros HH; case HH; clear HH; intros HH; try discriminate; subst k1.\n         absurd (0 = 1); auto with arith.\n         apply nsreachable_unique with (1 := Hk1); auto.\n    * intros HH; case HH; clear HH; intros HH; try discriminate; subst k.\n      case Hk2; simpl; auto.\n  + intros; discriminate.\n  + case in_states; intros; discriminate.\n- unfold get_number.\n  generalize (in_states_correct init_state s1); case in_states; intros G1.\n  + generalize (in_states_correct init_state s2); case in_states;\n      intros G2; auto.\n    rewrite H2 in G2.\n    case G2; intros k (Hk, (Hk1,Hk2)).\n    assert (k = 0); subst.\n      apply nsreachable_unique with init_state; auto.\n      split; try apply nreach0; intros m Hm; contradict Hm; auto with arith.\n    case Hk2; auto.\n   + case G1; rewrite H1; exists 0; repeat (split; auto with arith);\n       try constructor.\n     intros m Hm; contradict Hm; auto with arith.\nQed.\n\nLemma solve_correct n m p s s1 s2 :\n  (s1, s2) = fst (iter2s n) -> m <= n ->\n  nsreachable m s -> \n  nsreachable (m - p) (fold_left (fun s a => m2f a s) (solve p s s1 s2) s).\nProof.\nintro H; generalize m s; elim p; clear m p s; simpl; auto.\nintros m; rewrite <- minus_n_O; auto.\nintros p Hrec m; case m; clear m; simpl.\n- intros s _ HH; case HH; intros HH1 _; inversion_clear HH1.\n  rewrite get_next_init with (1 := H).\n  split; try apply nreach0; intros m1 Hm1; contradict Hm1; auto with arith.\n- intros m s H1 H2.\n  assert (F1: m < n); auto with arith.\n  generalize (get_next_correct _ _ _ _ _  H F1 H2); case get_next.\n  + intros a Ha; rewrite fold_left_cons.\n    apply Hrec; auto with arith.\n  +intros HH; case HH.\nQed.\n\n(* Main theorem: we get a path to the initial state *)\n\nLemma solve_init n s s1 s2 :\n  (s1, s2) = fst (iter2s n) ->\n  nlreachable n s -> \n  fold_left (fun s a => m2f a s) (solve n s s1 s2) s = init_state.\nProof.\nintros H1 H2.\ncase (nlreachable_bound _ _ H2); clear H2; intros m (H2, H3).\ngeneralize (solve_correct n m n s s1 s2 H1 H2 H3).\nreplace (m - n) with 0.\n- intros (HH,_); inversion HH; auto.\n- case (le_lt_or_eq _ _ H2); intros HH; subst; auto with arith.\n  rewrite not_le_minus_0; auto with arith.\nQed.\n\n(* Main theorem: and the path is \"small\"*)\n\nLemma solve_length n s s1 s2 :\n  length (solve n s s1 s2) <= n.\nProof.\nrevert s s1 s2; elim n; simpl; auto; clear n.\nintros n Hrec s s1 s2; case get_next; simpl; auto with arith.\nQed.\n", "meta": {"author": "thery", "repo": "minirubik", "sha": "12f0d5d0bbe8f1312f981a469c9467446faf3212", "save_path": "github-repos/coq/thery-minirubik", "path": "github-repos/coq/thery-minirubik/minirubik-12f0d5d0bbe8f1312f981a469c9467446faf3212/BasicRubik.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8976952811593496, "lm_q1q2_score": 0.8305745701703637}}
{"text": "(**\n\u672b\u5c3e\u518d\u5e30\u5224\u5b9a\u3059\u308b\u30b3\u30de\u30f3\u30c9\n\n2023_2_23\n\n@suharahiromichi\n\nsee. prolog/elpi/minifp.elpi\n*)\n\nFrom elpi Require Import elpi.\n\nFixpoint fib (n : nat) : nat :=\n\tmatch n with\n\t| O => O\n\t| S m => match m with\n\t\t\t | O => 1\n\t\t\t | S m' => fib m + fib m'\n\t\t\t end\n\tend.\nCompute fib 10.\t\t\t\t\t\t\t(* 55 *)\n\nFixpoint trec_fib (n a b : nat) : nat :=\n\tmatch n with\n\t| 0 => a\n\t| S m => trec_fib m b (a + b)\n\tend.\nCompute trec_fib 10 0 1.\t\t\t\t(* 55 *)\n\nFixpoint fact (n : nat) : nat :=\n\tmatch n with\n\t| O => 1\n\t| S m => n * fact m\n\tend.\nCompute fact 5.\t\t\t\t\t\t\t(* 120 *)\n\nFixpoint trec_fact (n a : nat) :nat :=\n\tmatch n with\n\t| 0 => a\n\t| S m => trec_fact m (n * a)\n\tend.\nCompute trec_fact 5 1.\t\t\t\t\t(* 120 *)\n\n(**\nfix (f\\ M) \u306e f \u304c\u3001match(\u30cd\u30b9\u30c8\u3057\u3066\u3082\u3088\u3044)\u306e\u7bc0\u306e\u6700\u5916\u5074\u306b\u9650\u3063\u3066\u51fa\u73fe\u3059\u308b\u3053\u3068\u3092\u30c1\u30a7\u30c3\u30af\u3059\u308b\u3002\n*)\nElpi Command tailrec.\nElpi Accumulate lp:{{\n/**\napp \u306e\u5148\u982d\u306b\u51fa\u73fe\u3059\u308b\u306a\u3089\u3070\u3001success\u3068\u3059\u308b\u3002\n*/\npred trec i:term i:term.\n%trec F M :- coq.say \"trec=\" F \",\" M, fail.\t\t% Check\ntrec F (fun _ _ M) :- pi n\\ trec F (M n).\ntrec F (match _ _ L) :-\tstd.exists L (trec F).\ntrec F (app [F | _]).\ntrec F (app [N | _]) :- trec F N.\n\n/**\napp \u306e\u5148\u982d\u4ee5\u5916\u306b\u51fa\u73fe\u3059\u308b\u306a\u3089\u3070\u3001success\u3068\u3059\u308b\u3002\n*/\npred occr i:term i:term.\n%occr F M :- coq.say \"occr=\" F \",\" M, fail.\t\t% Check\noccr F (fun _ _ M) :- pi n\\ occr F (M n).\noccr F (match _ _ L) :-\tstd.exists L (occr F).\n% app\u306e\u5148\u982d\u306bF\u304c\u51fa\u73fe\u3057\u305f\u5834\u5408\u306f\u3001\u305d\u308c\u4ee5\u5916\u306e\u7b87\u6240\u3060\u3051\u3067\u3092\u898b\u308b\u3002\noccr F (app [F | L]) :- !, std.exists L (occr F).\noccr F (app [N | L]) :- occr F N, !, std.exists L (occr F).\n% app\u306e\u5148\u982d\u306bF\u304c\u51fa\u73fe\u3057\u3057\u306a\u3044\u5834\u5408\u306f\u3001\u5168\u4f53\u3092\u898b\u308b\u3002\noccr F (app L) :- std.exists L (occr F).\noccr F F.\n\n/**\n\u3069\u3053\u306b\u3067\u3082\u51fa\u73fe\u3059\u308b\u306a\u3089\u3070\u3001success\u3068\u3059\u308b\u3002(\u4e0d\u4f7f\u7528)\n*/\npred in i:term i:term.\n%in F M :- coq.say \"in=\" F \",\" M, fail.\t\t\t% Check\nin F (fun _ _ M) :- pi n\\ in F (M n).\nin F (match _ _ L) :- std.exists L (in F).\nin F (app L) :- std.exists L (in F).\nin F F.\n\nmain [str Name] :-\n\tcoq.locate Name (const Const),\n  \tcoq.env.const Const (some Bo) Ty,\n  \tcoq.say \"tailrec=\" Bo,\t\t\t\t\t\t% Check\n\tBo = fix _ _ _ M,\n\tpi f\\ trec f (M f),\n\tnot (pi f\\ occr f (M f)).\t\t\t\t\t% \u304a\u304b\u3057\u304f\u306a\u3063\u305f\u3089\u3053\u3053\u3092\u5916\u3059\uff01\nmain [str Name] :-\t\n\tcoq.say Name \"IS NOT A RECURCEIVE FUNCTION.\",\n\t!, fail.\n}}.\nElpi Typecheck.\n\nFail Elpi tailrec fib.\nElpi tailrec trec_fib.\nFail Elpi tailrec fact.\nElpi tailrec trec_fact.\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/elpi/coq_elpi_tailrec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8976952825278492, "lm_q1q2_score": 0.830574564033394}}
{"text": "Theorem tautology: forall P : Prop, P -> P.\nProof.\n intros P H.\n assumption.\nQed.\n\nTheorem wrong: forall P : Prop, P.\nProof.\n intros P.\nAdmitted.\n\nTheorem Modus_ponens : forall P Q : Prop, \nP->(P->Q)->Q.\nProof.\nintros P Q.\nintros H1.\nintros H2.\napply H2. \nassumption.\nQed.\n\nTheorem Modus_tollens : forall P Q : Prop, ~Q /\\ (P->Q) -> ~P.\nProof.\nintros P Q.\nunfold not.\nintros.\napply H.\napply H. \nassumption.\nQed.\n\n\n(* \u8ab2\u984c3 *)\nTheorem Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q.\nProof.\nintros.\nunfold not in H0.\ndestruct H.\napply H0 in H.\ninversion H.\nassumption.\nQed.\n\n(* \u8ab2\u984c4 *)\nTheorem DeMorgan1 : forall P Q : Prop,  ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\nunfold not.\nintros.\ninversion H. \napply H1.\napply H0.\napply H1.\n\napply H0. \n\nQed.\n\n\nTheorem DeMorgan2 : forall P Q : Prop, ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\nunfold not.\nintros.\ninversion H.\napply H1. destruct H0. assumption.\napply H2 in H0. inversion H0.\nQed.\n\nTheorem DeMorgan3 : forall P Q : Prop, ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  unfold not.\n  intros.\n  apply conj.\n  intros.\n  destruct H. left.\n  assumption.\n  intros.  apply H. right. assumption.\nQed.\n\nTheorem NotNot_LEM : forall P : Prop, ~ ~(P \\/ ~P).\nProof.\n  unfold not.\n  intros. apply H.\n  right. intros.\n  apply H. left. assumption.\nQed.\n\nRequire Import Arith.\n\nSearchAbout lt _ _.", "meta": {"author": "moritanon", "repo": "Coq2014", "sha": "08d72e37ad035c91d1bcf109a68d1225fdaa11b4", "save_path": "github-repos/coq/moritanon-Coq2014", "path": "github-repos/coq/moritanon-Coq2014/Coq2014-08d72e37ad035c91d1bcf109a68d1225fdaa11b4/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.8933094103149355, "lm_q1q2_score": 0.8302778660365698}}
{"text": "From mathcomp \nRequire Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit.\n\n(* \n* In Coq the way a lambda is defined is as follows:\n* (fun n => n + 1) 2\n*\n* We can associate names with operations, using a definition:\n* Definition f := fun n => n + 1. \n*)\n\nDefinition f := fun n => n + 1.\n\n\nPrint f.\n\n\n(*\n* Within coq, well typed expressions can be computed\n* this means that they are reduced to a simpler form.\n*)\n\n\nDefinition h (n: nat) : nat -> nat := fun m => n + m * 2.\n\n\nDefinition repeat_twice (g : nat -> nat) : nat -> nat := fun x => g (g x).\n\n(* Coq also supports local definitions *)\nDefinition fun_with_local (g : nat) : nat := let x := g + 2 in x * x.\n\n(* booleans are a definition that are loaded\n* into coq upon launch. \n* \n* to use a boolean we can use an if then statement\n*)\n\nDefinition twoVthree (b : bool) := if b then 2 else 3.\n\n(* We can also do pattern matching with inductive data types *)\nDefinition prednn n := if n is p.+1 then p else n.\n\n(* for matching with multiple cases, we can use a match *)\n\nDefinition three_patterns n :=\n    match n with\n    | u.+1.+1.+1.+1 => u\n    | v.+1 => v\n    | 0 => n\n    end.\n\n\n(* also note that n.+1 is equivalent to (S n) *)\n\n\n(* we can define recursive functions in coq using fixpoint*)\nFixpoint addnn n m := if n is p.+1 then (addn p m).+1 else m.\n\nFixpoint eqnnn n m :=\n    match n, m with\n    | 0, 0 => true\n    | p.+1, q.+1 => eqn p q\n    | _, _ => false\n    end.\n\n\n(* \n* In coq terminology, we call a container a group of datatypes which have been grouped together so that they can be manipulated as a single object.  lists of nats *)\nInductive listn := niln | consn (hd : nat) (t1 : listn).\n\nInductive cust_list (A : Type) := cust_nil | cust_cons (hd : A) (t1 : cust_list A).\n\n(* Type is the type of all types, seq is Type -> Type - a type constructor*)\n(* mathcomp provides a series of definitions of lists\n* Check 1 :: 2 :: 3 :: nil.\n*)\n\n(* mathcomp also provides a utility tool for the repeated application of right associative\n* operations *)\nDefinition tandb (a b c : bool) := [&& a, b & c].\n(* the last element is always seperated by & rather than a comma *)\nEval compute in [seq i.+1 | i <- [:: 2; 3]].\n\n\n(* coq provides the record syntax for a shorthand equivalent to defining an inductive type\n* with a single data constructor.*)\n\nRecord making_a_point (A : Type) : Type := myPoint { x : A; y : nat; z : nat }.\n\n\nSection iterators.\n    Variables (T : Type) (A: Type).\n    Variables (f : T -> A -> A).\n\n    Fixpoint foldr a s :=\n        if s is x ::xs then f x (foldr a xs) else a.\n\n\n    Variable init : A.\n    Variables x1 x2 : T.\n\n    Eval compute in foldr init [:: x1; x2].\nEnd iterators.\n\nSection addition.\n\n    Fixpoint adds n m := if n is p.+1 then adds p m.+1 else m.\n    Fixpoint addn n m := if n is p.+1 then (adds p m).+1 else m.\n\n    Variable n : nat.\n\n    Eval simpl in (adds n.+1 7).-1.\n    Eval simpl in (addn n.+1 7).-1.\n\n\n\n\nEnd addition.\n\n\nSection exercises.\n\n    Inductive triple (A : Type) : Type := mk_triple (x : A) (y: A) (z: A).\n\n    Notation \"( a , b , c )\" := (mk_triple a b c).\n\n    Definition fst (A : Type) (p : triple A) : A := match p with\n    | mk_triple x _ _ => x\n    end.\n\n    Definition snd (A : Type) (p : triple A) : A := match p with mk_triple _ y _ => y end.\n\n    Definition thrd (A : Type) (p : triple A) : A := match p with mk_triple _ _ z => z end.\n\n\n    Notation \"p .1\" := (fst p). \n    Notation \"p .2\" := (snd p). \n    Notation \"p .3\" := (thrd p) (at level 2). \n\n        Eval compute in (4, 5, 8).1.\n        Eval compute in (4, 5, 8).2.\n        Eval compute in (4, 5, 8).3.\nEnd  exercises.\n\n\n(*\n* In this section the book describes how to state elementary candidate theorems starting with identities\n*\n* Coq provides the binary predicate eq with the infix notation =\n* this statement is used to state that two objects are equal\n*\n* we can start with a few of coq's ground equality statements\n*\n* ground means that the statements do not contain any parameter variables.\n*\n* The check command can not only be used to verify the type of some expression, but to also check whether a formal statement is well formed or not.\n*)\n\n\nCheck 3 = 3.\nCheck false && true = false.\n\n\n(*\n* much like the type system in coq ensures that function applications are correct, the type system also ensures that theorems are well formed.\n*\n* Formal statements in coq are themselves terms and have a type.\n*\n* The equlity statement is obtained by applying eq to two arguments of the same type, and results in a well formed term of type prop for proposition.\n*\n* While check ensures the formed ness of a formal theorem, it does not check the provability:\n*)\nCheck 3 = 4.\n\n\n\n\n(*\n* In order to establish that an equality holds, the user should announce that they are going to prove a lemma.\n* This can be done using a special command such as Lemma, Theorem, Remark, Corollary.\n*\n*\n* To begin a Proof of a theroem simply use the Proof command to indicate the start of the proof text.\n*\n*)\n\nLemma my_first_lemma : 3 = 3.\nProof.\n    (* in the coq system, the user builds a formal proof by providing instructions to the\n    * coq system that  describe the construction\n    *  of the proof\n    * the list of instruction is called a proof script, and the commands are tactics\n    *\n    * Once a proof is completed the Qed command can be called which verifies that the proof is actually correct.\n*)\n    (* The statement in question holds by definition as the two sides of the equality are\n    *  syntactically the same\n    * The by tactical applies a tactic, \n    * and then attempts to solve it by computation\n    * in this case as the values are the same by computation, no extra work is necassary.\n    *)\n    by [].\nQed.\nAbout my_first_lemma.\n\n(* ground identities are a special case of statements called identities.\n*\n* an identity is an equality relation A = B that holds regardless of the values that are substituted for variables in A and B.\n* for example we can state the identity expressing associativity of addition on natural numbers\n*\n*)\nLemma addnA (m n k : nat) : m + (n + k) = m + n + k.\nAdmitted.\n\n\nLemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nAdmitted.\n\nLemma my_second_lemma : 2 + 1 = 3.\nProof.\n    (* shallow embedded, so we can just compute the result to be the same.*)\n    by [].\nQed.\n\n\nLemma addSn m n : m.+1 + n = (m + n).+1.\nProof.\n    by [].\nQed.\n\nLemma negbK (b : bool) : ~~ (~~ b) = b.\nProof.\n    (* can not prove by computation,as b can not be expanded *)\n    by case: b.\nQed.\n\n\nLemma leqn0 n : (n <= 0) = (n == 0).\nProof.\n    by case: n => [| k].\nQed.\n\nFixpoint muln (m n : nat) : nat :=\n    if m is p.+1 then n + muln p n else 0.\n\nLemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0).\nProof.\n    case:  m => [| m] //.\n    case: n => [| k] //.\n    by rewrite muln0.\nQed.\n(* page 56 *)\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/book_math_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.9263037369059444, "lm_q1q2_score": 0.8302009935738164}}
{"text": "Require Import Arith.\n\nDefinition divides (n m:nat) := exists p:nat, p*n = m.\n\n\nLemma divides_O : forall n:nat, divides n 0.\nProof.\n  intro n; exists 0; simpl; trivial.\nQed.\n\nLemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).\nProof.\n intros n m H; elim H; intros q Hq.  \n exists (S q) ; simpl; auto.\nQed.\n\nLemma not_divides_plus : forall n m:nat, ~ divides n m -> ~ divides n (n+m).\nProof.\n intros n m H; red; intro H'; elim H'; intro y.\n case y; simpl.\n intro H2; apply H.\n cut (m=0).\n intro H3; rewrite H3; apply divides_O.\n Require Omega.\n omega.\n intros n0 Hn0.\n apply H.\n exists n0.\n omega.\nQed.\n\nLemma not_divides_lt : forall n m:nat, 0<m ->  m<n -> ~ divides n m.\nProof.\n intros n m H H0 H1.\n elim H1; intros q Hq.\n rewrite <- Hq in H.\n rewrite <- Hq in H0.\n generalize H H0; case q.\n simpl.  \n intros; absurd (0 < 0); auto with arith.\n clear H H0; intros y Hy Hy'.\n simpl in Hy'. \n absurd (n <= n + y * n); auto with arith. \nQed.\n\nLemma not_lt_2_divides : forall n m:nat, n <> 1 -> n < 2 -> 0 < m -> \n                        ~ divides n m.\nProof.\n intros n m H H0; cut (n=0).\n intro e;rewrite e.   \n case m.\n intro; absurd (0 < 0); auto with arith.\n intros n0 Hn0 H1.\n elim H1; intros q Hq.\n rewrite mult_0_r in Hq; discriminate Hq.\nRequire Import Omega.  \n omega.\nQed.\n  \nLemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\nProof.\n intros; omega.\nQed.\n\nLemma lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/  n=m.\nProof.\n intros; 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/autotac/SRC/primes_hyps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8301790955524626}}
{"text": "(**\n * PSet 1: Functional Programming in Coq\n\n  This assignment is designed as a file that you should download and complete in a Coq IDE.\n  Before doing that, you need to install Coq.  The installation instructions\n  are on the course website.\n*)\n\n(* \n Exercise: mult2 [10 points].\n Define a function that multiplies its input by 2.\n*)\n\nLet mult2 (x:nat) :nat := 2*x.\n\n(* What is the function's type? *)\n\n(* The type of the function is : \"nat -> nat\" *)\n\nPrint mult2.\n(*\n  Output:\n    mult2 = fun x : nat => 2 * x : nat -> nat \n*)\n\n(*  What is the result of computing the function on 0?  On 3110? *)\nEval compute in mult2 0.\n(* Output: \"0:nat\" *)\nEval compute in mult2 3110.\n(*Output: \"6220:nat\" *)\n\n\n(* \n  Exercise: xor [10 points].\n   Define a function that computes the xor of two [bool] inputs.\n   Do this by pattern matching on the inputs.\n*)\n\nLet xor (a:bool) (b:bool) :bool :=\nmatch a,b with \n| false,false => false\n| false,true => true\n| true,false => true\n| true,true => false\nend.\n\n(* What is the function's type?  *)\n(* The type of the function is \"bool->bool->bool\"  *)\nPrint xor.\n(*\n  Output:\n    xor = \n    fun a b : bool => if a then if b then false else true else if b then true else false\n     : bool -> bool -> bool\n*)\n\n(* Compute all four possible combinations of inputs to test your function.  *)\nEval compute in xor false false.\n(* Output: \"false:bool\" *)\nEval compute in xor false true.\n(* Output: \"true:bool\" *)\nEval compute in xor true false.\n(* Output: \"true:bool\" *)\nEval compute in xor true true.\n(* Output: \"false:bool\" *)\n\n\n(* \n  Exercise: is_none [20 points].\n   Define a function that returns [true] if its input is [None], and [false] otherwise.\n   Your function's type should be [forall A : Type, option A -> bool].\n   That means the function will actually need to take two inputs:\n     the first has type [Type], and the second is an option.\n   Hint:  model your solution on [is_empty] in the notes for this lecture.\n*)\n\nLet is_none (A:Type) (b:option A) :bool :=\nmatch b with \n| None => true\n| Some _=> false\nend.\n\nPrint is_none.\n(* The type: \"forall A : Type, option A -> bool\" *)\n\n(* Verification of definition *)\n(* Eval compute in is_none nat None. *)\n(* Output: = true : bool *)\n(* Eval compute in is_none nat (Some 2). *)\n(* Output: = false : bool *)\n\n\nRequire Import List.\nImport ListNotations.\n\n(*\n   Exercise: double_all [20 points].\n   There is a function [map] that was imported by the [Require Import List] command above.\n   First, check its type with [Check map].  Explain that type in your own words.\n   Second, print it with [Print map].  Note at the end of that which arguments are _implicit_.\n   For a discussion of what implicit means, see the notes for this lecture.\n   Third, use map to write your own function, which should double (i.e., multiply by 2)\n   every value of a list.\n   For example, [double_all [0;2;10]] should be [[0;4;20]].\n*)\n\nCheck map.\n(* \n  Output: \n    map\n     : forall A B : Type, (A -> B) -> list A -> list B \n*)\n\n(* \n    Map function takes in a function f:A->B and list l1 of type A and returns another list l2 of type B \n  and this is achieved for all types A and B. \n    Thus, for all types A and B, map takes in a function f:A->B and a list of type A  as inputs and outputs a list of type B.\n*)\n\nPrint map.\n\n(* \n  Output: \n    map = \n      fun (A B : Type) (f : A -> B) =>\n        fix map (l : list A) : list B := match l with\n                                 | [] => []\n                                 | a :: t => f a :: map t\n                                 end\n     : forall A B : Type, (A -> B) -> list A -> list B \n*)\n\n(*\nArguments A and B are implicit(they are enclosed within square braces). They can be inferred from the types of the arguments to the function.\nThe first argument f is of type A->B and the second arugment l is of type A.\n*)\n\nDefinition double_all (a:list nat) :=  ((map mult2) a).\n\n(*Verification of the Definition*)\n\n(* Eval compute in double_all [0;2;10]. *)\n\n(*\n  Output:\n     = [0; 4; 20]\n      : list nat\n*)\n\n(* Exercise: sum [20 points]\n   Write a function that sums all the natural numbers in a list.\n   Implement this two different ways:\n   - as a recursive function, using the [Fixpoint] syntax.\n   - as a nonrecursive function, using [Definition] and an application of [fold_left].\n*)\n\n(* This is the recursive function using [Fixpoint] syntax *)\n\nFixpoint sum (lst: list nat) :nat :=\nmatch lst with\n| [] => 0\n| h::t => h+(sum t)\nend.\n\n(* This is the non-recursive definition using [fold_left]*)\n\n(* Kindly comment the previous definition of sum and uncomment the following definition if the following definition is to be used *)\n(* Definition sum (lst: list nat): nat := fold_left (fun x y => x+y) lst 0. *)\n\n(* Verification of the definition *)\n(*\n  Eval compute in sum [1;5;7].\n  Eval compute in sum [20;40;12;89].\n  Eval compute in sum [].\n  Eval compute in sum [0].\n*)\n(* \n  Outputs:\n     = 13\n     : nat\n     = 0\n     : nat\n     = 0\n     : nat\n*)\n\nInductive day : Type :=\n  | sun : day\n  | mon : day\n  | tue : day\n  | wed : day\n  | thu : day\n  | fri : day\n  | sat : day.\n\nDefinition next_day d :=\n  match d with\n  | sun => mon\n  | mon => tue\n  | tue => wed\n  | wed => thu\n  | thu => fri\n  | fri => sat\n  | sat => sun\n  end.\n\n(* Exercise: thu after wed [20 points].\n   State a theorem that says [thu] is the [next_day] after [wed].\n   Write down in natural language how you would informally explain\n   to a human why this theorem is true.\n   ---> Don't skip this \"natural language\" part of the exercise;\n        it's crucial to develop intuition before proceeding.\n   Prove the theorem in Coq.\n*)\nTheorem thu_after_wed: next_day wed = thu.\nProof.\n  simpl. trivial.\nQed.\n(* \n  Natural language Explanation:\n  We have next_day function which provides the case-wise value for each of the 7 days defined in [Inductive day].\n  For proving that [next_day] of [wed] is [thu]:\n    1.We will find [next_day] of [wed] by applying the function [next_day] to [wed]. // Simpl tactic helps us do this \n    2.We will check/verify that this is [thu] and thus [next_day] of [wed] is thu.  // trivial tactic helps us do this.\n*)\n\n\n(* Exercise: wed before thu [30 points].\n   Below is a theorem that says if the day after [d] is [thu], then\n   [d] must be [wed].\n   Write down in natural language how you would informally explain\n   to a human why this theorem is true.\n   ---> Don't skip this \"natural language\" part of the exercise;\n        it's crucial to develop intuition before proceeding.\n   Prove the theorem in Coq.  To do that, delete the [Abort]\n   command, which tells Coq to discard the theorem,\n   then fill in your own proof.\n*)\n\nTheorem wed_proceeds_thu : forall d : day, next_day d = thu -> d = wed.\n\n(*\n  Natural Language Explanation:\n  To prove that if [next_day] [d] is [thu], then [d] must be wed:\n    1. We will compute the [next_day] [d] for all the days defined in [Inductive day] \n        // introd d.destruct d helps us in verifying the theorem for each of the days by creating a subgoal for each day\n    2. We will verify that either \n        [next_day] [d] is either not thu //tactic discriminate helps us with this.\n      or [next_day] [d] is thu and [d] is wed. //tactic trivial helps us with this.\n // Note that the simplification of function application([next_day] [d]) is done by discriminate or trivial tactic.\n\n*)\nProof.\nintros d. destruct d\n; discriminate || trivial. \nQed.\n\n(*.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. trivial.\n  simpl. discriminate.\n  simpl. discriminate.\n  simpl. discriminate.\n*)\n\n(* Exercise: tl_opt [20 points].\n   Define a function [tl_opt] such that [tl_opt lst] return [Some t] if [t] is the tail of [lst],\n   or [None] if [lst] is empty.\n   We have gotten you started by providing an obviously incorrect definition, below; you should\n   replace the body of the function with a correct definition.\n*)\n\nDefinition tl_opt {A : Type} (lst : list A) : option (list A) := \n match lst with\n| []   => None\n| h::t => Some t\nend.\n\n(* Verification of Definition: *)\n(* Eval compute in tl_opt [1;2;3]. *)\n(* Output:  = Some [2; 3] : option (list nat) *)\n(* Eval compute in tl_opt []. *)\n(* Output: = None : option (list ?A) *)\n\n(* Here is a new tactic: [rewrite x].  If [H: x = e] is an assumption in the\n   proof state, then [rewrite H] replaces [x] with [e] in the subgoal being proved.  For example,\n   here is a proof that incrementing 1 produces 2: *)\n\nTheorem inc1_is_2 : forall n, n=1 -> (fun x => x+1) n = 2.\nProof.\n  intros n n_is_1. rewrite n_is_1. trivial.\nQed.\n\n(* Exercise: tl_opt correct [20 points].\n   Using [rewrite], prove the following theorems. For both, first explain in natural language\n   why the theorem should hold, before moving on to prove it with Coq. *)\n\nTheorem nil_implies_tlopt_none :\n  forall A : Type, forall lst : list A,\n  lst = nil -> tl_opt lst = None.\n\nProof.\nintros A lst lst_is_null.\nrewrite lst_is_null. simpl. trivial.\nQed.\n(*\n   Natural Language Explanation:\n    Proving \"forall A : Type, forall lst : list A,  lst = nil -> tl_opt lst = None\" is a straightforward problem:\n    We will assume lst=nil(where lst is a list of type A where A is a type)  // the intros helps us in achieving this.\n    and will prove tl_opt lst = None\n    To prove tl_opt lst = None, we will apply the function tl_opt to the list lst. From the definition of function,\n    lst will match with empty list and returns None. // simpl tactics helps in this\n    We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this \n*)\nTheorem cons_implies_tlopt_some :\n  forall {A : Type} (h:A) (t : list A) (lst : list A),\n  lst = h::t -> tl_opt lst = Some t.\nProof.\nintros A h t lst lst_is_ht.\nrewrite lst_is_ht. simpl. trivial.\nQed.\n\n(* \n  Natural Language Explanation: \n  Proving \"forall {A : Type} (h:A) (t : list A) (lst : list A), lst = h::t -> tl_opt lst = Some t.\" is a straightforward problem:\n    We will assume lst=h:t(given that h is of type A and t is a list of type A and A is a type)  // Intros helps us with this.\n    and will prove tl_opt lst = Some t.\n    We will apply the function tl_opt to the list lst. \n    From the definition of function,\n    lst will not match with empty list and will match with h::t and returns Some t . // simpl tactics helps in this\n    We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this \n*)\n\n\n(*\n  Ignore the below statements:\n\n  Let a := simpl mult2 0.\n  Print a.\n  Let b:= mult2 3110.\n  Print b.\n  \n  Theorem a: mult2 0 = 0.\n  Proof.\n  auto.\n  Qed.\n\n  Print a.\n\n  Theorem b: mult2 3110 = 6220.\n  Proof.\n  auto.\n  Qed.\n\n  Print b.\n*)\n\n", "meta": {"author": "nvvishnu", "repo": "CS6225-Programs-and-Proofs", "sha": "6faa7d6a880b2243551086b562a292303724032e", "save_path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs", "path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs/CS6225-Programs-and-Proofs-6faa7d6a880b2243551086b562a292303724032e/pset1/pset1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.9407897534090149, "lm_q1q2_score": 0.8301790948829639}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions\n    ([forall x, P]).\n *)\n\n\n(** In Coq, the type of things that can (potentially)\n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated\n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P].\n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n *)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat\n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.\n *)\n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining Propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?\n *)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other datatype.\n\n    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.\n\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n *)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q].\n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" Conjuctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop,\n                  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop,\n                  P /\\ Q -> Q.\nProof.\n  intros.\n  inversion H.\n  apply H1.\nQed.\n\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop,\n                       P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n  Case \"left\". apply HQ.\n  Case \"right\". apply HP.  Qed.\n\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop,\n                      P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split. split.\n  apply HP. apply HQ. apply HR.\nQed.\n\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                        (at level 95, no associativity)\n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n                        (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n                    (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n  Case \"->\". apply HBA.\n  Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n                     P <-> P.\nProof.\n  intros. 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 H I.\n  inversion H.\n  inversion I.\n  split.\n    intros. apply H2. apply H0. apply H4.\n    intros. apply H1. apply H3. apply H4.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n                      P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n  Case \"left\". apply or_intror. apply HP.\n  Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n                       P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n  Case \"left\". right. apply HP.\n  Case \"right\". left. apply HQ.  Qed.\n\n\n\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n                                      P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n  Case \"left\". split.\n  SCase \"left\". left. apply HP.\n  SCase \"right\". left. apply HP.\n  Case \"right\". split.\n  SCase \"left\". right. apply HQ.\n  SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n                                      (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros. inversion H as [[HP | HQ] [HP' | HR]].\n  Case \"l\".\n    SCase \"l\". left. apply HP.\n    SCase \"r\". left. apply HP.\n  Case \"r\".\n    SCase \"l\". left. apply HP'.\n    SCase \"r\".\n      right. split.\n        apply HQ.\n        apply HR.\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  intros. split. intros.\n  Case \"l\". apply or_distributes_over_and_1. apply H.\n  Case \"r\". apply or_distributes_over_and_2.\nQed.\n\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n                      andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n  Case \"b = true\". destruct c.\n  SCase \"c = true\". apply conj. reflexivity. reflexivity.\n  SCase \"c = false\". inversion H.\n  Case \"b = false\". inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n                            b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (bool_prop) *)\nTheorem andb_false : forall b c,\n                       andb b c = false -> b = false \\/ c = false.\nProof.\n  intros.\n  destruct b.\n  Case \"true\". destruct c.\n    SCase \"true\". inversion H.\n    SCase \"false\". right. reflexivity.\n\n  Case \"false\". left. reflexivity.\nQed.\n\nTheorem orb_prop : forall b c,\n                     orb b c = true -> b = true \\/ c = true.\nProof.\n  intros.\n  destruct b.\n  Case \"true\". left. reflexivity.\n  Case \"false\". destruct c.\n    right. reflexivity.\n    inversion H.\nQed.\n\nTheorem orb_false_elim : forall b c,\n                           orb b c = false -> b = false /\\ c = false.\nProof.\n  intros.\n  destruct b.\n  Case \"true\". inversion H.\n  Case \"false\". split.\n    SCase \"l\". reflexivity.\n    SCase \"r\". destruct c.\n      inversion H.\n      reflexivity.\nQed.\n\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := .\n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n                               False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := X.\n\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to\n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n                                           (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n                       P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n *)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n                           (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not. intros.\n  unfold not in H0.\n  apply H0. apply H. apply H1.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n                                    ~ (P /\\ ~P).\nProof.\n  intros. unfold not. intros.\n  apply H. apply H.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n                               ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H.\n(* But now what? There is no way to \"invent\" evidence for [~P]\n     from evidence for [P]. *)\nAbort.\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n                       ((P -> Q) -> P) -> P.\nDefinition classic := forall P:Prop,\n                        ~~P -> P.\nDefinition excluded_middle := forall P:Prop,\n                                P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n                                      ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop,\n                              (P -> Q) -> (~P\\/Q).\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable) *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).\nProof.\n  intros. unfold not. intros. apply H.\n  right. intros. apply H.\n  left. apply H0.\nQed.\n\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n                                b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n  unfold not in H.\n  apply ex_falso_quodlibet.\n  apply H. reflexivity.   Qed.\n\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** **** Exercise: 2 stars (false_beq_nat) *)\nTheorem false_beq_nat : forall n m : nat,\n                          n <> m ->\n                          beq_nat n m = false.\nProof.\n  intros n. induction n.\n  Case \"0\".\n    intros. unfold not in H. destruct m.\n    SCase \"0\". apply ex_falso_quodlibet. apply H. reflexivity.\n    SCase \"S m\". reflexivity.\n  Case \"S n\".\n    unfold not in IHn.\n    intros.\n    unfold not in H.\n    destruct m.\n    SCase \"0\". reflexivity.\n    SCase \"S m\".\n      simpl.\n      apply IHn. intros.\n      apply H. apply eq_S. apply H0.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_false) *)\nTheorem beq_nat_false : forall n m,\n                          beq_nat n m = false -> n <> m.\nProof.\n  intros n. unfold not. induction n.\n  Case \"0\".\n    intros. destruct m.\n    SCase \"0\". inversion H.\n    SCase \"S m\". intros. inversion H0.\n  Case \"S n\".\n    intros. destruct m.\n    SCase \"0\". intros. inversion H0.\n    SCase \"S m\".\n      intros. inversion H.\n      apply IHn in H2.\n      apply H2.\n      inversion H0. reflexivity.\nQed.\n\n(** [] *)\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n", "meta": {"author": "dandougherty", "repo": "software-foundations", "sha": "67a136e3ec1360bd92f974c251958af5ffc83d09", "save_path": "github-repos/coq/dandougherty-software-foundations", "path": "github-repos/coq/dandougherty-software-foundations/software-foundations-67a136e3ec1360bd92f974c251958af5ffc83d09/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.9425067195846918, "lm_q1q2_score": 0.8301571734321752}}
{"text": "Theorem or_commut : forall P Q : Prop,  P \\/ Q  -> Q \\/ P.\nProof.  \n  intros P Q H.\n  destruct H as [H1 | H2].\n  + right. apply H1.\n  + left. apply H2.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  unfold not.\n  intros P [H1 H2].\n  apply H2.\n  apply H1.\nQed.\n\n Theorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  split.\n  + destruct H as [H1 | H2].\n     - left. apply H1.\n     - destruct H2 as [H21 H22].\n       right. apply H21.\n  + destruct H as [H1 | H2].\n     - left. apply H1.\n     - destruct H2 as [H21  H22].\n       right. apply H22.\nQed.\n\nTheorem or_distributes_over_and' : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros.\n  destruct H as [H1 H2].\n  destruct H1 as [H11 | H12].\n  + destruct H2 as [H21 | H22].\n     - left. apply H11.\n     - left. apply H11.\n  + destruct H2 as [H21 | H22].\n     - left. apply H21.\n     - right. split.\n       * apply H12.\n       * apply H22.\nQed.\n\n\n\n", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8301571601088283}}
{"text": "Require Import Arith.\nRequire Import ArithRing Ring.\nRequire Import Lia.\nImport Nat.\n\n(*\n  \u8fd9\u4e00\u6b21\u6211\u4eec\u7740\u91cd\u4ecb\u7ecd\u5982\u4f55\u7528Coq\u8bc1\u660e\u6d89\u53ca\u5230\u591a\u9879\u5f0f\u7684\u5b9a\u7406;\n  \u9996\u5148\u6211\u4eec\u53ef\u4ee5\u5b9a\u4e49\u4e00\u4e2a\u7b80\u5355\u7684\u9012\u5f52\u51fd\u6570\u7528\u4e8e\u8ba1\u7b97\u2211n.\n *)\n\nFixpoint sum (n : nat) :=\n  match n with\n  | 0 => 0\n  | S n' => n + sum n' \n  end.\n\n(*\u60f3\u8981\u8bc1\u660e2 * sum n = n * (n + 1)*)\n\nTheorem sum_1 : forall n : nat,\n    2 * sum n = n * (n + 1).\nProof.\n  induction n.\n  - (*n = 0*)\n    simpl. reflexivity.\n  - simpl. ring_simplify.\n    rewrite IHn.\n    ring_simplify. reflexivity.\nQed.\n\n(*\n  \u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4e0d\u65ad\u4f7f\u7528\u4ea4\u6362\u5f8b\u7ed3\u5408\u5f8b\u548c\u5206\u914d\u5f8b\u6765\u6539\u5199\u5f85\u8bc1\u660e\u7684\u9879\uff0c\n  \u4f46\u8fd9\u4e48\u505a\u662f\u975e\u5e38\u7e41\u6742\u4e14\u65e0\u8da3\u7684\u3002\n  \u90a3\u4e48\u6709\u4ec0\u4e48\u624b\u6bb5\u80fd\u591f\u5e2e\u52a9\u6211\u4eec\u81ea\u52a8\u5730\u5bf9\u5f85\u8bc1\u9879\u4f7f\u7528\u4e0a\u8ff0\u5b9a\u7406\u6539\u5199\u5462\uff1f\n  \u5de7\u5408\u7684\u662f\uff0c\u62bd\u8c61\u4ee3\u6570\u4e2d\u7684\u73af\u7ed3\u6784\u975e\u5e38\u5b8c\u7f8e\u5730\u5951\u5408\u6211\u4eec\u7684\u8981\u6c42\u3002\n  Coq\u63d0\u4f9b\u7684ring\u7b56\u7565\u80fd\u591f\u5bf9\u6240\u6709\u5728\u73af\u6216\u534a\u73af\u4e0a\u7684\u591a\u9879\u5f0f\u547d\u9898\u8fdb\u884c\u5316\u7b80,\n  \u90a3\u4e48\uff0c\u4ec0\u4e48\u662f\u73af\uff1f\n  \u4e0b\u9762\u7684\u4ee3\u7801\u7ed9\u51fa\u4e86\u4e00\u4e2a\u73af\u6216\u534a\u73af\u7ed3\u6784\u9700\u8981\u6ee1\u8db3\u7684\u6027\u8d28\u3002\n *)\n\nRecord ring_theory : Prop := mk_rt {\n  Radd_0_l    : forall x, 0 + x == x;\n  Radd_sym    : forall x y, x + y == y + x;\n  Radd_assoc  : forall x y z, x + (y + z) == (x + y) + z;\n  Rmul_1_l    : forall x, 1 * x == x;\n  Rmul_sym    : forall x y, x * y == y * x;\n  Rmul_assoc  : forall x y z, x * (y * z) == (x * y) * z;\n  Rdistr_l    : forall x y z, (x + y) * z == (x * z) + (y * z);\n  Rsub_def    : forall x y, x - y == x + -y;\n  Ropp_def    : forall x, x + (- x) == 0\n}.\n\nRecord semi_ring_theory : Prop := mk_srt {\n  SRadd_0_l   : forall n, 0 + n == n;\n  SRadd_sym   : forall n m, n + m == m + n ;\n  SRadd_assoc : forall n m p, n + (m + p) == (n + m) + p;\n  SRmul_1_l   : forall n, 1*n == n;\n  SRmul_0_l   : forall n, 0*n == 0;\n  SRmul_sym   : forall n m, n*m == m*n;\n  SRmul_assoc : forall n m p, n*(m*p) == (n*m)*p;\n  SRdistr_l   : forall n m p, (n + m)*p == n*p + m*p\n}.\n\n(*\n  ring\u7b56\u7565\u4f1a\u5229\u7528\u4e0a\u8ff0\u7684\u6027\u8d28\u5bf9\u5f85\u8bc1\u9879\u8fdb\u884c\u5316\u7b80\uff0c\n  \u8fd9\u4e2a\u8fc7\u7a0b\u662f\u81ea\u52a8\u5316\u7684\uff0c\u800c\u4e14\u5316\u7b80\u7684\u6548\u679c\u975e\u5e38\u597d\u3002\n *)\n\nFixpoint summation (n : nat) :=\n  match n with\n  | 0 => 0\n  | S n' => n ^ 2 + summation n' \n  end.\n(*\u2211 n^2*)\n\nTheorem sum_2 : forall n : nat,\n    6 * summation n = n * (2 * n + 1) *  (n + 1).\nProof.\n  induction n.\n  -simpl. reflexivity.\n  -simpl. ring_simplify.\n   rewrite IHn. ring.\nQed.\n\n(*\n  \u6211\u4eec\u53ef\u4ee5\u518d\u4e3e\u51e0\u4e2aring\u5e94\u7528\u7684\u4f8b\u5b50.\n *)\n\nFixpoint sum_3 (n : nat) :=\n  match n with\n  | 0 => 0\n  | S n' => n ^ 3 + sum_3 n'\n  end.\n\nTheorem sum_three : forall n : nat,\n    4 * sum_3 n = n * n * (n + 1) * (n + 1).\nProof.\n  induction n.\n  -simpl. reflexivity.\n  - simpl. ring_simplify.\n    rewrite IHn. ring.\nQed.\n\n(*\n  \u7136\u800cring\u5e76\u975e\u662f\u4e07\u80fd\u7684\uff0c\u5b83\u53ea\u80fd\u5904\u7406\"+\"\u548c\"*\"\u8fd0\u7b97\uff0c\n  \u4e00\u65e6\u8bc1\u660e\u5f0f\u4e2d\u51fa\u73b0\"-\"\uff0cring\u4e5f\u65e0\u53ef\u5948\u4f55.\n *)\n\nFixpoint summa (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n * (2 * n - 1) + summa n'\n  end.\n\n(*\u2211n*(2*n-1)*)\n\nTheorem summa_formula : forall n,\n  6 * summa n = n * (n + 1) * (4 * n - 1).\nProof.\n  induction n.\n  -auto.\n  -simpl. ring_simplify.\n   rewrite IHn. \n   destruct n.\n   +lia.\n   +lia.\nQed.\n\n", "meta": {"author": "Whu-Lambda", "repo": "Lambda-Cube", "sha": "6845929d9f816a350e65b33078657b14ae940693", "save_path": "github-repos/coq/Whu-Lambda-Lambda-Cube", "path": "github-repos/coq/Whu-Lambda-Lambda-Cube/Lambda-Cube-6845929d9f816a350e65b33078657b14ae940693/\u7b2c\u4e00\u6b21\u5206\u4eab\u4f1a/Coq \u5c0f\u8bfe\u5802/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.829426978649873}}
{"text": "Require Import ZArith.\nRequire Import Coq.Lists.List.\nRequire Import LiterateCoq.Tactics.\nRequire Coq.Program.Wf.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n\nInductive Expr : Set := \n| Num : Z -> Expr\n| Plus : Expr -> Expr -> Expr \n| Minus : Expr -> Expr -> Expr.\n\nFixpoint eval_Expr (e : Expr) : Z := \n  match e with\n  | Num n => n                               \n  | Plus e1 e2 => eval_Expr e1 + eval_Expr e2\n  | Minus e1 e2 => eval_Expr e1 - eval_Expr e2\n  end.\n\nInductive Op : Set :=\n| Push : Z -> Op\n| Add : Op\n| Sub : Op\n| OpCount : Op.\n              \nFixpoint compile_Expr (e : Expr) : list Op :=\n  match e with\n  | Num n => [Push n]\n  | Plus e1 e2 => compile_Expr e1 ++ compile_Expr e2 ++ [Add]\n  | Minus e1 e2 => compile_Expr e1 ++ compile_Expr e2 ++ [Sub]\n  end.\n\nFixpoint eval_Op (s : list Z) (ops : list Op) : option Z :=\n  match (ops, s) with\n  | ([], [n]) => Some n\n  | (Push z :: rest, _) => eval_Op (z :: s) rest \n  | (Add :: rest, n2 :: n1 :: ns) => eval_Op (n1 + n2 :: ns)%Z rest\n  | (Sub :: rest, n2 :: n1 :: ns) => eval_Op (n1 - n2 :: ns)%Z rest\n  | (OpCount :: rest, _) => eval_Op (Z.of_nat (length rest) :: s) rest\n  | _ => None\n  end.\n\nLemma eval_step : forall a : Expr, forall s : list Z, forall xs : list Op,\n      eval_Op s (compile_Expr a ++ xs) = eval_Op (eval_Expr a :: s) xs.\nProof.\n  hint_rewrite List.app_assoc_reverse.\n  induction a; intros; iauto; simpl;\n  hint_rewrite IHa2, IHa1;\n  iauto'.\nQed.\n\nLemma eval_step' : forall a : Expr, forall s : list Z,\n      eval_Op s (compile_Expr a) = eval_Op (eval_Expr a :: s) [].\nProof.\n  intros.\n  assert (H: compile_Expr a = compile_Expr a ++ []) by (rewrite app_nil_r; reflexivity); rewrite H; clear H.\n  hint eval_step.\n  iauto.\nQed.\n  \nTheorem compiler_correctness : forall a : Expr,\n    eval_Op [] (compile_Expr a) = Some (eval_Expr a).\nProof.\n  hint_rewrite eval_step.\n  hint_simpl.\n  induction a; iauto'.\nQed.\n  \nDefinition equiv_Expr (e1 e2 : Expr) : Prop := eval_Expr e1 = eval_Expr e2.\nDefinition equiv_Op (p1 p2 : list Op) : Prop := eval_Op [] p1 = eval_Op [] p2.\n\nInductive ExprCtxt : Set := \n| Hole : ExprCtxt\n| Plus1 : ExprCtxt -> Expr -> ExprCtxt\n| Plus2 : Expr -> ExprCtxt -> ExprCtxt \n| Minus1 : ExprCtxt -> Expr -> ExprCtxt\n| Minus2 : Expr -> ExprCtxt -> ExprCtxt .\n\nFixpoint link_Expr (c : ExprCtxt) (e : Expr) : Expr :=\n  match c with\n  | Hole => e\n  | Plus1 c' e' => Plus (link_Expr c' e) e'\n  | Plus2 e' c' => Plus e' (link_Expr c' e)\n  | Minus1 c' e' => Minus (link_Expr c' e) e'\n  | Minus2 e' c' => Minus e' (link_Expr c' e)\n  end.\n\nDefinition ctxtequiv_Expr (e1 e2 : Expr) : Prop :=\n  forall c : ExprCtxt, eval_Expr (link_Expr c e1) = eval_Expr (link_Expr c e2).\n\nInductive OpCtxt : Set :=\n| PushAdd : Z -> OpCtxt\n| PushSub : Z -> OpCtxt\n| Empty : OpCtxt.\n\nDefinition link_Op  (c : OpCtxt) (p : list Op) : list Op :=\n  match c with\n  | PushAdd n => Push n :: p ++ [Add]\n  | PushSub n => Push n :: p ++ [Sub]\n  | Empty => p\n  end.\n\n\nDefinition ctxtequiv_Op (p1 p2 : list Op) : Prop :=\n  forall c : OpCtxt, eval_Op [] (link_Op c p1) = eval_Op [] (link_Op c p2).\n\nLemma equivalence_reflection :\n  forall e1 e2 : Expr,\n  forall p1 p2 : list Op,\n  forall comp1 : compile_Expr e1 = p1,\n  forall comp2 : compile_Expr e2 = p2,\n  forall eqtarget : ctxtequiv_Op p1 p2,\n    ctxtequiv_Expr e1 e2.\nProof.\n  unfold ctxtequiv_Expr, ctxtequiv_Op in *.\n  intros.\n  induction c; simpl; try solve [hint_rewrite IHc; iauto];\n    (* NOTE(dbp 2018-04-16): Only the base case, for Hole, remains *)\n    [idtac].\n  (* NOTE(dbp 2018-04-16): In the hole case, we specialize the target ctxt equiv hypothesis to empty *)\n  specialize (eqtarget Empty);\n    simpl in eqtarget; repeat rewrite app_nil_r in eqtarget.\n  unfold link_Op in eqtarget.\n  \n  (* NOTE(dbp 2018-04-16): At this point, we know e1 -> p1, e2 -> p2, & p1 \u2248 p2,\n  and want e1 \u2248 e2, which follows from compiler correctness *)\n  rewrite <- comp1 in eqtarget. rewrite <- comp2 in eqtarget.\n  repeat rewrite compiler_correctness in eqtarget.\n\n  inversion eqtarget.\n  reflexivity.\nQed.\n\nLemma equivalence_preservation :\n  forall e1 e2 : Expr,\n  forall p1 p2 : list Op,\n  forall comp1 : compile_Expr e1 = p1,\n  forall comp2 : compile_Expr e2 = p2,\n  forall eqsource : ctxtequiv_Expr e1 e2,\n    ctxtequiv_Op p1 p2.\nProof.\nAbort.\n\nExample src_equiv : ctxtequiv_Expr (Plus (Num 1) (Num 1)) (Num 2).\nProof.\n  unfold ctxtequiv_Expr.\n  induction c; simpl; try rewrite IHc; iauto.\nQed.\n\nExample target_not_equiv :\n  eval_Op [] (OpCount :: compile_Expr (Plus (Num 1) (Num 1)) ++ [Add]) <>\n  eval_Op [] (OpCount :: compile_Expr (Num 2) ++ [Add]).\nProof.\n  simpl.\n  congruence.\nQed.\n\nDefinition backtranslate (c : OpCtxt) : ExprCtxt :=\n  match c with\n  | PushAdd n => Plus2 (Num n) Hole\n  | PushSub n => Minus2 (Num n) Hole\n  | Empty => Hole\n  end.\n\nLemma back_translation_equiv :\n  forall c : OpCtxt,\n  forall p : list Op,\n  forall e : Expr,\n  forall c' : ExprCtxt, \n    compile_Expr e = p ->\n    backtranslate c = c' ->\n    eval_Op [] (link_Op c p) = Some (eval_Expr (link_Expr c' e)).\nProof.\n  hint_rewrite eval_step, eval_step'.\n  intros.\n  match goal with\n  | [ c : OpCtxt |- _] => destruct c\n  end; \n    match goal with\n    | [ H : backtranslate _ = _ |- _] => invert H\n    end; simpl; iauto. \nQed.\n\n \nLemma equivalence_preservation :\n  forall e1 e2 : Expr,\n  forall p1 p2 : list Op,\n  forall comp1 : compile_Expr e1 = p1,\n  forall comp2 : compile_Expr e2 = p2,\n  forall eqsource : ctxtequiv_Expr e1 e2,\n    ctxtequiv_Op p1 p2.\nProof.\n  unfold ctxtequiv_Expr, ctxtequiv_Op in *.\n  intros.\n\n  remember (backtranslate c) as c'.\n  destruct c; iauto;\n\n  erewrite back_translation_equiv with (e := e1) (c' := c'); iauto;\n  erewrite back_translation_equiv with (e := e2) (c' := c'); iauto;\n  specialize (eqsource c'); simpl in *; congruence.\nQed.", "meta": {"author": "dbp", "repo": "howtoprovefullabstraction", "sha": "cfd7110e19e419a679d5e4b7d38b5cb3e582bd60", "save_path": "github-repos/coq/dbp-howtoprovefullabstraction", "path": "github-repos/coq/dbp-howtoprovefullabstraction/howtoprovefullabstraction-cfd7110e19e419a679d5e4b7d38b5cb3e582bd60/src/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.8292109186553867}}
{"text": "\n(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  \n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros n B. simpl. apply b_sum with (n:=n) (m:=n+0).\n    apply B.\n    apply b_sum.\n      apply B.\n      apply b_0.\n  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros n H.\n  apply g_plus3. apply g_plus5. apply g_plus5. apply H. Qed.\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\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\n\n(** **** Exercise: 2 stars (gorgeous_sum)  *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m Hn Hm.\n  induction Hn as [ | n' | n'].\n    simpl. apply Hm.\n    apply g_plus3 with (n:=n'+m). apply IHHn.\n    apply g_plus5 with (n:=n'+m). apply IHHn.\n  Qed.\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\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *) \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(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  intros n m Hn Hm.\n  induction Hn.\n    Case \"n = 0\". simpl. apply Hm.\n    Case \"n = S n\". simpl. apply ev_SS with (n:=n+m). apply IHHn.\n  Qed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we \n   can _look_ at that evidence for more information. For example, consider \n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead \n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice)  *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H.\n  inversion H.\n  inversion H1.\n  apply H3.\n  Qed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However, \n   we can define inductive predicates about any type of data. For example, \n   suppose we would like to characterize lists of _even_ length. We can \n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof. \n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H. \n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil. \n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l. \n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n    \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(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - 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(** **** 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(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n\n(* $Date: 2014-09-18 22:39:20 +0900 (2014\u5e7409\u670818\u65e5 (\u6728)) $ *)\n\n\n", "meta": {"author": "tyage", "repo": "coq-practice", "sha": "bb6e60c7cbd87bebea786abc58821d22ce822eba", "save_path": "github-repos/coq/tyage-coq-practice", "path": "github-repos/coq/tyage-coq-practice/coq-practice-bb6e60c7cbd87bebea786abc58821d22ce822eba/task/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8288909502812937}}
{"text": "Inductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\nNotation \"[ ]\" := nil.\nNotation \"h :: t\" := (cons h t)\n                     (at level 60, right associativity).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O   => []\n  | S c => n :: (repeat n c)\n  end.\n\nFixpoint length xs : nat :=\n  match xs with\n  | []    => O\n  | h::t => S (length t)\n  end.\n\nFixpoint concat xs ys : natlist :=\n  match xs with\n  | []   => ys\n  | h::t => h :: (concat t ys)\n  end.\n\nNotation \"xs ++ ys\" := (concat xs ys)\n                       (at level 60, right associativity).\n\nAxiom N0 : nat.\nAxiom L0 : natlist.\n\nDefinition head xs : nat :=\n  match xs with\n  | []   => N0\n  | h::_ => h\n  end.\n\nDefinition tail xs : natlist :=\n  match xs with\n  | []   => []\n  | _::t => t\n  end.\n\nFixpoint nonZeros xs : natlist :=\n  match xs with\n  | []   => []\n  | h::t => match h with\n            | O   => nonZeros t\n            | S _ => h :: nonZeros t\n            end\n  end.\n\nFixpoint notb b : bool :=\n  match b with | true => false | false => true end.\n\nFixpoint eqb m n : bool :=\n  match (m,n) with\n  | (O,O) => true\n  | (S m,S n) => eqb m n\n  | _ => false\n  end.\n\nFixpoint gtb m n : bool :=\n  match (m,n) with\n  | (O,_) => false\n  | (_,O) => true\n  | (S m,S n) => gtb m n\n  end.\n\nFixpoint isEven n : bool :=\n  match n with\n  | O    => true\n  | S n' => notb (isEven n')\n  end.\n\nFixpoint oddMembers xs : natlist :=\n  match xs with\n  | []   => []\n  | h::t => if isEven h\n            then oddMembers t\n            else h :: oddMembers t\n  end.\n\nDefinition countOddMembers xs : nat :=\n  length (oddMembers xs).\n\nFixpoint alternate xs ys : natlist :=\n  match (xs,ys) with\n  | ([],ys) => ys\n  | (xs,[]) => xs\n  | (x::xs,y::ys) => x :: y :: (alternate xs ys)\n  end.\n\nFixpoint count n xs : nat :=\n  match xs with\n  | []   => O\n  | h::t => if eqb n h\n            then 1 + count n t\n            else count n t\n  end.\n\nDefinition bag := natlist.\n\nDefinition sum : bag -> bag -> bag := concat.\n\nDefinition add : nat -> bag -> bag := cons.\n\nDefinition member : nat -> bag -> bool := fun n b => gtb (count n b) 0.\n\nTheorem nil_concat : forall l, [] ++ l = l.\nProof.\n  simpl. reflexivity.\nQed.\n\nTheorem nil_concat_right : forall l, l ++ [] = l.\nProof.\n  induction l as [| x l'].\n    simpl. reflexivity.\n    simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem tail_length_pred : forall l, pred (length l) = length (tail l).\nProof.\n  intros l.\n  destruct l as [| x l'].\n    simpl. reflexivity.\n    simpl. reflexivity.\nQed.\n\nFixpoint reverse l : natlist :=\n  match l with\n  | []   => []\n  | h::t => reverse t ++ [h]\n  end.\n\nTheorem concat_length : forall l l', length (l ++ l') = length l + length l'.\nProof.\n  intros.\n  induction l. destruct l'.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem add_1_is_S : forall n, S n = n + 1.\nProof.\n  intro n. simpl.\n  induction n.\n    simpl. reflexivity.\n    simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem reverse_preserves_length : forall l, length l = length (reverse l).\nProof.\n  intros l.\n  induction l.\n    simpl. reflexivity.\n    simpl. rewrite IHl.\n    rewrite concat_length.\n    simpl. rewrite add_1_is_S. reflexivity.\nQed.\n\nTheorem concat_associative : forall a b c, (a ++ b) ++ c = a ++ b ++ c.\nProof.\n  intros.\n  induction a. destruct b. destruct c.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHa. reflexivity.\nQed.\n\nTheorem reverse_distributes_concat :\n  forall l l', reverse (l ++ l') = reverse l' ++ reverse l.\nProof.\n  intros.\n  induction l. destruct l'.\n    simpl. reflexivity.\n    simpl. rewrite nil_concat_right. reflexivity.\n    simpl. rewrite IHl. rewrite concat_associative. reflexivity.\nQed.\n\nTheorem reverse_append : forall l n, reverse (l ++ [n]) = n :: reverse l.\nProof.\n  intros.\n  induction l.\n    simpl. reflexivity.\n    simpl. rewrite IHl. simpl. reflexivity.\nQed.\n\nTheorem reverse_prepend : forall l n, reverse (n :: l) = reverse l ++ [n].\nProof.\n  intros.\n  destruct l as [| h t].\n    simpl. reflexivity.\n    simpl. reflexivity.\nQed.\n\nTheorem reverse_involutive : forall l, reverse (reverse l) = l.\nProof.\n  intros.\n  induction l.\n    simpl. reflexivity.\n    simpl. rewrite reverse_append. rewrite IHl. reflexivity.\nQed.\n\nFixpoint andb b b' : bool :=\n  match (b,b') with\n  | (true,true) => true\n  | _ => false\n  end.\n\nFixpoint eqb_natlist l l' : bool :=\n  match l,l' with\n  | [],[] => true\n  | h::t,[] => false\n  | [],h::t => false\n  | h::t,h'::t' => andb (eqb h h') (eqb_natlist t t')\n  end.\n\nFixpoint leb m n : bool :=\n  match m,n with\n  | _,O => false\n  | O,S _ => true\n  | S m, S n => leb m n\n  end.\n\nTheorem count_member_nonzero :\n  forall s, leb 0 (count 1 (1::s)) = true.\nProof.\n  intros.\n  simpl. reflexivity.\nQed.\n\nTheorem concat_count : forall x l l', count x l + count x l' = count x (l ++ l').\n  intros.\n  induction l. destruct l'.\n    simpl. reflexivity.\n    simpl. reflexivity. simpl.\n    case (eqb x n).\n      simpl. rewrite IHl. reflexivity.\n      simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem rev_eq_natlist : forall l l', l = l' -> reverse l = reverse l'.\nProof.\n  intros.\n  induction l. destruct l'.\n    simpl. reflexivity.\n    simpl. rewrite <- reverse_prepend.\n    rewrite <- H. simpl. reflexivity.\n    rewrite H. reflexivity.\nQed.\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/natlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8918110526265554, "lm_q1q2_score": 0.8288852179058092}}
{"text": "\n(*Inductive predicates*)\nInductive even : nat -> Prop :=\n| even0 : even 0\n| evenS : forall x:nat, even x -> even (S (S x)).\n\nLemma even_0: even 0.\nProof.\n    apply even0.\nQed.\n\nLemma even_20: even 20.\nProof.\n    repeat (apply evenS).\n    apply even0.\nQed.\n\nRequire Import Arith.\n\nLemma even_mult : forall x, even x -> exists y, x = 2*y.\nProof.\n    intros x H.\n    induction H.\n    exists 0.\n    ring.\n    destruct IHeven as [y Heq].\n    rewrite Heq.\n    exists (S y).\n    ring.\nQed.\n\nLemma not_even_1 : ~even 1.\nProof.\n    intros even1.\n    inversion even1.\nQed.\n\nLemma even_inv : forall x, even (S (S x)) -> even x.\nProof.\n    intros x H.\n    inversion H.\n    assumption.\nQed.\n\n\n\n\n    ", "meta": {"author": "James-Oswald", "repo": "Coq-In-A-Hurry", "sha": "d9ba73090affe7d7c8a324bf726f709a7b949a15", "save_path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry", "path": "github-repos/coq/James-Oswald-Coq-In-A-Hurry/Coq-In-A-Hurry-d9ba73090affe7d7c8a324bf726f709a7b949a15/Chapter9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.8288700151854256}}
{"text": "From LF Require Export Basics.\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem multi_0_r : forall n:nat,\n    n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite plus_n_O.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_n_sm : forall n m:nat,\n    S(n + m) = n + (S m).\nProof.\n  intros.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\n  \nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_n_sm.\n    reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n    (n + m) = (m + n).\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - simpl.\n    rewrite <- plus_n_O.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_n_sm.\n    reflexivity.\nQed.\n\n\n\n\n\n\n", "meta": {"author": "StarGazerM", "repo": "my-foolish-code", "sha": "2991997f9be4523bf190ef4143df8b0d89e528cf", "save_path": "github-repos/coq/StarGazerM-my-foolish-code", "path": "github-repos/coq/StarGazerM-my-foolish-code/my-foolish-code-2991997f9be4523bf190ef4143df8b0d89e528cf/lf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545318852121, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.8287603026248394}}
{"text": "Require Import Setoid.\n\nClass Group (A : Type) := GroupDef {\n  zero     : A;\n  op       : A -> A -> A;\n  inv      : A -> A;\n  l_op_id  : forall x: A, op zero x = x;\n  r_op_id  : forall x: A, op x zero = x;\n  l_op_inv : forall x: A, op (inv x) x = zero;\n  r_op_inv : forall x: A, op x (inv x) = zero;\n  op_assoc : forall x y z: A, op (op x y) z = op x (op y z);\n}.\n\nDefinition sub {A: Type} `{Group A} (x y: A) := op x (inv y).\n\nLemma op_sub {A: Type} `{Group A} (x y : A) : op (sub x y) y = x.\nProof.\n  unfold sub. rewrite op_assoc. rewrite l_op_inv. rewrite r_op_id. auto.\nQed.\n\nLemma sub_op {A: Type} `{Group A} (x y : A) : sub (op x y) y = x.\nProof.\n  unfold sub. rewrite op_assoc. rewrite r_op_inv. rewrite r_op_id. auto.\nQed.\n\nLemma group_equation_l_simp {A: Type} `{Group A} (a b c : A) : op a b = op a c -> b = c.\nProof.\n  intro H0. assert (op (inv a) (op a b) = op (inv a) (op a c)).\n  - rewrite H0. auto.\n  - rewrite <- op_assoc, <- op_assoc, l_op_inv, l_op_id, l_op_id in H1. auto.\nQed.\n\nLemma group_equation_r_simp {A: Type} `{Group A} (a b c : A) : op a c = op b c -> a = b.\nProof.\n  intro H0. assert (op (op a c) (inv c) = op (op b c) (inv c)).\n  - rewrite H0. auto.\n  - rewrite op_assoc, op_assoc, r_op_inv, r_op_id, r_op_id in H1. auto.\nQed.\n\nLemma sub_zero_uniq {A: Type} `{Group A} (x y: A) : sub x y = zero -> x = y.\nProof.\n  unfold sub. rewrite <- (r_op_inv y). intros H0. \n  apply group_equation_r_simp with (c := inv y). auto.\nQed.\n\nLemma group_op_inv {A: Type} `{Group A} (x y: A) : inv (op x y) = op (inv y) (inv x).\nProof.\n  unfold sub. apply group_equation_l_simp with (a := y). \n  rewrite <- op_assoc, r_op_inv, l_op_id.\n  apply group_equation_l_simp with (a := x).\n  rewrite r_op_inv, <- op_assoc, r_op_inv. auto.\nQed.\n\n\n\n\n\nClass Field (A : Type) `{Group A} := FieldDef {\n  one       : A;\n  mul       : A -> A -> A;\n  mul_inv   : A -> A;\n  op_comm   : forall x y: A, op x y = op y x;\n  mul_comm  : forall x y: A, mul x y = mul y x;\n  l_mul_id  : forall x: A, mul one x = x;\n  r_mul_id  : forall x: A, mul x one = x;\n  l_mul_inv : forall x: A, mul (mul_inv x) x = one;\n  r_mul_inv : forall x: A, mul x (mul_inv x) = one;\n  mul_assoc : forall x y z: A, mul (mul x y) z = mul x (mul y z);\n  distr     : forall x y z: A, mul x (op y z) = op (mul x y) (mul x z);\n}.\n\nLemma field_zero_mul_l {A: Type} `{Field A} (x: A) : mul x zero = zero.\nProof.\n  assert (zero = op (mul x (op zero one)) (inv x)). {\n    rewrite l_op_id, r_mul_id, r_op_inv. auto.\n  } \n  rewrite H1 at 2. rewrite distr, r_mul_id, op_assoc, r_op_inv, r_op_id. auto.\nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/Master/Lib/Algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.8286895181564254}}
{"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 Basics.\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  - (* n = 0 *)\n    reflexivity. (* so far so good... *)\n  - (* n = S n' *)\n    simpl.       (* ...but here we are stuck again *)\nAbort.\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n\n\nTheorem 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\n\nTheorem 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\nTheorem 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\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  intros. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity.  Qed.\n\n\nTheorem double_plus_2:\n  forall m n: nat, double m + double n = double (m + n).\n\nProof. (*FILL IN HERE *)\n  intros. induction m as [|n' IHn'].\n  reflexivity.\n  simpl. rewrite IHn'. reflexivity. Qed.\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. induction n as [|n' IHn'].\n  reflexivity. \n  rewrite IHn'.\n  simpl.\n  rewrite negb_involutive.\n  reflexivity.\n  Qed.\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/CA03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.9390248216946319, "lm_q1q2_score": 0.8286216641489506}}
{"text": "(*|\n###################################\nHow to give a counterxample in Coq?\n###################################\n\n:Link: https://stackoverflow.com/q/13862940\n|*)\n\n(*|\nQuestion\n********\n\nIs it possible to give a counterexample for a statement which doesn't\nhold in general? Like, for example that the all quantor does not\ndistribute over the connective ``or``. How would you state that to\nbegin with?\n|*)\n\nParameter X : Set.\nParameter P : X -> Prop.\nParameter Q : X -> Prop.\n\n(* This holds in general *)\nTheorem forall_distributes_over_and :\n  (forall x : X, P x /\\ Q x) -> (forall x : X, P x) /\\ (forall x : X, Q x).\nProof.\n  intro H. split. apply H. apply H.\nQed.\n\n(* This doesn't hold in general *)\nTheorem forall_doesnt_distributes_over_or :\n  (forall x : X, P x \\/ Q x) -> (forall x : X, P x) \\/ (forall x : X, Q x).\nAbort.\n\n(*|\nAnswer (Ptival)\n***************\n\nHere is a quick and dirty way to prove something similar to what you\nwant:\n|*)\n\nTheorem forall_doesnt_distributes_over_or :\n  ~ (forall X P Q, (forall x : X, P x \\/ Q x) ->\n                   (forall x : X, P x) \\/ (forall x : X, Q x)).\nProof.\n  intros H.\n  assert (X : forall x : bool, x = true \\/ x = false).\n  - destruct x; intuition.\n  - specialize (H _ (fun b => b = true) (fun b => b = false) X).\n    destruct H as [H | H].\n    now specialize (H false).\n    now specialize (H true).\nQed.\n\n(*|\nI have to quantify ``X``, ``P`` and ``Q`` inside the negation in order\nto be able to provide the one I want. You couldn't quite do that with\nyour ``Parameter``\\ s as they somehow fixed an abstract ``X``, ``P``\nand ``Q``, thus making your theorem potentially true.\n|*)\n\n(*|\nAnswer (Yves)\n*************\n\nIn general, if you want to produce a counterexample, you can state the\nnegation of the formula and then prove that this negation is\nsatisfied.\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-give-a-counterxample-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8286017356615824}}
{"text": "Definition sig_extract (A:Set) (P:A -> Prop) (x:sig P) : A :=\n  match x with\n  | exist a Ha => a\n  end.\n\nTheorem sig_extract_ok :\n forall (A:Set) (P:A -> Prop) (y:sig P), P (sig_extract A P y).\nProof.\n intros A P y; case y; simpl; trivial.\nQed.\n\nRequire Import ZArith.\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_pair' : forall a b:Z, 0 < b -> Z * Z.\n intros a b Hb.\n apply (sig_extract _ _ (div_pair a b Hb)).\nDefined.\n\nTheorem div_pair'_ok :\n forall (a b:Z) (H:0 < b),\n   let p := div_pair' a b H in\n   a = fst p * b + snd p /\\ 0 <= snd p < b.\n intros a b H.\n pattern (div_pair' a b H).\n unfold div_pair'; apply sig_extract_ok.\nQed.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/progav/SRC/extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.8286017268533131}}
{"text": "(** Exercise sheet for lecture 4: Tactics in Coq.\n\nWritten by Ralph Matthes.\n *)\n\n(** * Exercise 1\nFormalize the solutions of exercise 1 of Lecture 1.\n\n[[\nFor each of the following types, write down an element of that type, if it has one. If it does not have any elements, you should establish that this is the case. But first think how this can be done in type theory! It ought to be just another construction.\n\n1.    A \u00d7 (B + C) \u2192 A \u00d7 B + A \u00d7 C, given types A, B, C\n2.    (A \u2192 A) \u2192 (A \u2192 A), given type A (for extra credit, write down five elements of this type)\n3.    Id_nat (0, succ 0)\n4.    \u2211 (A : Universe) (A \u2192 empty) \u2192 empty\n5.    \u220f (n : nat), \u2211 (m : nat), (n = 2 * m) + (n = 2 * m + 1), assuming you have got arithmetic\n6.    (\u2211 (x : A) B \u00d7 P x) \u2192 B \u00d7 \u2211 (x : A) P x, given types A, B, and P : A \u2192 Universe\n7.    B \u2192 (B \u2192 A) \u2192 A, given types A and B\n8.    B \u2192 \u220f (A : Universe) (B \u2192 A) \u2192 A, given type B\n9.    (\u220f (A : Universe) (B \u2192 A) \u2192 A) \u2192 B, given type B\n]]\n\nFor the present exercise, this means: state the formula as a lemma, give a proof interactively if there is a proof, and give a counter-example otherwise, i.e., give specific parameters and a proof of the negation of the statement.\n\nMore precise instructions and hints:\n\n1. Use \u2a3f in place of the + and pay attention to operator precedence.\n\n2. Write a function that provides different elements for any natural number argument, not just five elements; for extra credits: state correctly that they are different - for a good choice of [A]; for more extra credits: prove that they are different.\n\n3. An auxiliary function may be helpful - better recall the trick.\n\n4. The symbol for Sigma-types is \u2211, not \u03a3.\n\n5. Same as 1; and there is need for module UniMath.Foundations.NaturalNumbers, e.g., for Lemma natpluscomm.\n\n6.-9. no further particulars\n*)\n\nRequire Import UniMath.Foundations.Preamble.\nRequire Import UniMath.Foundations.PartA.\nRequire Import UniMath.Foundations.NaturalNumbers.\n\n\n\n(** * Exercise 2\nDefine two computable strict comparison operators for natural numbers based on the fact that m < n iff\nn - m <> 0 iff (m+1) - n = 0. Prove that the two operators are equal (using function extensionality, i.e., [funextfunStatement] in the UniMath library).\n\nIt may be helpful to use the definitions of the exercises for lecture 2. The following lemmas on substraction sub in the natural numbers may be useful:\n\na) sub n (S m) = pred (sub n m)\n\nb) sub 0 n = 0\n\nc) pred (sub 1 n) = 0\n\nd) sub (S n) (S m) = sub n m\n\n*)\n\n\n(** from exercises to Lecture 2: *)\nDefinition ifbool (A : UU) (x y : A) : bool -> A :=\n  bool_rect (\u03bb _ : bool, A) x y.\n\nDefinition negbool : bool -> bool := ifbool bool false true.\n\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n  nat_rect (\u03bb _ : nat, A) a f.\n\nDefinition pred : nat -> nat := nat_rec nat 0 (fun x _ => x).\n\nDefinition is_zero : nat -> bool := nat_rec bool true (\u03bb _ _, false).\n\nDefinition iter (A : UU) (a : A) (f : A \u2192 A) : nat \u2192 A :=\n  nat_rec A a (\u03bb _ y, f y).\n\nNotation \"f \u0302 n\" := (\u03bb x, iter _ x f n) (at level 10).\n\nDefinition sub (m n : nat) : nat := pred \u0302 n m.\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/Part4_Tactics_UniMath/exercises_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.9173026595857204, "lm_q1q2_score": 0.8285941758097852}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import class_set.\n\nDefinition BinaryRelation (U:Type) := U -> U -> Prop.\n\nSection BinaryRelation.\n\n  Variable U:Type.\n  Variable R: BinaryRelation U.\n\n  Definition reflexive : Prop := forall (x:U), R x x.\n  Definition transitive : Prop := forall (x y z:U), R x y -> R y z -> R x z.\n  Definition symmetric : Prop := forall (x y:U), R x y -> R y x.\n  Definition antisymmetric : Prop := forall (x y:U), R x y -> R y x -> x = y.\n  Definition total_relation: Prop := forall (x y:U), R x y \\/ R y x.\n\n  Definition equivalence := reflexive /\\ transitive /\\ symmetric.\n  Definition pre_order := reflexive /\\ transitive.\n  Definition partiality_order :=  pre_order /\\ antisymmetric.\n  Definition total_order := partiality_order /\\ total_relation.\n\n  Definition right_unique: Prop := forall (x y z:U), R x y -> R x z -> y = z.\n  Definition left_total: Prop := forall (x:U), exists y:U, R x y.\n  Definition functional_relaton: Prop := right_unique /\\ left_total.\n\nEnd BinaryRelation.\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/binary_relation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992969868542, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8283777199163168}}
{"text": "Require Import Coq.Setoids.Setoid.\nRequire Import Coq.Lists.List.\nRequire Import PeanoNat.\nRequire Import Bool.\nRequire Import Coq.Program.Basics.\n\n(* Locate \"*\". *)\n(* Definition aaa (l: (list nat * bool)): nat := fold_left mult 0 if evenb. *)\n\n(* G - \u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c \u0433\u0440\u0443\u043f\u043f\u044b *)\nClass Semigroup G : Type :=\n{\n    mult : G -> G -> G;\n    assoc : forall x y z:G,\n        mult x (mult y z) = mult (mult x y) z\n}.\n\nClass Monoid G `{Hsemi: Semigroup G} : Type :=\n{\n  e : G;\n  left_id : forall x: G, mult e x = x;\n}.\n\nClass Group G `{Hmono: Monoid G} : Type :=\n{\n    inv : G -> G;\n    left_inv : forall x: G, mult (inv x) x = e;\n}.\n\nClass AbelianGroup G `{Hgr: Group G} : Type :=\n{\n    comm : forall (x y : G), mult x y = mult y x;\n}.\n\nDeclare Scope group_scope.\nInfix \"*\" := mult (at level 40, left associativity) : group_scope.\nOpen Scope group_scope.\n\nSection Group_theorems.\n\n  Variable G: Type.\n  Context `{Hgr: Group G}.\n\n  (* \u2116 24 *)\n  (* \u0412\u0441\u043f\u043e\u043c\u043e\u0433\u0430\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u043b\u0435\u043c\u043c\u0430, \u043d\u0443\u0436\u043d\u0430 \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c *)\n  (* \u041f\u0443\u0441\u0442\u044c a, b \u2014 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u044b\u0435 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u044b G. *)\n  (* \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e \u043a\u0430\u0436\u0434\u043e\u0435 \u0438\u0437 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439 ax = b \u0438 ya = b *)\n  (* \u0438\u043c\u0435\u0435\u0442, \u0438 \u043f\u0440\u0438\u0442\u043e\u043c \u0440\u043e\u0432\u043d\u043e \u043e\u0434\u043d\u043e, \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0432 \u0434\u0430\u043d\u043d\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u0435. *)\n  (* \u0423\u0441\u043b\u043e\u0432\u0438\u0435 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0441\u0442\u0438 \u043c\u043e\u0436\u043d\u043e \u0432\u044b\u0440\u0430\u0437\u0438\u0442\u044c *)\n  (* \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c: \u0435\u0441\u043b\u0438 a*b1 = a*b2 \u0438\u043b\u0438 b1*a = b2*a, \u0442\u043e *)\n  (* b1 = b2. *)\n  (* Set Printing All. *)\n  Proposition left_cancel : forall a x y:G,\n      a * x = a * y -> x = y.\n  Proof.\n    intros a x y H. assert (inv a * (a * x) = inv a * (a * y))\n      as Hinvx.\n    - rewrite H. reflexivity.\n    - repeat rewrite assoc in Hinvx. rewrite left_inv in Hinvx. repeat rewrite left_id in Hinvx. assumption.\n  Qed.\n\n  Proposition left_cancel_alt_proof : forall a x y:G,\n      a * x = a * y -> x = y.\n  Proof.\n    intros a x y H.\n    (* \u0417\u0434\u0435\u0441\u044c \u0441\u0430\u043c\u043e\u0435 \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u043e\u0435: \u043f\u043e \u0441\u0443\u0442\u0438 \u044d\u0442\u043e \u0443\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u0435 \u0433\u0438\u043f\u043e\u0442\u0435\u0437\u044b \u0441\u043b\u0435\u0432\u0430 \u043d\u0430 inv a *)\n    (* f_equal : forall (A B : Type) (f : A -> B) (x y : A), *)\n    (*    x = y -> f x = f y *)\n    apply f_equal with (f := fun g:G => inv a * g) in H. repeat rewrite assoc in H. repeat rewrite left_inv in H. repeat rewrite left_id in H. assumption.\n  Qed.\n\n  Proposition right_id : forall x:G, x * e = x.\n  Proof.\n    intro. apply left_cancel with (a := inv x). rewrite assoc. repeat rewrite left_inv. rewrite left_id. reflexivity.\n  Qed.\n\n  Proposition right_inv:\n    forall x:G, x * inv x = e.\n  Proof.\n    intro. apply left_cancel with (a := inv x). rewrite assoc.\n    rewrite left_inv. rewrite left_id. rewrite right_id. reflexivity.\n  Qed.\n\n  Proposition right_inv_unique: forall x y:G, x * y = e -> inv x = y.\n  Proof.\n    intros x y H. apply left_cancel with (a := x). transitivity e.\n    - apply right_inv.\n    - symmetry. assumption.\n  Qed.\n\n  (* \u2116 20.1 \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e e^{\u22121} = e. *)\n  Proposition e_inv : (inv e) = e.\n  Proof.\n    rewrite <- left_inv with (x:=e) at 2. rewrite right_id. reflexivity.\n  Qed.\n\n  (* \u2116 20.2 \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e (a^{\u22121})^{\u22121} = a. *)\n  Proposition inv_involution : forall x:G, inv (inv x) = x.\n  Proof.\n    intro. apply right_inv_unique. apply left_inv.\n  Qed.\n\n  (* \u2116 23.1 \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e \u0432 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u0435: *)\n  (* 1) (a*b)^{\u22121} = b^{\u22121} * a^{\u22121} *)\n  Proposition inv_prod : forall x y:G, inv (x*y) = inv y * inv x.\n  Proof.\n    intros x y. apply right_inv_unique. rewrite assoc. rewrite <- assoc with (z := inv y). rewrite right_inv. rewrite right_id. rewrite right_inv. reflexivity.\n  Qed.\n\n  (* \u2116 23.2 \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e \u0432 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u0435: *)\n  (* (a_1 * (a_2 * a_3) * ... a_n * a) = a * (a_1 * a_2 * a_3 * ... * e) *)\n  Proposition extra1 : forall (a: G) (lst: list G), fold_left mult lst a = mult a (fold_left mult lst e).\n  Proof.\n    intros a lst. revert a. induction lst as [| a' lst' IH].\n    - intros a. simpl. rewrite right_id. reflexivity.\n    - intros a. simpl. rewrite left_id. rewrite IH. rewrite (IH a'). rewrite assoc. reflexivity.\n  Qed.\n\n  Definition commutator : G -> G -> G :=\n    fun x y:G => x * y * inv x * inv y.\n\n  Notation \"[ x , y ]\" := (commutator x y).\n\n  Proposition commutator_inv : forall x y:G, inv [x, y] = [y, x].\n  Proof.\n    intros. unfold commutator. repeat rewrite inv_prod. repeat rewrite inv_involution. repeat rewrite assoc. reflexivity.\n  Qed.\n\n  Definition commutes_with : G -> G -> Prop :=\n    fun x y:G => x * y = y * x.\n\n  Proposition product_commutes :\n    forall x y z:G, commutes_with x z -> commutes_with y z ->\n               commutes_with (x * y) z.\n  Proof.\n    intros x y z Hxz Hyz. red. rewrite <- assoc. rewrite Hyz. rewrite assoc. rewrite Hxz. rewrite <- assoc. reflexivity.\n  Qed.\n\n  (* \u2116 24.2 *)\n  Proposition right_cancel : forall x y z:G, x * z = y * z -> x = y.\n  Proof.\n    intros x y z H. apply f_equal with (f := fun g:G => g * inv z) in H. repeat rewrite <- assoc in H. repeat rewrite right_inv in H. repeat rewrite right_id in H. assumption.\n  Qed.\n\n  (* \u2116 19 \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e \u0434\u043b\u044f \u043b\u044e\u0431\u043e\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 a \u0433\u0440\u0443\u043f\u043f\u044b \u0441\u0443\u0449\u0435-\n\u0441\u0442\u0432\u0443\u0435\u0442 \u0435\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u043e\u0431\u0440\u0430\u0442\u043d\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 inv a. *)\n  Proposition left_inv_unique: forall y: G, exists x: G, (x * y = e /\\ forall x':G, x'*y = e -> x = x').\n  Proof.\n    intros y. exists (inv y). split.\n    - apply left_inv.\n    (* left_cancel : forall x y z:G, *)\n    (* x * y = x * z -> y = z. *)\n    - intros x' H. rewrite <- (left_inv y) in H. apply right_cancel in H. rewrite H. reflexivity.\n  Qed.\n\n  Proposition commutator_e_impl_commutes : forall x y:G, [x, y] = e -> commutes_with x y.\n  Proof.\n    intros x y H. red. unfold commutator in H. rewrite <- right_inv with (x:=y) in H. apply f_equal with (f := fun g:G => g * y) in H. rewrite <- assoc in H. rewrite left_inv in H. rewrite right_id in H.  rewrite <- (assoc y _ _) in H. rewrite left_inv in H. rewrite <- right_inv with (x:=x) in H. apply f_equal with (f := fun g:G => g * x) in H. rewrite <- assoc in H. rewrite left_inv in H. rewrite right_id in H. rewrite assoc in H. rewrite <- (assoc _ x _) in H. rewrite right_inv in H. rewrite right_id in H. assumption.\n  Qed.\n\n  Proposition commutes_impl_commutator_e : forall x y:G, commutes_with x y -> [x, y] = e.\n  Proof.\n    intros x y H. unfold commutator. red in H. apply f_equal with (f := fun g:G => g * inv x) in H. rewrite <- (assoc _ x _) in H. rewrite right_inv in H. rewrite right_id in H. apply f_equal with (f := fun g:G => g * inv y) in H. rewrite right_inv in H. assumption.\n  Qed.\n\n  (* \u0421\u043e\u043f\u0440\u044f\u0436\u0435\u043d\u0438\u0435, \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 *)\n  Definition conjugation (x y: G) : G :=\n    inv y * x * y.\n\n  Notation \"x ^ y\" := (conjugation x y).\n\n  Proposition xy_conj_e : forall x y z:G, (x^z) * (y^z)  = (x*y)^z.\n  Proof.\n    intros. unfold conjugation. rewrite <- (assoc (inv z) y z). rewrite (assoc (inv z * x * z) (inv z) (y * z)). rewrite <- (assoc ((inv z) * x) z (inv z)). rewrite right_inv. rewrite right_id. repeat rewrite assoc. reflexivity.\n  Qed.\n\n  Proposition e_conj_y_eq_e : forall x:G, e^x = e.\n  Proof.\n    intro. unfold conjugation. rewrite <- assoc. rewrite left_id. apply left_inv.\n  Qed.\n\n  Proposition x_conj_e_eq_x : forall x:G, x^e = x.\n  Proof.\n    intro. unfold conjugation. rewrite e_inv. rewrite left_id. rewrite right_id. reflexivity.\n  Qed.\n\n  Proposition x_min1 : forall x y:G, (inv x)^y = inv (x^y).\n  Proof.\n    intros. unfold conjugation. repeat rewrite inv_prod. rewrite inv_involution. rewrite assoc. reflexivity.\n  Qed.\n\n  Proposition x_y_z : forall x y z:G, (x^y)^z = x^(y*z).\n  Proof.\n    intros. unfold conjugation. rewrite inv_prod. repeat rewrite assoc. reflexivity.\n  Qed.\n\n  Proposition fold_unfold : forall lst: list G, inv (fold_left mult lst e) = fold_left mult (map inv (rev lst)) e.\n  Proof.\n    intro. induction lst as [| a lst' IH'].\n    - simpl. apply e_inv.\n    - simpl. rewrite left_id. rewrite extra1. rewrite inv_prod. rewrite IH'. rewrite map_app. simpl. rewrite fold_left_app. simpl. reflexivity.\n  Qed.\n\n  (* \u2116 25 *)\n  Proposition aa_e_commutative : forall a b: G, (forall x : G, x * x = e) -> commutes_with a b.\n  Proof.\n    intros a b He. specialize (He a) as Ha. specialize (He b) as Hb. rewrite <- Hb in Ha. apply f_equal with (f := fun g:G => b * g * b) in Ha. repeat rewrite assoc in Ha. rewrite <- (assoc (b*a) a b) in Ha. rewrite <- (assoc (b*b) b b) in Ha. rewrite Hb in Ha. rewrite left_id in Ha.\n    specialize (He (a*b)) as Hab. rewrite <- Hab in Ha. apply f_equal with (f := fun g:G => g * (inv (a*b))) in Ha. rewrite <- (assoc (b*a) (a*b) (inv (a*b))) in Ha. rewrite <- (assoc (a*b) (a*b) (inv (a*b))) in Ha. rewrite right_inv in Ha. repeat rewrite right_id in Ha. unfold commutes_with. symmetry in Ha. assumption.\n  Qed.\n\n  Lemma aa_e_commutative' : (forall x : G, x * x = e) -> (forall x : G, x = inv x).\n  Proof.\n    intros. specialize (H x) as Hx. rewrite <- (left_inv x) in Hx. apply (right_cancel x (inv x) x) in Hx. assumption.\n  Qed.\n\n  Lemma aa_e_commutative'' : forall a b: G, (forall x : G, x * x = e) -> commutes_with a b.\n  Proof.\n    intros. unfold commutes_with. rewrite (aa_e_commutative' H a) at 2. rewrite (aa_e_commutative' H b) at 2. rewrite <- inv_prod. rewrite <- (aa_e_commutative' H (a*b)). reflexivity.\n  Qed.\n\n  Fixpoint pow (a: G) (n: nat) {struct n} : G :=\n    match n with\n    | 0 => e\n    | S n' => a * (pow a n')\n    end.\n\n  Notation \"a ** b\" := (pow a b) (at level 35, right associativity).\n\n  (* \u2116 27 *)\n  Proposition a_pow_m_n : forall (a: G) (n m: nat), (pow a n)*(pow a m) = pow a (n + m).\n  Proof.\n    intros. induction n as [| n' IH] ; simpl.\n    - rewrite left_id. reflexivity.\n    - rewrite <- IH. rewrite assoc. reflexivity.\n  Qed.\n\n  (* \u2116 26 *)\n  Proposition a_pow_m : forall (a: G) (n: nat), inv (pow a n) = pow (inv a) n.\n  Proof.\n    intros. apply right_cancel with (z := (pow a n)). rewrite left_inv. symmetry. induction n as [| n' IHn'].\n    - simpl. apply left_id.\n    - rewrite <- Nat.add_1_r at 1. rewrite <- (a_pow_m_n (inv a) n' 1). simpl. rewrite right_id. rewrite assoc. rewrite <- (assoc (pow (inv a) n') (inv a) a). rewrite left_inv. rewrite right_id. assumption.\n  Qed.\n\n  Proposition e_pow_n_eq_e : forall (n: nat), (pow e n) = e.\n  Proof.\n    intros. induction n as [| n' IH] ; simpl; try reflexivity.\n    rewrite left_id. apply IH.\n  Qed.\n\n  (* \u2116 28 *)\n  Proposition theo_28 : forall (a: G) (n m: nat), (pow (pow a n) m) = pow a (n * m).\n  Proof.\n    intros. induction m as [| m' IH] ; simpl.\n    - rewrite <- mult_n_O. simpl. reflexivity.\n    - rewrite IH. rewrite Nat.mul_succ_r. rewrite Nat.add_comm. rewrite <- a_pow_m_n. reflexivity.\n  Qed.\n\n  Proposition a_pow_comm : forall (a: G) (n m: nat), commutes_with (pow a n) (pow a m).\n  Proof.\n    intros. unfold commutes_with. repeat rewrite a_pow_m_n. rewrite Nat.add_comm. reflexivity.\n  Qed.\n\n  (* \u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0432\u0441\u0435\u0445 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0441\u043f\u0438\u0441\u043a\u0430 *)\n  Fixpoint prod (lst : list G) :=\n    match lst with\n    | nil => e\n    | h :: t => h * (prod t)\n    end.\n\n  (* Pos.to_nat *)\n  (* Pos2Nat.inj_add: forall p q : positive, Pos.to_nat (p + q) = Pos.to_nat p + Pos.to_nat q *)\n  (* Proposition lemma1 : forall () zpow a (Z.pos_sub p p0) = (pow a p) * inv (pow a p0). *)\n    (* Search Pos_to_nat. *)\n  (* Proposition a_pow_m_n : forall (a: G) (n m: nat), (pow a n)*(pow a m) = pow a (n + m). *)\n\n  (* Proposition pow_i_neq_poq_j: *)\n  (*   forall i j a n, order a n ->  i < j < n -> *)\n  (*              pow a i <> pow a j. *)\n\n  (*   forall (i, j: nat) (a: G) (n: nat), order a n ->  i < j < n -> *)\n  (*              pow a i <> pow a j. *)\n  (*   Proof. *)\n  (*     intro. *)\n\nClass r_action (S: Type) (r_action: S -> G -> S) : Type :=\n{\n  property: forall (x y: G) (s: S), r_action s (x*y) = r_action (r_action s x) y;\n  e_property: forall (s: S), r_action s e = s\n}.\n\nInstance exists_GG : r_action G (mult) :=\n{\n  property := fun x y s => assoc s x y;\n  e_property := right_id\n}.\n\nDefinition commutative_group := forall (x y : G),\n    (mult x y) = (mult y x).\n\nEnd Group_theorems.\n\nSection Subgroup.\n  (* \u041f\u0443\u0441\u0442\u044c \u0434\u0430\u043d\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e - \u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c \u0433\u0440\u0443\u043f\u043f\u044b *)\n  Variable G: Type.\n  (* \u0413\u0440\u0443\u043f\u043f\u043e\u0432\u044b\u0435 \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u0430 *)\n  Context `{Hgr: Group G}.\n\n  Axiom functional_extensionality :\n  forall A (B : A -> Type)\n         (f g : forall a, B a),\n    (forall a, f a = g a) ->\n    f = g.\n\n  Axiom proof_irrelevance :\n  forall (P : Prop) (p q : P), p = q.\n\n  (* \u041f\u0440\u0435\u0434\u0438\u043a\u0430\u0442, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u044e\u0449\u0438\u0439 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e *)\n  Variable P : G -> Prop.\n  (* \u0415\u0434\u0438\u043d\u0438\u0446\u0430 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0443 *)\n  Variable s_e: P(e).\n  (* \u0423\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u0435 2-\u0445 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0443 *)\n  Variable mul_axiom: forall x y: sig P, P (proj1_sig x * proj1_sig y).\n  (* \u041e\u0431\u0440\u0430\u0442\u043d\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0443 *)\n  Variable inv_axiom: forall x: sig P, P (inv (proj1_sig x)).\n\n  (* \u0424-\u0446\u0438\u044f \u0443\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u044f 2-\u0445 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430: *)\n  (* (\u0443\u043c\u043d\u043e\u0436\u0435\u043d\u0438\u0435 2-\u0445 \u043f\u0435\u0440\u0432\u044b\u0445 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0439 | s_mul) *)\n  Definition mult1 x y := exist P (proj1_sig x * proj1_sig y) (mul_axiom x y).\n  (* \u0424-\u0446\u0438\u044f \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u044f \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u0434\u043b\u044f \u0434\u0430\u043d\u043d\u043e\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 *)\n  Definition inv1 (x: sig P) : sig P := exist P (inv (proj1_sig x)) (inv_axiom x).\n\n  Theorem assoc1: forall x y z: sig P,\n      mult1 x (mult1 y z) = mult1 (mult1 x y) z.\n  Proof.\n    intros [x Px] [y Py] [z Pz].\n    set (Hproj1 := assoc x y z).\n    - unfold mult1. simpl. set (R := exist P (x * (y * z))\n    (mul_axiom (exist P x Px)\n           (exist P (y * z) (mul_axiom (exist P y Py) (exist P z Pz))))).\n      set (L := exist P (x * y * z)\n                      (mul_axiom\n                         (exist P (x * y) (mul_axiom (exist P x Px) (exist P y Py)))\n                         (exist P z Pz))).\n      set (Q := @eq_sig G P R L Hproj1). apply Q. simpl. apply proof_irrelevance.\n  Qed.\n\n  Instance semigroupSubgroup : Semigroup (sig P) :=\n  {\n    mult := mult1;\n    assoc := assoc1\n  }.\n\n  (* e \u0441 \u0434\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044c\u0441\u0442\u0432\u043e\u043c \u0442\u043e\u0433\u043e, \u0447\u0442\u043e e \u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0438\u0442 \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0443 *)\n  Definition sub_e := exist P e s_e.\n  Theorem subgroup_left_id: forall x: (sig P), mult1 sub_e x = x.\n  Proof.\n    intros [x Px]. set (x_pair := exist P x Px). unfold mult1. simpl. set (Q := @eq_sig G P (exist P (e * x) (mul_axiom sub_e x_pair)) x_pair). simpl in Q. apply (Q (left_id _)). apply proof_irrelevance.\n  Qed.\n\n  Instance monoidSubgroup : Monoid (sig P) :=\n  {\n    e := sub_e;\n    left_id := subgroup_left_id;\n  }.\n\n  Definition sub_inv (x: sig P): sig P := exist P (inv (proj1_sig x)) (inv_axiom x).\n  Theorem subgroup_left_inv: forall x: (sig P), mult1 (inv1 x) x = sub_e.\n  Proof.\n    intros [x Px]. set (x_pair := exist P x Px). unfold mult1. simpl.\n    set (Q := @eq_sig G P (exist P (inv x * x) (mul_axiom (inv1 x_pair) x_pair)) sub_e). simpl in Q.\n    apply (Q (left_inv x)). apply proof_irrelevance.\n  Qed.\n\n  Instance subgroup_Group : Group (sig P) :=\n  {\n    inv := sub_inv;\n    left_inv := subgroup_left_inv;\n  }.\n\n  Context `{Hab: @AbelianGroup G _ _ Hgr}.\n\n  Theorem AbelianSubgroup_Abelian: forall x y: (sig P), x * y = y * x.\n  Proof.\n    intros. set (Q := @eq_sig G P (x*y) (y*x)). simpl in Q. apply (Q (comm (proj1_sig x) (proj1_sig y))). apply proof_irrelevance.\n  Qed.\n\n  Instance Abelian_subgroup_Group : AbelianGroup (sig P) :=\n  {\n    comm := AbelianSubgroup_Abelian;\n  }.\n\n  Definition Normal_subgroup (x y: G) (p: P x) := P (conjugation G x y).\n\n  (* \u0421\u043e\u043f\u0440\u044f\u0436\u0435\u043d\u0438\u0435 - \u044d\u0442\u043e \u0438\u0437\u043e\u043c\u043e\u0440\u0444\u0438\u0437\u043c \u0433\u0440\u0443\u043f\u043f\u044b \u0432 \u0441\u0430\u043c\u0443 \u0441\u0435\u0431\u044f *)\n  (* 99 \u0414\u043e\u043a\u0430\u0436\u0438\u0442\u0435, \u0447\u0442\u043e \u0432 \u043a\u043e\u043c\u043c\u0443\u0442\u0430\u0442\u0438\u0432\u043d\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u0435 \u0432\u0441\u044f\u043a\u0430\u044f \u043f\u043e\u0434\u0433\u0440\u0443\u043f\u043f\u0430 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u0439 \u043f\u043e\u0434\u0433\u0440\u0443\u043f\u043f\u043e\u0439. *)\n\n  Theorem EveryAbelianSubgroup_normal: forall (x: sig P) (y: G), Normal_subgroup (proj1_sig x) y (proj2_sig x).\n  Proof.\n    intros x y. destruct x. simpl. unfold Normal_subgroup. unfold conjugation. rewrite comm. rewrite assoc. rewrite right_inv. rewrite left_id. apply p.\n  Qed.\n\nEnd Subgroup.\n\nSection Homomorphismus.\n\n  Variable G: Type.\n  Context `{Gsemi: Semigroup G}.\n\n  Variable F: Type.\n  Context `{Fsemi: Semigroup F}.\n\n  Record Homomorphism: Type :=\n    Build_homomorphism\n    {\n        f: G -> F;\n        proof: forall (x y: G), f (mult x y) = mult (f x) (f y)\n    }.\n\n    Record Isomorphism: Type :=\n    Build_isomorphism\n      {\n        fun1: Homomorphism;\n        fun2: F -> G;\n        left_right_id: forall (x: G), fun2 ((f fun1) x) = x;\n        right_left_id: forall (y: F), (f fun1) (fun2 y) = y;\n        (* Homo_f: forall (a b: G), fun1 (a * b) = (fun1 a) * (fun1 b); *)\n        (* Homo_right: forall (a b: G2), right (a * b) = (right a) * (right b) *)\n      }.\n\n  Theorem homo1 (phi: Homomorphism) (Hcomm: commutative_group G) (Hsur: forall (f1: F), exists (g: G), (f phi g) = f1):\n      (commutative_group F).\n  Proof.\n    unfold commutative_group. intros. destruct (Hsur x). destruct (Hsur y). rewrite <- H. rewrite <- H0. rewrite <- (proof phi x0). rewrite <- (proof phi x1). rewrite (Hcomm x0 x1). reflexivity.\n  Qed.\n\n  (* 133. \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e \u043f\u0440\u0438 \u0433\u043e\u043c\u043e\u043c\u043e\u0440\u0444\u0438\u0437\u043c\u0435 \u0433\u0440\u0443\u043f\u043f\u044b G \u0432 *)\n  (* \u0433\u0440\u0443\u043f\u043f\u0443 F \u0435\u0434\u0438\u043d\u0438\u0446\u0430 \u0433\u0440\u0443\u043f\u043f\u044b G \u043f\u0435\u0440\u0435\u0445\u043e\u0434\u0438\u0442 \u0432 \u0435\u0434\u0438\u043d\u0438\u0446\u0443 \u0433\u0440\u0443\u043f\u043f\u044b F . *)\n  Theorem homomorphism_saves_e: forall (phi: Homomorphism) `{Hmono: @Monoid G Gsemi} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono}, (f phi) e = e.\n  Proof.\n    intros. apply (left_cancel_alt_proof F (f phi e)). rewrite <- (proof phi e e). rewrite left_id. rewrite right_id.\n    - reflexivity.\n    - apply Fgroup.\n  Qed.\n    (* Theorem homo2 (phi: Homomorphism): (f phi e) = e. *)\n  (* Proof. *)\n  (*   apply left_cancel with (Hsemi := Hsemi0) (Hmono := Hmono0) (x := (f phi e)). *)\n  (*   - apply Fsemi. *)\n  (*   - rewrite  <- (proof phi e). rewrite left_id. rewrite (@right_id F _ _ Fsemi). reflexivity. *)\n  (* Qed. *)\n\n  (* 134 *)\n  Theorem homomorphism_saves_inv: forall (x: G) (phi: Homomorphism) `{Hmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Hmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono}, (f phi (inv x)) = inv (f phi x).\n  Proof.\n    intros. apply (left_cancel_alt_proof F (f phi x)). rewrite <- (proof phi). rewrite right_inv. rewrite right_inv. apply homomorphism_saves_e. apply Fgroup.\n  Qed.\n\n  Definition Im_prop (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (y: F) := exists x: G, y = (f phi x).\n\n  Definition Im (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} := sig (Im_prop phi).\n\n  Definition Im_mult (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y: (Im phi)): Im phi.\n  Proof.\n    exists (mult (proj1_sig x) (proj1_sig y)). unfold Im_prop. destruct x. destruct y. destruct i. destruct i0. simpl. exists (x1*x2). rewrite (proof phi). rewrite <- e0. rewrite <- e1. reflexivity.\n  Defined.\n\n  Theorem Im_mult_assoc: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y z: Im phi), Im_mult phi x (Im_mult phi y z) = Im_mult phi (Im_mult phi x y) z.\n  Proof.\n    intros phi Gmono Ggroup Fmono Fgroup x y z. unfold Im_mult. destruct x. destruct y. destruct z. simpl. destruct i. destruct i0. destruct i1. assert (Hproj1: x * (x0 * x1) = (x * x0 * x1)).\n    - apply assoc.\n    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end.\n      set (Q := @eq_sig F (Im_prop phi) name1 name2 Hproj1). apply Q. simpl. apply proof_irrelevance.\n  Qed.\n\n  Instance semigroupIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Semigroup (@Im phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    mult := Im_mult phi;\n    assoc := Im_mult_assoc phi\n  }.\n\n  Definition Im_e (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Im phi.\n  Proof.\n    exists e. exists e. symmetry. apply homomorphism_saves_e. apply Fgroup.\n  Defined.\n\n  Theorem Im_mult_left_id: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)), Im_mult phi (Im_e phi) x = x.\n  Proof.\n    intros phi Gmono Ggroup Fmono Fgroup x. unfold Im_mult. destruct x as [x0 Px]. destruct Px. assert (H_left_id: e * x0 = x0).\n    - apply left_id.\n    - simpl. match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig F (Im_prop phi) name1 name2 H_left_id). apply Q. simpl. apply proof_irrelevance.\n  Qed.\n\n  Instance monoidIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Monoid (@Im phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    e := Im_e phi;\n    left_id := Im_mult_left_id phi\n  }.\n\n  Definition Im_inv (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)) : Im phi.\n  Proof.\n    destruct x as [y P]. exists (inv y). destruct P as [x H]. set(H_inv := homomorphism_saves_inv x). exists (inv x). rewrite H. symmetry. apply H_inv.\n  Defined.\n\n  Theorem Im_mult_left_inv: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)), Im_mult phi (Im_inv phi x) x = Im_e phi.\n  Proof.\n    intros phi Gmon Ggroup Fmono Fgroup x. unfold Im_mult. destruct x as [y P]. destruct P as [x Py]. simpl. assert (H_left_inv: inv y * y = e).\n    - apply left_inv.\n    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig F (Im_prop phi) name1 name2 H_left_inv). apply Q. apply proof_irrelevance.\n  Qed.\n\n  Instance groupIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Group (@Im phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    inv := Im_inv phi;\n    left_inv := Im_mult_left_inv phi\n  }.\n\n  (* \u042f\u0434\u0440\u043e \u0433\u043e\u043c\u043e\u043c\u043e\u0440\u0444\u0438\u0437\u043c\u0430 *)\n  Definition Ker (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} := sig (fun x => (f phi x) = e).\n\n  Definition Ker_mult (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y: Ker phi): Ker phi.\n  Proof.\n    destruct x as [x Px]. destruct y as [y Py]. exists (mult x y). rewrite (proof phi). rewrite Px. rewrite Py. rewrite left_id. reflexivity.\n  Defined.\n\n  Theorem Ker_mult_assoc: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y z: Ker phi), Ker_mult phi x (Ker_mult phi y z) = Ker_mult phi (Ker_mult phi x y) z.\n  Proof.\n    intros phi Gmono Ggroup Fmono Fgroup x y z. destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold Ker_mult.\n    assert (Hassoc: x * (y * z) = (x * y * z)).\n    - apply assoc.\n    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hassoc). apply Q. unfold proj1_sig. unfold proj2_sig. simpl. apply proof_irrelevance.\n  Qed.\n\n  Instance semigroupKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Semigroup (@Ker phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    mult := Ker_mult phi;\n    assoc := Ker_mult_assoc phi\n  }.\n\n  Definition Ker_e (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Ker phi.\n  Proof.\n    exists e. apply homomorphism_saves_e. apply Fgroup.\n  Defined.\n\n  Theorem Ker_mult_left_id: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)), Ker_mult phi (Ker_e phi) x = x.\n  Proof.\n    intros phi Gmono Ggroup Fmono Fgroup x. destruct x as [x0 Px]. unfold Ker_mult. unfold Ker_e. assert (Hleft_id: e * x0 = x0).\n    - apply left_id.\n    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hleft_id). apply Q. simpl. apply proof_irrelevance.\n  Qed.\n\n  Instance monoidKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Monoid (@Ker phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    e := Ker_e phi;\n    left_id := Ker_mult_left_id phi\n  }.\n\n  Definition Ker_inv (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)): Ker phi.\n  Proof.\n    destruct x as [x P]. exists (inv x). rewrite (@homomorphism_saves_inv x phi Gmono Ggroup Fmono Fgroup). rewrite P. apply e_inv.\n  Defined.\n\n  Theorem Ker_mult_left_inv: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)), Ker_mult phi (Ker_inv phi x) x = Ker_e phi.\n  Proof.\n    intros phi Gmono Ggroup Fmono Fgroup x. destruct x as [x0 Px]. unfold Ker_mult. unfold Ker_e. unfold Ker_inv. assert (Hinv: (inv x0) * x0 = e).\n    - apply left_inv.\n    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hinv). apply Q. apply proof_irrelevance.\n  Qed.\n\n  Instance groupKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Group (@Ker phi Gmono Ggroup Fmono Fgroup) :=\n  {\n    inv := Ker_inv phi;\n    left_inv := Ker_mult_left_inv phi\n  }.\n\nEnd Homomorphismus.\n\n(* 135. \u041f\u0443\u0441\u0442\u044c f1 : G \u2192 F \u0438 f2 : F \u2192 H \u2014 \u0433\u043e\u043c\u043e\u043c\u043e\u0440\u0444\u0438\u0437\u043c\u044b. *)\n(* \u0414\u043e\u043a\u0430\u0437\u0430\u0442\u044c, \u0447\u0442\u043e f2 f1 : G \u2192 H \u2014 \u0433\u043e\u043c\u043e\u043c\u043e\u0440\u0444\u0438\u0437\u043c. *)\nTheorem homomorphism_mult_homo: forall (G F H: Type) `{Gsemi: Semigroup G} `{Fsemi: Semigroup F} `{Hsemi: Semigroup H} (phi1: Homomorphism G F) (phi2: Homomorphism F H) (x y: G), (f F H phi2 (f G F phi1 (x*y))) = (f _ _ phi2 (f _ _ phi1 x)) * (f _ _ phi2 (f _ _ phi1 y)).\nProof.\n  intros. rewrite (proof G F). rewrite (proof F H). reflexivity.\nQed.\n\nDefinition homomorphism_composition (G F H: Type) `{Gsemi: Semigroup G} `{Fsemi: Semigroup F} `{Hsemi: Semigroup H} (phi1: Homomorphism G F) (phi2: Homomorphism F H) := Build_homomorphism G H (fun x: G => (f F H phi2) (f G F phi1 x)) (homomorphism_mult_homo G F H phi1 phi2).\n(* Section Isomorphismus. *)\n\n  (* Record Isomorphism: Type := *)\n  (*   Build_isomorphism *)\n  (*   { *)\n  (*       phi: G1 -> G2; *)\n  (*       totality: forall (x: G1), exists (y: G2), phi x = y; *)\n  (*       injectivity: forall (x1 x2: G1), (phi x1) = (phi x2) -> x1 = x2; *)\n  (*       operation_preservation: forall (a b: G1), phi (a * b) = (phi a) * (phi b) *)\n  (*   }. *)\n\n(* End Isomorphismus. *)\n\nTheorem th01: forall (G F: Type) `{Hgr1: Semigroup G} `{Hgr2: Semigroup F} (phi: Isomorphism G F), forall (a b: F), (fun2 _ _ phi) (a * b) = ((fun2 _ _ phi) a) * ((fun2 _ _ phi) b).\nProof.\n  intros. rewrite <- (right_left_id _ _ phi a). rewrite <- (right_left_id _ _ phi b). rewrite <- (proof G F (fun1 _ _ phi)). repeat rewrite (left_right_id _ _ phi). reflexivity.\nQed.\n\nTheorem th1: forall (G F: Type) `{Hgr1: Semigroup G} `{Hgr2: Semigroup F} (phi: Isomorphism G F), Isomorphism F G.\nProof.\n  intros. set (Homo2 := th01 G F phi). set (phi1 := phi). destruct phi. simpl in Homo2.\n  set (Homo1 := Build_homomorphism F G fun4 Homo2).\n  apply (Build_isomorphism F G Homo1 (f G F fun3)).\n  - apply (right_left_id G F phi1).\n  - apply (left_right_id G F phi1).\nQed.\n\n(* \u0415\u0441\u043b\u0438 \u0433\u0440\u0443\u043f\u043f\u0430 \u0438\u0437\u043e\u043c\u043e\u0440\u0444\u043d\u0430 \u043f\u043e\u043b\u0443\u0433\u0440\u0443\u043f\u043f\u0435, \u0442\u043e \u043f\u043e\u043b\u0443\u0433\u0440\u0443\u043f\u043f\u0430 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0433\u0440\u0443\u043f\u043f\u043e\u0439 *)\n   (* compose (phi1.(phi)) (psi.(phi)) =1 id). *)\n\n(* Print exist. *)\n(* Lemma l (r1 r2 : { R : nat -> nat -> bool | *)\n(*                    forall n, R n n = true }) : *)\n(*   (forall n1 n2, proj1_sig r1 n1 n2 = proj1_sig r2 n1 n2) -> *)\n(*   r1 = r2. *)\n(* Proof. *)\n(*   destruct r1 as [r1 H1], r2 as [r2 H2]. *)\n(*   simpl. *)\n(*   intros H. *)\n(*   assert (H': r1 = r2). *)\n(*   { apply functional_extensionality. *)\n(*     intros n1. *)\n(*     apply functional_extensionality. *)\n(*     intros n2. *)\n(*     apply H. } *)\n(*   subst r2. *)\n(*   rename r1 into r. *)\n(*   f_equal. *)\n(*   apply proof_irrelevance. *)\n(* Qed. *)\n\n(* Inductive bool: Set := *)\n(*   | true *)\n(*   | false. *)\n\n(* Lemma equality_commutes: *)\n(*   forall (a: bool) (b: bool), a = b -> b = a. *)\n(* Proof. *)\n(*   intros. *)\n(*   subst a. *)\n(*   reflexivity. *)\n(* Qed. *)\n\nInductive megaeq: forall (A B: Type) (x: A) (y: B), Prop :=\n  megarefl A x : megaeq A A x x.\n\nSection generatedSubgroup.\n  (* \u041f\u0443\u0441\u0442\u044c \u0434\u0430\u043d\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e - \u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c \u0433\u0440\u0443\u043f\u043f\u044b *)\n  Variable G: Type.\n  (* \u0413\u0440\u0443\u043f\u043f\u043e\u0432\u044b\u0435 \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u0430 *)\n  Context `{Hgr: Group G}.\n\n  Definition id_or_inv (P1: G -> Prop): Type := ((sig P1) * bool).\n  Definition invert_list (P: G -> Prop) (l: list (id_or_inv P)): (list (id_or_inv P)) :=\n    rev (\n        map\n          (fun x => (fst x, negb (snd x)))\n          l).\n\n  Lemma inv_app (P: G -> Prop) (l1: list (id_or_inv P)) (l2: list (id_or_inv P)):\n      invert_list P (l1 ++ l2) = invert_list P l2 ++ invert_list P l1.\n  Proof.\n    destruct l1 as [| x t].\n    - unfold invert_list. simpl. rewrite app_nil_r. reflexivity.\n    - unfold invert_list. simpl. rewrite map_app. rewrite rev_app_distr. rewrite <- app_assoc. reflexivity.\n  Qed.\n\n  Definition gfold (P1: G -> Prop) (l: list (id_or_inv P1)) :=\n    fold_right\n      mult e\n      (map (fun (v: (sig P1) * bool) =>\n              if snd v\n              then (proj1_sig (fst v))\n              else inv (proj1_sig (fst v)))\n           l).\n\n  (* \u041f\u043e\u0440\u043e\u0436\u0434\u0430\u044e\u0449\u0435\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0433\u0440\u0443\u043f\u043f\u044b G \u2014 \u044d\u0442\u043e \u043f\u043e\u0434\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e S \u0432 G, \u0442\u0430\u043a\u043e\u0435, \u0447\u0442\u043e \u043a\u0430\u0436\u0434\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 G \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0437\u0430\u043f\u0438\u0441\u0430\u043d \u043a\u0430\u043a \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043a\u043e\u043d\u0435\u0447\u043d\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 S \u0438 \u0438\u0445 \u043e\u0431\u0440\u0430\u0442\u043d\u044b\u0445.  *)\n  Definition generatedSubgroup (P1: G -> Prop) :=\n    sig (fun x =>\n           @ex\n             (list (id_or_inv P1))\n             (fun l =>\n                (x = gfold P1 l))).\n\n\n  Theorem generatedSubgroup_mul: forall (P1: G -> Prop) (x y: list (id_or_inv P1)), gfold P1 (x ++ y) = gfold P1 x * gfold P1 y.\n  Proof.\n    intros. unfold gfold. induction x as [|x0 x].\n    - simpl. rewrite left_id. reflexivity.\n    - simpl. rewrite <- assoc. rewrite IHx. reflexivity.\n  Qed.\n\n  Lemma unapp L (x: L) (l: list L): x::l = (x::nil)++l.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma gfold_inv (P: G -> Prop) (l: list (id_or_inv P)): gfold P (invert_list P l) = inv (gfold P l).\n  Proof.\n    induction l as [|x t].\n    - unfold gfold. simpl. symmetry. apply e_inv.\n    - rewrite unapp. rewrite inv_app. rewrite generatedSubgroup_mul. rewrite generatedSubgroup_mul. rewrite inv_prod. rewrite IHt. unfold gfold. simpl. destruct (snd x).\n      +  simpl. repeat rewrite right_id. reflexivity. apply Hgr. apply Hgr.\n      + simpl. repeat rewrite right_id. rewrite inv_involution. reflexivity. apply Hgr. apply Hgr.\n  Qed.\n\n\n  Definition mult_gen (P1: G -> Prop) (x y: generatedSubgroup P1): generatedSubgroup P1.\n  Proof.\n    unfold generatedSubgroup. destruct x as [x0 Px]. destruct y as [y0 Py]. exists (x0 * y0). destruct Px as [list_x Px]. destruct Py as [list_y Py]. exists (list_x ++ list_y). symmetry. rewrite Px. rewrite Py. apply generatedSubgroup_mul.\n  Defined.\n\n  Theorem generatedSubgroup_assoc: forall (P1: G -> Prop) (x y z: generatedSubgroup P1), mult_gen P1 x (mult_gen P1 y z) = mult_gen P1 (mult_gen P1 x y) z.\n  Proof.\n    intros. assert (Hproj1: proj1_sig (mult_gen P1 x (mult_gen P1 y z)) = proj1_sig (mult_gen P1 (mult_gen P1 x y) z)).\n    - destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold mult_gen. simpl.\n      rewrite assoc. reflexivity.\n    - destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold mult_gen. simpl.\n      match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G _ name1 name2 Hproj1). apply Q. simpl. apply proof_irrelevance. (* unfold eq_rect. destruct Px as [x0 Px]. destruct Py as [y0 Py]. destruct Pz as [z0 Pz]. subst. simpl. unfold eq_sym. unfold eq_ind_r. unfold eq_ind. simpl. assert (Hassoc: x0 ++ y0 ++ z0 = (x0 ++ y0) ++ z0). *)\n      (* + apply app_assoc. *)\n      (* + match goal with |- ?L = ?R => set (name3 := L); set (name4 := R) end. set (Q := @eq_sig (list (id_or_inv P1)) _ name3 name4 Hassoc). *)\n  Qed.\n\n  Instance semigroupGeneratedSubgroup (P1: G -> Prop) : Semigroup (generatedSubgroup P1) :=\n  {\n    mult := mult_gen P1;\n    assoc := generatedSubgroup_assoc P1\n  }.\n\n  Definition e_gen (P1: G -> Prop): generatedSubgroup P1.\n  Proof.\n    unfold generatedSubgroup. exists e. exists nil. unfold gfold. simpl. reflexivity.\n  Defined.\n\n  Theorem generatedSubgroup_left_id: forall (P1: G -> Prop) (x: generatedSubgroup P1), mult_gen P1 (e_gen P1) x = x.\n  Proof.\n    intros. destruct x as [x Px]. unfold e_gen. simpl. unfold mult_gen. simpl. match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G _ name1 name2 (left_id x)). apply Q. simpl. apply proof_irrelevance.\nQed.\n\n  Instance monoidGeneratedSubgroup (P1: G -> Prop) : Monoid (generatedSubgroup P1) :=\n  {\n    e := e_gen P1;\n    left_id := generatedSubgroup_left_id P1\n  }.\n\n  Definition inv_gen (P1: G -> Prop) (x: generatedSubgroup P1): generatedSubgroup P1.\n  Proof.\n    unfold generatedSubgroup. destruct x as [x Px]. exists (inv x). unfold gfold. destruct Px as [l0 Px]. simpl. reflexivity.\n  Defined.\n\n\n  (* Definition commutant := { x : G | exists l: list (G*G), x = fold (fun p a => mult1 (commutator (fst p) (snd p)) a) e l }. *)\nEnd generatedSubgroup.\n\n\nSection CartesianGroupProduct.\n  (* \u041f\u0443\u0441\u0442\u044c \u0434\u0430\u043d\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e - \u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c \u0433\u0440\u0443\u043f\u043f\u044b *)\n  Variable G: Type.\n  Variable H: Type.\n  (* \u0413\u0440\u0443\u043f\u043f\u043e\u0432\u044b\u0435 \u0441\u0432\u043e\u0439\u0441\u0442\u0432\u0430 *)\n  Context `{Hgr1: Group G}.\n  Context `{Hgr2: Group H}.\n\n  Definition mulp (x y : G * H): (G * H) := (mult (fst x) (fst y), mult (snd x) (snd y)).\n\n  Theorem assocGroupProduct: forall x y z: G * H,\n      mulp x (mulp y z) = mulp (mulp x y) z.\n  Proof.\n    intros. unfold mulp. simpl. rewrite (@assoc G). rewrite (@assoc H). reflexivity.\n  Qed.\n\n  Instance semigroupGroupProduct : Semigroup (G * H) :=\n  {\n    mult := mulp;\n    assoc := assocGroupProduct;\n  }.\n\n  Definition groupProduct_e: (G * H) := (e, e).\n\n  Theorem GroupProductLeftId: forall x: G * H,\n      mult groupProduct_e x = x.\n  Proof.\n    intros. unfold groupProduct_e. destruct x. unfold mult. simpl. unfold mulp. simpl. repeat rewrite left_id. reflexivity.\n  Qed.\n\n  Instance monoidGroupProduct : Monoid (G * H) :=\n  {\n    e := groupProduct_e;\n    left_id := GroupProductLeftId;\n  }.\n\n  Definition groupProduct_inv (x: G*H) := (inv (fst x), inv(snd x)).\n\n  Theorem groupProduct_left_inv : forall x: (G * H), mult (groupProduct_inv x) x = groupProduct_e.\n  Proof.\n    intros. destruct x. unfold mult. simpl. unfold mulp. simpl. repeat rewrite left_inv. unfold groupProduct_e. reflexivity.\n  Qed.\n\n  Instance groupGroupProduct : Group (G * H) :=\n  {\n      inv := groupProduct_inv;\n      left_inv := groupProduct_left_inv;\n  }.\n\n  Theorem projectHomomorphismus : forall (x y: (G * H)), fst (mult x y) = mult (fst x) (fst y).\n  Proof.\n    intros. simpl. reflexivity.\n  Qed.\n\n  Theorem projectHomomorphismus2 : forall (x y: (G * H)), snd (mult x y) = mult (snd x) (snd y).\n  Proof.\n    intros. simpl. reflexivity.\n  Qed.\n\n  Definition rec_fst := Build_homomorphism (G*H) G fst projectHomomorphismus.\n\n  Definition rec_snd := Build_homomorphism (G*H) H snd projectHomomorphismus2.\n\n  Definition get_e_pair (x: G): (G*H) := (x, e).\n\n  Theorem projectHomomorphismus3 : forall (x y: G), get_e_pair (mult x y) = mult (get_e_pair x) (get_e_pair y).\n  Proof.\n    intros. unfold get_e_pair. simpl. unfold mulp. simpl. rewrite left_id. reflexivity.\n  Qed.\n\n  Definition rec_get_e_pair := Build_homomorphism G (G*H) get_e_pair projectHomomorphismus3.\n\n  Context `{Gab: @AbelianGroup G Hsemi Hmono Hgr1}.\n  Context `{Hab: @AbelianGroup H _ _ Hgr2}.\n\n  Theorem AbelianProduct: forall (x y : (G*H)), mult x y = mult y x.\n  Proof.\n    intros. unfold mult. simpl. unfold mulp. rewrite (@comm G _ _ _ Gab). rewrite (@comm H _ _ _ Hab). reflexivity.\n  Qed.\nEnd CartesianGroupProduct.\nClose Scope group_scope.\n", "meta": {"author": "usr345", "repo": "groups", "sha": "bb841f040cf663c7ceec080f355583e8ce470a76", "save_path": "github-repos/coq/usr345-groups", "path": "github-repos/coq/usr345-groups/groups-bb841f040cf663c7ceec080f355583e8ce470a76/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8872046011730964, "lm_q1q2_score": 0.8281441071361685}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** * From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** * Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n    induction n.\n    simpl. apply ev_0.\n    simpl. apply ev_SS. apply IHn.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n    intros n m.\n    intros Evn Evm.\n    induction Evn.\n    simpl. apply Evm.\n    simpl. apply ev_SS.\n    apply IHEvn.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Example *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    intros n.\n    intros B.\n    assert (lemma : 2*n = n + n).\n    simpl. apply f_equal. apply plus_0_r.\n    rewrite -> lemma.\n    apply b_sum. \n    apply B.\n    apply B.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   intros n m.\n   intros B.\n   induction m.\n   simpl.\n   apply b_0.\n   simpl.\n   apply b_sum.\n   apply B.\n   apply IHm.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n    intros n G.\n    apply g_plus5.\n    apply g_plus5.\n    apply g_plus3.\n    apply G.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n    intros n m N M.\n    induction N.\n    simpl. apply M.\n    apply g_plus3. apply IHN.\n    apply g_plus5. apply IHN.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n    intros n B.\n    induction B.\n    apply g_0.\n    apply g_plus3. apply g_0.\n    apply g_plus5. apply g_0.\n    apply gorgeous_sum. \n    apply IHB1.\n    apply IHB2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   intros x y z.\n   rewrite plus_assoc.\n   replace (x+z) with (z+x).\n   reflexivity.\n   apply plus_comm.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   simpl. apply g_0.\n   rewrite -> helper_g_times2.\n    apply g_plus3. rewrite -> helper_g_times2. apply g_plus3. fold plus.\n    rewrite <- plus_assoc. apply IHgorgeous.\n   rewrite -> helper_g_times2. apply g_plus5. fold plus.\n   rewrite -> helper_g_times2. apply g_plus5. fold plus.\n   rewrite <- plus_assoc. apply IHgorgeous.\nQed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n.\n  intros E.\n  inversion E.\n  inversion H0.\n  apply H2.\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 H. inversion H. inversion H1. inversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n    intros n m.\n    intros EV.\n    intros evn.\n    induction evn.\n    simpl in EV.\n    apply EV.\n    apply IHevn.\n    inversion EV.\n    apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p.\n  intros enm enp.\n\n assert (e1: ev (n + m + (n + p))).\n apply ev_sum. apply enm. apply enp.\n\n replace (n + m + (n+ p)) with (n+n+(m+p)) in e1.\n apply ev_ev__ev with (n:=n+n). apply e1.  \n assert(lemmad: forall n, n+n = double n).\n induction n0.\n    reflexivity. simpl. apply f_equal. rewrite <- plus_n_Sm.\n    apply f_equal. apply IHn0.\n\n rewrite -> lemmad. apply double_even.\n\n rewrite <- plus_assoc.\n rewrite <- plus_assoc.\n apply f_equal.\n rewrite plus_comm.\n rewrite <- plus_assoc.\n apply f_equal.\n apply plus_comm.\nQed.\n(** [] *)\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X: Type}:  list X -> Prop :=\n    | pal_nil: pal []\n    | pal_add: forall x: X, forall l: list X,\n                pal l -> pal (x :: (snoc l x))\n    | pal_one: forall x: X, pal [x].\n\nTheorem snoc_rev_comm : forall X:Type, forall l1 l2: list X, forall x : X,\n    l1 ++ (snoc l2 x) = (snoc (l1++l2) x).\nProof.\n    intros X.  intros l1 l2 x.\n    induction l1. reflexivity.\n    simpl. apply f_equal.\n    apply IHl1.\nQed.\n\nTheorem pal1: forall X: Type, forall l: list X, pal(l ++ rev l).\nProof.\n    intros X l.\n    induction l.\n    simpl. apply pal_nil.\n    simpl.\n    rewrite snoc_rev_comm.\n    apply pal_add.\n    apply IHl.\nQed.\n\nTheorem pal2: forall X: Type, forall l: list X,\n    pal l -> l = rev l.\nProof.\n    intros X. intros l.\n    intros P.\n    induction P. reflexivity.\n    rewrite IHP.\n    simpl.\n    rewrite rev_snoc.\n    rewrite rev_involutive.\n    simpl.\n    apply f_equal.\n    rewrite <- IHP.\n    reflexivity.\n    reflexivity. \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.\nTheorem list_munger: forall X: Type, forall l: list X, forall x0 x1: X,\n    x1 :: l = (snoc l x0)\n*)\n\nTheorem empty_rev : forall X : Type, forall l: list X,\n    rev l = [] -> l = [].\nProof.\n    intros X l. \n    intros H.\n    destruct l.\n    reflexivity.\n    simpl in H.\n    destruct (rev l).\n    inversion H.\n    inversion H.\nQed.\n\nLemma ble_nat_0_implies_0: forall n: nat,\n    ble_nat n 0 = true -> n = 0.\nProof. intros n. destruct n. reflexivity.  intros H. inversion H. Qed.\n\nLemma length_0_implies_nil: forall X: Type, forall l: list X,\n    length l = 0 -> l = [].\nProof. intros X l. intros H. destruct l. reflexivity. inversion H. Qed.\n\nLemma rev_len_ind: forall X: Type, forall l: list X, forall x: X, \n    length (snoc l x) = S (length l).\nProof. \n    intros X l x.\n    induction l.\n    reflexivity.\n    simpl.\n    apply f_equal.\n    apply IHl.\nQed.\n\nLemma rev_len: forall X: Type, forall l: list X,\n    length l = length (rev l).\nProof.\n    intros X l.\n    induction l.\n    reflexivity.\n    simpl.\n    rewrite rev_len_ind.\n    apply f_equal.\n    apply IHl.\nQed.\n\nLemma ble_nat_0: forall n : nat, ble_nat n 0 = true -> n = 0.\nProof. intros n. destruct n. reflexivity. intros H. inversion H. Qed.\n\nLemma smaller_than_trans_1: forall n m: nat,\n    ble_nat n m = true -> ble_nat n (S m) = true.\nProof.\n    intros n m.\n    generalize dependent m.\n    induction n.\n    intros m.\n    reflexivity.\n\n    induction m.\n    intros H.\n    simpl. inversion H.\n    intros H.\n    apply IHn.\n    apply H.\nQed.\n\nLemma smaller_than_trans: forall n m: nat,\n    ble_nat (S n) m = true -> ble_nat n m = true.\nProof.\n    intros n m H.\n    inversion H.\n    destruct m. inversion H1.\n    rewrite H1.\n\n\n    destruct n.\n    reflexivity.\n    simpl.\n    destruct m.\n    inversion H.\n    inversion H.\n    rewrite H2.\n    apply smaller_than_trans_1.\n    apply H2.\nQed.\n\nTheorem palindrome_converse_strong: forall X: Type, forall l: list X,\n    forall m: nat,\n    ble_nat (length l) m = true ->\n    l = rev l ->\n    pal l.\nProof.\n    intros X l m.\n    generalize dependent l.\n    induction m.\n\n    intros l.\n    intros H.\n    apply ble_nat_0_implies_0 in H.\n    apply length_0_implies_nil in H.\n    rewrite H.\n    intros.\n    apply pal_nil.\n\n    intros l.\n    intros Length_H.\n    intros Rev_H.\n\n    destruct l.\n    apply pal_nil.\n    destruct (rev l) eqn:Heq.\n    assert (LNIL: l = []).\n    apply empty_rev.\n    apply Heq.\n    rewrite LNIL.\n    apply pal_one.\n    replace (l) with (rev (rev l)).\n    rewrite Heq.\n    simpl.\n    inversion Rev_H.\n    rewrite Heq in H0.\n    simpl in H0.\n    inversion H0.\n    apply pal_add.\n    apply IHm.\n\n    inversion Length_H.\n    rewrite H3.\n    rewrite H2 in H3.\n    rewrite rev_len_ind in H3.\n    rewrite rev_len. rewrite rev_involutive.\n    apply smaller_than_trans.\n    apply H3.\n    rewrite -> rev_involutive.\n    rewrite H2 in Heq.\n    rewrite rev_snoc in Heq.\n    inversion Heq.\n    rewrite -> rev_involutive.\n    symmetry. apply H3.\n    apply rev_involutive.\nQed.\n\nTheorem palindrome_converse: forall X: Type, forall l: list X,\n    l = rev l -> pal l.\nProof.\n\n    intros X.\n    intros l.\n    apply palindrome_converse_strong with (m:=length l).\n    symmetry.\n    apply ble_nat_refl.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\nInductive subseq:  list nat -> list nat -> Prop :=\n| subseq_nil:    subseq [] []\n| subseq_space:  forall n: nat, forall l1 l2: list nat, subseq l1 l2 -> subseq l1 (n::l2)\n| subseq_add:    forall n: nat, forall l1 l2: list nat, subseq l1 l2 -> subseq (n::l1) (n::l2)\n.\n\nTheorem subseq_refl: forall l: list nat, subseq l l.\nProof.\n    induction l.\n    apply subseq_nil.\n    apply subseq_add.\n    apply IHl.\nQed.\n\nLemma app_nil_r: forall X: Type, forall l: list X,\n    l ++ [] = l.\nProof. intros X. induction l. reflexivity. simpl. apply f_equal. apply IHl. Qed.\n\nTheorem subseq_nil_x: forall l: list nat, subseq l [] -> l = [].\nProof. intros l. intros H. inversion H. reflexivity. Qed.\n\nTheorem subseq_nil_l: forall l: list nat, subseq [] l.\nProof. induction l. apply subseq_nil. apply subseq_space. apply IHl. Qed.\n\nTheorem subseq_snoc: forall l1 l2: list nat, forall n : nat,\n    subseq l1 l2 -> subseq l1 (snoc l2 n).\nProof.\n    intros l1 l2 n.\n    intros H.\n    induction H.\n    apply subseq_nil_l.\n    simpl.\n    apply subseq_space. apply IHsubseq.\n    simpl. apply subseq_add. apply IHsubseq.\nQed.\n\nTheorem subseq_app: forall l1 l2 l3: list nat, subseq l1 l2 -> subseq l1 (l2 ++ l3).\n    intros l1 l2 l3.\n    intros H.\n    induction H.\n    apply subseq_nil_l.\n    simpl. apply subseq_space. apply IHsubseq.\n    simpl. apply subseq_add. apply IHsubseq.\nQed.\n\n\n\nLemma subseq_simpl: forall n: nat, forall l1 l2 : list nat, subseq (n::l1) l2 -> \n    subseq l1 l2.\nProof.\n    intros n l1 l2.\n    induction l2.\n    intros H.\n    inversion H.\n    intros H.\n    inversion H.\n    apply subseq_space. apply IHl2. apply H2.\n    apply subseq_space. apply H1.\nQed.\n\nLemma subseq_move: forall n : nat, forall l1 l2 : list nat, subseq (n::l1) (n::l2) -> \n    subseq l1 l2.\nProof. intros n l1 l2.\n    intros H.\n    inversion H.\n    apply subseq_simpl in H2.\n    apply H2.\n    apply H1.\nQed.\n\nTheorem beq_nat_false_subseq: forall l1 l2: list nat, forall n1 n2: nat,\n    beq_nat n1 n2 = false ->\n    subseq (n1::l1) (n2::l2) ->\n    subseq (n1::l1) l2.\nProof.\n    intros l1 l2 n1 n2.\n    intros beq H.\n\n    inversion H.\n    apply H2.\n    rewrite H3 in beq.\n    rewrite <- beq_nat_refl in beq.\n    inversion beq.\nQed.\n\n(** \n*               1       2\n*       0     0 1     0 2 0 0 0\n*   9 9 0 9 9 0 1 9 9 0 2 0 0 0 9 9\n* *)\nTheorem subseq_transitive: forall l1 l2 l3: list nat, subseq l1 l2 -> subseq l2 l3 ->\n    subseq l1 l3.\nProof.\n    intros l1 l2 l3.\n    intros H1 H2.\n    generalize dependent l1.\n    generalize dependent l2.\n    induction l3.\n    intros. apply subseq_nil_x in H2. rewrite H2 in H1. apply H1.\n    intros. inversion H2. \n    Case \"FOO\".\n    subst. apply subseq_space.\n    apply IHl3 with (l2:=l2). apply H3. apply H1.\n    subst. inversion H1. subst. apply subseq_space. apply IHl3 with (l2:=l0). apply H3. apply H4.\n    subst. apply subseq_add. \n    apply IHl3 with (l2:=l0). apply H3. apply H4.\nQed.\n(* FILL IN HERE *)\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*)\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]. Proof.  apply c2. apply c2. apply c1.  Qed.\nExample R2: R 1 [1;2;1;0]. Proof. apply c3. apply c2. apply c3. apply c3. apply c2.\n    apply c2. apply c2. apply c1. Qed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\nInductive total_relation: nat -> nat -> Prop :=\n    | arb: forall n m: nat, total_relation n m.\n\nExample tr_1: total_relation 10 20. apply arb. Qed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation: nat -> nat -> Prop :=\n.\nTheorem empty_relation_implies_False: forall n m: nat,\n    empty_relation n m -> False.\nProof.\n    intros.\n    inversion H.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\nLemma le_0_implies_0 : forall n: nat, n <= 0 -> n = 0.\nProof.\n    intros n.\n    destruct n. reflexivity. intros H. inversion H.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n    induction n. apply le_n. apply le_S. apply IHn. Qed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n    intros.\n    generalize dependent m.\n    generalize dependent n.\n    induction o.\n    intros. inversion H0. subst. inversion H. apply le_n.\n    intros. inversion H0. subst. apply H.\n            subst. apply le_S. apply IHo with (n:=n).\n            apply H2. apply H.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n    intros.\n    induction H. apply le_n. apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n    intros.\n    inversion H. apply le_n.\n    apply le_trans with (n:=S n).\n    apply le_S. apply le_n.\n    apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n    intros a b.\n    induction b.\n    assert(a = a + 0). symmetry. apply plus_0_r.\n    symmetry in H. rewrite H. apply le_n.\n    assert(S(a + b) = a + S b).\n    apply plus_n_Sm.\n    symmetry in H.\n    rewrite H.\n    apply le_S.\n    apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n intros.\n split.\n apply le_trans with (n:= S(n1+n2)).\n apply n_le_m__Sn_le_Sm.\n apply le_plus_l. apply H.\n apply le_trans with (n:= S(n1+n2)).\n rewrite plus_comm.\n apply n_le_m__Sn_le_Sm.\n apply le_plus_l.\n apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n    intros.\n    apply le_S. unfold lt in H. apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n intros.\n generalize dependent n.\n induction m. destruct n. intros. inversion H. apply le_n. intros. inversion H.\n destruct n. intros. apply O_le_n.\n intros.\n inversion H.\n apply n_le_m__Sn_le_Sm.\n apply IHm.\n apply H1.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n    intros. generalize dependent n.\n    induction m.\n    intros. inversion H. reflexivity.\n    intros.\n    destruct n.\n    reflexivity.\n    simpl. apply IHm. apply Sn_le_Sm__n_le_m. apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n    intros.\n    apply le_ble_nat.\n    apply le_trans with (n:=m).\n    apply ble_nat_true. apply H.\n    apply ble_nat_true. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n intros.\n intros H1.\n apply le_ble_nat in H1.\n destruct (ble_nat n m).\n inversion H. inversion H1.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\nExample r_1: R 1 1 2. Proof. apply c2. apply c3. apply c1. Qed.\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\nTheorem nat_R: forall n m o :nat, n + m = o -> R n m o.\nProof.\n    intros.\n    generalize dependent m.\n    generalize dependent o.\n    induction n.\n    simpl. intros. subst. induction o. apply c1. apply c3. apply IHo.\n    intros.\n    destruct o. inversion H.\n    apply c2. apply IHn. inversion H. reflexivity.\nQed.\n\nTheorem R_nat: forall n m o: nat, R n m o -> (n + m = o). Proof.\n intros m n o. intro H.\n induction H. reflexivity.\n rewrite  plus_Sn_m. apply f_equal. apply IHR.\n rewrite <- plus_n_Sm. apply f_equal. apply IHR.\n inversion IHR.\n rewrite  <- plus_n_Sm  in H1.\n inversion H1.\n reflexivity.\n rewrite plus_comm. apply IHR.\nQed.\n\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop)  (n: nat): Prop :=\n    (oddb n = true -> Podd n)   /\\\n    (oddb n = false -> Peven n).\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n    intros.\n    unfold combine_odd_even.\n    destruct (oddb n).\n    split. apply H.  apply H0.\n    split. apply H. apply H0.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros.\n  apply H.\n  apply H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros.\n  apply H. apply H0.\nQed.\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n: nat) (f: nat->Prop): Prop :=\n    match n with \n    | S n' => f n -> (true_upto_n__true_everywhere n' f)\n    | 0 => forall m: nat, f m\n    end.\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. unfold true_upto_n__true_everywhere. reflexivity.  Qed.\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "darioush", "repo": "sf", "sha": "454c7f98022e2d935703c3038caa041cda835a17", "save_path": "github-repos/coq/darioush-sf", "path": "github-repos/coq/darioush-sf/sf-454c7f98022e2d935703c3038caa041cda835a17/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8279016855594374}}
{"text": "(* week_39a_binary_trees.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\nRequire Import Arith Bool unfold_tactic.\n\n(* ********** *)\n\nInductive binary_tree_nat : Type :=\n  | Leaf : nat -> binary_tree_nat\n  | Node : binary_tree_nat -> binary_tree_nat -> binary_tree_nat.\n\nDefinition bt_0 :=\n  Leaf 42.\n\nDefinition bt_1 :=\n  Node (Leaf 10)\n       (Leaf 20).\n\nDefinition bt_2 :=\n  Node (Node (Leaf 10)\n             (Leaf 20))\n       (Leaf 30).\n\n(*\nPrint bt_2.\nbt_2 = Node (Node (Leaf 10) (Leaf 20)) (Leaf 30)\n     : binary_tree_nat\n*)\n\n(* ********** *)\n\n(* A unit test: *)\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_test_for_number_of_leaves (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 1)\n  &&\n  (candidate bt_1 =n= 2)\n  &&\n  (candidate bt_2 =n= 3)\n  &&\n  (candidate (Node bt_1 bt_2) =n= 5)\n  .\n\nDefinition specification_of_number_of_leaves (number_of_leaves : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     number_of_leaves (Leaf n) = 1)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     number_of_leaves (Node t1 t2) = (number_of_leaves t1) + (number_of_leaves t2)).\n\nTheorem there_is_only_one_number_of_leaves :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_number_of_leaves f ->\n    specification_of_number_of_leaves g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_number_of_leaves.\n  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> Hf_leaf.\n  rewrite -> Hg_leaf.\n  reflexivity.\n\n  rewrite -> Hf_node.\n  rewrite -> Hg_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\nFixpoint number_of_leaves_ds (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n =>\n      1\n    | Node t1 t2 =>\n      (number_of_leaves_ds t1) + (number_of_leaves_ds t2)\n  end.\n\nLemma unfold_number_of_leaves_ds_leaf :\n  forall n : nat,\n    number_of_leaves_ds (Leaf n) = 1.\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\nLemma unfold_number_of_leaves_ds_node :\n  forall t1 t2 : binary_tree_nat,\n    number_of_leaves_ds (Node t1 t2) =\n    (number_of_leaves_ds t1) + (number_of_leaves_ds t2).\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\nDefinition number_of_leaves_v0 (t : binary_tree_nat) : nat :=\n  number_of_leaves_ds t.\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v0.\n(*\n     = true\n     : bool\n*)\n\n(* Homework:\n   write a version number_of_leaves_v1\n   that uses an accumulator.\n*)\n\n(* ********** *)\n\n(* Exercise:\n   do the same as above for computing the number of nodes\n   of a binary tree.\n*)\n\n(* ********** *)\n\n(* end of week_39a_binary_trees.v *)", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w39/week_39a_binary_trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.9252299555457567, "lm_q1q2_score": 0.8278860257324216}}
{"text": "Module logic.\n\nDefinition tautology : Prop :=\n  forall P : Prop, P -> P.\nTheorem proof_tautology : tautology.\nProof.\n intros P H. assumption. Qed.\n\nTheorem prop_trans : forall P Q R : Prop,\n  (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  intros P Q R H0 H1.\n  intros H.\n  apply H1. apply H0. apply H. Qed.\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\nCheck  and.\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\nCheck conj.\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP. Qed.  \n\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  assumption. Qed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n  apply HQ.\n  apply HP. Qed.\nPrint and_commut.\n\nTheorem and_assoc : forall P Q R : Prop,\n  (P /\\ Q) /\\ R -> P /\\ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H as [[HP HQ] HR].\n  split. apply HP.\n split. apply HQ. apply HR. Qed.\n\nTheorem conj_fact : forall P Q R : Prop,\n  P /\\ Q -> Q /\\ R -> P /\\ R.\nProof.\n  intros P Q R H0 H1.\n  inversion H0 as [HP HQ].\n  inversion H1 as [_ HR].\n split. apply HP. apply HR. Qed.\n\nDefinition iff (P Q : Prop) : Prop := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q) (at level 95, no associativity) : type_scope.\nCheck 1=1 <-> 2=2.\n\nTheorem iff_implies : forall P Q :Prop,\n  P <-> Q -> P -> Q.\n Proof.\n  intros P Q H. inversion H as [HPQ HQp]. apply HPQ. Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  P <-> Q -> Q <-> P.\nProof.\n  intros P Q H.\n  inversion H as [HPQ HQP].\n  split. apply HQP. apply HPQ. Qed.\n\nTheorem iff_refl : forall P : Prop, P <-> P.\n  intro P.\n split. apply proof_tautology. apply proof_tautology. Qed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  P <-> Q -> Q <-> R -> P <-> R.\nProof.\n  intros P Q R H0 H1.\n  inversion H0 as [HPQ HQP].\n  inversion H1 as [HQR HRQ].\n  assert (HPR : P -> R). intro H'. apply HQR. apply HPQ. apply H'.\n  assert (HRP: R -> P). intro H'. apply HQP. apply HRQ. apply H'.\n split. apply HPR. apply HRP. Qed.\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\nCheck or_introl.\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\nTheorem or_comm : forall P Q : Prop,\n  (P \\/ Q) -> (Q \\/ P).\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n  apply or_intror. apply HP.\n  apply or_introl. apply HQ. Qed.\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R H.\n  inversion  H as [HP | HQandR].\n  split.\n  apply or_introl. apply HP.\n  apply or_introl. apply HP.\n  inversion HQandR as [HQ HR].\n  split.\n  apply or_intror. apply HQ.\n  apply or_intror. apply HR. Qed.\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H as [HPandQ HPandR].\n  inversion HPandQ as [HP | HQ].\n  inversion HPandR as [_ | HR].\n  apply or_introl.  apply HP.\n  apply or_introl.  apply HP.\n  inversion HPandR as [HP | HR].\n  apply or_introl. apply HP.\n  apply or_intror. split. apply HQ. apply HR. Qed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  apply or_distributes_over_and_1.\n apply  or_distributes_over_and_2. Qed. \n\nTheorem andb_true__and : forall b c : bool,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  intros b c H.\n  destruct b. split. reflexivity.\n  destruct c. reflexivity. discriminate.\n  split. discriminate.\n  destruct c. reflexivity. discriminate. Qed.\n\nTheorem and__andb_true : forall b c : bool,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  intros b c H. inversion H as [Hb Hc].\n  rewrite -> Hb. rewrite -> Hc. reflexivity. Qed.\n\nTheorem andb_true_theorem : forall b c : bool,\n  (andb b c = true) <-> (b = true /\\ c = true).\nProof.\n  intros b c. split.\n  apply andb_true__and. apply and__andb_true. Qed.\n\nTheorem andb_false__or : forall b c : bool,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b. apply or_intror. destruct c. simpl in H. apply H.\n  reflexivity.\n  apply or_introl. reflexivity. Qed. \n\nTheorem andb_comm : forall b c : bool,\n  andb b c = andb c b.\nProof.\n  intros b c.\n  destruct b.\n  destruct c. reflexivity. reflexivity.\n  destruct c. reflexivity. reflexivity. Qed.\n\nTheorem or__andb_false : forall b c : bool,\n  b = false \\/ c = false -> andb b c = false.\nProof.\n  intros b c H.\n  inversion H as [Hb | Hc].\n  rewrite -> Hb. reflexivity.\n  rewrite -> Hc. rewrite -> andb_comm. reflexivity. Qed. \n\nTheorem andb_false_theorem : forall b c : bool,\n  (andb b c = false) <-> (b = false \\/ c = false).\nProof.\n  intros b c.\n  split.\n  apply andb_false__or.\n  apply or__andb_false. Qed.\n\nTheorem orb_true__or : forall b c : bool,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b. apply or_introl. reflexivity.\n  destruct c. apply or_intror. reflexivity.\n  simpl in H. discriminate. Qed. \n\nTheorem orb_comm : forall b c :bool,\n  orb b c = orb c b.\nProof.\n  intros b c.\n  destruct b.\n  destruct c. reflexivity. reflexivity.\n  destruct c. reflexivity. reflexivity. Qed.\n  \nTheorem or__orb_true : forall b c : bool,\n  b = true \\/ c = true -> orb b c = true.\nProof.\n  intros b c H.\n  inversion H as [Hb | Hc].\n  rewrite -> Hb. reflexivity.\n  rewrite -> Hc. rewrite -> orb_comm. reflexivity. Qed.\n\nTheorem orb_true_theorem : forall b c : bool,\n  (orb b c = true) <-> (b = true \\/ c = true).\nProof.\n  intros b c. split.\n  apply orb_true__or.\n  apply or__orb_true. Qed.\n\nTheorem orb_false__and : forall b c : bool,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b. \n  destruct c.\n  simpl in H. discriminate.\n  simpl in H. discriminate.\n  destruct c.\n  simpl in H. discriminate.\n  split. reflexivity. reflexivity. Qed.\n  \nTheorem and__orb_false : forall b c : bool,\n  b = false /\\ c = false -> orb b c = false.\nProof.\n  intros b c H.\n  inversion H as [Hb Hc].\n  rewrite -> Hb. rewrite Hc. reflexivity. Qed.\n\nTheorem orb_false_theorem : forall b c : bool,\n  (orb b c = false) <-> (b = false /\\ c = false).\nProof.\n  intros b c. split.\n  apply orb_false__and.\n  apply and__orb_false. Qed.\n\nInductive False : Prop := .\nTheorem False_implies_nonsence : \n  False -> true = false.\nProof.\n  intro H. inversion H. Qed.\nTheorem nonsence_implies_False :\n  true = false -> False.\n Proof.\n  intro H. inversion H. Qed.\nTheorem eq_False_nonsence : \n  true = false <-> False.\n Proof.\n  split.\n  apply nonsence_implies_False.\n  apply False_implies_nonsence. Qed.\nTheorem ex_falso_quodlibet : forall P : Prop,\n  False -> P.\nProof.\n  intros P H. inversion H. Qed.\n\nInductive True : Prop := tl : False -> True.\nDefinition not (P : Prop) : Prop :=  P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\n\nTheorem not_False :  ~ False.\nProof.\n  intro F. inversion F. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HnotP].\n  apply HnotP in HP. inversion HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof. \n  intros P H0. intro H. apply H. apply H0. Qed.\n\n Theorem from_double_neg : forall P : Prop,\n  ~~P -> P.\n  intros P.  unfold not. intro H.\n  Admitted.\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H. intro HQ. intro HP.\n  apply HQ. apply H. apply HP. Qed.\n  \nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intro P. intro H.\n  inversion H as [HP HnotP].\n  apply HnotP. apply HP. Qed.\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true : forall b,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  reflexivity.\n  unfold not in H. apply ex_falso_quodlibet.\n  apply H. reflexivity. Qed.\n\nTheorem true_then_not_false : forall b : bool,\n  b = true -> b <> false.\nProof.\n  intros b H. unfold not.\n  destruct b. intro H0. \n  discriminate. discriminate. Qed. \n \nTheorem true_is_not_false : forall b : bool,\n  (b <> false) <-> (b = true).\nProof.\n  intros b. split.\n  apply not_false_then_true.\n  apply true_then_not_false. Qed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem noteq_Sn_Sm_then_noteq_n_m : forall n m : nat,\n  S n <> S m -> n <> m.\nProof.\n  intros n m H. unfold not in H. unfold not.\n  intro H0. apply H. rewrite -> H0. reflexivity. Qed.\n\nTheorem eq_S : forall n m : nat,\n  S n = S m -> n = m.\n Proof.\n  intro n. induction n as [| n'].\n  intros m H. inversion H. reflexivity.\n  intros m H. inversion H. reflexivity. Qed. \n\nTheorem noteq_n_m_then_noteq_Sn_Sm : forall n m : nat,\n  n <> m -> S n <> S m.\nProof.\n  intros n m H.\n  unfold not in H. unfold not. intro H0.\n  apply H. apply eq_S. apply H0. Qed. \n\nTheorem noteq_Sn_Sm__noteq_n_m : forall n m : nat,\n  (S n <> S m) <-> (n <> m).\nProof.\n  intros n m. split.\n  apply noteq_Sn_Sm_then_noteq_n_m.\n  apply noteq_n_m_then_noteq_Sn_Sm. Qed.\n\nTheorem not_eq_then_beq_false : forall n1 n2 : nat,\n  n1 <> n2 -> beq_nat n1 n2 = false.\nProof.\n  intros n1.  induction n1 as [| n1'].\n  intros n2 H. induction n2 as [| n2'].\n  simpl. unfold not in H. apply False_implies_nonsence. apply H. reflexivity.\n  simpl. reflexivity. \n  intros n2 H. induction n2 as [| n2'].\n  simpl. reflexivity.\n  simpl. rewrite IHn1'. reflexivity. apply noteq_Sn_Sm_then_noteq_n_m.\n  apply H. Qed.\n\nTheorem zero_is_not_Sn : forall n : nat, 0 <> S n.\nProof.\n  intro n. unfold not. intro H0. inversion H0. Qed.\n\nTheorem noteq_sym : forall X : Type, forall p q : X,\n  p <> q -> q <> p.\nProof.\n  intros X P Q H. unfold not in H. unfold not. intro H0.\n  apply H. rewrite -> H0. reflexivity. Qed.\n\nTheorem beq_false_then__not_eq : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  intros n. induction n as [| n'].\n  intros m H. induction m as [| m'].\n  simpl in H. discriminate. apply zero_is_not_Sn.\n  intros m H. induction m as [| m']. apply noteq_sym. apply zero_is_not_Sn.\n  simpl in H. apply noteq_n_m_then_noteq_Sn_Sm. apply IHn'. apply H.\n  Qed.\n\nTheorem not_eq__beq_false : forall n n' : nat,\n  (n <> n') <-> (beq_nat n n' = false).\nProof.\n  intros n n'. split.\n  apply not_eq_then_beq_false.\n  apply beq_false_then__not_eq. Qed. \n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem four_ev' : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_plus4' : forall n : nat,\n  ev n -> ev (4 + n).\nProof.\n  intros n H. simpl. apply ev_SS. apply ev_SS. assumption.\n  Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nTheorem double_even : forall n : nat,\n  ev (double n).\nProof.\n  intro n. induction n as [| n'].\n  simpl. apply ev_0.\n  simpl. apply ev_SS. apply IHn'. Qed.\n\nTheorem SSev_even : forall n : nat,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. apply E'. Qed.\n\nTheorem ev_1_plus_m : forall m : nat,\n  ev 1 -> ev m -> ev (1+m).\nProof.\n  intros m H1 H2. inversion H1. Qed. \n\nInductive ex (X : Type) (P : X -> Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2).\n  reflexivity. Qed.\n\nExample exists_example_1' : exists n,\n     n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity. Qed.\n\nTheorem exists_example_2 : forall n,\n     (exists m, n = 4 + m) ->\n     (exists o, n = 2 + o).\nProof.\n  intros n H.\n  inversion H as [m Hm].\n  exists (2 + m).\n  apply Hm. Qed.\n\nTheorem dist_not_exists : forall (X : Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros X P H. unfold not. intro H1. inversion H1.\n  apply H0. apply H. Qed.\n\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q) -> P) -> P.\nDefinition classic := forall P : Prop,\n  ~~P -> P.\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q : Prop,\n  ~(~P/\\~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q : Prop,\n  (P -> Q) -> (~P \\/ Q).\n\nTheorem exmiddle_classic : \n  excluded_middle -> classic.\nProof.\n  unfold excluded_middle. unfold classic.\n  intro H. intro P. unfold not. intro H1.\n  assert (H2 : (P \\/ ~P) -> ((P -> False) -> False) -> P).\n  intros Hpnp Hpf. destruct Hpnp as [Hp | Hnp].\n  apply Hp. unfold not in Hnp. apply Hpf in Hnp. inversion Hnp.\n  apply H2. apply H. apply H1. Qed.\n\nTheorem implies_to_or_ex_middle :\n  implies_to_or -> excluded_middle.\nProof.\n  intro H. unfold excluded_middle. unfold implies_to_or in H.\n  intro P. apply or_comm. apply H. intro HP. apply HP. Qed.\n\nTheorem peirce_to_classic :\n  classic -> peirce.\nProof.\n  intro H.  unfold peirce. unfold classic in H. unfold not in H.\n  intros P Q. intro  H0.  Admitted.\n\nTheorem morgan_classic : \n   de_morgan_not_and_not -> classic.\nProof.\n  intro H. unfold classic. unfold  de_morgan_not_and_not in H.\n  intro P. intro H0. \n  assert (Hl : ~~P -> ~(~ P /\\ ~ P)). intro H'. \n  unfold not. unfold not in H'. intro H''. destruct H'' as [Hp Hq].\n  apply H' in Hp. apply Hp.\n  apply Hl in H0. apply H in H0. destruct H0 as [Hp | Hq].\n  apply Hp. apply Hq. Qed.  \n\nTheorem morgan_implies : \n   de_morgan_not_and_not -> implies_to_or.\nProof.\n  intro H. unfold implies_to_or. unfold de_morgan_not_and_not in H.\n  intros P Q. intro H0. apply H. Admitted.\n\nTheorem morgan_exmiddle : \n   de_morgan_not_and_not -> excluded_middle.\nProof. Admitted.\n\nTheorem x_to_exist : forall X : Type, forall P : X -> Prop, forall x : X,\n  P x -> exists x, P x.\nProof.\n  intros X P x. intro H. exists x. apply H. Qed.\n\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X :Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros H0. intros X P. intro H1. \n  intro x. unfold not in H1. assert (H : ((P x -> False) -> False) -> P x).\n  intro H. assert (Hl : ((P x -> False) -> False)  = ~ (~ P x) ). unfold not. reflexivity.\n  rewrite Hl in H. apply exmiddle_classic in H0. unfold classic in H0.\n  apply H0. apply H. apply H. intro H2. Admitted.\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.\nAdmitted.\n\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 :\n  ~ (2 <= 1).\nProof.\n  intros H. inversion H. inversion H1. Qed.\n\n\n\n\n\nEnd logic.", "meta": {"author": "jeorp", "repo": "SoftwareFoundations_reading", "sha": "1d85b5360f1225af103a9a78424aa8df02d234cd", "save_path": "github-repos/coq/jeorp-SoftwareFoundations_reading", "path": "github-repos/coq/jeorp-SoftwareFoundations_reading/SoftwareFoundations_reading-1d85b5360f1225af103a9a78424aa8df02d234cd/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8791467690927438, "lm_q1q2_score": 0.8278522089499766}}
{"text": "(* T7: Proposiciones definidas inductivamente *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export T6_Logica.\nRequire Coq.omega.Omega.\n1\n(* El contenido del tema es\n   1. Proposiciones definidas inductivamente.\n   2. Usando evidencias en demostraciones.\n      1. Inversi\u00f3n sobre evidencias.\n      2. Inducci\u00f3n sobre evidencias.\n   3. Relaciones inductivas.\n   4. Caso de estudio: Expresiones regulares.\n      1. Introducci\u00f3n.\n      2. La t\u00e1ctica remember .\n   5. Caso de estudio: Mejora de la reflexi\u00f3n.\n   6. Ejercicios adicionales.\n      1.Extended Exercise: A Verified Regular-Expression Matcher\n*)\n\n(* =====================================================================\n   \u00a7 1. Proposiciones definidas inductivamente.\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1. Definir inductivamente la proposici\u00f3n\n      es_par: nat -> Prop\n   tal que (es_par n) expresa que n es un n\u00famero par.\n   ------------------------------------------------------------------ *)\n\nInductive es_par: nat -> Prop :=\n| es_par_0  : es_par 0\n| es_par_SS : forall n : nat, es_par n -> es_par (S (S n)).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2. Demostrar que\n      es_par 4.\n   ------------------------------------------------------------------ *)\n\n(* 1\u00aa demostraci\u00f3n *)\nTheorem es_par_4: es_par 4.\nProof.\n  apply es_par_SS. (* es_par 2 *)\n  apply es_par_SS. (* es_par 0 *)\n  apply es_par_0.\nQed.\n\n(* 2\u00aa demostraci\u00f3n *)\nTheorem es_par_4': es_par 4.\nProof.\n  apply (es_par_SS 2 (es_par_SS 0 es_par_0)).\nQed.\n\n(* Nota *)\nCheck es_par_0.                             (* es_par 0 *)\nCheck es_par_SS.                            (* forall n : nat,\n                                                es_par n -> es_par (S (S n)) *)\nCheck (es_par_SS 0).                        (* es_par 0 -> es_par 2 *)\nCheck (es_par_SS 0 es_par_0).               (* es_par 2 *)\nCheck (es_par_SS 2).                        (* es_par 2 -> es_par 4 *)\nCheck (es_par_SS 2 (es_par_SS 0 es_par_0)). (* es_par 4 *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.3. Demostrar que\n      forall n : nat, es_par n -> es_par (4 + n).\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_suma4:\n  forall n : nat, es_par n -> es_par (4 + n).\nProof.\n  intros n.        (* n : nat\n                      ============================\n                      es_par n -> es_par (4 + n) *)\n  simpl.           (* es_par n -> es_par (S (S (S (S n)))) *)\n  intros Hn.       (* Hn : es_par n\n                      ============================\n                      es_par (S (S (S (S n)))) *)\n  apply es_par_SS. (* es_par (S (S n)) *)\n  apply es_par_SS. (* es_par n *)\n  apply Hn.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.1. Demostrar que\n      forall n : nat, es_par (doble n).\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_doble:\n  forall n : nat, es_par (doble n).\nProof.\n  induction n as [|n' HI].\n  -                        (* es_par (doble 0) *)\n    simpl.                 (* es_par 0 *)\n    apply es_par_0.\n  -                        (* n' : nat\n                              HI : es_par (doble n')\n                              ============================\n                              es_par (doble (S n')) *)\n    simpl.                 (* es_par (S (S (doble n'))) *)\n    apply es_par_SS.       (* es_par (doble n') *)\n    apply HI.\nQed.\n\n(* =====================================================================\n   \u00a7 2. Usando evidencias en demostraciones\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Nota. Programaci\u00f3n y demostraci\u00f3n en Coq son dos lados de la misma\n   moneda. En progrmaci\u00f3n se procesan datos y en demostraci\u00f3n se\n   procesan evidencias.\n   ------------------------------------------------------------------ *)\n\n(* =====================================================================\n   \u00a7\u00a7 2.1. Inversi\u00f3n sobre evidencias\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.1. Demostrar que\n      forall n : nat,\n        es_par n -> es_par (pred (pred n)).\n      ------------------------------------------------------------------ *)\n\n(* 1\u00aa demostraci\u00f3n *)\nTheorem es_par_menos_2:\n  forall n : nat,\n    es_par n -> es_par (pred (pred n)).\nProof.\n  intros n E.               (* n : nat\n                               E : es_par n\n                               ============================\n                               es_par (Nat.pred (Nat.pred n)) *)\n  inversion E as [| n' E'].\n  -                         (* H : 0 = n\n                               ============================\n                               es_par (Nat.pred (Nat.pred 0)) *)\n    simpl.                  (* es_par 0 *)\n    apply es_par_0.\n  -                         (* n' : nat\n                               E' : es_par n'\n                               H : S (S n') = n\n                               ============================\n                               es_par (Nat.pred (Nat.pred (S (S n')))) *)\n    simpl.                  (* es_par n' *)\n    apply E'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. La t\u00e1ctica (inversion E), donde E es la etiqueta de una\n   proposici\u00f3n P definida inductivamente, genera para cada uno de los\n   constructores de P las condiciones bajo las que se puede usar el\n   constructor para demostrar P.\n   ------------------------------------------------------------------ *)\n\n(* 2\u00aa demostraci\u00f3n *)\nTheorem es_par_menos_2':\n  forall n : nat,\n    es_par n -> es_par (pred (pred n)).\nProof.\n  intros n E.              (* n : nat\n                              E : es_par n\n                              ============================\n                              es_par (Nat.pred (Nat.pred n)) *)\n  destruct E as [| n' E'].\n  -                        (* es_par (Nat.pred (Nat.pred 0)) *)\n    simpl.                 (* es_par 0 *)\n    apply es_par_0.\n  -                        (* E' : es_par n'\n                              ============================\n                              es_par (Nat.pred (Nat.pred (S (S n')))) *)\n    simpl.                 (* es_par n' *)\n    apply E'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. Uso de destruct sobre evidencia con (destruct E as [| n' E']).\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.2. Demostrar que\n      forall n : nat,\n       es_par (S (S n)) -> es_par n.\n   ------------------------------------------------------------------ *)\n\n(* 1\u00ba intento *)\nTheorem es_parSS_es_par:\n  forall n : nat,\n    es_par (S (S n)) -> es_par n.\nProof.\n  intros n E.              (* n : nat\n                              E : es_par (S (S n))\n                              ============================\n                              es_par n *)\n  destruct E as [| n' E'].\n  -                        (* n : nat\n                              ============================\n                              es_par n *)\nAbort.\n\n(* ---------------------------------------------------------------------\n   Nota. Mal funcionamiento de destruct sobre evidencias de t\u00e9rminos\n   compuestos.\n   ------------------------------------------------------------------ *)\n\n(* 2\u00ba intento *)\nTheorem es_parSS_es_par:\n  forall n : nat,\n    es_par (S (S n)) -> es_par n.\nProof.\n  intros n E.               (* n : nat\n                               E : es_par (S (S n))\n                               ============================\n                               es_par n *)\n  inversion E as [| n' E']. (* n' : nat\n                               E' : es_par n\n                               H : n' = n\n                               ============================\n                               es_par n *)\n  apply E'.\nQed.\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1.3. Demostrar que\n      ~ es_par 1.\n   ------------------------------------------------------------------ *)\n\nTheorem uno_no_es_par:\n  ~ es_par 1.\nProof.\n  intros H.    (* H : es_par 1\n                  ============================\n                  False *)\n  inversion H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. uso de inversi\u00f3n sobre evidencia para contradicci\u00f3n.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.1.1. Demostrar que\n      forall n : nat,\n        es_par (S (S (S (S n)))) -> es_par n.\n   ------------------------------------------------------------------ *)\n\nTheorem SSSS_es_par:\n  forall n : nat,\n    es_par (S (S (S (S n)))) -> es_par n.\nProof.\n  intros n E.                 (* n : nat\n                                 E : es_par (S (S (S (S n))))\n                                 ============================\n                                 es_par n *)\n  inversion E as [|n' E'].    (* n' : nat\n                                 E' : es_par (S (S n))\n                                 H : n' = S (S n)\n                                 ============================\n                                 es_par n *)\n  inversion E' as [|n'' E'']. (* n'' : nat\n                                 E'' : es_par n\n                                 H0 : n'' = n\n                                 ============================\n                                 es_par n *)\n  apply E''.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.1.2. Demostrar que\n      es_par 5 -> 2 + 2 = 9.\n   ------------------------------------------------------------------ *)\n\nTheorem consecuencia_de_5_es_par:\n  es_par 5 -> 2 + 2 = 9.\nProof.\n  intros E1.                (* E1 : es_par 5\n                               ============================\n                               2 + 2 = 9 *)\n  inversion E1 as [|n2 E2]. (* n2 : nat\n                               E2 : es_par 3\n                               H : n2 = 3\n                               ============================\n                               2 + 2 = 9 *)\n  inversion E2 as [|n3 E3]. (* n3 : nat\n                               E3 : es_par 1\n                               H0 : n3 = 1\n                               ============================\n                               2 + 2 = 9 *)\n  inversion E3 as [|n4 E4].\nQed.\n\n(* =====================================================================\n   \u00a7\u00a7 2.2. Inducci\u00f3n sobre evidencias\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.2.1. Demostrar que\n      forall n : nat,\n        es_par n -> exists k, n = doble k.\n   ------------------------------------------------------------------ *)\n\n(* 1\u00ba intento*)\nLemma es_par_par_1:\n  forall n : nat,\n    es_par n -> exists k, n = doble k.\nProof.\n  intros n E.               (* n : nat\n                               E : es_par n\n                               ============================\n                               exists k : nat, n = doble k *)\n  inversion E as [| n' E'].\n  -                         (* H : 0 = n\n                               ============================\n                               exists k : nat, 0 = doble k *)\n    exists 0.                    (* 0 = doble 0 *)\n    reflexivity.\n  -                         (* n' : nat\n                               E' : es_par n'\n                               H : S (S n') = n\n                               ============================\n                               exists k : nat, S (S n') = doble k *)\n    simpl.                  (* exists k : nat, S (S n') = doble k *)\n    assert (I : (exists k', n' = doble k') ->\n                (exists k, S (S n') = doble k)).\n    +                       (* (exists k' : nat, n' = doble k') ->\n                               exists k : nat, S (S n') = doble k *)\n      intros [k' Hk'].      (* k' : nat\n                               Hk' : n' = doble k'\n                               ============================\n                               exists k : nat, S (S n') = doble k *)\n      rewrite Hk'.          (* exists k : nat, S (S (doble k')) = doble k *)\n      exists (S k').             (* S (S (doble k')) = doble (S k') *)\n      reflexivity.\n    +                       (* I : (exists k' : nat, n' = doble k') ->\n                                   exists k : nat, S (S n') = doble k\n                               ============================\n                               exists k : nat, S (S n') = doble k *)\n      apply I.              (* exists k' : nat, n' = doble k' *)\nAbort.\n\n(* 2\u00ba intento *)\nLemma es_par_par:\n  forall n : nat,\n    es_par n -> exists k, n = doble k.\nProof.\n  intros n E.                 (* n : nat\n                                 E : es_par n\n                                 ============================\n                                 exists k : nat, n = doble k *)\n  induction E as [|n' E' HI].\n  -                           (* exists k : nat, 0 = doble k *)\n    exists 0.                      (* 0 = doble 0 *)\n    reflexivity.\n  -                           (* n' : nat\n                                 E' : es_par n'\n                                 HI : exists k : nat, n' = doble k\n                                 ============================\n                                 exists k : nat, S (S n') = doble k *)\n    destruct HI as [k' Hk'].  (* k' : nat\n                                 Hk' : n' = doble k'\n                                 ============================\n                                 exists k : nat, S (S n') = doble k *)\n    rewrite Hk'.              (* exists k : nat, S (S (doble k')) = doble k *)\n    exists (S k').                 (* S (S (doble k')) = doble (S k') *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.2.2. Demostrar que\n      forall n : nat,\n        es_par n <-> exists k, n = doble k.\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_par_syss:\n  forall n : nat,\n    es_par n <-> exists k, n = doble k.\nProof.\n  intros n.             (* n : nat\n                           ============================\n                           es_par n <-> (exists k : nat, n = doble k) *)\n  split.\n  -                     (* es_par n -> exists k : nat, n = doble k *)\n    apply es_par_par.\n  -                     (* (exists k : nat, n = doble k) -> es_par n *)\n    intros [k Hk].      (* n, k : nat\n                           Hk : n = doble k\n                           ============================\n                           es_par n *)\n    rewrite Hk.         (* es_par (doble k) *)\n    apply es_par_doble.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.1. Demostrar que\n      forall n m : nat,\n        es_par n -> es_par m -> es_par (n + m).\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_suma:\n  forall n m : nat,\n    es_par n -> es_par m -> es_par (n + m).\nProof.\n  intros n m E1 E2.              (* n, m : nat\n                                    E1 : es_par n\n                                    E2 : es_par m\n                                    ============================\n                                    es_par (n + m) *)\n  induction E1 as [|n' E3 HIn'].\n  -                              (* es_par (0 + m) *)\n    simpl.                       (* es_par m *)\n    apply E2.\n  -                              (* m, n' : nat\n                                    E3 : es_par n'\n                                    E2 : es_par m\n                                    HIn' : es_par (n' + m)\n                                    ============================\n                                    es_par (S (S n') + m) *)\n    destruct E2 as [|m' E4].\n    +                            (* es_par (S (S n') + 0) *)\n      simpl.                     (* es_par (S (S (n' + 0))) *)\n      apply es_par_SS.           (* es_par (n' + 0) *)\n      apply HIn'.\n    +                            (* m' : nat\n                                    E4 : es_par m'\n                                    HIn' : es_par (n' + S (S m'))\n                                    ============================\n                                    es_par (S (S n') + S (S m')) *)\n      simpl.                     (* es_par (S (S (n' + S (S m')))) *)\n      apply es_par_SS.           (* es_par (n' + S (S m')) *)\n      apply HIn'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.2. Se considera la siguiente definici\u00f3n alternativa de\n   ser par\n      Inductive es_par': nat -> Prop :=\n      | es_par'_0    : es_par' 0\n      | es_par'_2    : es_par' 2\n      | es_par'_suma : forall n m, es_par' n -> es_par' m -> es_par' (n + m).\n\n   Demostrar que\n      forall n : nat,\n        es_par' n <-> es_par n.\n   ------------------------------------------------------------------ *)\n\nInductive es_par': nat -> Prop :=\n  | es_par'_0    : es_par' 0\n  | es_par'_2    : es_par' 2\n  | es_par'_suma : forall n m, es_par' n -> es_par' m -> es_par' (n + m).\n\nLemma es_par'_es_par_L1:\n  forall n : nat,\n    es_par' n -> es_par n.\nProof.\n  intros n E.          (* n : nat\n                          E : es_par' n\n                          ============================\n                          es_par n *)\n  induction E.\n  -                    (* es_par 0 *)\n    apply es_par_0.\n  -                    (* es_par 2 *)\n    apply es_par_SS.   (* es_par 0 *)\n    apply es_par_0.\n  -                    (* n, m : nat\n                          E1 : es_par' n\n                          E2 : es_par' m\n                          IHE1 : es_par n\n                          IHE2 : es_par m\n                          ============================\n                          es_par (n + m) *)\n    apply es_par_suma.\n    +                  (* es_par n *)\n      apply IHE1.\n    +                  (* es_par m *)\n      apply IHE2.\nQed.\n\nLemma es_par'_es_par_L2:\n  forall n : nat,\n    es_par n -> es_par' n.\nProof.\n  intros n E.                 (* n : nat\n                                 E : es_par n\n                                 ============================\n                                 es_par' n *)\n  induction E.\n  -                           (* es_par' 0 *)\n    apply es_par'_0.\n  -                           (* IHE : es_par' n\n                                 ============================\n                                 es_par' (S (S n)) *)\n    assert (es_par' (2 + n)).\n    +                         (* es_par' (2 + n) *)\n      apply es_par'_suma.\n      *                       (* es_par' 2 *)\n        apply es_par'_2.\n      *                       (* es_par' n *)\n        apply IHE.\n    +                         (* H : es_par' (2 + n)\n                                 ============================\n                                 es_par' (S (S n)) *)\n      apply H.\nQed.\n\nTheorem es_par'_es_par:\n  forall n : nat,\n    es_par' n <-> es_par n.\nProof.\n  split.\n  - apply es_par'_es_par_L1.\n  - apply es_par'_es_par_L2.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.3. Demostrar que\n      forall n m : nat,\n        es_par (n+m) -> es_par n -> es_par m.\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_es_par_es_par:\n  forall n m : nat,\n    es_par (n+m) -> es_par n -> es_par m.\nProof.\n  intros n m Enm En.              (* n, m : nat\n                                     Enm : es_par (n + m)\n                                     En : es_par n\n                                     ============================\n                                     es_par m *)\n  induction En as [|n' En' HIn'].\n  -                               (* Enm : es_par (0 + m)\n                                     ============================\n                                     es_par m *)\n    apply Enm.\n  -                               (* m, n' : nat\n                                     Enm : es_par (S (S n') + m)\n                                     En' : es_par n'\n                                     HIn' : es_par (n' + m) -> es_par m\n                                     ============================\n                                     es_par m *)\n    apply HIn'.                   (* es_par (n' + m) *)\n    simpl in Enm.                 (* Enm : es_par (S (S (n' + m))) *)\n    apply es_parSS_es_par.        (* es_par (S (S (n' + m))) *)\n    apply Enm.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 2.2.4. Demostrar que\n      forall n m p : nat,\n        es_par (n+m) -> es_par (n+p) -> es_par (m+p).\n   ------------------------------------------------------------------ *)\n\nTheorem es_par_suma_suma:\n  forall n m p : nat,\n    es_par (n+m) -> es_par (n+p) -> es_par (m+p).\nProof.\n  intros n m p H.             (* n, m, p : nat\n                                 H : es_par (n + m)\n                                 ============================\n                                 es_par (n + p) -> es_par (m + p) *)\n  apply es_par_es_par_es_par. (* es_par ((n + p) + (m + p))) *)\n  rewrite suma_conmutativa.   (* es_par ((m + p) + (n + p)) *)\n  rewrite suma_permutada.     (* es_par (n + ((m + p) + p)) *)\n  rewrite <- suma_asociativa.  (* es_par (n + (m + (p + p))) *)\n  rewrite suma_asociativa.    (* es_par ((n + m) + (p + p)) *)\n  apply es_par_suma.\n  -                           (* es_par (n + m) *)\n    apply H.\n  -                           (* es_par (p + p) *)\n    rewrite <- doble_suma.     (* es_par (doble p) *)\n    apply es_par_doble.\nQed.\n\n(* =====================================================================\n   \u00a7 3. Relaciones inductivas\n   ================================================================== *)\n\n\n(* ---------------------------------------------------------------------\n   Notas.\n   1. Las proposiciones con un argumento definen conjuntos; por ejemplo,\n      es_par define el conjunto de los n\u00fameros pares.\n   2. Las proposiciones con dos argumento definen relaciones.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Nota. Creamos el m\u00f3dulo para redefinir la relaci\u00f3n menor o igual\n   (definida por le) como menOig.\n   ------------------------------------------------------------------ *)\n\nModule RelInd.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.1. Definir inductivamente la relaci\u00f3n\n      menOig: nat -> nat -> Prop\n   tal que (menOig n m) expresa que n es menor o igual que m.\n   ------------------------------------------------------------------ *)\n\nInductive menOig: nat -> nat -> Prop :=\n  | menOig_n : forall n, menOig n n\n  | menOig_S : forall n m, (menOig n m) -> (menOig n (S m)).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.2. Definir (m <= n) como abreviatura de (menOig m n).\n   ------------------------------------------------------------------ *)\n\nNotation \"m <= n\" := (menOig m n).\n\n(* ---------------------------------------------------------------------\n   Nota. Sobre la relaciones (p.e. <=) se pueden usar las mismas\n   t\u00e1cticas que sobre las propiedades (p.e. es_par).\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.3. Demostrar que\n      3 <= 3.\n   ------------------------------------------------------------------ *)\n\nTheorem prop_menOig1:\n  3 <= 3.\nProof.\n  apply menOig_n.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.4. Demostrar que\n      3 <= 6.\n   ------------------------------------------------------------------ *)\n\nTheorem prop_menOig2 :\n  3 <= 6.\nProof.\n  apply menOig_S. (* 3 <= 5 *)\n  apply menOig_S. (* 3 <= 4 *)\n  apply menOig_S. (* 3 <= 3 *)\n  apply menOig_n.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.5. Demostrar que\n      (2 <= 1) -> 2 + 2 = 5.\n   ------------------------------------------------------------------ *)\n\nTheorem prop_menOig3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H.       (* H : 2 <= 1\n                     ============================\n                     2 + 2 = 5 *)\n  inversion H.    (* n, m : nat\n                     H2 : 2 <= 0\n                     H1 : n = 2\n                     H0 : m = 0\n                     ============================\n                     2 + 2 = 5 *)\n  inversion H2.\nQed.\n\nEnd RelInd.\n\n(* ---------------------------------------------------------------------\n   Nota. En lo que sigue, usaremos la predefiida le en lugar de menOig.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.6. Definir la relaci\u00f3n\n      mayor : nat -> nat -> Prop\n   tal que (menor m n) expresa que m es menor que n.\n   ------------------------------------------------------------------ *)\n\nDefinition menor (n m : nat) := le (S n) m.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.7. Definir la abreviatura (m < n) para (menor m n).\n   ------------------------------------------------------------------ *)\n\nNotation \"m < n\" := (menor m n).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.8. Definir inductivamente la relaci\u00f3n\n      cuadrado_de: nat -> nat -> Prop :=\n   tal que (cuadrado x y) expresa que y es el cuadrado de x.\n   ------------------------------------------------------------------ *)\n\nInductive cuadrado_de: nat -> nat -> Prop :=\n  | cuad : forall n : nat, cuadrado_de n (n * n).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.9. Definir inductivamente la relaci\u00f3n\n      siguiente_nat : nat -> nat -> Prop\n   tal que (siguiente_nat x y) expresa que y es el siguiente de x.\n   ------------------------------------------------------------------ *)\n\nInductive siguiente_nat : nat -> nat -> Prop :=\n  | sn : forall n : nat, siguiente_nat n (S n).\n\n(* ---------------------------------------------------------------------\n   Ejemplo 3.9. Definir inductivamente la relaci\u00f3n\n      siguiente_par : nat -> nat -> Prop :=\n   tal que (siguiente_par x y) expresa que y es el siguiente  n\u00famero par\n   de x.\n   ------------------------------------------------------------------ *)\n\nInductive siguiente_par : nat -> nat -> Prop :=\n  | sp_1 : forall n, es_par (S n) -> siguiente_par n (S n)\n  | sp_2 : forall n, es_par (S (S n)) -> siguiente_par n (S (S n)).\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.1. Definir inductivamente la relaci\u00f3n\n      relacion_total : nat -> nat -> Prop\n   que expresa que todos los elementos est\u00e1n relacionados.\n   ------------------------------------------------------------------ *)\n\nInductive relacion_total : nat -> nat -> Prop :=\n  | rt : forall n m : nat, relacion_total n m.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.2. Definir inductivamente la relaci\u00f3n\n      relacion_vacia : nat -> nat -> Prop\n   que expresa que ning\u00fan par de elementos est\u00e1n relacionados.\n   ------------------------------------------------------------------ *)\n\nInductive relacion_vacia : nat -> nat -> Prop :=\n  .\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.1. En los distintos apartados de este ejercicio se\n   demostrar\u00e1n propiedades de las relaciones <= y <.\n\n   Demostrar que\n      forall m n o  : nat,\n        m <= n -> n <= o -> m <= o.\n   ------------------------------------------------------------------ *)\n\nLemma le_trans :\n  forall m n o  : nat,\n    m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Emn Eno.     (* m, n, o : nat\n                               Emn : m <= n\n                               Eno : n <= o\n                               ============================\n                               m <= o *)\n  generalize dependent Emn. (* m <= n -> m <= o *)\n  generalize dependent m.   (* forall m : nat, m <= n -> m <= o *)\n  induction Eno.\n  -                         (* forall m : nat, m <= n -> m <= n *)\n    intros.                 (* n, m : nat\n                               Emn : m <= n\n                               ============================\n                               m <= n *)\n    apply Emn.\n  -                         (* n, m : nat\n                               Eno : n <= m\n                               IHEno : forall m0 : nat, m0 <= n -> m0 <= m\n                               ============================\n                               forall m0 : nat, m0 <= n -> m0 <= S m *)\n    intros.                 (* m0 : nat\n                               Emn : m0 <= n\n                               ============================\n                               m0 <= S m *)\n    apply le_S.             (* m0 <= m *)\n    apply IHEno.            (* m0 <= n *)\n    apply Emn.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.2. Demostrar que\n      forall n : nat,\n        0 <= n.\n   ------------------------------------------------------------------ *)\n\nTheorem O_le_n :\n  forall n : nat,\n    0 <= n.\nProof.\n  intros n.                (* n : nat\n                              ============================\n                              0 <= n *)\n  induction n as [|n' HI].\n  -                        (* 0 <= 0 *)\n    apply le_n.\n  -                        (* n' : nat\n                              HI : 0 <= n'\n                              ============================\n                              0 <= S n' *)\n    apply le_S.            (* 0 <= n' *)\n    apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.3. Demostrar que\n      forall n m,\n        n <= m -> S n <= S m.\n   ------------------------------------------------------------------ *)\n\nTheorem n_le_m__Sn_le_Sm :\n  forall n m,\n    n <= m -> S n <= S m.\nProof.\n  intros n m E.               (* n, m : nat\n                                 E : n <= m\n                                 ============================\n                                 S n <= S m *)\n  induction E as [|n' E' HI].\n  -                           (* S n <= S n *)\n    apply le_n.\n  -                           (* n, n' : nat\n                                 E' : n <= n'\n                                 HI : S n <= S n'\n                                 ============================\n                                 S n <= S (S n') *)\n    apply le_S.               (* S n <= S n' *)\n    apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.4. Demostrar que\n      forall n m : nat,\n        S n <= S m -> n <= m.\n   ------------------------------------------------------------------ *)\n\nLemma n_le_Sn :\n  forall n : nat,\n    n <= S n.\nProof.\n  intros.     (* n : nat\n                 ============================\n                 n <= S n *)\n  apply le_S. (* n <= n *)\n  apply le_n.\nQed.\n\nTheorem Sn_le_Sm__n_le_m :\n  forall n m : nat,\n    S n <= S m -> n <= m.\nProof.\n  intros n m E.                     (* n, m : nat\n                                       E : S n <= S m\n                                       ============================\n                                       n <= m *)\n  inversion E.\n  -                                 (* H0 : n = m\n                                       ============================\n                                       m <= m *)\n    apply le_n.\n  -                                 (* m0 : nat\n                                       H0 : S n <= m\n                                       H : m0 = m\n                                       ============================\n                                       n <= m *)\n    apply le_trans with (n := S n).\n    +                               (* n <= S n *)\n      apply n_le_Sn.\n    +                               (* S n <= m *)\n      apply H0.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.5. Demostrar que\n      forall a b : nat,\n        a <= a + b.\n   ------------------------------------------------------------------ *)\n\nTheorem le_suma_i :\n  forall a b : nat,\n    a <= a + b.\nProof.\n  intros.                   (* a, b : nat\n                               ============================\n                               a <= a + b *)\n  induction a as [|a' HI].\n  -                         (* 0 <= 0 + b *)\n    apply O_le_n.\n  -                         (* a', b : nat\n                               HI : a' <= a' + b\n                               ============================\n                               S a' <= S a' + b *)\n    simpl.                  (* S a' <= S (a' + b) *)\n    apply n_le_m__Sn_le_Sm. (* a' <= a' + b *)\n    apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.6. Demostrar que\n      forall n1 n2 m : nat,\n        n1 + n2 < m ->\n        n1 < m /\\ n2 < m.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_menor :\n  forall n1 n2 m : nat,\n    n1 + n2 < m ->\n    n1 < m /\\ n2 < m.\nProof.\n  unfold menor.                 (*\n                                   ============================\n                                   forall n1 n2 m : nat,\n                                    S (n1 + n2) <= m ->\n                                    S n1 <= m /\\ S n2 <= m *)\n  intros n1 n2 m H.             (* n1, n2, m : nat\n                                   H : S (n1 + n2) <= m\n                                   ============================\n                                   S n1 <= m /\\ S n2 <= m *)\n  split.\n  -                             (* S n1 <= m *)\n    induction H.\n    +                           (* S n1 <= S (n1 + n2) *)\n      apply n_le_m__Sn_le_Sm.   (* n1 <= n1 + n2 *)\n      apply le_suma_i.\n    +                           (* IHle : S n1 <= m\n                                   ============================\n                                   S n1 <= S m *)\n      apply le_S.               (* S n1 <= m *)\n      apply IHle.\n  -                             (* S n2 <= m *)\n    induction H.\n    +                           (* S n2 <= S (n1 + n2) *)\n      apply n_le_m__Sn_le_Sm.   (* n2 <= n1 + n2 *)\n      rewrite suma_conmutativa. (* n2 <= n2 + n1 *)\n      apply le_suma_i.\n    +                           (* IHle : S n2 <= m\n                                   ============================\n                                   S n2 <= S m *)\n      apply le_S.               (* S n2 <= m *)\n      apply IHle.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.7. Demostrar que\n      forall n m : nat,\n        n < m ->\n        n < S m.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_S :\n  forall n m : nat,\n    n < m ->\n    n < S m.\nProof.\n  unfold menor. (*\n                   ============================\n                   forall n m : nat, S n <= m -> S n <= S m *)\n  intros n m H. (* n, m : nat\n                   H : S n <= m\n                   ============================\n                   S n <= S m *)\n  apply le_S.   (* S n <= m *)\n  apply H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.8. Demostrar que\n      forall n m : nat,\n        menor_o_igual n m = true -> n <= m.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_o_igual_adecuado :\n  forall n m : nat,\n    menor_o_igual n m = true -> n <= m.\nProof.\n  intros n.                   (* n : nat\n                                 ============================\n                                 forall m : nat,\n                                  menor_o_igual n m = true -> n <= m *)\n  induction n as [|n' HIn'].\n  -                           (* forall m : nat,\n                                  menor_o_igual 0 m = true -> 0 <= m *)\n    intros.                   (* m : nat\n                                 H : menor_o_igual 0 m = true\n                                 ============================\n                                 0 <= m *)\n    apply O_le_n.\n  -                           (* n' : nat\n                                 HIn' : forall m : nat,\n                                         menor_o_igual n' m = true -> n' <= m\n                                 ============================\n                                 forall m : nat,\n                                  menor_o_igual (S n') m = true -> S n' <= m *)\n    destruct m as [|m'].\n    +                         (* menor_o_igual (S n') 0 = true -> S n' <= 0 *)\n      simpl.                  (* false = true -> S n' <= 0 *)\n      intros H.               (* H : false = true\n                                 ============================\n                                 S n' <= 0 *)\n      inversion H.\n    +                         (* m' : nat\n                                 ============================\n                                 menor_o_igual (S n') (S m') = true ->\n                                 S n' <= S m *)\n      simpl.                  (* menor_o_igual n' m' = true -> S n' <= S m' *)\n      intros.                 (* H : menor_o_igual n' m' = true\n                                 ============================\n                                 S n' <= S m' *)\n      apply n_le_m__Sn_le_Sm. (* n' <= m' *)\n      apply HIn'.             (* menor_o_igual n' m' = true *)\n      apply H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.9. Demostrar que\n      forall n m : nat,\n        n <= m ->\n        menor_o_igual n m = true.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_o_igual_correcto :\n  forall n m : nat,\n    n <= m ->\n    menor_o_igual n m = true.\nProof.\n  intros.                 (* n, m : nat\n                             H : n <= m\n                             ============================\n                             menor_o_igual n m = true *)\n  generalize dependent n. (* m : nat\n                             ============================\n                             forall n : nat,\n                              n <= m -> menor_o_igual n m = true *)\n  induction m.\n  -                       (* forall n : nat,\n                              n <= 0 -> menor_o_igual n 0 = true *)\n    intros n H.           (* n : nat\n                             H : n <= 0\n                             ============================\n                             menor_o_igual n 0 = true *)\n    inversion H.          (* H0 : n = 0\n                             ============================\n                             menor_o_igual 0 0 = true *)\n    simpl.                (* true = true *)\n    reflexivity.\n  -                       (* m : nat\n                             IHm : forall n : nat,\n                                    n <= m -> menor_o_igual n m = true\n                             ============================\n                             forall n : nat,\n                              n <= S m -> menor_o_igual n (S m) = true *)\n    destruct n.\n    +                     (* 0 <= S m -> menor_o_igual 0 (S m) = true *)\n      simpl.              (* 0 <= S m -> true = true *)\n      intros.             (* H : 0 <= S m\n                             ============================\n                             true = true *)\n      reflexivity.\n    +                     (* n : nat\n                             ============================\n                             S n <= S m -> menor_o_igual (S n) (S m) = true *)\n      intros.             (* H : S n <= S m\n                             ============================\n                             menor_o_igual (S n) (S m) = true *)\n      simpl.              (* menor_o_igual n m = true *)\n      apply IHm.          (* n <= m *)\n      apply le_S_n.       (* S n <= S m *)\n      apply H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.10. Demostrar que\n      forall n m o : nat,\n        menor_o_igual n m = true ->\n        menor_o_igual m o = true ->\n        menor_o_igual n o = true.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_o_igual_true_trans :\n  forall n m o : nat,\n    menor_o_igual n m = true ->\n    menor_o_igual m o = true ->\n    menor_o_igual n o = true.\nProof.\n  intros n m o Hnm Hmo.                  (* n, m, o : nat\n                                            Hnm : menor_o_igual n m = true\n                                            Hmo : menor_o_igual m o = true\n                                            ============================\n                                            menor_o_igual n o = true *)\n  apply menor_o_igual_correcto.          (* n <= o *)\n  apply le_trans with (n := m).\n  -                                      (* n <= m *)\n    apply menor_o_igual_adecuado in Hnm. (* Hnm : n <= m *)\n    apply Hnm.\n  -\n    apply menor_o_igual_adecuado in Hmo. (* Hmo : m <= o *)\n    apply Hmo.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3.11. Demostrar que\n      forall n m : nat,\n        menor_o_igual n m = true <-> n <= m.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_o_igual_syss :\n  forall n m : nat,\n    menor_o_igual n m = true <-> n <= m.\nProof.\n  split.\n  - apply menor_o_igual_adecuado.\n  - apply menor_o_igual_correcto.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.4.1. Se considera la relaci\u00f3n\n      R : nat -> nat -> nat -> Prop\n   definida inductivamente por\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   Demostrar que\n      R 1 1 2.\n   ------------------------------------------------------------------ *)\n\nModule R.\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\nTheorem R112 : R 1 1 2.\nProof.\n  apply c2. (* R 0 1 1 *)\n  apply c3. (* R 0 0 0 *)\n  apply c1.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.4.2. Definir una funci\u00f3n\n      fR (m:nat) (n:nat) : nat\n   tal que se verifique\n      forall m n o : nat, R m n o <-> fR m n = o\n   y demostrar dicha propiedad\n   ------------------------------------------------------------------ *)\n\nDefinition fR (m:nat) (n:nat) : nat :=\n  m + n.\n\nTheorem R_equiv_fR_L1 :\n  forall m n o : nat,\n    R m n o -> fR m n = o.\nProof.\n  intros.                           (* m, n, o : nat\n                                       H : R m n o\n                                       ============================\n                                       fR m n = o *)\n  unfold fR.                        (* m + n = o *)\n  induction H.\n  -                                 (* 0 + 0 = 0 *)\n    simpl.                          (* 0 = 0 *)\n    reflexivity.\n  -                                 (* IHR : m + n = o\n                                       ============================\n                                       S m + n = S o *)\n    simpl.                          (* S (m + n) = S o *)\n    rewrite IHR.                    (* S o = S o *)\n    reflexivity.\n  -                                 (* IHR : m + n = o\n                                       ============================\n                                       m + S n = S o *)\n    rewrite suma_conmutativa.       (* S n + m = S o *)\n    simpl.                          (* S (n + m) = S o *)\n    rewrite <- IHR.                  (* S (n + m) = S (m + n) *)\n    rewrite suma_conmutativa.       (* S (m + n) = S (m + n) *)\n    reflexivity.\n  -                                 (* IHR : S m + S n = S (S o)\n                                       ============================\n                                       m + n = o *)\n    simpl in IHR.                   (* IHR : S (m + S n) = S (S o)\n                                       ============================\n                                       m + n = o *)\n    inversion IHR.                  (* H1 : m + S n = S o\n                                       ============================\n                                       m + n = o *)\n    rewrite suma_conmutativa in H1. (* H1 : S n + m = S o\n                                       ============================\n                                       m + n = o *)\n    simpl in H1.                    (* H1 : S (n + m) = S o\n                                       ============================\n                                       m + n = o *)\n    inversion H1.                   (* H2 : n + m = o\n                                       ============================\n                                       m + n = n + m *)\n    rewrite suma_conmutativa.       (* n + m = n + m *)\n    reflexivity.\n  -                                 (* IHR : m + n = o\n                                       ============================\n                                       n + m = o *)\n    rewrite suma_conmutativa.       (* m + n = o *)\n    apply IHR.\nQed.\n\nTheorem R_equiv_fR_L2a :\n  forall n : nat, R 0 n n.\nProof.\n  induction n as [|n' HI].\n  -                        (* R 0 0 0 *)\n    apply c1.\n  -                        (* n' : nat\n                              HI : R 0 n' n'\n                              ============================\n                              R 0 (S n') (S n') *)\n    apply c3.              (* R 0 n' n' *)\n    apply HI.\nQed.\n\nTheorem R_equiv_fR_L2 :\n  forall m n o : nat,\n    fR m n = o -> R m n o.\nProof.\n  intros m.                (* m : nat\n                              ============================\n                              forall n o : nat, fR m n = o -> R m n o *)\n  unfold fR.               (* forall n o : nat, m + n = o -> R m n o *)\n  induction m as [|m' HI].\n  -                        (* forall n o : nat, 0 + n = o -> R 0 n o *)\n    simpl.                 (* forall n o : nat, n = o -> R 0 n o *)\n    intros.                (* n, o : nat\n                              H : n = o\n                              ============================\n                              R 0 n o *)\n    rewrite H.             (* R 0 o o *)\n    apply R_equiv_fR_L2a.\n  -                        (* m' : nat\n                              HI : forall n o : nat, m' + n = o -> R m' n o\n                              ============================\n                              forall n o:nat, S m' + n = o -> R (S m') n o *)\n    simpl.                 (* forall n o:nat, S (m' + n) = o -> R (S m') n o *)\n    intros.                (* n, o : nat\n                              H : S (m' + n) = o\n                              ============================\n                              R (S m') n o *)\n    rewrite <- H.           (* R (S m') n (S (m' + n)) *)\n    apply c2.              (* R m' n (m' + n) *)\n    apply HI.              (* m' + n = m' + n *)\n    reflexivity.\nQed.\n\nTheorem R_equiv_fR :\n  forall m n o : nat,\n    R m n o <-> fR m n = o.\nProof.\n  split.\n  - apply R_equiv_fR_L1.\n  - apply R_equiv_fR_L2.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.4.3. Demostrar que\n      ~(R 2 2 6)\n   ------------------------------------------------------------------ *)\n\nTheorem R_226 : ~(R 2 2 6).\nProof.\n  rewrite R_equiv_fR. (* fR 2 2 <> 6 *)\n  unfold fR.          (* 2 + 2 <> 6 *)\n  intros H.           (* H : 2 + 2 = 6\n                         ============================\n                         False *)\n  inversion H.\nQed.\n\nEnd R.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.5.1. Una lista xs es sublista de ys si todos los\n   elementos de xs ocurren en ys en el mismo orden, posiblemente con\n   algunos elementos entre ellos. Por ejemplo,\n      [1;2;3]\n   es sublista de cada una de las siguientes\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   pero no es sublista de ninguna de las siguiente\n      [1;2]\n      [1;3]\n      [5;6;2;1;7;3;8].\n\n   Definir inductivamente la propiedad\n      sublista {X : Type} : list X -> list X -> Prop\n   tal que (sublista xs ys) expresa que xs es una sublista de ys.\n   ------------------------------------------------------------------ *)\n\nInductive sublista {X : Type} : list X -> list X -> Prop :=\n  | sl1 : forall xs, sublista nil xs\n  | sl2 : forall x xs ys, sublista xs ys -> sublista (x :: xs) (x :: ys)\n  | sl3 : forall x xs ys, sublista xs ys -> sublista xs (x :: ys).\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.5.2. Demostrar que\n      forall (X :Type) (xs : list X),\n        sublista xs xs.\n   ------------------------------------------------------------------ *)\n\nTheorem sublista_refl :\n  forall (X :Type) (xs : list X),\n    sublista xs xs.\nProof.\n  intros X xs.                 (* X : Type\n                                  xs : list X\n                                  ============================\n                                  sublista xs xs *)\n  induction xs as [|x xs' HI].\n  -                            (* sublista [ ] [ ] *)\n    apply sl1.\n  -                            (* x : X\n                                  xs' : list X\n                                  HI : sublista xs' xs'\n                                  ============================\n                                  sublista (x :: xs') (x :: xs') *)\n    apply sl2.                 (* sublista xs' xs' *)\n    apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.5.3. Demostrar que\n      forall (X : Type) (xs ys zs : list X),\n        sublista xs ys -> sublista xs (ys ++ zs).\n   ------------------------------------------------------------------ *)\n\nTheorem sublista_conc :\n  forall (X : Type) (xs ys zs : list X),\n    sublista xs ys -> sublista xs (ys ++ zs).\nProof.\n  intros X xs ys zs H.               (* X : Type\n                                        xs, ys, zs : list X\n                                        H : sublista xs ys\n                                        ============================\n                                        sublista xs (ys ++ zs) *)\n  induction H as [ xs'\n                 | x xs' ys' H' HI\n                 | x xs' ys' H' HI].\n  -                                  (* X : Type\n                                        zs, xs' : list X\n                                        ============================\n                                        sublista [ ] (xs' ++ zs) *)\n    apply sl1.\n  -                                  (* x : X\n                                        xs', ys' : list X\n                                        H' : sublista xs' ys'\n                                        HI : sublista xs' (ys' ++ zs)\n                                        ============================\n                                        sublista (x::xs') ((x::ys') ++ zs) *)\n    simpl.                           (* sublista (x::xs') (x::(ys' ++ zs)) *)\n    apply sl2.                       (* sublista xs' (ys' ++ zs) *)\n    apply HI.\n  -                                  (* x : X\n                                        xs', ys' : list X\n                                        H' : sublista xs' ys'\n                                        HI : sublista xs' (ys' ++ zs)\n                                        ============================\n                                        sublista xs' ((x :: ys') ++ zs) *)\n    simpl.                           (* sublista xs' (x :: (ys' ++ zs)) *)\n    apply sl3.                       (* sublista xs' (ys' ++ zs) *)\n    apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.5.4. Demostrar que\n      forall (X :Type) (xs ys zs : list X),\n        sublista xs ys ->\n        sublista ys zs ->\n        sublista xs zs.\n   ------------------------------------------------------------------ *)\n\nTheorem sublista_trans :\n  forall (X :Type) (xs ys zs : list X),\n    sublista xs ys ->\n    sublista ys zs ->\n    sublista xs zs.\nProof.\n  intros X xs ys zs H12 H23.             (* X : Type\n                                            xs, ys, zs : list X\n                                            H12 : sublista xs ys\n                                            H23 : sublista ys zs\n                                            ============================\n                                            sublista xs zs *)\n  generalize dependent H12.              (* X : Type\n                                            xs, ys, zs : list X\n                                            H23 : sublista ys zs\n                                            ============================\n                                            sublista xs ys -> sublista xs zs *)\n  generalize dependent xs.               (* forall xs : list X,\n                                             sublista xs ys -> sublista xs zs *)\n  induction H23 as [ xs'\n                   | x xs' ys' H23' HI\n                   | x xs' ys' H23' HI].\n  -                                      (* xs' : list X\n                                            ============================\n                                            forall xs : list X,\n                                             sublista xs [ ] ->\n                                             sublista xs xs' *)\n    intros.                              (* xs', xs : list X\n                                            H12 : sublista xs [ ]\n                                            ============================\n                                            sublista xs xs' *)\n    inversion H12.                       (* xs0 : list X\n                                            H : [ ] = xs\n                                            H0 : xs0 = [ ]\n                                            ============================\n                                            sublista [ ] xs' *)\n    apply sl1.\n  -                                      (* x : X\n                                            xs', ys' : list X\n                                            H23' : sublista xs' ys'\n                                            HI : forall xs : list X,\n                                                  sublista xs xs' ->\n                                                  sublista xs ys'\n                                            ============================\n                                            forall xs : list X,\n                                             sublista xs (x :: xs') ->\n                                             sublista xs (x :: ys') *)\n    intros.                              (* xs : list X\n                                            H12 : sublista xs (x :: xs')\n                                            ============================\n                                            sublista xs (x :: ys') *)\n    inversion H12.\n    +                                    (* xs0 : list X\n                                            H : [ ] = xs\n                                            H0 : xs0 = x :: xs'\n                                            ============================\n                                            sublista [ ] (x :: ys') *)\n      apply sl1.\n    +                                    (* xs : list X\n                                            H12 : sublista xs (x :: xs')\n                                            x0 : X\n                                            xs0, ys : list X\n                                            H1 : sublista xs0 xs'\n                                            H0 : x0 :: xs0 = xs\n                                            H : x0 = x\n                                            H2 : ys = xs'\n                                            ============================\n                                            sublista (x :: xs0) (x :: ys') *)\n      apply sl2.                         (* sublista xs0 ys' *)\n      apply HI.                          (* sublista xs0 xs' *)\n      apply H1.\n    +                                    (* xs : list X\n                                            H12 : sublista xs (x :: xs')\n                                            x0 : X\n                                            xs0, ys : list X\n                                            H1 : sublista xs xs'\n                                            H0 : xs0 = xs\n                                            H : x0 = x\n                                            H2 : ys = xs'\n                                            ============================\n                                            sublista xs (x :: ys') *)\n      apply sl3.                         (* sublista xs ys' *)\n      apply HI.                          (* sublista xs xs' *)\n      apply H1.\n  -                                      (* x : X\n                                            xs', ys' : list X\n                                            H23' : sublista xs' ys'\n                                            HI : forall xs : list X,\n                                                  sublista xs xs' ->\n                                                  sublista xs ys'\n                                            ============================\n                                            forall xs : list X,\n                                             sublista xs xs' ->\n                                             sublista xs (x :: ys') *)\n    intros.                              (* xs : list X\n                                            H12 : sublista xs xs'\n                                            ============================\n                                            sublista xs (x :: ys') *)\n    apply sl3.                           (* sublista xs ys' *)\n    apply HI.                            (* sublista xs xs' *)\n    apply H12.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.6.1. Se condidera la relaci\u00f3n R definida inductivamente por\n      Inductive R : nat -> list nat -> Prop :=\n        | c1 : R 0 []\n        | c2 : forall n l, R n l -> R (S n) (n :: l)\n        | c3 : forall n l, R (S n) l -> R n l.\n\n   Demostrar que\n      R 2 [1;0]\n   ------------------------------------------------------------------ *)\n\nInductive R : nat -> list nat -> Prop :=\n  | c1 : R 0 []\n  | c2 : forall n l, R n l -> R (S n) (n :: l)\n  | c3 : forall n l, R (S n) l -> R n l.\n\nTheorem R1 : R 2 [1;0].\nProof.\n  apply c2. (* R 1 [0] *)\n  apply c2. (* R 0 [ ] *)\n  apply c1.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.6.2. Demostrar que\n      R 1 [1;2;1;0].\n   ------------------------------------------------------------------ *)\n\nTheorem R2 : R 1 [1;2;1;0].\nProof.\n  apply c3. (* R 2 [1; 2; 1; 0] *)\n  apply c2. (* R 1 [2; 1; 0] *)\n  apply c3. (* R 2 [2; 1; 0] *)\n  apply c3. (* R 3 [2; 1; 0] *)\n  apply c2. (* R 2 [1; 0] *)\n  apply c2. (* R 1 [0] *)\n  apply c2. (* R 0 [ ] *)\n  apply c1.\nQed.\n\n(* =====================================================================\n   \u00a7 4. Caso de estudio:Expresiones regulares\n   ================================================================== *)\n\n(* =====================================================================\n   \u00a7\u00a7 4.1. Introducci\u00f3n\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.1. Definir inductivamente la proposici\u00f3n reg_exp para\n   representar las expresiones regulares.\n   ------------------------------------------------------------------ *)\n\nInductive reg_exp {T : Type} : Type :=\n  | EmptySet : reg_exp\n  | EmptyStr : reg_exp\n  | Char     : T -> reg_exp\n  | App      : reg_exp -> reg_exp -> reg_exp\n  | Union    : reg_exp -> reg_exp -> reg_exp\n  | Star     : reg_exp -> reg_exp.\n\n\n(* ---------------------------------------------------------------------\n   Nota. La coincidencia entre expresiones regulares y cadenas es la\n   siguiente:\n   - EmptySet no coincide con ninguna cadena.\n\n   - EmptyStr coincide con la cadena vav\u00eda [].\n\n   - (Char x) coincide con la cadena cuyo \u00fanico elemento es x, [x]-\n\n   - Si e1 coincide con s1 y e2 con s2, entonces [App e1 e2]\n     coincide con (s1 ++ s2).\n\n   - Si e1 o e2 coincide con s, entonces (Union e1 e2) tambi\u00e9n\n     coincide con s.\n\n   - Si la cadena s se puede escribir como (s1 ++ ... ++ sk) y la\n     expresi\u00f3n e coincide con cada una de las si, entonces (Star e)\n     coincide con s.\n\n   - (Star e) coincide con la cadena vac\u00eda.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.2. Definir inductivamente la proposici\u00f3n\n      exp_match {T} : list T -> reg_exp -> Prop\n   tal que (exp_match xs e) expresa que la expresi\u00f3n regualar e coincide\n   con la cadena xs.\n   ------------------------------------------------------------------ *)\n\nInductive exp_match {T} : list T -> reg_exp -> Prop :=\n  | MEmpty   : exp_match [] EmptyStr\n  | MChar    : forall x, exp_match [x] (Char x)\n  | MApp     : forall s1 re1 s2 re2,\n                 exp_match s1 re1 ->\n                 exp_match s2 re2 ->\n                 exp_match (s1 ++ s2) (App re1 re2)\n  | MUnionL  : forall s1 re1 re2,\n                 exp_match s1 re1 ->\n                 exp_match s1 (Union re1 re2)\n  | MUnionR  : forall re1 s2 re2,\n                 exp_match s2 re2 ->\n                 exp_match s2 (Union re1 re2)\n  | MStar0   : forall re, exp_match [] (Star re)\n  | MStarApp : forall s1 s2 re,\n                 exp_match s1 re ->\n                 exp_match s2 (Star re) ->\n                 exp_match (s1 ++ s2) (Star re).\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.3. Definir la abreviatura (s =~ e) para (exp_match s e).\n   ------------------------------------------------------------------ *)\n\nNotation \"s =~ e\" := (exp_match s e) (at level 80).\n\n(* ---------------------------------------------------------------------\n   Nota. Las reglas de coincidencia son\n\n       ----------------                     (MEmpty)\n        [] =~ EmptyStr\n\n       ---------------                      (MChar)\n        [x] =~ Char x\n\n         s1 =~ re1    s2 =~ re2\n        -------------------------           (MApp)\n         s1 ++ s2 =~ App re1 re2\n\n              s1 =~ re1\n        ---------------------               (MUnionL)\n         s1 =~ Union re1 re2\n\n              s2 =~ re2\n        ---------------------               (MUnionR)\n         s2 =~ Union re1 re2\n\n        ---------------                     (MStar0)\n         [] =~ Star re\n\n         s1 =~ re    s2 =~ Star re\n        ---------------------------         (MStarApp)\n           s1 ++ s2 =~ Star re\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.4. Demostrar que\n      [1] =~ Char 1.\n   ------------------------------------------------------------------ *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.5. Demostrar que\n      [1; 2] =~ App (Char 1) (Char 2).\n   ------------------------------------------------------------------ *)\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  -                       (* [1] =~ Char 1 *)\n    apply MChar.\n  -                       (* [2] =~ Char 2 *)\n    apply MChar.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.6. Demostrar que\n      ~ ([1; 2] =~ Char 1).\n   ------------------------------------------------------------------ *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H.    (* H : [1; 2] =~ Char 1\n                  ============================\n                  False *)\n  inversion H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.7. Definir la funci\u00f3n\n      reg_exp_of_list {T} (xs : list T) :=\n   tal que (reg_exp_of_list xs) es una expresi\u00f3n regular e tal que xs\n   coincide con e. Por ejemplo,\n\n      Compute (reg_exp_of_list [1; 2; 3]).\n      = App (Char 1) (App (Char 2) (App (Char 3) EmptyStr))\n   ------------------------------------------------------------------ *)\n\nFixpoint reg_exp_of_list {T} (xs : list T) :=\n  match xs with\n  | []       => EmptyStr\n  | x :: xs' => App (Char x) (reg_exp_of_list xs')\n  end.\n\nCompute (reg_exp_of_list [1; 2; 3]).\n(* = App (Char 1) (App (Char 2) (App (Char 3) EmptyStr)) *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.8. Demostrar que\n      [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\n   ------------------------------------------------------------------ *)\n\nExample reg_exp_ex4 :\n  [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  simpl. apply (MApp [1]).\n  -                        (* [1] =~ Char 1 *)\n    apply MChar.\n  -                        (* [2; 3] =~ App (Char 2) (App (Char 3) EmptyStr) *)\n    apply (MApp [2]).\n    +                      (* [2] =~ Char 2 *)\n      apply MChar.\n    +                      (* [3] =~ App (Char 3) EmptyStr *)\n      apply (MApp [3]).\n      *                    (* [3] =~ Char 3 *)\n        apply MChar.\n      *                    (* [ ] =~ EmptyStr *)\n        apply MEmpty.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.9. Demostrar que si la cadena s coincide con la expresi\u00f3n\n   regular e, entonces tambi\u00e9n coincide con (Star e).\n   ------------------------------------------------------------------ *)\n\nLemma MStar1 :\n  forall T s (e : @reg_exp T) ,\n    s =~ e ->\n    s =~ Star e.\nProof.\n  intros T s e H.           (* T : Type\n                               s : list T\n                               e : reg_exp\n                               H : s =~ e\n                               ============================\n                               s =~ Star e *)\n  rewrite <- (conc_nil _ s). (* s ++ [ ] =~ Star e *)\n  apply (MStarApp s [] e).\n  -                         (* s =~ e *)\n    apply H.\n  -                         (* [ ] =~ Star e *)\n    apply MStar0.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. Uso de (rewrite <- (conc_nil _ s)) para transformar la\n   expresi\u00f3n en la forma conveniente para aplicar la regla MStarApp.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.1.1. Demostrar que ninguna cadena coincide con EmptySet\n   ------------------------------------------------------------------ *)\n\nLemma empty_is_empty :\n  forall T (s : list T),\n    ~ (s =~ EmptySet).\nProof.\n  intros T s H. (* T : Type\n                   s : list T\n                   H : s =~ EmptySet\n                   ============================\n                   False *)\n  inversion H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.1.2. Demostrar que si una cadena coincide con alguna de\n   las expresiones regulares e1 o e2, entonces tambi\u00e9n coincide con\n   (Union e1 e2).\n   ------------------------------------------------------------------ *)\n\nLemma MUnion' :\n  forall T (s : list T) (e1 e2 : @reg_exp T),\n    s =~ e1 \\/ s =~ e2 ->\n    s =~ Union e1 e2.\nProof.\n  intros T s e1 e2 [H1 | H2].\n  -                           (* T : Type\n                                 s : list T\n                                 e1, e2 : reg_exp\n                                 H1 : s =~ e1\n                                 ============================\n                                 s =~ Union e1 e2 *)\n    apply (MUnionL s e1).     (* s =~ e1 *)\n    apply H1.\n  -                           (* T : Type\n                                 s : list T\n                                 e1, e2 : reg_exp\n                                 H2 : s =~ e2\n                                 ============================\n                                 s =~ Union e1 e2 *)\n    apply (MUnionR _ s e2).   (* s =~ e2 *)\n    apply H2.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.1.3. Demostrar que\n      forall T (ss : list (list T)) (re : reg_exp),\n        (forall s, In s ss -> s =~ re) ->\n        fold app ss [] =~ Star re.\n   ------------------------------------------------------------------ *)\n\nLemma MStar' :\n  forall T (xss : list (list T)) (e : reg_exp),\n    (forall xs, En xs xss -> xs =~ e) ->\n    fold conc xss [] =~ Star e.\nProof.\n  intros T xss e H. (* T : Type\n                       xss : list (list T)\n                       e : reg_exp\n                       H : forall xs : list T, En xs xss -> xs =~ e\n                       ============================\n                       fold conc xss [ ] =~ Star e *)\n  induction xss as [|xs' xss' HI].\n  -                 (* H : forall xs : list T, En xs [ ] -> xs =~ e\n                       ============================\n                       fold conc [ ] [ ] =~ Star e *)\n    simpl.          (* [ ] =~ Star e *)\n    apply MStar0.\n  -                 (* xs' : list T\n                       xss' : list (list T)\n                       e : reg_exp\n                       H : forall xs : list T, En xs (xs' :: xss') -> xs =~ e\n                       HI : (forall xs : list T, En xs xss' -> xs =~ e) ->\n                            fold conc xss' [ ] =~ Star e\n                       ============================\n                       fold conc (xs' :: xss') [ ] =~ Star e *)\n    simpl.          (* xs' ++ fold conc xss' [ ] =~ Star e *)\n    apply (MStarApp xs' (fold conc xss' [ ]) e).\n    +               (* xs' =~ e *)\n      apply H.      (* En xs' (xs' :: xss') *)\n      simpl.        (* xs' = xs' \\/ En xs' xss' *)\n      left.         (* xs' = xs' *)\n      reflexivity.\n    +               (* fold conc xss' [ ] =~ Star e *)\n      apply HI.     (* forall xs : list T, En xs xss' -> xs =~ e *)\n      intros xs H1. (* xs : list T\n                       H1 : En xs xss'\n                       ============================\n                       xs =~ e *)\n      apply H.      (* En xs (xs' :: xss') *)\n      simpl.        (* xs' = xs \\/ En xs xss' *)\n      right.        (* En xs xss' *)\n      apply H1.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.2. Demostrar que\n      forall T (s1 s2 : list T),\n        s1 =~ reg_exp_of_list s2 <-> s1 = s2.\n   ------------------------------------------------------------------ *)\n\nLemma reg_exp_of_list_spec_L1 :\n  forall T (s1 s2 : list T),\n    s1 =~ reg_exp_of_list s2 -> s1 = s2.\nProof.\n  intros.                  (* T : Type\n                              s1, s2 : list T\n                              H : s1 =~ reg_exp_of_list s2\n                              ============================\n                              s1 = s2 *)\n  generalize dependent s1. (* forall s1 : list T,\n                               s1 =~ reg_exp_of_list s2 -> s1 = s2 *)\n  induction s2.\n  -                        (* forall s1 : list T,\n                               s1 =~ reg_exp_of_list [ ] -> s1 = [ ] *)\n    intros.                (* s1 : list T\n                              H : s1 =~ reg_exp_of_list [ ]\n                              ============================\n                              s1 = [ ] *)\n    inversion H.           (* H0 : [ ] = s1\n                              ============================\n                              [ ] = [ ] *)\n    reflexivity.\n  -                        (* x : T\n                              s2 : list T\n                              IHs2 : forall s1 : list T,\n                                      s1 =~ reg_exp_of_list s2 -> s1 = s2\n                              ============================\n                              forall s1 : list T,\n                               s1 =~ reg_exp_of_list (x::s2) -> s1 = x::s2 *)\n    intros.                (* s1 : list T\n                              H : s1 =~ reg_exp_of_list (x :: s2)\n                              ============================\n                              s1 = x :: s2 *)\n    inversion H.           (* s0 : list T\n                              re1 : reg_exp\n                              s3 : list T\n                              re2 : reg_exp\n                              H3 : s0 =~ Char x\n                              H4 : s3 =~ reg_exp_of_list s2\n                              H2 : s0 ++ s3 = s1\n                              H0 : re1 = Char x\n                              H1 : re2 = reg_exp_of_list s2\n                              ============================\n                              s0 ++ s3 = x :: s2 *)\n    inversion H3.          (* x0 : T\n                              H5 : [x0] = s0\n                              H7 : x0 = x\n                              ============================\n                              [x] ++ s3 = x :: s2 *)\n    subst.                 (*   s3 : list T\n                              H : [x] ++ s3 =~ reg_exp_of_list (x :: s2)\n                              H3 : [x] =~ Char x\n                              H4 : s3 =~ reg_exp_of_list s2\n                              ============================\n                              [x] ++ s3 = x :: s2 *)\n    simpl.                 (* x :: s3 = x :: s2 *)\n    simpl in H.            (* H : x::s3 =~ App (Char x) (reg_exp_of_list s2)\n                              ============================\n                              x :: s3 = x :: s2 *)\n    apply f_equal.         (* s3 = s2 *)\n    apply IHs2.            (* s3 =~ reg_exp_of_list s2 *)\n    apply H4.\nQed.\n\nLemma conc_unitaria :\n  forall (T : Type) (x : T) (xs : list T),\n    x :: xs = [x] ++ xs.\nProof.\n  reflexivity.\nQed.\n\nLemma reg_exp_of_list_spec_L2 :\n  forall T (s1 s2 : list T),\n    s1 = s2 -> s1 =~ reg_exp_of_list s2.\nProof.\n  intros.                  (* T : Type\n                              s1, s2 : list T\n                              H : s1 = s2\n                              ============================\n                              s1 =~ reg_exp_of_list s2 *)\n  generalize dependent s2. (* forall s2 : list T,\n                               s1 = s2 -> s1 =~ reg_exp_of_list s2 *)\n  induction s1.\n  -                        (* forall s2 : list T,\n                               [ ] = s2 -> [ ] =~ reg_exp_of_list s2 *)\n    intros.                (* s2 : list T\n                              H : [ ] = s2\n                              ============================\n                              [ ] =~ reg_exp_of_list s2 *)\n    inversion H.           (* H, H0 : [ ] = s2\n                              ============================\n                              [ ] =~ reg_exp_of_list [ ] *)\n    simpl.                 (* [ ] =~ EmptyStr *)\n    apply MEmpty.\n  -                        (* x : T\n                              s1 : list T\n                              IHs1 : forall s2 : list T,\n                                      s1 = s2 -> s1 =~ reg_exp_of_list s2\n                              ============================\n                              forall s2 : list T,\n                               x :: s1 = s2 -> x :: s1 =~ reg_exp_of_list s2 *)\n    intros s2 H.           (* s2 : list T\n                              H : x :: s1 = s2\n                              ============================\n                              x :: s1 =~ reg_exp_of_list s2 *)\n    rewrite conc_unitaria. (* [x] ++ s1 =~ reg_exp_of_list s2 *)\n    rewrite <- H.           (* [x] ++ s1 =~ reg_exp_of_list (x :: s1) *)\n    simpl.\n    apply (MApp [x] (Char x)\n                s1 (reg_exp_of_list s1)).\n\n    *                      (* [x] =~ Char x *)\n      apply MChar.\n    *                      (* s1 =~ reg_exp_of_list s1 *)\n      apply IHs1.          (* s1 = s1 *)\n      reflexivity.\nQed.\n\nLemma reg_exp_of_list_spec :\n  forall T (s1 s2 : list T),\n    s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  split.\n  - apply reg_exp_of_list_spec_L1.\n  - apply reg_exp_of_list_spec_L2.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.3. Definir la funci\u00f3n\n      re_chars {T : Type} (re : reg_exp) : list T\n   tal que (re_chars e) es la lista de los caracteres en la expresi\u00f3n\n   regurlar e.\n   ------------------------------------------------------------------ *)\n\nFixpoint re_chars {T : Type} (e : reg_exp) : list T :=\n  match e with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App e1 e2 => re_chars e1 ++ re_chars e2\n  | Union e1 e2 => re_chars e1 ++ re_chars e2\n  | Star re => re_chars re\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.1.4. Demostrar que si una cadena s coincide con una expresi\u00f3n\n   regular e, entonces todos los elementos de s son caracteres de e; es\n   decir,\n      forall (T : Type) (s : list T) (re : reg_exp) (x : T),\n        s =~ re ->\n        En x s ->\n        En x (re_chars re).\n   ------------------------------------------------------------------ *)\n\nTheorem in_re_match :\n  forall (T : Type) (s : list T) (re : reg_exp) (x : T),\n    s =~ re ->\n    En x s ->\n    En 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  -\n    apply Hin.\n  -\n    apply Hin.\n  -\n    simpl.\n    rewrite En_conc in *.\n    destruct Hin as [Hin | Hin].\n    +\n      left.\n      apply (IH1 Hin).\n    +\n      right.\n      apply (IH2 Hin).\n  -\n    simpl.\n    rewrite En_conc.\n    left.\n    apply (IH Hin).\n  -\n    simpl.\n    rewrite En_conc.\n    right.\n    apply (IH Hin).\n  -\n    destruct Hin.\n  -\n    simpl.\n    rewrite En_conc in Hin.\n    destruct Hin as [Hin | Hin].\n    +\n      apply (IH1 Hin).\n    +\n      apply (IH2 Hin).\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.3.1. Definir, por recursi\u00f3n, la funci\u00f3n\n      re_not_empty {T : Type} (e : @reg_exp T) : bool\n   tal que (re_not_empty e) se verifica si existe una cadena s que\n   coincide con e.\n   ------------------------------------------------------------------ *)\n\nFixpoint re_not_empty {T : Type} (e : @reg_exp T) : bool :=\n  match e with\n  | EmptySet    => false\n  | EmptyStr    => true\n  | Char _      => true\n  | App e1 e2   => (re_not_empty e1) && (re_not_empty e2)\n  | Union e1 e2 => (re_not_empty e1) || (re_not_empty e2)\n  | Star _      => true\nend.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1.4.2. Demostrar que\n      forall T (re : @reg_exp T),\n        (exists s, s =~ re) <-> re_not_empty re = true.\n   ------------------------------------------------------------------ *)\n\nLemma re_not_empty_correct :\n  forall T (re : @reg_exp T),\n    (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  split.\n  - intros H.\n    induction re as [|\n                     | c\n                     | re1 IH1 re2 IH2\n                     | re1 IH1 re2 IH2\n                     | s IH].\n    +\n      inversion H.\n      inversion H0.\n    +\n      reflexivity.\n    +\n      reflexivity.\n    +\n      simpl.\n      apply conj_verdad_syss.\n      destruct H as [s0 eq].\n      inversion eq.\n      split.\n      *\n        apply IH1.\n        exists s1.\n        apply H2.\n      *\n        apply IH2.\n        exists s2.\n        apply H3.\n    +\n      simpl.\n      apply disy_verdad_syss.\n      destruct H as [s0 eq].\n      inversion eq.\n      *\n        left.\n        apply IH1.\n        exists s0.\n        apply H1.\n      *\n        right.\n        apply IH2.\n        exists s0.\n        apply H1.\n    +\n      reflexivity.\n  -\n    intros H.\n    induction re as [\n                    |\n                    | c\n                    | re1 IH1 re2 IH2\n                    | re1 IH1 re2 IH2\n                    | s IH].\n    +\n      inversion H.\n    +\n      exists [].\n      apply MEmpty.\n\n    +\n      exists [c].\n      apply MChar.\n    +\n      simpl in H.\n      apply conj_verdad_syss in H.\n      destruct H as [ne1 ne2].\n      apply IH1 in ne1.\n      apply IH2 in ne2.\n      destruct ne1 as [s1 eq1].\n      destruct ne2 as [s2 eq2].\n      exists (s1 ++ s2). apply MApp.\n      *\n        apply eq1.\n      *\n        apply eq2.\n    +\n      simpl in H.\n      apply disy_verdad_syss in H.\n      destruct H as [H|H].\n      *\n        apply IH1 in H.\n        destruct H as [s eq].\n        exists s.\n        apply MUnionL. apply eq.\n      *\n        apply IH2 in H.\n        destruct H as [s eq].\n        exists s.\n        apply MUnionR. apply eq.\n    +\n      exists [].\n      apply MStar0.\nQed.\n\n(* =====================================================================\n   \u00a7\u00a7 4.2. La t\u00e1ctica remember\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 4.2.1. Demostrar que\n      forall T (s1 s2 : list T) (re : @reg_exp T),\n        s1 =~ Star re ->\n        s2 =~ Star re ->\n        s1 ++ s2 =~ Star re.\n   ------------------------------------------------------------------ *)\n\n(* 1\u00aa intento *)\nLemma star_app:\n  forall T (s1 s2 : list T) (re : @reg_exp T),\n    s1 =~ Star re ->\n    s2 =~ Star re ->\n    s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  inversion H1.\n  -\n    simpl.\n    intros H3.\n    apply H3.\n  -\n    subst.\n    intros H4.\n    rewrite <- conc_asociativa.\n    apply (MStarApp s0 (s3 ++ s2) re).\n    +\n      apply H0.\n    +\n      apply (MStarApp s3 s2 re).\nAbort.\n\n\n(* 2\u00aa intento *)\nLemma star_app:\n  forall T (s1 s2 : list T) (re : @reg_exp T),\n    s1 =~ Star re ->\n    s2 =~ Star re ->\n    s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  induction H1\n    as [\n       | x'\n       | s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH\n       | re1 s2' re2 Hmatch IH\n       | re''\n       | s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  -\n    simpl.\n    intros H.\n    apply H.\n  -\n    (* s2 =~ Char x' -> [x'] ++ s2 =~ Char x' *)\nAbort.\n\n(* ---------------------------------------------------------------------\n   Notas.\n   1- El problema est\u00e1 en que la induci\u00f3n sobre hip\u00f3tesis s\u00f3lo funciona\n      bien si todos sus argumentos son variables.\n   2. En este caso, uno esta una expresi\u00f3n compuesta (Star re).\n   3. Se puede intentar generalizar sobre los argumentos compuestos.\n   4.\n   ------------------------------------------------------------------ *)\n\n(* 3\u00aa intento *)\nLemma star_app:\n  forall T (s1 s2 : list T) (re re' : reg_exp),\n    re' = Star re ->\n    s1 =~ re' ->\n    s2 =~ Star re ->\n    s1 ++ s2 =~ Star re.\nAbort.\n\n(* ---------------------------------------------------------------------\n   Nota. La t\u00e1ctica (remember e as x) a\u00f1ade al contexto la ecuaci\u00f3n\n   (x = e) y sustituye todas las ocurrencias de la expresi\u00f3n e por la\n   variable x.\n   ------------------------------------------------------------------ *)\n\n(* 4\u00ba intento *)\nLemma star_app:\n  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 [\n       | x'\n       | s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH\n       | re1 s2' re2 Hmatch IH\n       | re''\n       | s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n    intros s H.\n    apply H.\n  -\n    inversion Heqre'.\n    rewrite H0 in IH2, Hmatch1.\n    intros s2 H1.\n    rewrite <- conc_asociativa.\n    apply MStarApp.\n    +\n      apply Hmatch1.\n    +\n      apply IH2.\n      *\n        reflexivity.\n      *\n        apply H1.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.2.1. Demostrar que\n      forall T (s : list T) (re : reg_exp),\n        s =~ Star re ->\n        exists ss : list (list T),\n          s = fold conc ss []\n          /\\ forall s', En s' ss -> s' =~ re.\n   ------------------------------------------------------------------ *)\n\nLemma MStar'' :\n  forall T (s : list T) (re : reg_exp),\n    s =~ Star re ->\n    exists ss : list (list T),\n      s = fold conc ss []\n      /\\ forall s', En s' ss -> s' =~ re.\nProof.\n  intros T s re H1.\n  remember (Star re) as re'.\n  induction H1\n    as [\n       | x'\n       | s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH\n       | re1 s2' re2 Hmatch IH\n       | re''\n       | s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n  -\n    inversion Heqre'.\n    exists [].\n    simpl.\n    split.\n    +\n      reflexivity.\n    +\n      intros s' H.\n      exfalso.\n      apply H.\n  -\n    inversion Heqre'.\n    apply IH2 in Heqre'.\n    destruct Heqre' as [ss0 [eq1 eq2]].\n    exists (s1 :: ss0).\n    simpl.\n    split.\n    +\n      rewrite <- eq1.\n      reflexivity.\n    +\n      intros s'.\n      intros [H|H].\n      *\n        rewrite <- H.\n        rewrite <- H0.\n        apply Hmatch1.\n      *\n        apply eq2.\n        apply H.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3. En este ejercicio se formaliza el lema del bombeo para\n   lenguajes regulares http://bit.ly/2o6Pb1D que, informalmente, dice\n   que cualquier palabra suficientemente larga en un lenguaje regular\n   puede ser bombeada - eso es, repetir una secci\u00f3n en la mitad de la\n   palabra un n\u00famero arbitrario de veces - para producir una nueva\n   palabra que tambi\u00e9n pertenece al mismo lenguaje.\n\n   M\u00e1s formalmente, sea L un lenguaje regular. Entonces existe un entero\n   p \u2265 1 (al que llamaremos \"longitud de bombeo\" y que depender\u00e1\n   exclusivamente de L) tal que cualquier cadena w perteneciente a L, de\n   longitud mayor o igual que p, puede escribirse como w = xyz\n   (p. ej. dividiendo w en tres subcadenas), de forma que se satisfacen\n   las siguientes condiciones: 1. |y| \u2265 1 2. |xy| \u2264 p 3.  \u2200 i / i \u2265 0,\n   xy^iz \u2208 L\n\n   y es la subcadena que puede ser bombeada (borrada o repetida un\n   n\u00famero i de veces como se indica en (3), y la cadena resultante\n   seguir\u00e1 perteneciendo a L. (1) significa que la cadena y que se\n   bombea debe tener como m\u00ednimo longitud uno. (2) significa que y debe\n   estar dentro de los p primeros caracteres. No hay restricciones\n   acerca de x o z.\n   ------------------------------------------------------------------ *)\n\nModule Pumping.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3.1. Definir la funci\u00f3n\n      pumping_constant {T} (re : @reg_exp T) : nat\n   tal que (pumping_constant re) es el menor longitud de las cadenas\n   bombables respecto de re.\n   ------------------------------------------------------------------ *)\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\n  match re with\n  | EmptySet      => 0\n  | EmptyStr      => 1\n  | Char _        => 2\n  | App re1 re2   =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _        => 1\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3.2. Definir la funci\u00f3n\n      napp {T} (n : nat) (l : list T) : list T\n   tal que (napp n xs) es la cadena obtenida repitiendo n veces la\n   cadena xs. Por ejemplo,\n      napp 3 [1;2] = [1; 2; 1; 2; 1; 2]\n   ------------------------------------------------------------------ *)\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0    => []\n  | S n' => l ++ napp n' l\n  end.\n\nCompute (napp 3 [1;2]).\n(* = [1; 2; 1; 2; 1; 2] *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3.3. Demostrar que\n      forall T (n m : nat) (l : list T),\n        napp (n + m) l = napp n l ++ napp m l.\n   ------------------------------------------------------------------ *)\n\nLemma napp_plus:\n  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  -\n    reflexivity.\n  -\n    simpl.\n    rewrite IHn, conc_asociativa.\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3.4. Demostrar el lema del bombeo:\n      forall T (re : @reg_exp T) s,\n        s =~ re ->\n        pumping_constant re <= longitud s ->\n        exists s1 s2 s3,\n          s = s1 ++ s2 ++ s3 /\\\n          s2 <> [] /\\\n          forall m, s1 ++ napp m s2 ++ s3 =~ re.\n   ------------------------------------------------------------------ *)\n\nImport Coq.omega.Omega.\n\nLemma orb_lt_or_iff :\n  forall a b c d,\n    a <= b \\/ c <= d <->\n    menor_o_igual a b || menor_o_igual c d = true.\nProof.\n  split.\n  -\n    intros [H | H].\n    +\n      apply menor_o_igual_syss in H.\n      rewrite H.\n      simpl.\n      reflexivity.\n    +\n      apply menor_o_igual_syss in H.\n      rewrite H.\n      destruct (menor_o_igual a b).\n      *\n        reflexivity.\n      *\n        reflexivity.\n  -\n    intros.\n    destruct (menor_o_igual a b) eqn:H1.\n    +\n      left.\n      apply menor_o_igual_syss.\n      apply H1.\n    +\n      simpl in H.\n      right.\n      apply menor_o_igual_syss.\n      apply H.\nQed.\n\nLemma plus_le_plus :\n  forall a b c d,\n    a + b <= c + d -> a <= c \\/ b <= d.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma napp_star_star :\n  forall T (l : list T) re m,\n    l =~ Star re -> napp m l =~ Star re.\nProof.\n  intros T l re.\n  induction m as [|m'].\n  -\n    simpl.\n    intros H.\n    apply MStar0.\n  -\n    simpl.\n    intros H.\n    apply star_app.\n    +\n      apply H.\n    +\n      apply IHm'.\n      apply H.\nQed.\n\nLemma napp_star :\n  forall T (l : list T) re m,\n    l =~ re -> napp m l =~ Star re.\nProof.\n  intros T l re m H.\n  apply napp_star_star.\n  replace l with (l ++ []).\n  apply MStarApp.\n  apply H.\n  apply MStar0.\n  apply conc_nil.\nQed.\n\nLemma pumping :\n  forall T (re : @reg_exp T) s,\n    s =~ re ->\n    pumping_constant re <= longitud s ->\n    exists s1 s2 s3,\n      s = s1 ++ s2 ++ s3 /\\\n      s2 <> [] /\\\n      forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [\n       | x\n       | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH\n       | re1 s2 re2 Hmatch IH\n       | re\n       | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  -\n    simpl.\n    omega.\n  -\n    simpl.\n    omega.\n  -\n    simpl.\n    intros.\n    rewrite conc_longitud in H.\n    apply plus_le_plus in H.\n    induction H.\n    +\n      apply IH1 in H.\n      destruct H, H, H.\n      exists x, x0, (x1++s2).\n      split.\n      *\n        destruct H.\n        rewrite H.\n        rewrite <- conc_asociativa.\n        rewrite <- conc_asociativa.\n        reflexivity.\n      *\n        destruct H.\n        destruct H0.\n        split.\n        --\n          assumption.\n        --\n          intros.\n          rewrite 2 conc_asociativa.\n          apply MApp.\n          rewrite <- conc_asociativa.\n          apply H1.\n          assumption.\n    +\n      apply IH2 in H.\n      destruct H, H, H, H.\n      exists (s1++x), x0, x1.\n      split.\n      *\n        rewrite <- conc_asociativa.\n        rewrite H.\n        reflexivity.\n      *\n        destruct H0.\n        split.\n        assumption.\n        intros.\n        rewrite <- conc_asociativa.\n        apply MApp.\n        assumption.\n        apply H1.\n  - simpl.\n    intros.\n    apply (le_trans (pumping_constant re1)) in H.\n    apply IH in H.\n    destruct H, H, H, H.\n    exists x, x0, x1.\n    split.\n    +\n      assumption.\n    +\n      destruct H0.\n      split.\n      *\n        assumption.\n      *\n        intros.\n        apply MUnionL.\n        apply H1.\n    +\n      apply le_plus_l.\n  -\n    simpl.\n    intros.\n    rewrite suma_conmutativa in H.\n    rewrite <- le_plus_l in H.\n    apply IH in H.\n    destruct H, H, H, H.\n    exists x, x0, x1.\n    split.\n    +\n      assumption.\n    +\n      destruct H0.\n      split.\n      *\n        assumption.\n      *\n        intros.\n        apply MUnionR.\n        apply H1.\n  -\n    simpl.\n    intros.\n    inversion H.\n  -\n    destruct s1 eqn:Hs1.\n    +\n      simpl in *.\n      intros.\n      apply IH2.\n      assumption.\n    +\n      simpl in *.\n      intros.\n      exists [], s1, s2.\n      split.\n      --\n        rewrite Hs1.\n        reflexivity.\n      --\n        split.\n        ++\n          intros contra.\n          rewrite contra in Hs1.\n          inversion Hs1.\n        ++\n          intros.\n          simpl.\n          apply star_app.\n      *\n        apply napp_star.\n        rewrite Hs1.\n        assumption.\n      *\n        assumption.\nQed.\n\nEnd Pumping.\n\n(* =====================================================================\n   \u00a7 5. Caso de estudio: Mejora de la reflexi\u00f3n\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 5.1. Demostrar que\n      forall (n : nat) (xs : list nat),\n        filtra (iguales_nat n) xs <> [] ->\n        En n xs.\n   ------------------------------------------------------------------ *)\n\nTheorem filter_not_empty_In :\n  forall (n : nat) (xs : list nat),\n    filtra (iguales_nat n) xs <> [] ->\n    En n xs.\nProof.\n  intros n xs.\n  induction xs as [|x xs' IHxs'].\n  -\n    simpl.\n    intros H.\n    apply H.\n    reflexivity.\n  -\n    simpl.\n    destruct (iguales_nat n x) eqn:H.\n    +\n      intros _.\n      rewrite iguales_nat_bool_prop in H.\n      rewrite H.\n      left.\n      reflexivity.\n    +\n      intros H'.\n      right.\n      apply IHxs'.\n      apply H'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. Se simplifica la demostraci\u00f3n en filter_not_empty_In'.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 5.2. Definir inductivamente la propiedad\n      reflect (P : Prop) : bool -> Prop\n   que expresa que la propiedad P se refleja en el booleano b; es decir,\n   (reflect P b) se verifica syss (P <-> b = true).\n   ------------------------------------------------------------------ *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n  | ReflectT : P -> reflect P true\n  | ReflectF : ~ P -> reflect P false.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 5.3. Demostrar que\n      forall (P : Prop) (b : bool),\n        (P <-> b = true) -> reflect P b.\n   ------------------------------------------------------------------ *)\n\nTheorem iff_reflect :\n  forall (P : Prop) (b : bool),\n    (P <-> b = true) -> reflect P b.\nProof.\n  intros P b H.\n  destruct b.\n  -\n    apply ReflectT.\n    rewrite H.\n    reflexivity.\n  -\n    apply ReflectF.\n    rewrite H.\n    intros H'.\n    inversion H'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 5.1. Demostrar que\n      forall (P : Prop) (b : bool),\n        reflect P b -> (P <-> b = true).\n   ------------------------------------------------------------------ *)\n\nTheorem reflect_iff :\n  forall (P : Prop) (b : bool),\n    reflect P b -> (P <-> b = true).\nProof.\n  intros.\n  inversion H.\n  -\n    split.\n    +\n      intros.\n      reflexivity.\n    +\n      intros _.\n      assumption.\n  -\n    split.\n    +\n      intros.\n      apply H0 in H2.\n      inversion H2.\n    +\n      intros.\n      inversion H2.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 5.4. Demostrar que\n      forall n m : nat,\n        reflect (n = m) (iguales_nat n m).\n   ------------------------------------------------------------------ *)\n\nLemma iguales_natP :\n  forall n m : nat,\n    reflect (n = m) (iguales_nat n m).\nProof.\n  intros n m.\n  apply iff_reflect.\n  rewrite iguales_nat_bool_prop.\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 5.5. Demostrar que\n      forall (n : nat) (xs : list nat),\n        filtra (iguales_nat n) xs <> [] ->\n        En n xs.\n   ------------------------------------------------------------------ *)\n\nTheorem filter_not_empty_In' :\n  forall (n : nat) (xs : list nat),\n    filtra (iguales_nat n) xs <> [] ->\n    En n xs.\nProof.\n  intros n xs.\n  induction xs as [|x xs' HI].\n  -\n    simpl.\n    intros H.\n    apply H.\n    reflexivity.\n  -\n    simpl.\n    destruct (iguales_natP n x) as [H | H].\n    +\n      intros _.\n      rewrite H.\n      left.\n      reflexivity.\n    +\n      intros H'.\n      right.\n      apply HI.\n      apply H'.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 5.2. Se considera la funci\u00f3n\n      count : nat -> list nat -> nat\n   definida por\n      Fixpoint count (n : nat) (xs : list nat) : nat :=\n        match xs with\n        | [] => 0\n        | x :: xs' => (if iguales_nat n x then 1 else 0) + count n xs'\n        end.\n\n   Demostrar que\n      forall (n : nat) (xs : list nat),\n        count n xs = 0 -> ~(En n xs).\n   ------------------------------------------------------------------ *)\n\nFixpoint count (n : nat) (xs : list nat) : nat :=\n  match xs with\n  | [] => 0\n  | x :: xs' => (if iguales_nat n x then 1 else 0) + count n xs'\n  end.\n\nTheorem iguales_natP_practice :\n  forall (n : nat) (xs : list nat),\n    count n xs = 0 -> ~(En n xs).\nProof.\n  induction xs as [|x xs' HI].\n  -\n    simpl.\n    intros _.\n    intros H.\n    assumption.\n  -\n    simpl.\n    destruct (iguales_natP n x) as [H | H].\n    +\n      intros H1.\n      inversion H1.\n    +\n      simpl.\n      intros H1 [H2 | H2].\n      *\n        apply H.\n        symmetry.\n        apply H2.\n      *\n        apply HI in H1.\n        apply H1.\n        apply H2.\nQed.\n\n(* =====================================================================\n   \u00a7 6. Ejercicios adicionales.\n   ================================================================== *)\n\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.1.1. Definir inductivamente la propiedad\n      noTartamudea {X:Type} : list X -> Prop\n   tal que (noTartamudea xs) expresa que xs es una lista sin elementos\n   consecutivos iguales.\n   ------------------------------------------------------------------ *)\n\nInductive noTartamudea {X:Type} : list X -> Prop :=\n  | nt_vacia    : noTartamudea []\n  | nt_unitaria : forall x, noTartamudea [x]\n  | nt_general  : forall x y xs, x <> y ->\n                            noTartamudea (y::xs) ->\n                            noTartamudea (x::y::xs).\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.1.2. Demostrar que\n      noTartamudea [3;1;4;1;5;6].\n   ------------------------------------------------------------------ *)\n\n(* 1\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_1: noTartamudea [3;1;4;1;5;6].\nProof.\n  apply nt_general.\n  -\n    apply iguales_nat_falso_syss.\n    auto.\n  -\n    apply nt_general.\n    +\n      apply iguales_nat_falso_syss.\n      auto.\n    +\n      apply nt_general.\n      *\n        apply iguales_nat_falso_syss.\n        auto.\n      *\n        apply nt_general.\n        --\n          apply iguales_nat_falso_syss.\n          auto.\n        --\n          apply nt_general.\n          ++\n            apply iguales_nat_falso_syss.\n            auto.\n          ++\n            apply nt_unitaria.\nQed.\n\n(* 2\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_1a: noTartamudea [3;1;4;1;5;6].\nProof.\n  repeat constructor; apply iguales_nat_falso_syss; auto.\nQed.\n\n(* ---------------------------------------------------------------------\n   Nota. Uso de repetici\u00f3n de repeticiones (con repeat) y concatenaci\u00f3n\n   (con ;) de t\u00e1cticas.\n   ------------------------------------------------------------------ *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.1.3. Demostrar que\n      noTartamudea (@nil nat).\n   ------------------------------------------------------------------ *)\n\n(* 1\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_2a:\n  noTartamudea (@nil nat).\nProof.\n  apply nt_vacia.\nQed.\n\n(* 2\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_2:\n  noTartamudea (@nil nat).\nProof.\n  repeat constructor; apply iguales_nat_falso_syss; auto.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.1.4. Demostrar que\n      noTartamudea [5].\n   ------------------------------------------------------------------ *)\n\nExample prop_noTartamudea_3a:\n  noTartamudea [5].\nProof.\n  apply nt_unitaria.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.1.5. Demostrar que\n      not (noTartamudea [3;1;1;4]).\n   ------------------------------------------------------------------ *)\n\n(* 1\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_4a:\n  not (noTartamudea [3;1;1;4]).\nProof.\n  intro.\n  inversion H.\n  subst.\n  clear H H2.\n  inversion H4.\n  subst.\n  apply H1.\n  reflexivity.\nQed.\n\n(* 2\u00aa demostraci\u00f3n *)\nExample prop_noTartamudea_4:\n  not (noTartamudea [3;1;1;4]).\nProof.\n  intro.\n  repeat match goal with\n           h: noTartamudea _ |- _ => inversion h; clear h; subst\n         end.\n  apply H1 ; reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.2.1. Definir inductivamente la relaci\u00f3n\n      in_merge {X : Type} : list X -> list X -> list X\n   tal que (in_merge xs ys zs) expresa que zs es la lista obtenida\n   intercalando los elementos de xs e ys. Por ejemplo,\n      in_merge [1;6;2] [4;3] [1;4;6;2;3]\n   ------------------------------------------------------------------ *)\n\nInductive in_merge {X : Type} : list X -> list X -> list X -> Prop :=\n  | merge_vacioI  : forall xs, in_merge [] xs xs\n  | merge_vacioD  : forall xs, in_merge xs [] xs\n  | merge_general : forall x xs y ys zs, in_merge xs ys zs ->\n                                    in_merge (x::xs) (y::ys) (x::y::zs).\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.2.2. Demostrar que\n      forall (X : Type) (xs ys zs : list X) (p : X -> bool),\n        in_merge xs ys zs ->\n        Todos (fun x => p x = true) xs ->\n        Todos (fun x => p x = false) ys ->\n        filtra p zs = xs.\n   ------------------------------------------------------------------ *)\n\nLemma filter_nothing :\n  forall (X : Type) (p: X -> bool) (xs: list X),\n    Todos (fun x => p x = false) xs ->\n    filtra p xs = [].\nProof.\n  intros X p.\n  induction xs as [|x xs' HI].\n  -\n    reflexivity.\n  -\n    simpl.\n    intros [H1 H2].\n    rewrite H1.\n    apply HI.\n    apply H2.\nQed.\n\nLemma filter_everything :\n  forall (X : Type) (p : X -> bool) (xs : list X),\n    Todos (fun x => p x = true) xs ->\n    filtra p xs = xs.\nProof.\n  intros X p.\n  induction xs as [|s xs' HI].\n  -\n    reflexivity.\n  -\n    simpl.\n    intros [H1 H2].\n    rewrite H1.\n    rewrite HI.\n    +\n      reflexivity.\n    +\n      apply H2.\nQed.\n\nTheorem filter_spec :\n  forall (X : Type) (xs ys zs : list X) (p : X -> bool),\n  in_merge xs ys zs ->\n  Todos (fun x => p x = true) xs ->\n  Todos (fun x => p x = false) ys ->\n  filtra p zs = xs.\nProof.\n  intros X xs ys zs p H Hxs Hys.\n  induction H as [ xs'\n                 | xs'\n                 | x xs' y ys' zs' HI].\n  -\n    apply filter_nothing.\n    apply Hys.\n  -\n    apply filter_everything.\n    apply Hxs.\n  -\n    assert (Hx : p x = true).\n    +\n      apply Hxs.\n    +\n      simpl.\n      rewrite Hx.\n      apply f_equal.\n      *\n        assert (Hy : p y = false).\n        --\n          apply Hys.\n        --\n          rewrite Hy.\n          apply IHHI.\n          ++\n            apply Hxs.\n          ++\n            apply Hys.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.3.1. Definir inductivamente la propiedad\n      pal {X : Type} : list X -> Prop\n   tal que (pal xs) expresa que xs es un pal\u00edndromo.\n   ------------------------------------------------------------------ *)\n\nInductive pal {X : Type} : list X -> Prop :=\n  | pal_vacio   : pal []\n  | pal_unit    : forall x, pal [x]\n  | pal_general : forall x xs, pal xs -> pal (x::xs++[x]).\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.3.2. Demostrar que\n      pal [3;3].\n   ------------------------------------------------------------------ *)\n\nLemma pa_ej1 : pal [3;3].\nProof.\n  assert ([3;3] = (3::[]++[3])).\n  -\n    simpl.\n    reflexivity.\n  -\n    rewrite H.\n    apply pal_general.\n    apply pal_vacio.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 6.3.3. Demostrar que\n      pal [3;5;3].\n   ------------------------------------------------------------------ *)\n\nLemma pa_ej2 : pal [3;5;3].\nProof.\n  assert ([3;5;3] = (3::[5]++[3])).\n  -\n    simpl.\n    reflexivity.\n  -\n    rewrite H.\n    apply pal_general.\n    apply pal_unit.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.6.4. Demostrar que\n      forall (X : Type) (xs : list X),\n        pal (xs ++ inversa xs).\n   ------------------------------------------------------------------ *)\n\nLemma pal_app_rev : forall (X : Type) (xs : list X),\n    pal (xs ++ inversa xs).\nProof.\n  intros X xs.\n  induction xs as [| x xs' HI].\n  -\n    simpl.\n    apply pal_vacio.\n  -\n    simpl.\n    assert (x :: xs' ++ inversa xs' ++ [x] =\n            x :: (xs' ++ inversa xs') ++ [x]).\n    +\n      rewrite conc_asociativa.\n      reflexivity.\n    +\n      rewrite H.\n      apply pal_general.\n      apply HI.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.6.5. Demostrar que\n      forall (X : Type) (xs : list X),\n         pal xs -> xs = inversa xs.\n   ------------------------------------------------------------------ *)\n\nLemma pal_rev : forall (X : Type) (xs : list X),\n    pal xs -> xs = inversa xs.\nProof.\n  intros X xs H.\n  induction H as [ | x | x xs _ HI].\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    rewrite inversa_conc.\n    simpl.\n    rewrite <- HI.\n    reflexivity.\nQed.\n\nLemma palindrome_converse_aux1 : forall (X:Type) (l l': list X) (a b: X),\n    a :: l = l' ++ b :: nil -> (a = b /\\ l = nil) \\/ exists k, l = k ++ b :: nil.\n\nLemma tool2 : forall (X:Type) (l1 l2 : list X) (a b: X),\n     l1 ++ a :: nil = l2 ++ b :: nil -> a = b /\\ l1 = l2.\n\nLemma palindrome_converse_aux: forall (X: Type) (n: nat) (xs: list X),\n    longitud xs <= n -> xs = inversa xs -> pal xs.\nProof.\n  induction n as [|n' HI].\n  -\n    intros xs H H0.\n    assert (xs = []).\n    +\n      destruct xs as [|y ys].\n      *\n        reflexivity.\n      *\n        simpl in H.\n        inversion H.\n    +\n      rewrite H1.\n      apply pal_vacio.\n  -\n    intros xs H H0.\n    destruct xs as [|y ys].\n    +\n      apply pal_vacio.\n    +\n\n\n\n\n\nLemma palindrome_converse : forall (X : Type) (xs : list X),\n    xs = inversa xs -> pal xs.\nProof.\n  intros X xs H.\n  induction xs as [|x xs' HI].\n  -\n    apply pal_vacio.\n  -\n    destruct xs' as [|y ys].\n    +\n      apply pal_unit.\n    +\n\n\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Again, the converse direction is significantly more difficult, due\n    to the lack of evidence.  Using your definition of [pal] from the\n    previous exercise, prove that\n\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (NoDup)  *)\n(** Recall the definition of the [In] property from the [Logic]\n    chapter, which asserts that a value [x] appears at least once in a\n    list [l]: *)\n\n(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=\n   match l with\n   | [] => False\n   | x' :: l' => x' = x \\/ In A x l'\n   end *)\n\n(** Your first task is to use [In] to define a proposition [disjoint X\n    l1 l2], which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in\n    common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [In] to define an inductive proposition [NoDup X\n    l], which should be provable exactly when [l] is a list (with\n    elements of type [X]) where every member is different from every\n    other.  For example, [NoDup nat [1;2;3;4]] and [NoDup\n    bool []] should be provable, while [NoDup nat [1;2;1]] and\n    [NoDup bool [true;true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (pigeonhole_principle)  *)\n(** The _pigeonhole principle_ states a basic fact about counting: if\n    we distribute more than [n] items into [n] pigeonholes, some\n    pigeonhole must contain at least two items.  As often happens, this\n    apparently trivial fact about numbers requires non-trivial\n    machinery to prove, but we now have enough... *)\n\n(** First prove an easy useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  En x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a property [repeats] such that [repeats X l] asserts\n    that [l] contains at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now, here's a way to formalize the pigeonhole principle.  Suppose\n    list [l2] represents a list of pigeonhole labels, and list [l1]\n    represents the labels assigned to a list of items.  If there are\n    more items than labels, at least two items must have the same\n    label -- i.e., list [l1] must contain repeats.\n\n    This proof is much easier if you use the [excluded_middle]\n    hypothesis to show that [In] is decidable, i.e., [forall x l, (En x\n    l) \\/ ~ (En x l)].  However, it is also possible to make the proof\n    go through _without_ assuming that [In] is decidable; if you\n    manage to do this, you will not need the [excluded_middle]\n    hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\n   excluded_middle ->\n   (forall x, En x l1 -> En x l2) ->\n   length l2 < length l1 ->\n   repeats l1.\nProof.\n   intros X l1. induction l1 as [|x l1' IHl1'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ================================================================= *)\n(** ** Extended Exercise: A Verified Regular-Expression Matcher *)\n\n(** We have now defined a match relation over regular expressions and\n    polymorphic lists. We can use such a definition to manually prove that\n    a given regex matches a given string, but it does not give us a\n    program that we can run to determine a match autmatically.\n\n    It would be reasonable to hope that we can translate the definitions\n    of the inductive rules for constructing evidence of the match relation\n    into cases of a recursive function reflects the relation by recursing\n    on a given regex. However, it does not seem straightforward to define\n    such a function in which the given regex is a recursion variable\n    recognized by Coq. As a result, Coq will not accept that the function\n    always terminates.\n\n    Heavily-optimized regex matchers match a regex by translating a given\n    regex into a state machine and determining if the state machine\n    accepts a given string. However, regex matching can also be\n    implemented using an algorithm that operates purely on strings and\n    regexes without defining and maintaining additional datatypes, such as\n    state machines. We'll implemement such an algorithm, and verify that\n    its value reflects the match relation. *)\n\n(** We will implement a regex matcher that matches strings represeneted\n    as lists of ASCII characters: *)\nRequire Export Coq.Strings.Ascii.\n\nDefinition string := list ascii.\n\n(** The Coq standard library contains a distinct inductive definition\n    of strings of ASCII characters. However, we will use the above\n    definition of strings as lists as ASCII characters in order to apply\n    the existing definition of the match relation.\n\n    We could also define a regex matcher over polymorphic lists, not lists\n    of ASCII characters specifically. The matching algorithm that we will\n    implement needs to be able to test equality of elements in a given\n    list, and thus needs to be given an equality-testing\n    function. Generalizing the definitions, theorems, and proofs that we\n    define for such a setting is a bit tedious, but workable. *)\n\n(** The proof of correctness of the regex matcher will combine\n    properties of the regex-matching function with properties of the\n    [match] relation that do not depend on the matching function. We'll go\n    ahead and prove the latter class of properties now. Most of them have\n    straightforward proofs, which have been given to you, although there\n    are a few key lemmas that are left for you to prove. *)\n\n\n(** Each provable [Prop] is equivalent to [True]. *)\nLemma provable_equiv_true : forall (P : Prop), P -> (P <-> True).\nProof.\n  intros.\n  split.\n  - intros. constructor.\n  - intros _. apply H.\nQed.\n\n(** Each [Prop] whose negation is provable is equivalent to [False]. *)\nLemma not_equiv_false : forall (P : Prop), ~P -> (P <-> False).\nProof.\n  intros.\n  split.\n  - apply H.\n  - intros. inversion H0.\nQed.\n\n(** [EmptySet] matches no string. *)\nLemma null_matches_none : forall (s : string), (s =~ EmptySet) <-> False.\nProof.\n  intros.\n  apply not_equiv_false.\n  unfold not. intros. inversion H.\nQed.\n\n(** [EmptyStr] only matches the empty string. *)\nLemma empty_matches_eps : forall (s : string), s =~ EmptyStr <-> s = [ ].\nProof.\n  split.\n  - intros. inversion H. reflexivity.\n  - intros. rewrite H. apply MEmpty.\nQed.\n\n(** [EmptyStr] matches no non-empty string. *)\nLemma empty_nomatch_ne : forall (a : ascii) s, (a :: s =~ EmptyStr) <-> False.\nProof.\n  intros.\n  apply not_equiv_false.\n  unfold not. intros. inversion H.\nQed.\n\n(** [Char a] matches no string that starts with a non-[a] character. *)\nLemma char_nomatch_char :\n  forall (a b : ascii) s, b <> a -> (b :: s =~ Char a <-> False).\nProof.\n  intros.\n  apply not_equiv_false.\n  unfold not.\n  intros.\n  apply H.\n  inversion H0.\n  reflexivity.\nQed.\n\n(** If [Char a] matches a non-empty string, then the string's tail is empty. *)\nLemma char_eps_suffix : forall (a : ascii) s, a :: s =~ Char a <-> s = [ ].\nProof.\n  split.\n  - intros. inversion H. reflexivity.\n  - intros. rewrite H. apply MChar.\nQed.\n\n(** [App re0 re1] matches string [s] iff [s = s0 ++ s1], where [s0]\n    matches [re0] and [s1] matches [re1]. *)\nLemma app_exists : forall (s : string) re0 re1,\n    s =~ App re0 re1 <->\n    exists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\nProof.\n  intros.\n  split.\n  - intros. inversion H. exists s1, s2. split.\n    * reflexivity.\n    * split. apply H3. apply H4.\n  - intros [ s0 [ s1 [ Happ [ Hmat0 Hmat1 ] ] ] ].\n    rewrite Happ. apply (MApp s0 _ s1 _ Hmat0 Hmat1).\nQed.\n\n(** **** Exercise: 3 stars, optional (app_ne)  *)\n(** [App re0 re1] matches [a::s] iff [re0] matches the empty string\n    and [a::s] matches [re1] or [s=s0++s1], where [a::s0] matches [re0]\n    and [s1] matches [re1].\n\n    Even though this is a property of purely the match relation, it is a\n    critical observation behind the design of our regex matcher. So (1)\n    take time to understand it, (2) prove it, and (3) look for how you'll\n    use it later. *)\nLemma app_ne : forall (a : ascii) s re0 re1,\n    a :: s =~ (App re0 re1) <->\n    ([ ] =~ re0 /\\ a :: s =~ re1) \\/\n    exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** [s] matches [Union re0 re1] iff [s] matches [re0] or [s] matches [re1]. *)\nLemma union_disj : forall (s : string) re0 re1,\n    s =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof.\n  intros. split.\n  - intros. inversion H.\n    + left. apply H2.\n    + right. apply H2.\n  - intros [ H | H ].\n    + apply MUnionL. apply H.\n    + apply MUnionR. apply H.\nQed.\n\n(** **** Exercise: 3 stars, optional (star_ne)  *)\n(** [a::s] matches [Star re] iff [s = s0 ++ s1], where [a::s0] matches\n    [re] and [s1] matches [Star re]. Like [app_ne], this observation is\n    critical, so understand it, prove it, and keep it in mind.\n\n    Hint: you'll need to perform induction. There are quite a few\n    reasonable candidates for [Prop]'s to prove by induction. The only one\n    that will work is splitting the [iff] into two implications and\n    proving one by induction on the evidence for [a :: s =~ Star re]. The\n    other implication can be proved without induction.\n\n    In order to prove the right property by induction, you'll need to\n    rephrase [a :: s =~ Star re] to be a [Prop] over general variables,\n    using the [remember] tactic.  *)\n\nLemma star_ne : forall (a : ascii) s re,\n    a :: s =~ Star re <->\n    exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re /\\ s1 =~ Star re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The definition of our regex matcher will include two fixpoint\n    functions. The first function, given regex [re], will evaluate to a\n    value that reflects whether [re] matches the empty string. The\n    function will satisfy the following property: *)\nDefinition refl_matches_eps m :=\n  forall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).\n\n(** **** Exercise: 2 stars, optional (match_eps)  *)\n(** Complete the definition of [match_eps] so that it tests if a given\n    regex matches the empty string: *)\nFixpoint match_eps (re: @reg_exp ascii) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (match_eps_refl)  *)\n(** Now, prove that [match_eps] indeed tests if a given regex matches\n    the empty string.  (Hint: You'll want to use the reflection lemmas\n    [ReflectT] and [ReflectF].) *)\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define other functions that use [match_eps]. However, the\n    only property of [match_eps] that you'll need to use in all proofs\n    over these functions is [match_eps_refl]. *)\n\n\n(** The key operation that will be performed by our regex matcher will\n    be to iteratively construct a sequence of regex derivatives. For each\n    character [a] and regex [re], the derivative of [re] on [a] is a regex\n    that matches all suffixes of strings matched by [re] that start with\n    [a]. I.e., [re'] is a derivative of [re] on [a] if they satisfy the\n    following relation: *)\n\nDefinition is_der re (a : ascii) re' :=\n  forall s, a :: s =~ re <-> s =~ re'.\n\n(** A function [d] derives strings if, given character [a] and regex\n    [re], it evaluates to the derivative of [re] on [a]. I.e., [d]\n    satisfies the following property: *)\nDefinition derives d := forall a re, is_der re a (d a re).\n\n(** **** Exercise: 3 stars, optional (derive)  *)\n(** Define [derive] so that it derives strings. One natural\n    implementation uses [match_eps] in some cases to determine if key\n    regex's match the empty string. *)\nFixpoint derive (a : ascii) (re : @reg_exp ascii) : @reg_exp ascii\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** The [derive] function should pass the following tests. Each test\n    establishes an equality between an expression that will be\n    evaluated by our regex matcher and the final value that must be\n    returned by the regex matcher. Each test is annotated with the\n    match fact that it reflects. *)\nExample c := ascii_of_nat 99.\nExample d := ascii_of_nat 100.\n\n(** \"c\" =~ EmptySet: *)\nExample prop_der0 : match_eps (derive c (EmptySet)) = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char c: *)\nExample prop_der1 : match_eps (derive c (Char c)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char d: *)\nExample prop_der2 : match_eps (derive c (Char d)) = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ App (Char c) EmptyStr: *)\nExample prop_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ App EmptyStr (Char c): *)\nExample prop_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Star c: *)\nExample prop_der5 : match_eps (derive c (Star (Char c))) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char c) (Char d): *)\nExample prop_der6 :\n  match_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char d) (Char c): *)\nExample prop_der7 :\n  match_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 4 stars, optional (derive_corr)  *)\n(** Prove that [derive] in fact always derives strings.\n\n    Hint: one proof performs induction on [re], although you'll need\n    to carefully choose the property that you prove by induction by\n    generalizing the appropriate terms.\n\n    Hint: if your definition of [derive] applies [match_eps] to a\n    particular regex [re], then a natural proof will apply\n    [match_eps_refl] to [re] and destruct the result to generate cases\n    with assumptions that the [re] does or does not match the empty\n    string.\n\n    Hint: You can save quite a bit of work by using lemmas proved\n    above. In particular, to prove many cases of the induction, you\n    can rewrite a [Prop] over a complicated regex (e.g., [s =~ Union\n    re0 re1]) to a Boolean combination of [Prop]'s over simple\n    regex's (e.g., [s =~ re0 \\/ s =~ re1]) using lemmas given above\n    that are logical equivalences. You can then reason about these\n    [Prop]'s naturally using [intro] and [destruct]. *)\nLemma derive_corr : derives derive.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define the regex matcher using [derive]. However, the only\n    property of [derive] that you'll need to use in all proofs of\n    properties of the matcher is [derive_corr]. *)\n\n\n(** A function [m] matches regexes if, given string [s] and regex [re],\n    it evaluates to a value that reflects whether [s] is matched by\n    [re]. I.e., [m] holds the following property: *)\nDefinition matches_regex m : Prop :=\n  forall (s : string) re, reflect (s =~ re) (m s re).\n\n(** **** Exercise: 2 stars, optional (regex_match)  *)\n(** Complete the definition of [regex_match] so that it matches\n    regexes. *)\nFixpoint regex_match (s : string) (re : @reg_exp ascii) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (regex_refl)  *)\n(** Finally, prove that [regex_match] in fact matches regexes.\n\n    Hint: if your definition of [regex_match] applies [match_eps] to\n    regex [re], then a natural proof applies [match_eps_refl] to [re]\n    and destructs the result to generate cases in which you may assume\n    that [re] does or does not match the empty string.\n\n    Hint: if your definition of [regex_match] applies [derive] to\n    character [x] and regex [re], then a natural proof applies\n    [derive_corr] to [x] and [re] to prove that [x :: s =~ re] given\n    [s =~ derive x re], and vice versa. *)\nTheorem regex_refl : matches_regex regex_match.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* =====================================================================\n   \u00a7 Bibliograf\u00eda\n   =====================================================================\n\n+ \"Inductively defined propositions\" de Peirce et als.\n  http://bit.ly/2Lejw7s *)\n", "meta": {"author": "jaalonso", "repo": "DAOconCoq", "sha": "8546d31ef0827e6191427757737dfca24180f97f", "save_path": "github-repos/coq/jaalonso-DAOconCoq", "path": "github-repos/coq/jaalonso-DAOconCoq/DAOconCoq-8546d31ef0827e6191427757737dfca24180f97f/teorias/T7_PropInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765316406923, "lm_q2_score": 0.9059898165759307, "lm_q1q2_score": 0.8277816333108834}}
{"text": "Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nDefinition bag := natlist.\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n  \nFixpoint count (v : nat) (s : bag) : nat :=\n    match s with \n    | nil => O \n    | h :: t => match eqb v h with \n        | true => 1 + count v t\n        | false => count v t\n        end\n    end.\n\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.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nFixpoint remove_one (v : nat) (s: bag) : bag :=\n    match s with \n    | nil => nil \n    | h :: t => match eqb v h with\n        | true => t\n        | false => h :: remove_one v t\n        end\n    end.\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\n\n(* EXERCISE *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n    intros s. simpl. reflexivity. Qed.\n\n(* The following lemma about leb might help you in the next exercise (it will also be useful in later chapters). *)\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity. Qed.\n\n\n(* EXERCISE *)\n(* the previous lemma ended up helping! *)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n    intros s. induction s as [| n s' IHs'].\n    - simpl. reflexivity.\n    - destruct n. \n     + simpl. rewrite -> leb_n_Sn. reflexivity.\n     + simpl. rewrite -> IHs'. reflexivity.\n    Qed.\n\n(* EXERCISE *)\n(*  An injective function is one-to-one: it maps distinct inputs to distinct outputs, without any collisions. *)\nTheorem involution_injective : forall (f : nat -> nat),\n    (forall n : nat, n = f (f n)) -> (forall n1 n2 : nat, f n1 = f n2 -> n1 = n2).\nProof.\n    intros f H0 n1 n2 H1.\n    rewrite -> H0.\n    rewrite <- H1.\n    rewrite <- H0.\n    reflexivity.\n    Qed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof. Admitted.\n\n(* EXERCISE *)\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2. intros H.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\n  Qed.\n  \n  \n  ", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/exercises/list_ex_part2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8277127138378926}}
{"text": "Inductive Nat : Type :=\n  | Z : Nat\n  | S : Nat -> Nat.\n\nFixpoint add (m n:Nat) : Nat :=\n  match m with\n    | Z => n\n    | S m' => S (add m' n)\n  end.\n\nNotation \"m + n\" := (add m n).\nNotation \"0\" := Z.\nNotation \"1\" := (S Z).\n\n\nLemma s_equality : forall m n:Nat, m = n -> S m = S n.\n  intros.\n  induction m.\n  rewrite H.\n  auto.\n  rewrite H.\n  auto.\nQed.\n\nLemma add_identity : forall m:Nat, m + 0 = m.\n  intros.\n  elim m.\n  simpl.\n  auto.\n  simpl.\n  intros.\n  apply s_equality.\n  apply H.\nQed.\n\nLemma add_s_equality : forall m n:Nat, m + (S n) = S (m + n).\nProof.\n  intros.\n  induction m.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHm.\n  reflexivity.\nQed.\n\nLemma add_s : forall m : Nat, S m = m + (S Z).\nProof.\n  intros.\n  induction m.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHm.\n  reflexivity.\nQed.\n\nLemma add_commutative : forall m n:Nat, m + n = n + m.\nProof.\n  intros.\n  induction m as [ | m IHm ].\n  simpl.\n  rewrite add_identity.\n  reflexivity.\n  simpl.\n  rewrite add_s_equality.\n  rewrite IHm.\n  reflexivity.\nQed.\n\nFixpoint mult (m n : Nat) :=\n  match m with\n    | Z => Z\n    | S m' => n + (mult m' n)\n  end.\n\nNotation \"m * n\" := (mult m n).\n\nLemma mult_identity : forall m : Nat, m * 1 = m.\nProof.\n  intros.\n  induction m.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHm.\n  reflexivity.\nQed.\n\nLemma mult_zero : forall m : Nat, m * 0 = 0.\nProof.\n  intros.\n  induction m.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHm.\n  reflexivity.\nQed.\n\nLemma add_assoc : forall m n o : Nat, m + (n + o) = (m + n) + o.\nProof.\n  intros.\n  induction m.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHm.\n  reflexivity.\nQed.\n\nLemma mult_distributive : forall m n o : Nat, m * (n + o) = (m * n) + (m * o).\nProof.\nAdmitted.\n\nLemma mult_associative : forall m n o : Nat, m * (n * o) = (m * n) * o.\nProof.\nAdmitted.\n\nLemma mult_s : forall m n : Nat, m * (S n) = (m * n) + m.\nProof.\nAdmitted.\n\nLemma mult_commutative : forall m n : Nat, m * n = n * m.\nProof.\n  intros.\n  induction m.\n  simpl.\n  rewrite mult_zero.\n  reflexivity.\n  simpl.\n  rewrite add_s.\n  rewrite mult_distributive.\n  rewrite mult_identity.\n  rewrite IHm.\n  rewrite add_commutative.\n  reflexivity.\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Practice/Naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025386, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.8273878344861119}}
{"text": "(* week_40a_binary_trees.v *)\n(* dIFP 2014-2015, Q1, Week 40 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\nRequire Import Arith Bool unfold_tactic.\n\nLemma plus_1_l :\n  forall n : nat,\n    1 + n = S n.\nProof.\n  intro n.\n  rewrite -> plus_Sn_m.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\n(* Data type of binary trees of natural numbers: *)\n\nInductive binary_tree_nat : Type :=\n  | Leaf : nat -> binary_tree_nat\n  | Node : binary_tree_nat -> binary_tree_nat -> binary_tree_nat.\n\n(* There is one base case: leaves.\n   There is one induction case, with two subtrees.\n*)\n\n(* ********** *)\n\n(* Sample of binary trees of natural numbers: *)\n\nDefinition bt_0 :=\n  Leaf 42.\n\nDefinition bt_1 :=\n  Node (Leaf 10)\n       (Leaf 20).\n\nDefinition bt_2 :=\n  Node (Node (Leaf 10)\n             (Leaf 20))\n       (Leaf 30).\n\n(*\nPrint bt_2.\nbt_2 = Node (Node (Leaf 10) (Leaf 20)) (Leaf 30)\n     : binary_tree_nat\n*)\n\n(* ********** *)\n\n(* How many leaves are there in a given binary tree? *)\n\n(* A unit test: *)\n\nDefinition unit_test_for_number_of_leaves (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 1)\n  &&\n  (candidate bt_1 =n= 2)\n  &&\n  (candidate bt_2 =n= 3)\n  &&\n  (candidate (Node bt_1 bt_2) =n= 5)\n  .\n\n(* ***** *)\n\n(* A specification: *)\n\nDefinition specification_of_number_of_leaves (number_of_leaves : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     number_of_leaves (Leaf n) = 1)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     number_of_leaves (Node t1 t2) = number_of_leaves t1 + number_of_leaves t2).\n\n(* ***** *)\n\n(* Uniqueness of the specification: *)\n\nTheorem there_is_only_one_number_of_leaves :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_number_of_leaves f ->\n    specification_of_number_of_leaves g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_number_of_leaves.\n  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> Hf_leaf.\n  rewrite -> Hg_leaf.\n  reflexivity.\n\n  rewrite -> Hf_node.\n  rewrite -> Hg_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* A first implementation, in direct style: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_ds (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n =>\n      1\n    | Node t1 t2 =>\n      (number_of_leaves_ds t1) + (number_of_leaves_ds t2)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_ds_Leaf :\n  forall n : nat,\n    number_of_leaves_ds (Leaf n) = 1.\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\nLemma unfold_number_of_leaves_ds_Node :\n  forall t1 t2 : binary_tree_nat,\n    number_of_leaves_ds (Node t1 t2) =\n    (number_of_leaves_ds t1) + (number_of_leaves_ds t2).\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v0 (t : binary_tree_nat) : nat :=\n  number_of_leaves_ds t.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v0.\n(*\n     = true\n     : bool\n*)\n\n(* ***** *)\n\n(* The first implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v0.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v0.\n  split.\n\n  exact unfold_number_of_leaves_ds_Leaf.\n\n  exact unfold_number_of_leaves_ds_Node.\nQed.\n\n(* ***** *)\n\n(* A second implementation, with an accumulator: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_acc (t : binary_tree_nat) (a : nat) : nat :=\n  match t with\n    | Leaf n =>\n      1 + a  (* or even better: S a *)\n    | Node t1 t2 =>\n      number_of_leaves_acc t1 (number_of_leaves_acc t2 a)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_acc_Leaf :\n  forall n a : nat,\n    number_of_leaves_acc (Leaf n) a = 1 + a.\nProof.\n  unfold_tactic number_of_leaves_acc.\nQed.\n\nLemma unfold_number_of_leaves_acc_Node :\n  forall (t1 t2 : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc (Node t1 t2) a =\n    number_of_leaves_acc t1 (number_of_leaves_acc t2 a).\nProof.\n  unfold_tactic number_of_leaves_acc.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v1 (t : binary_tree_nat) : nat :=\n  number_of_leaves_acc t 0.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v1.\n(*\n     = true\n     : bool\n*)\n\n(* The second implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  (* Hum, we are stuck.  Let's venture a helpful lemma: *)\nAbort.\n\nLemma about_number_of_leaves_acc_tentative :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc t a = (number_of_leaves_acc t 0) + a.\nProof.\nAdmitted.\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves_second_attempt :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc_tentative.\n  reflexivity.\n  (* Yay, the proof goes through.\n     So let's prove the helpful lemma. *)\nAbort.\n\nLemma about_number_of_leaves_acc :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc t a = (number_of_leaves_acc t 0) + a.\nProof.\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intro a.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  (* Induction case: *)\n  intro a.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> (IHt1 (number_of_leaves_acc t2 0)).\n  (* postlude: *)\n  apply plus_assoc.\nQed.\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* The two implementations implement the same function: *)\n\nTheorem number_of_leaves_v0_and_v1_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v0 t = number_of_leaves_v1 t.\nProof.\n  (* Pedestrian attempt: *)\n  intro t.\n  unfold number_of_leaves_v0.\n  unfold number_of_leaves_v1.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> unfold_number_of_leaves_ds_Leaf.\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  rewrite -> unfold_number_of_leaves_ds_Node.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\n\n  Restart.\n\n  (* Reusing what we did before: *)\n\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v1\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves).\n\n  Restart.\n\n  (* Reusing what we did before, less concisely: *)\n\n  intro t.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v1\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves\n           t).\nQed.\n\n(* ***** *)\n\n(* A third implementation, with higher-order functions: *)\n\nDefinition compose_nat (f g : nat -> nat) (n : nat) :=\n  f (g n).\n\nNotation \"F << G\" := (compose_nat F G) (at level 70, right associativity).\n\nCompute (S << S) 40.\n\nCompute ((fun x => 2 + x) << (fun y => 10 * y)) 4.\n\nLemma unfold_compose_nat :\n  forall (f g : nat -> nat)\n          (n : nat),\n    compose_nat f g n = f (g n).\nProof.\n  unfold_tactic compose_nat.\nQed.\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_higher_order (t : binary_tree_nat) : nat -> nat :=\n  match t with\n    | Leaf n =>\n      S\n    | Node t1 t2 =>\n      (number_of_leaves_higher_order t1) << (number_of_leaves_higher_order t2)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_higher_order_Leaf :\n  forall n : nat,\n    number_of_leaves_higher_order (Leaf n) = S.\nProof.\n  unfold_tactic number_of_leaves_higher_order.\nQed.\n\nLemma unfold_number_of_leaves_higher_order_Node :\n  forall (t1 t2 : binary_tree_nat),\n    number_of_leaves_higher_order (Node t1 t2) =\n    ((number_of_leaves_higher_order t1) << (number_of_leaves_higher_order t2)).\nProof.\n  unfold_tactic number_of_leaves_higher_order.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v2 (t : binary_tree_nat) : nat :=\n  number_of_leaves_higher_order t 0.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v2.\n(*\n     = true\n     : bool\n*)\n\n(* The second implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v2.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v2.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_higher_order_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_higher_order_Node.\n  rewrite -> unfold_compose_nat.\n(* Aha: number_of_leaves_v2 is the same as number_of_leaves_v1! *)\nAbort.\n\nLemma about_number_of_leaves_higher_order :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_higher_order t a =\n    number_of_leaves_acc t a.\nProof.\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  intro a.\n  rewrite -> unfold_number_of_leaves_higher_order_Leaf.\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> (plus_1_l a).\n  reflexivity.\n\n  intro a.\n  rewrite -> unfold_number_of_leaves_higher_order_Node.\n  rewrite -> unfold_compose_nat.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  reflexivity.\nQed.\n\nTheorem number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v2.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v2.\n  split.\n\n  intro n.\n  rewrite -> about_number_of_leaves_higher_order.\n  exact (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> about_number_of_leaves_higher_order.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  rewrite -> about_number_of_leaves_higher_order.\n  rewrite -> about_number_of_leaves_higher_order.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* A fourth implementation, in CPS: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_cps (ans : Type) (t : binary_tree_nat) (k : nat -> ans) : ans :=\n  match t with\n    | Leaf n =>\n      k 1\n    | Node t1 t2 =>\n      number_of_leaves_cps\n        ans\n        t1\n        (fun n1 => number_of_leaves_cps\n                     ans\n                     t2\n                     (fun n2 => k (n1 + n2)))\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_cps_Leaf :\n  forall (ans : Type)\n         (n : nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans (Leaf n) k = k 1.\nProof.\n  unfold_tactic number_of_leaves_cps.\nQed.\n\nLemma unfold_number_of_leaves_cps_Node :\n  forall (ans : Type)\n         (t1 t2 : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans (Node t1 t2) k =\n    number_of_leaves_cps\n      ans\n      t1\n      (fun n1 => number_of_leaves_cps\n                   ans\n                   t2\n                   (fun n2 => k (n1 + n2))).\nProof.\n  unfold_tactic number_of_leaves_cps.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v3 (t : binary_tree_nat) : nat :=\n  number_of_leaves_cps nat t (fun n => n).\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v3.\n(*\n     = true\n     : bool\n*)\n\n(* The fourth implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  (* Hum, we are stuck.  Let's venture a helpful lemma: *)\nAbort.\n\nLemma about_number_of_leaves_cps_tentative :\n  forall (ans : Type)\n         (t : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans t k =\n    k (number_of_leaves_cps nat t (fun n => n)).\nProof.\nAdmitted.\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves_second_attempt :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> about_number_of_leaves_cps_tentative.\n  rewrite -> about_number_of_leaves_cps_tentative.\n  reflexivity.\n  (* Yay, the proof goes through.\n     So let's prove the helpful lemma. *)\nAbort.\n\nLemma about_number_of_leaves_cps :\n  forall (ans : Type)\n         (t : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans t k =\n    k (number_of_leaves_cps nat t (fun n => n)).\nProof.\n  intros ans t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intro k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  (* Induction case: *)\n  intro k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  symmetry.\n  (* OK, left-hand side then: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  (* And we are stuck.\n     Let's strengthen the induction hypothesis. *)\n\n  Restart.\n\n  intros ans t.\n  revert ans.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  (* Induction case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  symmetry.\n  (* OK, left-hand side then: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> about_number_of_leaves_cps.\n  rewrite -> about_number_of_leaves_cps.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* The four implementations implement the same function: *)\n\nTheorem number_of_leaves_v0_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v0 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v3\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\nTheorem number_of_leaves_v1_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v1 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v1\n           number_of_leaves_v3\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\nTheorem number_of_leaves_v2_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v2 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v2\n           number_of_leaves_v3\n           number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\n(* ********** *)\n\n(* Exercise:\n   Revisit how to compute the number of nodes\n   of a binary tree.\n*)\nDefinition unit_test_for_number_of_nodes (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 0)\n    &&\n    (candidate bt_1 =n= 1)\n    &&\n    (candidate bt_2 =n= 2).\n\nDefinition specification_of_number_of_nodes (number_of_nodes : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     number_of_nodes (Leaf n) = 0)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     number_of_nodes (Node t1 t2) = S (number_of_nodes t1 + number_of_nodes t2)).\n\nTheorem there_is_only_one_number_of_nodes :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_number_of_nodes f ->\n    specification_of_number_of_nodes g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_number_of_nodes.\n  intros [S_f_leaf S_f_node] [S_g_leaf S_g_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n    rewrite S_g_leaf.\n    exact (S_f_leaf n).\n\n  rewrite S_f_node.\n  rewrite S_g_node.\n  rewrite IHt1.\n  rewrite IHt2.\n  reflexivity.\nQed.\n\nFixpoint number_of_nodes_ds (t : binary_tree_nat) : nat :=\n  match t with\n      | Leaf n =>\n        0\n      | Node t1 t2 =>\n        S (number_of_nodes_ds t1 + number_of_nodes_ds t2)\n  end.\n\nLemma unfold_number_of_nodes_ds_leaf :\n  forall n : nat,\n    number_of_nodes_ds (Leaf n) = 0.\nProof.\n  unfold_tactic number_of_nodes_ds.\nQed.\n\nLemma unfold_number_of_nodes_ds_node :\n  forall t1 t2 : binary_tree_nat,\n    number_of_nodes_ds (Node t1 t2) = S (number_of_nodes_ds t1 + number_of_nodes_ds t2).\nProof.\n  unfold_tactic number_of_nodes_ds.\nQed.\n\nDefinition number_of_nodes_v0 (t : binary_tree_nat) : nat :=\n  number_of_nodes_ds t.\n\nCompute unit_test_for_number_of_nodes number_of_nodes_v0.\n\n(* MANGLER number_of_nodes_v0_fits_the_specification_of_number_of_nodes *)\n\n(* ********** *)\n\n(* Food for thought (with thanks to John Anker):\n   For any binary tree,\n   how would you compare its number of leaves and its number of nodes?\n   Is there a relation?  If so, could you formalize it in Coq?\n*)\n\n(* ********** *)\n\n(* end of week_40a_binary_trees.v *)", "meta": {"author": "skodborg", "repo": "dIFP-2014", "sha": "f97dbfc4fde41b5c5bc7c23f13701683fe57644c", "save_path": "github-repos/coq/skodborg-dIFP-2014", "path": "github-repos/coq/skodborg-dIFP-2014/dIFP-2014-f97dbfc4fde41b5c5bc7c23f13701683fe57644c/week_40a_binary_trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.9304582559762669, "lm_q1q2_score": 0.8269529487519042}}
{"text": "Require Import Arith.\n\nLemma fib_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 -> \n  (forall n:nat, P n -> P (S n) -> P (S (S n))) -> \n  forall n:nat, P n.\nProof.\n intros P H0 H1 HSSn n.\n cut (P n /\\ P (S n)).\n tauto.\n elim n.\n split; auto.\n intros n0 Hn0; case Hn0; auto.\nQed.\n\n\nFixpoint fib (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S O => 1\n  | S (S p as q) => fib p + fib q\n  end.\n\n(* A geralisation of the fibonacci sequence, parameterized by\n   its two first items *)\n\nFixpoint general_fib (a0 a1 n:nat) {struct n} : nat :=\n  match n with\n  | O => a0\n  | S p => general_fib a1 (a0 + a1) p\n  end.\n\nDefinition fib_tail (n:nat) := general_fib 1 1 n.\n\nEval compute in (fib_tail 10).\n\n\nLemma general_fib_1 : forall a b:nat, general_fib a b 1 = b.\nProof.\n simpl; auto.\nQed.\n\nLemma general_fib_S :\n forall a b n:nat, general_fib a b (S n) = general_fib b (a + b) n.\nProof.\n simpl; auto.\nQed.\n\nLemma general_fib_2 :\n forall a b n:nat,\n   general_fib a b (S (S n)) = general_fib a b n + general_fib a b (S n).\nProof.\n intros a b n; generalize a b.\n elim n.\n simpl; auto.\n intros n0 H a0 b0.\n pattern (general_fib a0 b0 (S (S (S n0)))); rewrite general_fib_S.\n pattern (general_fib a0 b0 (S (S n0))); rewrite general_fib_S.\n pattern (general_fib a0 b0 (S n0)); rewrite general_fib_S.\n apply H.\nQed.\n\nLemma fib_SSn : forall n:nat, fib (S (S n)) = fib n + fib (S n).\nProof.\n simpl; auto.\nQed.\n\nLemma linear_fibo_equiv : forall n:nat, fib_tail n = fib n.\nProof.\n intro n; elim n using fib_ind.  \n simpl; auto. \n simpl; auto. \n unfold fib_tail.\n intros n0 e0 e1; rewrite general_fib_2. \n rewrite e0; rewrite e1.\n rewrite fib_SSn; 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/progav/SRC/fib_tail.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.894789468908171, "lm_q1q2_score": 0.8269123608168534}}
{"text": "(*Zhiwei Wu, Wenrui Meng 1 hour for each *)\n(** * MoreProp: More about Propositions and Evidence *)\n\nRequire Export \"Prop\".\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** A _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop].  Although we haven't mentioned it\n    explicitly, we have already seen numerous examples. *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** We've seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we can give\n    a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n fun (n : nat) => match (oddb n) with\n                  | true => Podd n  \n                  | false => Peven n end.\n\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\nintros. unfold combine_odd_even. simpl. destruct (oddb n).  \nCase \"true\". apply H. reflexivity.\nCase \"false\". apply H0. reflexivity.\nQed. \n(*\nintros. remember (oddb n) as b. destruct b.\nCase \"odd\".\nunfold combine_odd_even. rewrite <- Heqb. apply H. trivial.\n\nCase \"even\".\nunfold combine_odd_even. rewrite <- Heqb. apply  H0. trivial. Qed.\n*)\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\nintros. unfold combine_odd_even in H. rewrite H0 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    oddb n = false ->\n    Peven n.\nProof.\nintros. unfold combine_odd_even in H. rewrite -> H0 in H.\napply H. Qed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(* $Date: 2013-02-06 20:56:12 -0500 (Wed, 06 Feb 2013) $ *)\n\n", "meta": {"author": "steven7woo", "repo": "Coq-CIS500", "sha": "405653248c19d78ec35f4b7bc2b2144c4aa92738", "save_path": "github-repos/coq/steven7woo-Coq-CIS500", "path": "github-repos/coq/steven7woo-Coq-CIS500/Coq-CIS500-405653248c19d78ec35f4b7bc2b2144c4aa92738/For_wenrui/MoreProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8947894682067639, "lm_q1q2_score": 0.8269123601686535}}
{"text": "Require Import primRec Arith ArithRing List.\nImport extEqualNat.\n\n\n(** ** Solution to an exercise  *)\n\nDefinition double n := n * 2.\n\nLemma doubleIsPR : isPR 1 double.\nProof.\n  unfold double; apply compose1_2IsPR.\n  - apply idIsPR.\n  - apply const1_NIsPR.\n  - apply multIsPR.\nQed.\n\n(* begin snippet expDef *)\n\nFixpoint exp n p :=\n  match p with\n    0 => 1\n  | S m =>  exp n m * n\n  end.\n\n(* end snippet expDef *)\n\nDefinition exp_alt := fun a b => nat_rec (fun _ => nat)\n                                     1\n                                     (fun _ y =>  y * a)\n                                     b.\n\n\nRemark  exp_alt_ok : extEqual 2 exp_alt exp. \nProof.\n  intros x y; induction y; cbn; auto.\nQed.\n\n\n\nLemma exp_alt_PR : isPR 2 exp_alt.\nProof.\n  unfold exp_alt.\n    apply swapIsPR.\n    apply ind1ParamIsPR.\n    + apply filter011IsPR.\n      apply multIsPR.\n    + apply const1_NIsPR.\nQed.\n\nLemma expIsPR : isPR 2 exp.\nProof.\n  destruct exp_alt_PR as [x Hx].\n  exists x.\n  apply extEqualTrans with exp_alt; auto.\n  apply exp_alt_ok.\nQed.\n\n(* begin snippet tower2Def *)\n\nFixpoint tower2 n :=\n  match n with\n    0 => 1\n  | S p => exp 2 (tower2 p)\n  end.\n\n(* end snippet tower2Def *)\n\nDefinition tower2_alt h : nat :=  nat_rec (fun n => nat)\n                                1\n                                (fun _  y =>  exp 2 y)\n                                h.\n\nRemark tower2_alt_ok  : extEqual 1 tower2_alt tower2.\nProof. intro x; induction x; cbn; auto. Qed.\n\nLemma tower2_alt_PR : isPR 1 tower2_alt.\nProof.\nunfold tower2_alt;  apply indIsPR.\n    +  apply filter01IsPR.\n       eapply compose1_2IsPR.\n       * apply const1_NIsPR.\n       * apply idIsPR.\n       * apply expIsPR.\n         Qed.\n\nLemma tower2IsPR : isPR 1 tower2.\nProof.\n destruct tower2_alt_PR as [x Hx].\n exists x.\n apply extEqualTrans with tower2_alt; [auto | apply tower2_alt_ok].\nQed.\n\n(* begin snippet factDef *)    \nFixpoint fact n :=\n  match n with 0 => 1\n          |   S p  => n * fact p\n  end.\n(* end snippet factDef *)    \n\nDefinition fact_alt\n  : nat -> nat :=\n  fun a => nat_rec _ 1 (fun x y =>  S x * y) a.\n\nRemark fact_alt_ok : extEqual 1 fact_alt fact.\nProof.\n  intro x;induction x; cbn; auto.\nQed.\n\nLemma fact_altIsPR : isPR 1 fact_alt.\nProof.\n  unfold fact_alt; apply indIsPR.\n  apply compose2_2IsPR.\n  +  apply filter10IsPR; apply succIsPR.\n  +  apply filter01IsPR; apply idIsPR.\n  +  apply multIsPR.\nQed.\n\nLemma factIsPR : isPR 1 fact.\nProof.\n  destruct fact_altIsPR as [x Hx].\n  exists x; apply extEqualTrans with fact_alt; [trivial | ].\n  apply fact_alt_ok.\nQed.\n\n\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/solutions_exercises/MorePRExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.919642533380189, "lm_q1q2_score": 0.8268702636947324}}
{"text": "(** **** KE DING 8318 *)\n\n(** * MoreProp: More about Propositions and Evidence *)\n\nRequire Export \"Prop\".\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** A _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop].  Although we haven't mentioned it\n    explicitly, we have already seen numerous examples. *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** We've seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we can give\n    a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n : nat => if (oddb n) then Podd n\n                             else Peven n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n Hodd Heven.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  Case \"oddb n = true\".\n    apply Hodd.\n    reflexivity.\n  Case \"oddb n = false\".\n    apply Heven.\n    reflexivity.\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 Hc Hb.\n  unfold combine_odd_even in Hc.\n  rewrite -> Hb in Hc.\n  apply Hc.\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 Hc Hb.\n  unfold combine_odd_even in Hc.\n  rewrite -> Hb in Hc.\n  apply Hc.\n\n(** [] *)\n\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n : nat)(P : nat -> Prop) : Prop :=\n  match n with\n    | O => forall m, P m\n    | S n' => even (S n') -> true_upto_n__true_everywhere n' P\n  end.\n\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n\n(** [] *)\n\n(* $Date: 2013-02-06 21:18:41 -0500 (Wed, 06 Feb 2013) $ *)\n\n(** **** KE DING 8318 *)\n\n", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/MoreProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.9111797166446536, "lm_q1q2_score": 0.8267244950512748}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\n\nInductive even : nat -> Prop :=\n  | ev_0 : even 0\n  | ev_SS (n : nat) (H : even n) : even (S (S n)).\n(* equavlent\nInductive even' : nat -> Prop :=\n  | ev_0' : even' 0\n  | ev_SS' : forall n, even' n -> even' (S (S n)). \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\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\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 double_axiom1 : forall n,\n  double (S n) = S (S (double n)).\nProof.\n  intros. unfold double. simpl.\n  rewrite plus_comm. simpl. reflexivity.\nQed. \n\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  unfold double. intros.\n  induction n as [|n' IHn'].\n  - simpl. apply ev_0.\n  - simpl. rewrite -> plus_comm. simpl.\n    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  - left. reflexivity.\n  - right. exists n'. split. \n    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,\n  even (S (S n)) -> even n.\nProof.\n intros n H. apply ev_inversion in H. destruct H.\n - discriminate H.\n - destruct H as [n' [Hnm Hev]]. injection Hnm.\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 n0 E0.\n  inversion E0 as [|n1 E1].\n  inversion E1 as [|n2 E2].\n  apply E2.\nQed.\n\nTheorem even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  intros E. \n  inversion E. inversion H0.\n  inversion H2.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. \nQed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. 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  - exists 0. reflexivity.\n  - assert (I : (exists k', n' = double k')\n            ->  (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k').\n      rewrite <- double_axiom1. reflexivity. }\n  apply I.\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  - exists 0. reflexivity.\n  - destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k').\n    rewrite double_axiom1. 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\nAxiom plus_aux_axiom1 : forall n m,\n  n + n + (m + m) = n + m + (n + m).\n\nTheorem ev_sum : forall n m, \n  even n -> even m -> even (n + m).\nProof.\n  intros. apply ev_even_iff.\n  apply ev_even_iff in H.\n  apply ev_even_iff in H0.\n  destruct H0 as [k0 H0].\n  destruct H as [k1 H1].\n  rewrite H0. rewrite H1. exists (k1 + k0).\n  unfold double. rewrite plus_aux_axiom1. \n  reflexivity.\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,\n  even' n <-> even n.\nProof.\n  intros. split.\n  - intros H. induction H.\n    apply ev_0. apply ev_SS. apply ev_0.\n    apply ev_sum. apply IHeven'1.\n    apply IHeven'2.\n  - intros E. induction E.\n    apply even'_0. \n    assert (I : n+ 2 = S (S n)). \n    { rewrite plus_comm. simpl. reflexivity. }\n    rewrite <- I. apply even'_sum. \n    apply IHE. apply even'_2.\nQed.\n\nAxiom plus_and_diff : forall n m k,\n  n + m = k -> n = k - m.\n\nAxiom plus_and_diff2 : forall n m,\n  n + n - (m + m) = n - m + (n - m).\n\nTheorem ev_ev__ev : forall n m,\n  even (n+m) -> even n -> even m.\nProof.\n  intros. apply ev_even_iff.\n  apply ev_even_iff in H.\n  apply ev_even_iff in H0.\n  destruct H as [i Hi]. destruct H0 as [j Hj].\n  rewrite Hj in Hi. rewrite plus_comm in Hi.\n  apply plus_and_diff in Hi. rewrite Hi. \n  unfold double. exists (i - j).\n  apply plus_and_diff2.\nQed.\n\nAxiom plus_n_assoc : forall n m k,\n  n - k + (m - k) = n - k + m - k.\n\nAxiom plus_n_aux : forall i j n,\n  i + i - n + (j + j) - n =\n    i + j - n + (i + j - n).\n\nTheorem ev_plus_plus : forall n m p,\n  even (n+m) -> even (n+p) -> even (m+p).\nProof.\n  intros. apply ev_even_iff.\n  apply ev_even_iff in H. \n  apply ev_even_iff in H0.\n  destruct H as [i Hi]. destruct H0 as [j Hj].\n  exists (i + j - n). rewrite plus_comm in Hi.\n  rewrite plus_comm in Hj. \n  apply plus_and_diff in Hi.\n  apply plus_and_diff in Hj.\n  rewrite Hi. rewrite Hj. \n  rewrite plus_n_assoc. unfold double.\n  apply plus_n_aux.\nQed.\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n n : le n n\n  | le_S n m (H : le n m) : le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\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. \nQed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2.\nQed.\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 n : even (S n) -> next_even n (S n)\n  | ne_2 n (H : even (S (S n))) : next_even n (S (S n)).\n\nLemma le_trans : forall m n o, \n  m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H0 H1.\n  destruct H0. apply H1. \n  induction H1.\n  + apply le_S. apply H0.\n  + apply le_S. apply IHle. \nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n as [|n' IHn'].\n  apply le_n. apply le_S. apply IHn'.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros. induction H.\n  reflexivity. apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros. inversion H.\n  - reflexivity. \n  - apply (le_trans n (S n) m).\n    apply le_S. apply le_n. apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. rewrite plus_comm. \n  induction b as [|b' IHb'].\n  - simpl. reflexivity.\n  - simpl. apply le_S. apply IHb'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt. intros.\n  inversion H.\n  - split. apply n_le_m__Sn_le_Sm. \n    apply le_plus_l. apply n_le_m__Sn_le_Sm. \n    rewrite plus_comm. apply le_plus_l.\n  - split.\n    + apply n_le_m__Sn_le_Sm. \n      rewrite <- H1 in H.\n      apply Sn_le_Sm__n_le_m in H.\n      apply (le_trans n1 (n1 + n2) m0).\n      apply le_plus_l. apply H.\n    + apply n_le_m__Sn_le_Sm.\n      rewrite <- H1 in H.\n      apply Sn_le_Sm__n_le_m in H.\n      apply (le_trans n2 (n1 + n2) m0).\n      rewrite plus_comm. apply le_plus_l. \n      apply H.\nQed. \n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply n_le_m__Sn_le_Sm.\n  apply (le_trans n (S n) m).\n  apply le_S. apply le_n. apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intros. generalize dependent n. \n  induction m as [|m' IHm'].\n  - induction n as [|n' IHn'].\n    + intros H. apply le_n.\n    + intros H. simpl in H. discriminate H.\n  - induction n as [|n' IHn'].\n    + assert (I : S m' = 0 + S m').\n      { reflexivity. } rewrite I. intros H.\n      apply le_plus_l.\n    + intros H. apply n_le_m__Sn_le_Sm.\n      apply IHm'. simpl in H. apply H.\nQed.\n\nTheorem leb_n_n : forall n,\n  n <=? n = true.\nProof.\n  intros. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. apply IHn'.\nQed. \n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\nProof.\n  intros. generalize dependent n.\n  induction m as [|m' IHm'].\n  - intros n H. inversion H. reflexivity.\n  - intros n H. inversion H. \n    simpl. apply leb_n_n. \n    induction n as [|n' IHn'].\n    reflexivity. apply IHm'. \n    apply (le_trans n' (S n') m').\n    apply le_S. apply le_n. apply H1.\nQed.\n\nTheorem leb_true_trans : forall n m o,\n  n <=? m = true -> \n    m <=? o = true -> \n      n <=? o = true.\nProof.\n  intros. apply leb_correct.\n  apply leb_complete in H.\n  apply leb_complete in H0.\n  apply (le_trans n m o). apply H. apply H0.\nQed.\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  split.\n  apply leb_complete. apply leb_correct.\nQed.\n\nModule R.\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 m n o (H : R m n o) : R (S m) n (S o)\n   | c3 m n o (H : R m n o) : R m (S n) (S o)\n   | c4 m n o (H : R (S m) (S n) (S (S o))) : R m n o\n   | c5 m n o (H : R m n o) : R n m o.\n\nTheorem R_m_n_o : forall (m n o:nat),\n  R m n o <-> m + n = o.\nProof.\n  split.\n  - intros. induction H.\n    + reflexivity.\n    + simpl. apply f_equal. apply IHR.\n    + rewrite <- plus_n_Sm. simpl. apply f_equal. apply IHR.\n    + rewrite <- plus_n_Sm in IHR. simpl in IHR. injection IHR. \n      intros. apply H0.\n    + rewrite plus_comm. apply IHR.\n  -  generalize n o. induction m.\n    + intros n0. induction n0.\n      * simpl. intros. rewrite <- H. apply c1.\n      * simpl. intros. rewrite <- H. apply c3. \n        apply IHn0 with (o := n0). simpl. reflexivity.\n    + intros n0. induction n0.\n      * simpl. intros. rewrite plus_comm in H. \n        simpl in H. rewrite <- H. apply c2.\n        apply IHm. rewrite plus_comm. reflexivity.\n      * simpl. rewrite plus_comm. simpl. intros.\n        rewrite <- H. apply c3. apply IHn0.\n        simpl. apply f_equal. rewrite plus_comm.\n        reflexivity.\nQed. \n\nEnd R.\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | sub_nil : forall l, subseq [] l\n  | sub_one : forall n l1 l2, \n      subseq l1 l2 -> subseq l1 (n :: l2)\n  | sub_two : forall n l1 l2, \n      subseq l1 l2 -> subseq (n :: l1) (n :: l2).\n\nTheorem subseq_refl : forall (l : list nat), \n  subseq l l.\nProof.\n  intros. induction l as [|h t IHt].\n  - apply sub_nil.\n  - apply sub_two. apply IHt.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros. induction H.\n  - apply sub_nil.\n  - apply sub_one. apply IHsubseq.\n  - apply sub_two. apply IHsubseq.\nQed. \n\nTheorem subseq_aux_0 : forall n (l1 l2:list nat),\n  subseq (n :: l1) l2 -> subseq l1 l2.\nProof. \n  intros.\n  induction l2.\n  - inversion H.\n  - apply sub_one. inversion H.\n    + apply IHl2. apply H2.\n    + apply H1.\nQed.\n\nTheorem subseq_aux_1 : forall n (l1 l2 : list nat),\n  subseq (n :: l1) (n :: l2) -> subseq l1 l2.\nProof.\n  intros. inversion H.\n  apply subseq_aux_0 in H2. apply H2.\n  apply H1. \nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  intros l1 l2 l3. \n  generalize dependent l1.\n  generalize dependent l2.\n  generalize dependent l3.\n  induction l3.\n  - intros l2 l1 H0 H1. inversion H1.\n    rewrite <- H in H0. apply H0.\n  - intros l2 l1 H0 H1. inversion H1.\n    + rewrite <- H in H0. inversion H0.\n      apply sub_nil.\n    + destruct H0 as [| h | h].\n      * apply sub_nil.\n      * apply sub_one. \n        apply IHl3 with (l2 := h :: l2).\n        apply sub_one. apply H0. apply H3.\n      * apply sub_one.\n        apply IHl3 with (l2 := h :: l2).\n        apply sub_two. apply H0. apply H3.\n    + destruct H0 as [| h | h].\n      * apply sub_nil.\n      * apply sub_one.\n        apply IHl3 with (l2 := l2).\n        apply H0. injection H2. intros.\n        rewrite H in H6. rewrite H6 in H1.\n        apply subseq_aux_1 in H1. apply H1.\n      * injection H2. intros. rewrite <- H6.\n        rewrite H. apply sub_two. \n        apply IHl3 with (l2 := l2).\n        apply H0. rewrite <- H in H1.\n        rewrite H6 in H1. \n        apply subseq_aux_1 in H1.\n        apply H1. \nQed.\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(*\nProvable:\n   R 1 [1;2;1;0] \nNot provable:\n   R 2 [1;0]\n   R 6 [3;2;1;0]\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\nInductive exp_match {T} : \n  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 : 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. apply MStar0.\nQed.\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros T s H. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) \n                (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s re1 re2 [H0 | H1].\n  apply MUnionL. apply H0.\n  apply MUnionR. apply H1.\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.\n  generalize dependent s1.\n  induction s2. \n  - simpl. intros s1. split. \n    + intros H. inversion H. reflexivity.\n    + intros. rewrite H. apply MEmpty.\n  - split. \n    + intros H. inversion H. \n      inversion H3. simpl.\n      apply f_equal. apply IHs2.\n      apply H4.\n    + intros H. rewrite H. simpl.\n      apply (MApp [x] (Char x) s2 _).\n      apply MChar. apply IHs2.\n      reflexivity.\nQed.\n\nLemma MStar' : forall T (ss : list (list T)) \n              (re : reg_exp),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros. induction ss as [|s' ss' IHss'].\n  - simpl. apply MStar0.\n  - simpl. apply MStarApp. apply H. simpl.\n    left. reflexivity. apply IHss'.\n    intros s H1. apply H. simpl. right.\n    apply H1.\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 as\n  [| x'\n   | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n   | s1 re1 re2 Hmatch IH\n   | re1 s2 re2 Hmatch IH\n   | re \n   | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  - apply Hin.\n  - apply Hin.\n  - simpl. rewrite In_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + left. apply (IH1 Hin). \n    + right. apply (IH2 Hin).\n  - simpl. rewrite In_app_iff.\n    left. apply (IH Hin).\n  - simpl. rewrite In_app_iff.\n    right. apply (IH Hin).\n  - destruct Hin.\n  - simpl. rewrite In_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    + apply (IH1 Hin).\n    + apply (IH2 Hin).\nQed.\n\nTheorem app_aux_1 : forall X (l1 l2 l3 : list X),\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof. Admitted.\n\nLemma star_app: forall T (s1 s2 : list T) (re : @reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  remember (Star re) as re'.\n  generalize dependent s2.\n  induction H1\n  as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n     |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n     |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  - (* MEmpty *) discriminate.\n  - (* MChar *) discriminate.\n  - (* MApp *) discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n  - injection Heqre'. \n    intros Heqre'' s H.\n    apply H.\n  - injection Heqre'. intros H0.\n    intros s2 H1. rewrite app_aux_1.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2. rewrite H0. \n      reflexivity. apply H1.\nQed.\n\nFixpoint re_not_empty {T : Type} \n        (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 \n                && re_not_empty re2\n  | Union re1 re2 => re_not_empty re1 \n                || 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) \n      <-> re_not_empty re = true.\nProof.\n  intros. split.\n  - intros H. destruct H as [s].\n    induction H. reflexivity.\n    reflexivity. simpl. \n    rewrite IHexp_match1.\n    rewrite IHexp_match2. \n    reflexivity. simpl. \n    rewrite IHexp_match.\n    reflexivity. simpl. \n    rewrite IHexp_match.\n    apply orb_true_iff. \n    right. reflexivity.\n    reflexivity. reflexivity.\n  - intros H. induction re.\n    + discriminate. \n    + exists []. apply MEmpty. \n    + exists [t]. apply MChar. \n    + simpl in H. apply andb_true_iff in H.\n      destruct H as [H0 H1].\n      destruct IHre1. apply H0.\n      destruct IHre2. apply H1.  \n      exists (x ++ x0). apply MApp.\n      apply H. apply H2.\n    + simpl in H. apply orb_true_iff in H.\n      destruct H as [H0 | H1].\n      * apply IHre1 in H0. destruct H0.\n        exists x. apply MUnionL.\n        apply H.\n      * apply IHre2 in H1. destruct H1.\n        exists x. apply MUnionR. \n        apply H.\n    + exists []. apply MStar0.\nQed.  \n\n(*\nLemma MStar' : forall T (ss : list (list T)) \n              (re : reg_exp),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nLemma MStar'' : forall T (s : list T) (re : reg_exp),\n  s =~ Star re ->\n  exists ss : list (list T),\n    s = fold app ss []\n    /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  intros. remember (Star re) as re'.\n  induction H.\n  - discriminate.\n  - (* MChar *) discriminate.\n  - (* MApp *) discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n  - exists []. split. reflexivity.\n    simpl. intros s. \n    apply ex_falso_quodlibet.\n  - exists [s1;s2]. split. simpl.\n    rewrite app_nil_r. reflexivity.\n    intros s' H1. unfold In in H1.\n    injection Heqre'. intros H2.\n    destruct H1 as [H1 | [H1 | H1]].\n    + rewrite <- H1. rewrite <- H2.\n      apply H.\n    + rewrite <- H1. \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/indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.9073122132152182, "lm_q1q2_score": 0.8267244771392445}}
{"text": "(* The file takes https://github.com/coq-community/topology as reference *)\n\nGeneralizable All Variables.\n\nRequire Export FormalMath.lib.Sets_ext.\nRequire Import FormalMath.lib.FiniteType.\nRequire Import Coq.Logic.ClassicalChoice.\n\nClass OpenSet (A: Type) := open: Ensemble A -> Prop.\n#[global] Typeclasses Transparent OpenSet.\n\nClass TopologicalSpace (A: Type) {Ao: OpenSet A} : Prop :=\n  {\n    full_open: open Full_set;\n    any_union_open: forall (f: Family A),\n        (forall s, In f s -> open s) -> open (FamilyUnion f);\n    intersection_open: forall (s1 s2: Ensemble A),\n        open s1 -> open s2 -> open (Intersection s1 s2);\n  }.\n\nDefinition topology_basis {A: Type} (B: Family A): Prop :=\n  (forall (x: A), exists b, In B b /\\ In b x) /\\\n  (forall (x: A) (b1 b2: Ensemble A),\n      In B b1 -> In B b2 -> In (Intersection b1 b2) x ->\n      exists b3, In B b3 /\\ In b3 x /\\ Included b3 (Intersection b1 b2)).\n\nDefinition basis_to_open {A} (B: Family A): OpenSet A :=\n  fun u => forall x, In u x -> exists b, In B b /\\ In b x /\\ Included b u.\n\nLemma topology_basis_TopologicalSpace: forall A (B: Family A),\n    topology_basis B -> @TopologicalSpace A (basis_to_open B).\nProof.\n  intros. destruct H as [?B ?B]. split; unfold open, basis_to_open; intros.\n  - destruct (B0 x) as [b [? ?]]. exists b. repeat split; auto.\n  - destruct H0. destruct (H _ H0 _ H1) as [b [? [? ?]]]. exists b.\n    repeat split; auto. repeat intro. exists S; auto.\n  - destruct H1. destruct (H _ H1) as [b1 [? [? ?]]].\n    destruct (H0 _ H2) as [b2 [? [? ?]]].\n    assert (In (Intersection b1 b2) x) by (split; easy).\n    specialize (B1 _ _ _ H3 H6 H9). destruct B1 as [b3 [? [? ?]]].\n    exists b3. unfold Included in H12. repeat split; auto; destruct (H12 _ H13); auto.\nQed.\n\nLemma topology_basis_open_is_all_union: forall A (B: Family A),\n    topology_basis B ->\n    forall S, basis_to_open B S <->\n              exists (F: Family A), Included F B /\\ S = FamilyUnion F.\nProof.\n  intros. destruct H as [?B ?B]. unfold basis_to_open. split; intros.\n  - assert (forall m: {x | In S x},\n               exists b, In B b /\\ In b (proj1_sig m) /\\ Included b S). {\n      intros. destruct m. simpl. now apply H. } destruct (choice _ H0) as [f ?].\n    exists (imageFamily f). split.\n    + repeat intro. destruct H2. subst. now destruct (H1 x).\n    + rewrite <- indexed_to_family_union. apply Extensionality_Ensembles.\n      split; red; intros.\n      * destruct (H1 (exist _ x H2)) as [? [? ?]]. simpl in *.\n        exists (exist _ x H2); auto.\n      * destruct H2. destruct (H1 i) as [? [? ?]]. auto.\n  - destruct H as [F [? ?]]. destruct (B0 x) as [b [? ?]]. rewrite H1 in H0.\n    inversion H0. subst. exists S0. repeat split; auto. repeat intro. exists S0; auto.\nQed.\n\nClass HausdorffSpace (A: Type) {Ao: OpenSet A}: Type :=\n  Hausdorff_prop: forall (x1 x2: A),\n    x1 <> x2 ->\n    { U1: Ensemble A & { U2: Ensemble A |\n      open U1 /\\ open U2 /\\ In U1 x1 /\\ In U2 x2 /\\ Intersection U1 U2 = Empty_set } }.\n\nSection TOPOLOGICAL_SPACE_PROP.\n\n  Context `{T: TopologicalSpace A}.\n\n  Lemma empty_open: open Empty_set.\n  Proof. rewrite <- empty_family_union. apply any_union_open. intros. easy. Qed.\n\n  Lemma union_open: forall (u v: Ensemble A), open u -> open v -> open (Union u v).\n  Proof.\n    intros.\n    assert (Union u v = FamilyUnion (Couple u v)). {\n      apply Extensionality_Ensembles. split; red; intros.\n      - destruct H1; [exists u | exists v]; auto with sets.\n      - destruct H1. destruct H1; [left | right]; easy.\n    } rewrite H1. apply any_union_open. intros. now destruct H2.\n  Qed.\n\n  Definition closed (u: Ensemble A): Prop := open (Complement u).\n\n  Lemma closed_compl_open: forall (S: Ensemble A), closed (Complement S) -> open S.\n  Proof. intros. red in H. now rewrite Complement_Complement in H. Qed.\n\n  Lemma full_closed: closed Full_set.\n  Proof. red. rewrite Full_compl_empty. apply empty_open. Qed.\n\n  Lemma empty_closed: closed Empty_set.\n  Proof. red. rewrite Empty_compl_full. apply full_open. Qed.\n\n  Lemma any_intersection_closed: forall (f: Family A),\n      (forall s, In f s -> closed s) -> closed (FamilyIntersection f).\n  Proof.\n    intros. red. rewrite family_intersection_compl_union. apply any_union_open.\n    intros. red in H0. specialize (H _ H0). now apply closed_compl_open.\n  Qed.\n\n  Lemma union_closed: forall (s1 s2: Ensemble A),\n      closed s1 -> closed s2 -> closed (Union s1 s2).\n  Proof. intros. red. rewrite De_Morgan_law1. apply intersection_open; auto. Qed.\n\n  Definition interior (S: Ensemble A): Ensemble A :=\n    FamilyUnion (fun U => open U /\\ Included U S).\n\n  Lemma interior_open: forall S, open (interior S).\n  Proof. intro. apply any_union_open. intros. red in H. now destruct H. Qed.\n\n  Lemma interior_Included: forall S, Included (interior S) S.\n  Proof. repeat intro. destruct H. destruct H. auto with sets. Qed.\n\n  Lemma open_interior_self: forall S, open S -> interior S = S.\n  Proof.\n    intros. apply Extensionality_Ensembles. split.\n    - apply interior_Included.\n    - repeat intro. exists S; auto with sets.\n  Qed.\n\n  Lemma interior_maximal: forall U S,\n      open U -> Included U S -> Included U (interior S).\n  Proof. repeat intro. exists U; auto with sets. Qed.\n\n  Lemma Included_interior_open: forall S, Included S (interior S) -> open S.\n  Proof.\n    intros. replace S with (interior S). 1: apply interior_open.\n    apply Extensionality_Ensembles. split; auto. apply interior_Included.\n  Qed.\n\n  Definition closure (S: Ensemble A): Ensemble A :=\n    FamilyIntersection (fun U => closed U /\\ Included S U).\n\n  Lemma closure_closed: forall S, closed (closure S).\n  Proof. intros. apply any_intersection_closed. intros. red in H. now destruct H. Qed.\n\n  Lemma closure_Included: forall S, Included S (closure S).\n  Proof. repeat intro. constructor. intros U ?. destruct H0. auto with sets. Qed.\n\n  Lemma closed_closure_self: forall S, closed S -> closure S = S.\n  Proof.\n    intros. apply Extensionality_Ensembles. split.\n    - repeat intro. destruct H0. apply H0. auto with sets.\n    - apply closure_Included.\n  Qed.\n\n  Lemma closure_minimal: forall U S,\n      closed U -> Included S U -> Included (closure S) U.\n  Proof. repeat intro. destruct H1. apply H1. auto with sets. Qed.\n\n  Definition isolated (x: A): Prop := open (Singleton x).\n\n  Definition isolated_in_set (x: A) (S: Ensemble A): Prop :=\n    In S x /\\ exists U, open U /\\ Intersection U S = Singleton x.\n\n  Definition discrete (U: Ensemble A): Prop :=\n    forall x, In U x -> isolated_in_set x U.\n\n  Definition connected: Prop :=\n    forall (S: Ensemble A), open S -> closed S -> S = Empty_set \\/ S = Full_set.\n\n  Definition compact: Prop :=\n    forall (C: Family A),\n      (forall U, In C U -> open U) -> FamilyUnion C = Full_set ->\n      exists (fC: Family A), Finite fC /\\ Included fC C /\\ FamilyUnion fC = Full_set.\n\n  Definition compact_set (S: Ensemble A): Prop :=\n    forall (C: Family A),\n      (forall U, In C U -> open U) -> Included S (FamilyUnion C) ->\n      exists (fC: Family A), Finite fC /\\ Included fC C /\\\n                             Included S (FamilyUnion fC).\n\n  Lemma compact_set_on_indexed_covers:\n    forall (S: Ensemble A) (Idx: Type) (C: IndexedFamily Idx A),\n      compact_set S ->\n      (forall idx: Idx, open (C idx)) -> Included S (IndexedUnion C) ->\n      exists idxSet: Ensemble Idx,\n        Finite idxSet /\\\n        Included S (IndexedUnion (fun i: {x: Idx | In idxSet x} => C (proj1_sig i))).\n  Proof.\n    intros. destruct (H (imageFamily C)) as [subcover].\n    - intros. destruct H2. subst y. apply H0.\n    - now rewrite indexed_to_family_union in H1.\n    - destruct H2 as [? []]. apply Finite_FiniteT in H2.\n      destruct (finite_choice _ _\n                              (fun (U:{x:Ensemble A | In subcover x}) (a:Idx) =>\n                                 proj1_sig U = C a)) as [choice_fun]; auto.\n      + intros. destruct x as [x]. simpl. apply H3 in i. destruct i. exists x; auto.\n      + exists (Im Full_set choice_fun). split.\n        * apply FiniteT_img; auto. intros. apply classic.\n        * repeat intro. apply H4 in H6. destruct H6.\n          assert (In (Im Full_set choice_fun) (choice_fun (exist _ S0 H6))). {\n            exists (exist _ S0 H6); constructor. }\n          exists (exist _ (choice_fun (exist _ S0 H6)) H8). simpl. now rewrite <- H5.\n  Qed.\n\n  Lemma finite_intersection_open: forall {Idx: Type} (F:IndexedFamily Idx A),\n      FiniteT Idx -> (forall i: Idx, open (F i)) -> open (IndexedIntersection F).\n  Proof.\n    intros. induction H.\n    - rewrite empty_indexed_intersection. apply full_open.\n    - assert (IndexedIntersection F =\n              Intersection (IndexedIntersection (fun x => F (Some x))) (F None)). {\n        apply Extensionality_Ensembles; split; red; intros.\n        - destruct H1. constructor.\n          + constructor. intros; apply H1.\n          + apply H1.\n        - destruct H1. destruct H1. constructor. intros.\n          destruct i; [apply H1 | apply H2]. }\n      rewrite H1. apply intersection_open.\n      + apply IHFiniteT. intros; apply H0.\n      + apply H0.\n    - destruct H1.\n      assert (IndexedIntersection F = IndexedIntersection (fun x => F (f x))). {\n        apply Extensionality_Ensembles; split; red; intros.\n        - constructor. destruct H3. intro; apply H3.\n        - constructor. destruct H3. intro; rewrite <- H2 with i. apply H3. }\n      rewrite H3. apply IHFiniteT. intro; apply H0.\n  Qed.\n\n  (* Theorem 26.3 of Topology *)\n  Lemma compact_of_Hausdorff_closed:\n    forall {Hau: HausdorffSpace A} (S: Ensemble A), compact_set S -> closed S.\n  Proof.\n    intros. red. apply Included_interior_open. repeat intro.\n    assert (forall y, In S y -> y <> x). {\n      intros. hnf in H0. intro. apply H0. now subst. }\n    remember (fun yS: {z: A | In S z} =>\n                let whole := Hausdorff_prop (proj1_sig yS) x (H1 _ (proj2_sig yS)) in\n                (projT1 whole, proj1_sig (projT2 whole))).\n    remember ((fun x: {z : A | In S z} => fst (p x)) :\n                IndexedFamily {z : A | In S z} A) as V.\n    assert (forall idx: {z: A | In S z}, open (V idx)). {\n      intros. subst. simpl. destruct idx as [z]. simpl. unfold Hausdorff_prop.\n      destruct Hau. destruct s. destruct a. simpl. easy. }\n    assert (Included S (IndexedUnion V)). {\n      repeat intro. exists (exist _ x0 H3). subst. simpl. unfold Hausdorff_prop.\n      destruct Hau. destruct s. simpl. tauto. }\n    destruct (compact_set_on_indexed_covers _ _ _ H H2 H3) as [idxSet []].\n    remember ((fun x: {z : A | In S z} => snd (p x)) :\n                IndexedFamily {z : A | In S z} A) as U.\n    hnf. exists (IndexedIntersection\n                   (fun i : {x : {z : A | In S z} | In idxSet x} => U (proj1_sig i))).\n    - hnf. split.\n      + apply finite_intersection_open.\n        * now apply Finite_FiniteT.\n        * intros. subst. simpl. unfold Hausdorff_prop. destruct Hau. simpl.\n          destruct s as [? [? []]]. now simpl.\n      + repeat intro. specialize (H5 _ H7). inversion H5. subst x1. clear H5.\n        inversion H6. subst x1. clear H6. specialize (H5 i). subst. simpl in H5, H8.\n        unfold Hausdorff_prop in H8, H5. destruct Hau. simpl in H8, H5.\n        destruct s. simpl in H5. destruct a as [_ [_ [_ [_ ?]]]].\n        assert (In (Intersection x1 x2) x0) by now constructor. rewrite H6 in H9.\n        inversion H9.\n    - hnf. constructor. intros. destruct i. simpl. subst. simpl. unfold Hausdorff_prop.\n      destruct x0. simpl. destruct Hau. simpl. destruct s. simpl. tauto.\n  Qed.\n\nEnd TOPOLOGICAL_SPACE_PROP.\n", "meta": {"author": "txyyss", "repo": "FormalMath", "sha": "35d2593efbc346433fe586b8f8dbaede046df6dc", "save_path": "github-repos/coq/txyyss-FormalMath", "path": "github-repos/coq/txyyss-FormalMath/FormalMath-35d2593efbc346433fe586b8f8dbaede046df6dc/Topology/TopologicalSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8856314647623015, "lm_q1q2_score": 0.8266756964263177}}
{"text": "Require Export P02.\n\n\n\n(** **** Exercise: 3 stars (optimize_0plus_b)  *)\n(** Since the [optimize_0plus] transformation doesn't change the value\n    of [aexp]s, we should be able to apply it to all the [aexp]s that\n    appear in a [bexp] without changing the [bexp]'s value.  Write a\n    function which performs that transformation on [bexp]s, and prove\n    it is sound.  Use the tacticals we've just seen to make the proof\n    as elegant as possible. *)\n\nFixpoint optimize_0plus (a:aexp) : aexp :=\n  match a with\n  | AId x              => AId x\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 st a,\n  aeval st (optimize_0plus a) = aeval st a.\nProof.\n  intros st a.\n  induction a;\n    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n    try reflexivity.\n  - (* APlus *)\n    destruct a1;\n      try (simpl; simpl in IHa1; rewrite IHa1;rewrite IHa2; reflexivity).\n    + (* a1 = ANum n *) destruct n; simpl; rewrite IHa2; reflexivity.\n    + (* a1 = AId i *) simpl. rewrite IHa2. reflexivity.\nQed.\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n  match b with\n  | BTrue       => BTrue\n  | BFalse      => BFalse\n  | BEq a1 a2   => BEq (optimize_0plus a1) (optimize_0plus a2)\n  | BLe a1 a2   => BLe (optimize_0plus a1) (optimize_0plus a2)\n  | BNot b1     => BNot (optimize_0plus_b b1)\n  | BAnd b1 b2  => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)\n  end.\n\nExample optimize_0plus_b_example1:\n  optimize_0plus_b (BEq \n     (AMult (APlus (ANum 0) (APlus (ANum 0) (ANum 3)))\n            (AMinus (ANum 5) (APlus (ANum 0) (ANum 1))))\n     (APlus (ANum 2)\n            (APlus (ANum 0)\n                   (APlus (ANum 0) (ANum 1)))))\n  = (BEq (AMult (ANum 3) (AMinus (ANum 5) (ANum 1)))\n         (APlus (ANum 2) (ANum 1))).\nProof. reflexivity. Qed.  \n\nTheorem optimize_0plus_b_sound : forall st b,\n  beval st (optimize_0plus_b b) = beval st b.\nProof.\n  intros st b.\n  induction b;\n    try (simpl; repeat rewrite optimize_0plus_sound; reflexivity);\n    try reflexivity.\n  - (* BNot *) simpl. rewrite IHb. reflexivity.\n  - (* BAnd *) simpl. rewrite IHb1. rewrite IHb2. 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/P03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.9046505299595162, "lm_q1q2_score": 0.8265579468649266}}
{"text": "(*|\n#############################################################\nEfficient Way of Defining Multiple Functions of the Same Type\n#############################################################\n\n:Link: https://stackoverflow.com/q/49600938\n|*)\n\n(*|\nQuestion\n********\n\nI would like to avoid copying and pasting the parameters and return\ntype of functions of the same type that I am trying to define. Since,\nin my opinion, that would be bad programming practice.\n\nFor example, I am defining the following functions:\n|*)\n\nDefinition R := nat. (* .none *)\nDefinition metric_non_negative {X : Type} (d : X -> X -> R) :=\n  forall x y : X, (d x y) >= 0.\n\nDefinition metric_identical_arguments {X : Type} (d : X -> X -> R) :=\n  forall x y : X, (d x y) = 0 <-> x = y.\n\n(*|\nI would like to be able to define both functions without repeatedly\ntyping the redundancy:\n\n.. code-block:: coq\n\n    {X : Type} (d : X -> X -> R)\n\nI would also like to potentially define a third function, in which\ncase the solution should generalize to the case where more than two\nfunctions of the same type are being defined. Is this possible, and\nhow so?\n\n----\n\n**A (Anton Trunov):** Does ``Section`` mechanism not solve your\nproblem?\n|*)\n\n(*|\nAnswer\n******\n\nAs Anton Trunov mentioned in his comment, it sounds exactly like you\nwant to use a section:\n|*)\n\nReset metric_non_negative. (* .none *)\nSection Metric.\n\n  Context {X : Type}.\n  Variable (d : X -> X -> R).\n\n  Definition metric_non_negative :=\n    forall x y : X, (d x y) >= 0.\n\n  Definition metric_identical_arguments :=\n    forall x y : X, (d x y) = 0 <-> x = y.\n\nEnd Metric.\n\n(*|\nNote that I've used ``Context`` to make ``X`` an implicit argument;\nyou can also use ``Set Implicit Arguments.`` and make it a\n``Variable`` to let Coq set its implicitness automatically.\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/efficient-way-of-defining-multiple-functions-of-the-same-type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8962513710552469, "lm_q1q2_score": 0.8262737008039458}}
{"text": "From mathcomp Require Import all_ssreflect. \n\n\n(** *** Exercise 1:\n    - Prove this statement by induction.\n      Relevant lemmas are\n         doubleS odd_double addn0 addnn mulnn\n         big_mkcond big_nat_recr\n*)\n\nLemma sum_odd n : \\sum_(0 <= i < n.*2 | odd i) i = n^2.\nProof.\n(*D*)elim: n => [|n IHn]; first by rewrite unlock.\n(*D*)rewrite doubleS big_mkcond 2?big_nat_recr // -big_mkcond /=.\n(*D*)rewrite {}IHn odd_double /= addn0 -addnn -!mulnn.\n(*D*)by rewrite mulSn mulnC mulSn addnA addSn addnC.\nQed.\n\n\n(** *** Exercise 2:\n    - Let's define the subtype of odd and even natural numbers\n    - Intrument Coq to recognize odd/even number built out\n      of product and successor\n    - Inherit on [odd_nat] the [eqType] structure \n*)\n\nStructure odd_nat := Odd {\n  oval :> nat;\n  oprop : odd oval\n}.\nLemma oddP (n : odd_nat) : odd n.\nProof. by case: n. Qed.\n\nStructure even_nat := Even {\n  eval :> nat;\n  eprop : ~~ (odd eval)\n}.\nLemma evenP (n : even_nat) : ~~ (odd n).\nProof. by case: n. Qed.\n\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. Fail by rewrite oddP evenP. Abort.\n\nCanonical even_0 := Even 0 isT.\n\nLemma oddS n : ~~ (odd n) -> odd n.+1.\nProof.\n(*D*)by rewrite /=; case: (odd n).\nQed.\n\nLemma evenS n : (odd n) -> ~~ (odd n.+1).\nProof.\n(*D*)by rewrite /=; case: (odd n).\nQed.\n\nCanonical odd_even (m : even_nat) :=\n  Odd m.+1 (oddS m (eprop m)).\nCanonical even_odd (m : odd_nat) :=\n(*D*)Even m.+1 (evenS m (oprop m)).\n\nLemma odd_mulP (n m : odd_nat) : odd (n * m).\nProof.\n(*D*)by rewrite odd_mul !oddP.\nQed.\nCanonical odd_mul (n m : odd_nat) :=\n(*D*)Odd (n * m) (odd_mulP n m).\n\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. by rewrite oddP evenP. Qed.\n\nFail Check forall n m : odd_nat, n == m.\n\nCanonical odd_subType :=\n(*D*)Eval hnf in [subType for oval].\nDefinition odd_eqMixin :=\n(*D*)Eval hnf in [eqMixin of odd_nat by <:].\nCanonical odd_eqType :=\n(*D*)Eval hnf in EqType odd_nat odd_eqMixin.\n\nCheck forall n m : odd_nat, n == m.\n\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/exercise4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.9019206659843132, "lm_q1q2_score": 0.82625819073745}}
{"text": "(* Exercise 1 *)\n(* Define an inductive type for the months in the gregorian calendar *)\n(*(the French civil calendar) *)\nInductive month : Set :=\n|January : month\n|February : month\n|March : month\n|April : month\n|May : month\n|June : month\n|July : month\n|August : month\n|September : month\n|October : month\n|November : month\n|December : month.\n\n(* Define an inductive type for the four seasons *)\nInductive season : Set :=\n|Autumn : season\n|Winter : season\n|Spring : season\n|Summer : season.\n\n(* What is the inductive principle generated in each case ?*)\nCheck month_ind.\nCheck season_ind.\n\n(* Define a function mapping each month to the season that contains *)\n(* most of its days, using pattern matching *)\nDefinition season_of_month (m : month) :=\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 => Autumn\n    |November => Autumn\n    |December => Autumn\n  end.\n\n(* Exercise 2 *)\n(* Define the boolean functions bool_xor, bool_and, bool_eq of type *)\n(*bool -> bool -> bool, and the function bool_not of type bool -> bool *)\nDefinition bool_not (b:bool) : bool := if b then false else true.\n\nDefinition bool_xor (b b':bool) : bool := if b then bool_not b' else b'.\n\nDefinition bool_and (b b':bool) : bool := if b then b' else false.\n\nDefinition bool_or (b b':bool) := if b then true else b'.\n\n\nDefinition bool_eq (b b':bool) := if b then b' else bool_not b'.\n  \n\n(* prove the following theorems:*)\nLemma bool_xor_not_eq : forall b1 b2 : bool,\n  bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof.\n  intros b1 b2; case b1; case b2; simpl; trivial.\nQed.\n\nLemma bool_not_and : forall b1 b2 : bool,\n  bool_not (bool_and b1 b2) = bool_or (bool_not b1) (bool_not b2).\nProof.\n  intros b1 b2; case b1; case b2; simpl; trivial.\nQed.\n\nLemma bool_not_not : forall b : bool, bool_not (bool_not b) = b.\nProof.\n intro b; case b; simpl; trivial.\nQed.\n\nLemma bool_or_not : forall b : bool, \n  bool_or b (bool_not b) = true.\nProof.\n  intro b; case b; simpl; trivial.\nQed.\n\nLemma bool_id_eq : forall b1 b2 : bool, \n  b1 = b2 <-> bool_eq b1 b2 = true.\nProof.\n  intros b1 b2 ;split.  \n intro H;rewrite  H;  case b2; trivial.\n case b1; case b2; simpl; trivial.\n  intro e;discriminate e.\nQed.\n\n\nLemma bool_not_or : forall b1 b2 : bool,\n  bool_not (bool_or b1 b2) = bool_and (bool_not b1) (bool_not b2).\nProof.\n  intros b1 b2; case b1; case b2; simpl; trivial.\nQed.\n\nLemma bool_or_and : 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; case b1; case b2; case b3; simpl; trivial.\nQed.\n\n(* Exercise 3 *)\n\n(* Let us consider again the type color defined in the lecture :*)\nInductive color:Type :=\n | white | black | yellow | cyan | magenta | red | blue | green.\n\n(* let us define the complement of a color *)\n\nDefinition compl (c : color) :=\n match c with \n | white => black \n | black => white\n | yellow => blue\n | cyan => red\n | magenta => green\n | red => cyan\n | blue => yellow\n | green => magenta\n end.\n\n(*\nProve the following results:*)\n\nLemma compl_compl : forall c, compl (compl c)= c.\nProof.\n intro c;case c;simpl;trivial.\nQed.\n\n\n\nLemma compl_injective : forall c c', compl c = compl c' -> c = c'.\nProof.\n intro c;case c;intro c';case c';simpl;intro e;try discriminate;trivial.\nQed.\n\n\n\n\nLemma compl_surjective : forall c, exists c', c= compl  c'.\nProof.\n intro c; exists (compl c);rewrite compl_compl;trivial.\nQed.\n\n\n\n\n\n(** Exercise 4 *)\n\n(* Define an inductive type formula : Type that represents the *)\n(*abstract language of propositional logic without variables: \nL = L /\\ L | L \\/ L | ~L | L_true | L_false\n*)\nInductive formula : Type :=\n|L_true : formula\n|L_false : formula\n|L_and : formula -> formula -> formula\n|L_or : formula -> formula -> formula\n|L_neg : formula -> formula.\n  \n\n(* Define a function formula_holds of type (formula -> Prop computing the *)\n(* Coq formula corresponding to an element of type formula *)\nFixpoint formula_holds (f : formula) : Prop :=\n  match f with\n    |L_true => True\n    |L_false => False\n    |L_and f1 f2 => (formula_holds f1) /\\ (formula_holds f2)\n    |L_or f1 f2 =>  (formula_holds f1) \\/ (formula_holds f2)\n    |L_neg f => ~(formula_holds f)\n  end.\n \n(* Define  a function isT_formula of type (formula -> bool) computing *)\n(* the intended truth value of (f : formula) *)\nFixpoint isT_formula (f : formula) : bool :=\n  match f with\n    |L_true => true\n    |L_false => false\n    |L_and f1 f2 => andb (isT_formula f1) (isT_formula f2)\n    |L_or f1 f2 =>  orb (isT_formula f1) (isT_formula f2)\n    |L_neg f => negb (isT_formula f)\n  end.\n\n\n(* prove that is (idT_formula f) evaluates to true, then its *)\n(*corresponding Coq formula holds ie.:*)\nRequire Import Bool.\nLemma isT_formula_correct : forall f : formula, \n   isT_formula f = true <-> formula_holds f.\nProof.\ninduction f; simpl; split; trivial.\n(* False *)\ndiscriminate.\nintro h; elim h.\n(* And *)\ncase_eq (isT_formula f1); intro h1; case_eq (isT_formula f2); intro\n   h2; try discriminate 1.\n  split; [apply IHf1 | apply IHf2]; trivial.\n\n  destruct IHf1 as [IHf1_1 IHf1_2].\n  destruct IHf2 as [IHf2_1 IHf2_2].\n  destruct 1.\n  rewrite IHf1_2; trivial.\n  rewrite IHf2_2; trivial.\n(* Or *)\ncase_eq (isT_formula f1); intro h1; case_eq (isT_formula f2); intro\n   h2; try discriminate 1.\n  left; apply IHf1; trivial.\n  left; apply IHf1; trivial.\n  right; apply IHf2; trivial.\n\nintro h.\ndestruct IHf1 as [IHf1_1 IHf1_2].\ndestruct IHf2 as [IHf2_1 IHf2_2].\ndestruct h as [h1 | h2].\n  rewrite IHf1_2; trivial.\n  rewrite IHf2_2; trivial.\n  SearchAbout orb.\n  rewrite orb_true_r; trivial.\n(* False *)\ndestruct IHf as [IHf_1 IHf_2].\ncase_eq (isT_formula f).\n  discriminate 2.\n  intros h1 _ h3.\n  generalize h1.\n  rewrite IHf_2; trivial.\n  discriminate 1.\ndestruct IHf as [IHf_1 IHf_2].\ncase_eq (isT_formula f); trivial.\nintros h1 h2.\nabsurd (formula_holds f); trivial.\napply IHf_1.\ntrivial.\nQed.\n\n\n\n\n(* Exercise 5 *)\n(* We use the inductive type defined in the lecture:*)\nInductive natBinTree : Set :=\n| Leaf : natBinTree\n| Node : nat -> natBinTree -> natBinTree -> natBinTree.\n\n(*\nDefine a function which sums all the values present in the tree.\n*)\nFixpoint sum_natBinTree (t : natBinTree) :=\n  match t with\n    |Leaf => 0\n    |Node n t1 t2 => n + (sum_natBinTree t1) + (sum_natBinTree t2)\n  end.\n\n(*\nDefine a function is_zero_present : natBinTree -> bool, which tests if \nthe value 0 is present in the tree.\n*)\nFixpoint is_zero_present (t : natBinTree) :=\n  match t with\n    |Leaf  => false\n    |Node n t1 t2 => \n      match n with\n        |0 => true\n          |_ => \n            (is_zero_present t1) || (is_zero_present t2)\n      end\n  end.\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/solutions/solutions/solutions5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.9161096055730491, "lm_q1q2_score": 0.826258185573071}}
{"text": "(*\nCheck nat_rect.\n*)\n\nFixpoint nat_rect' \n    (P:nat -> Type) \n    (p:P 0) \n    (q:forall (n:nat), P n -> P (S n)) \n    (n:nat) : P n :=\n    match n with \n    | 0     => p\n    | S m   => q m (nat_rect' P p q m)\n    end. \n\nDefinition nat_rect'' := fix f\n    (P:nat -> Type) \n    (p:P 0) \n    (q:forall (n:nat), P n -> P (S n))\n    (n:nat) : P n :=\n    match n with \n    | 0     => p\n    | S m   => q m (f P p q m)\n    end. \n\n\nLemma rect_correct : forall \n    (P:nat -> Type) \n    (p:P 0) \n    (q:forall (n:nat), P n -> P (S n))\n    (n:nat),\n    nat_rect' P p q n = nat_rect'' P p q n.\nProof. reflexivity. Qed.\n\nDefinition nat_rect3 \n    (P:nat -> Type) \n    (p:P 0) \n    (q:forall (n:nat), P n -> P (S n))\n    : forall (n:nat), P n :=\n    fix f (n:nat) : P n :=\n        match n with \n        | 0     => p\n        | S m   => q m (f m)\n        end. \nLemma rect3_correct : forall \n    (P:nat -> Type) \n    (p:P 0) \n    (q:forall (n:nat), P n -> P (S n))\n    (n:nat),\n    nat_rect3 P p q n = nat_rect' P p q n.\nProof. \n    intros P p q. induction n as [|n IH]. \n    - reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\n \n \nDefinition nat_ind' (P:nat -> Prop) := nat_rect' P. \nDefinition nat_rec' (P:nat -> Set)  := nat_rect' P.\n\n(*\nCheck nat_ind'.\nCheck nat_rec'.\n*)\n\nLemma plus_n_0' : forall (n:nat), plus n 0 = n.\nProof.\n    apply nat_ind'.\n    - reflexivity.\n    - intros n IH. simpl. rewrite IH. reflexivity.\nQed.\n\n(*\nCheck nat_rec'.\nnat_rec : forall P : nat -> Set,\n    P 0 -> \n    (forall n : nat, P n -> P (S n)) -> \n    forall n : nat, P n\n*)\n\nLemma nat_rec_init : \n    forall (P:nat -> Set),\n    forall (p:P 0),\n    forall (q: forall n, P n -> P (S n)),\n    nat_rec' P p q 0 = p.\nProof. reflexivity. Qed.\n\n\nLemma nat_rec_inc : \n    forall (P:nat -> Set),\n    forall (p:P 0),\n    forall (q: forall n, P n -> P (S n)),\n    forall (n:nat),\n    nat_rec' P p q (S n) = q n (nat_rec' P p q n).\nProof. reflexivity. Qed.\n\n\nDefinition plus': nat -> nat -> nat :=\n    nat_rec' (fun _ => nat -> nat) (fun m => m) (fun _ f m => S (f m)).\n\nLemma plus_0_n' : forall (n:nat), plus' 0 n = n.\nProof. reflexivity. Qed.\n\nLemma plus_Sn_m' : forall (n m:nat), plus' (S n) m = S (plus' n m).\nProof. reflexivity. Qed.\n\nLemma plus'_correct : forall (n m:nat), plus' n m = plus n m.\nProof.\n    apply (nat_ind' (fun n => forall (m:nat), plus' n m = plus n m)); \n    intros n; simpl.\n    - unfold plus'. unfold nat_rec'. unfold nat_rect'. reflexivity.\n    - intros IH m. rewrite plus_Sn_m', IH. 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/cpdt/recursion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.8260878949603794}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nAxiom replace_with_your_solution_here : forall {A : Type}, A.\n\n\n(*\nUse your solution of Homework 2 and prove correctness of your implementations.\nI'm repeating some (partial) definitions here just to make sure\nthe lemma statements make sense.\n*)\n\n(* A language of arithmetic expression *)\nInductive expr : Type :=\n| Const of nat\n| Plus of expr & expr\n| Minus of expr & expr\n| Mult of expr & expr.\n\nFixpoint eval (e : expr) : nat :=\n  match e with\n  | Const n => n\n  | Plus n m => addn (eval n) (eval m)\n  | Minus n m => subn (eval n) (eval m)\n  | Mult n m => muln (eval n) (eval m)\n  end.\n\n(* Stack language *)\nInductive instr := Push (n : nat) | Add | Sub | Mul.\n\nDefinition prog := seq instr.\nDefinition stack := seq nat.\n\nFixpoint run (p : prog) (s : stack) : stack :=\n  match p, s  with\n  | [::], t => s\n  | Push n :: r, t => run r (n :: t)\n  | Add :: r, n :: m :: t => run r ((addn m n) :: t)\n  | Sub :: r, n :: m :: t => run r ((subn m n) :: t)\n  | Mul :: r, n :: m :: t => run r ((muln m n) :: t)\n  | _, _ => [::]                               \n  end.\n\n(* Compiler from the expression language to the stack language *)\n                                                         \nFixpoint compile (e : expr) : prog :=\n  match e with\n  | Const n => [:: Push n]\n  | Plus m n => compile m ++ compile n ++ [:: Add]\n  | Minus m n => compile m ++ compile n ++ [:: Sub]\n  | Mult m n => compile m ++ compile n ++ [:: Mul]\n  end.\n\nArguments compile e : simpl nomatch.\n\nDefinition E := (Plus (Const 10) (Mult (Const 11) (Const 3))).\n                  \nCheck erefl : run (compile E) [::] = [:: eval E].\nCompute (compile E).\n\n(** Here is a correctness theorem for the compiler: it preserves the\nmeaning of programs. By \"meaning\", in this case, we just mean the final\nanswer computed by the program. For a high-level expression, the answer\nis the result of calling [eval]. For stack programs, the answer\nis whatever [run] leaves on the top of the stack. The correctness\ntheorem states that these answers are the same for an expression and\nthe corresponding compiled program. *)\n\nLemma run_order (e : expr) (p : prog) (s : stack) :\n  run (compile e ++ p) s = run p (eval e :: s).\nProof.\n  move : e p s.\n  elim.\n  - move => //.\n  - move => ex hx ey hy p s.\n    rewrite /= -!catA.\n    rewrite (hx (compile ey ++ [:: Add] ++ p) s).\n    rewrite (hy ([:: Add] ++ p) (eval ex :: s)).\n    by rewrite /=.\n  - move => ex hx ey hy p s.\n    rewrite /= -!catA.\n    rewrite (hx (compile ey ++ [:: Sub] ++ p) s).\n    rewrite (hy ([:: Sub] ++ p) (eval ex :: s)).\n    by rewrite /=.\n  - move => ex hx ey hy p s.\n    rewrite /= -!catA.\n    rewrite (hx (compile ey ++ [:: Mul] ++ p) s).\n    rewrite (hy ([:: Mul] ++ p) (eval ex :: s)).\n    by rewrite /=.\nQed.\n\nTheorem compile_correct e :\n  run (compile e) [::] = [:: eval e].\nProof.\n  move : (run_order e [::] [::]).\n  rewrite cats0.\n  exact.\nQed.\n\n(* ==== OPTIONAL part: decompiler ==== *)\n\nPrint option.\n\nFixpoint decompile_rec (p : prog) (s : seq expr) {struct p} : option expr :=\n  match p, s with\n  | Push n :: r, t => decompile_rec r (Const n :: s)\n  | Mul :: r, n :: m :: t => decompile_rec r (Mult m n :: t)\n  | Sub :: r, n :: m :: t => decompile_rec r (Minus m n :: t)\n  | Add :: r, n :: m :: t => decompile_rec r (Plus m n :: t)\n  | [::], [:: e] => Some e\n  | _, _ => None\n  end.\n\nArguments decompile_rec p s : simpl nomatch.\n  \nDefinition decompile (p : prog) : option expr := decompile_rec p [::].\n\n(** Prove [decompile] cancels [compile]. *)\n\nLemma decompile_rec_compile (e : expr) (p : prog) (s : seq expr) :\n  decompile_rec (compile e ++ p) s = decompile_rec p (e :: s).\nProof.\n  move : e p s.\n  elim.\n  - by move => //.\n  - move => em hm en hn p s.\n    move => /=.\n    rewrite -!catA.\n    rewrite hm hn.\n      by exact.\n  - move => em hm en hn p s.\n    move => /=.\n    rewrite -!catA.\n    rewrite hm hn.\n      by exact.\n  - move => em hm en hn p s.\n    move => /=.\n    rewrite -!catA.\n    rewrite hm hn.\n      by exact.\nQed.\n  \n\nLemma decompile_compile e :\n  decompile (compile e) = Some e.\nProof.\n  move : (decompile_rec_compile e [::] [::]).\n  rewrite /= cats0.\n  done.\nQed.\n\n(* Prove the [compile] function is injective *)\n\nDefinition decrec (p : prog) := decompile_rec p [::].\n\n(* Lemma compile_inj :\n  injective compile.\nProof.\n  rewrite /injective.\n  case => /=.\n  - move => n e.\n    move => h1.\n    move : (congr1 decompile h1).\n    rewrite decompile_compile /decompile /decompile_rec.\n    by case.      \n  - move => ex ey e.\n    case : e.\n    - move => n h1.\n      move : (congr1 decrec h1).\n      by rewrite /decrec !decompile_rec_compile /(compile (Const n)) //.\n    - move => em en.\n      rewrite /=.\n      move => h1.\n      move : (congr1 decrec h1).\n      rewrite /decrec !decompile_rec_compile /=.\n      case.\n      move => exm eyn.\n      set h2 := (proj2 (pair_equal_spec ex em ey en)) (conj exm eyn).\n        by exact (congr1 (fun '(x, y) => Plus x y) h2).\n    - move => em en.\n      rewrite /=.\n      move => h1.\n      move : (congr1 decrec h1).\n      rewrite /decrec !decompile_rec_compile /=.\n      case.\n        by exact.\n    - move => em en.\n      rewrite /=.\n      move => h1.\n      move : (congr1 decrec h1).\n      rewrite /decrec !decompile_rec_compile /=.\n      case.\n        by exact.  \n  - move => em en.\n    rewrite /=.\n    case.\n    - move => n.\n      rewrite /(compile (Const n)).\n      move => h1.\n      move : (congr1 decrec h1).\n        by rewrite !/decrec !decompile_rec_compile //.\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n        by rewrite !/decrec !decompile_rec_compile //.\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n      rewrite !/decrec !decompile_rec_compile //.\n      case.\n      move => emn ene.\n      set h2 := (proj2 (pair_equal_spec em n en e)) (conj emn ene).\n        by exact (congr1 (fun '(x, y) => Minus x y) h2).\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n        by rewrite !/decrec !decompile_rec_compile //.\n\n  - move => em en.\n    rewrite /=.\n    case.\n    - move => n.\n      rewrite /(compile (Const n)).\n      move => h1.\n      move : (congr1 decrec h1).\n        by rewrite !/decrec !decompile_rec_compile //.\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n        by rewrite !/decrec !decompile_rec_compile //.\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n      by rewrite !/decrec !decompile_rec_compile //.\n    - move => n.\n      rewrite /=.\n      move => e h1.\n      move : (congr1 decrec h1).\n      rewrite !/decrec !decompile_rec_compile //.\n      case.\n      move => emn ene.\n      set h2 := (proj2 (pair_equal_spec em n en e)) (conj emn ene).\n      by exact (congr1 (fun '(x, y) => Mult x y) h2).\nQed. *)\n\nLemma compile_inj :\n  injective compile.\nProof.\n  rewrite /injective.\n  move => ex ey h1.\n  move : (congr1 decompile h1).\n  rewrite !decompile_compile.\n  case.\n  exact.\nQed.\n", "meta": {"author": "mbakhterev", "repo": "csclub-coq-21", "sha": "9634684301b000748479cf4427db5c5ff79d6a14", "save_path": "github-repos/coq/mbakhterev-csclub-coq-21", "path": "github-repos/coq/mbakhterev-csclub-coq-21/csclub-coq-21-9634684301b000748479cf4427db5c5ff79d6a14/hw06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8918110346549901, "lm_q1q2_score": 0.8260878917469324}}
{"text": "Require Import List ssreflect ssrbool.\nFrom mathcomp Require Import eqtype ssrnat.\n\n(* Let's see how one would define insertion sort in OCaml:\n\n   let rec insert n l =\n     match l with\n       | [] -> [n]\n       | x::xs -> if n <= x then n::x::xs else x::(insert n xs)\n\n   let rec sort l =\n     match l with\n       | [] -> []\n       | x::xs -> insert x (sort xs)\n\n   As you saw during the lesson, the [insert] function is just some\n   particular proof of [nat -> list nat -> list nat]: it is the proof\n   that builds a new list by inserting its first arguments into its\n   second one. As any proof, it thus can be defined in Coq using tactics.\n *)\n\nDefinition insert (n:nat) (l:list nat) : list nat.\nProof.\n  (* The OCaml program is a recursive definition over l. I just do\n     exactly the same with the elim tactic. The induction hypothesis ih\n     is a proof of insert n xs : in fact it is the recursive call. *)\n  elim:l => [|x xs ih].\n  (* We start with the base case: we return the singleton list\n     containing only n. *)\n    apply:(n::nil).\n  (* We are now in the recursive case. We need to distinguish two cases\n     whether n <= x or not. *)\n  case h:(n <= x).\n  (* We are in the branch where n <= x. In this case, we can immediately\n     return the list n::x::xs *)\n    apply:(n::x::xs).\n  (* We now are in the branch where n > x. In this case, we want to\n     return x::(insert n xs). As we said, the recursive call is in fact\n     ih. *)\n  apply:(x::ih).\n  (* Our function is now defined using tactics. [Defined] checks that it\n     actually have the right type and defines it. *)\n Defined.\n\n\n(* We can check on some examples that it is indeed the insert function\n   we add in mind. Coq can actually compute with it! *)\n\nCompute (insert 5 (1::2::3::4::6::7::8::9::nil)).\nCompute (insert 5 (1::2::3::4::nil)).\n\n\n(* Now do the same for the sort function, and test it on some examples.\n   Hint: it takes only three tactics to define it! *)\n\nDefinition sort (l:list nat) : list nat.\nProof.\n  (* TODO *)\nDefined.\n\n\nCompute (sort (7::9::5::3::0::4::2::1::8::6::nil)).\n(* Add your own examples... *)\n\n\n(* Ok, so far we have understood that we can define function using\n   tactics. But our sorting function is no more that the OCaml version:\n   we did not prove it was actually returning a list that is sorted!\n   With tactics, we will be able to build the sorting function AND proof\n   its correctness at the same time... *)\n\n\n(* First, we need to define for a list of integers what it means to be\n   sorted: each element is smaller than all the following elements *)\n\nFixpoint smaller n l : Prop :=\n  match l with\n    | nil => true\n    | x::xs => n <= x /\\ smaller n xs\n  end.\n\n\nFixpoint sorted l : Prop :=\n  match l with\n    | nil => true\n    | x::xs => smaller x xs /\\ sorted xs\n  end.\n\n\n(* We give a very simple fact about smaller: if a is smaller than all\n   the elements of a list l, and n <= a, then n is also smaller than all\n   the elements of l. *)\n\nLemma smaller_trans n a l : smaller a l -> n <= a -> smaller n l.\nProof.\n  elim:l => /=.\n    done.\n  move => b l ih [h1 h2] h3.\n  split.\n    move/(_ a n b):leq_trans => h4.\n    by apply:h4.\n  by apply:ih.\nDefined.\n\n\n(* For a matter of time, we also give you some arithmetic lemmas that\n   you will need:\n\n   o leq_false_lt m n : (m <= n) = false -> (n < m)\n   o leq_false_leq n x : (n <= x) = false -> x <= n\n   o eq_refl (n:nat) : n == n\n   o gtn_eqF m n : m < n -> n == m = false\n   o leq_false_neq n a : (n <= a) = false -> n == a = false\n\n   Do not look at the proofs, just look at the statements above. *)\n\nLemma leq_trans n m p : m <= n -> n <= p -> m <= p.\nProof.\n  elim: n m p => [|i IHn] [|m] [|p]; try reflexivity.\n        move => h _. apply:h.\n      compute. discriminate 1.\n    move => _. compute => h. apply:h.\n  by move/(_ m p):IHn.\nDefined.\n\n\nLemma ltnW m n : m < n -> m <= n.\nProof. by apply:leq_trans. Defined.\n\n\nLemma leq_false_lt m n : (m <= n) = false -> (n < m).\nProof.\n  elim: m n => [|m IHm] [|n].\n        compute. discriminate 1.\n      compute. discriminate 1.\n    reflexivity.\n  by move/(_ n):IHm.\nDefined.\n\n\nLemma leq_false_leq n x : (n <= x) = false -> x <= n.\nProof.\n  move => h.\n  apply:ltnW.\n  by apply:leq_false_lt.\nDefined.\n\n\nLemma eq_refl (n:nat) : n == n.\nProof.\n  elim:n => [|n ih].\n    reflexivity.\n  exact:ih.\nDefined.\n\n\nLemma leqNgt m n : (m <= n) = ~~ (n < m).\nProof. by elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.\n\n\nLemma eqn_leq m n : (m == n) = (m <= n <= m).\nProof. elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.\n\n\nLemma gtn_eqF m n : m < n -> n == m = false.\nProof. by rewrite eqn_leq (leqNgt n) => ->. Defined.\n\n\nLemma leq_false_neq n a : (n <= a) = false -> n == a = false.\nProof.\n  move => h.\n  apply:gtn_eqF.\n  by apply: leq_false_lt.\nDefined.\n\n\n(* We are now ready to build the insert function and prove its\n   correctness at the same time. To do so, the Coq writing {l | P l}\n   that designates a list l that satisfies the predicate P: P is the\n   specification of the function.\n\n   The specification of the insert function is the following:\n   o if a is smaller that all the elements of l and a <= n then a is\n     smaller than all the elements of (insert n l)\n   o if l is sorted then (insert n l) is sorted *)\n\nDefinition insert_spec n l :\n  {l' |\n    (forall a, smaller a l -> a <= n -> smaller a l') /\\\n    (sorted l -> sorted l')}.\nProof.\n  (* The proof is a refinement of the proof of [insert], in which we\n     also build the proof of the specification of the function. So like\n     for defining [insert], we do an induction. *)\n  elim:l => [|x xs ih].\n  (* We present the base case. The answer is the singleton list\n     containing only n, together with a proof that this list satisfies\n     the specification. We first give the list, using the exists tactic.\n     *)\n    exists (n::nil).\n    (* Let's now prove the specification. It is a conjunction. *)\n    split.\n    (* On the first branch, we introduce a. *)\n      move => a.\n      (* We can simplify this goal: we know what [smaller a nil] and\n         [smaller a (n :: nil)] mean. *)\n      simpl.\n      (* In fact, this goal is trivially proved with done. *)\n      done.\n      (* Let's simplify the second branch: we know what [sorted nil] and\n         [sorted (n :: nil)] mean. *)\n    simpl.\n    (* In fact, this goal is trivially proved with done. *)\n    done.\n    (* Now do the recursive case. Do not forget to make a case analysis\n       whether n <= x or not. You can destruct a proof of {l | P l}\n       using the [case] tactic as usual. *)\n\n  (* TODO *)\nDefined.\n\n\n(* Let do the same for the sort function. *)\n\nDefinition sort_spec (l:list nat) : {l' | sorted l'}.\nProof.\n  (* TODO *)\nDefined.\n\n\n(* We now have defined functions that are correct (with respect to our\n   specification) by construction. Finally, Coq offers an extraction\n   mechanism, that automatically export them to OCaml, so we are sure\n   that the OCaml program is correct by construction. *)\n\nRequire Extraction.\nExtraction Language Ocaml.\nSet Extraction AccessOpaque.\n\n\nExtraction \"insert_sort.ml\" sort_spec.\n\n\n(* Have a look at the file \"insert_sort.mli\". You observe that the\n   function [sort_spec] has type [nat list -> nat list]: the extraction\n   mechanism \"forgets\" the proof of the correctness of this function,\n   since it has no signification in OCaml. You can test this extracted\n   function using the file \"test_sort.ml\". *)\n\n\n(* TO GO FURTHER *)\n\n\n(* I am sure you all have noticed that our specification is incomplete:\n   the sort function must not only return a sorted list, but this list\n   must be a permutation of the initial list! We now do the same job\n   with a complete specification. *)\n\n(* We first define our notion of permutation: (x::xs) and l2 are a\n   permutation if and only if xs and (remove x l2) are. *)\n\nFixpoint remove a (l:list nat) :=\n  match l with\n    | nil => None\n    | x::xs =>\n      if a == x then\n        Some xs\n      else\n        match remove a xs with\n          | Some xs' => Some (x::xs')\n          | None => None\n        end\n  end.\n\n\nFixpoint permutation l1 l2 : Prop :=\n  match l1, l2 with\n    | nil, nil => true\n    | nil, _ => False\n    | x::xs, _ =>\n      match remove x l2 with\n        | Some l2' => permutation xs l2'\n        | None => False\n      end\n  end.\n\n\n(* First prove that this relation is reflexive. *)\n\nLemma permutation_refl l: permutation l l.\nProof.\n  (* TODO *)\nDefined.\n\n\n(* Now define insertion and sort with the complete specification. *)\n\nDefinition insert_complete n l :\n  {l' |\n    (forall a, smaller a l -> a <= n -> smaller a l') /\\\n    (remove n l' = Some l) /\\\n    (sorted l -> sorted l' /\\ permutation (n::l) l')}.\nProof.\n  (* TODO *)\nDefined.\n\n\nDefinition sort_complete (l:list nat) : {l' | sorted l' /\\ permutation l l'}.\nProof.\n  (* TODO *)\nDefined.\n\n\nExtraction Language Ocaml.\nSet Extraction AccessOpaque.\n\n\nExtraction \"insert_sort.ml\" sort_complete.", "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/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8918110382493035, "lm_q1q2_score": 0.8260878914476517}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_congruencetransitive.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_congruenceflip :\n\tforall A B C D,\n\tCong A B C D ->\n\tCong B A D C /\\ Cong B A C D /\\ Cong A B D C.\nProof.\n\tintros A B C D.\n\tintros Cong_AB_CD.\n\tassert (Cong B A A B) as Cong_BA_AB by (apply cn_congruencereverse).\n\tassert (Cong C D D C) as Cong_CD_DC by (apply cn_congruencereverse).\n\tpose proof (lemma_congruencetransitive _ _ _ _ _ _ Cong_BA_AB Cong_AB_CD) as Cong_BA_CD.\n\tpose proof (lemma_congruencetransitive _ _ _ _ _ _ Cong_AB_CD Cong_CD_DC) as Cong_AB_DC.\n\tpose proof (lemma_congruencetransitive _ _ _ _ _ _ Cong_BA_AB Cong_AB_DC) as Cong_BA_DC.\n\tsplit.\n\texact Cong_BA_DC.\n\tsplit.\n\texact Cong_BA_CD.\n\texact Cong_AB_DC.\nQed.\n\nEnd Euclid.\n\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_congruenceflip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.8259983598124749}}
{"text": "(* March 1st, 2016. We skipped a lot of chapters *)\n\nInductive list (A:Type) : Type :=\n  | Nil : list A\n  | Cons : A -> list A -> list A.\n\nInductive ev : nat -> Prop :=\n  | ev_0: ev 0 (* constructor declaration *)\n  | ev_SS: forall (n:nat), ev n -> ev (S (S n)). (* also a constructor *)\n\nTheorem ev_example : ev 0.\nProof.\n  apply ev_0.\nQed.\n\nTheorem ev_example_nonzero : ev 14.\nProof.\n  repeat apply ev_SS.\n  apply ev_0.\nAbort.\n\n(* What's different from evenb *)\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S n) => evenb n\nend.\n\nFixpoint even (n:nat) : Prop := evenb n = true.\n\nTheorem even_ex : even 0.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem even_ex_bad : even 1.\nProof.\n  simpl.\nAbort.\n\nTheorem even_ex_big : even 14.\nProof.\n  simpl.\n  auto.\nQed.\n\n(* Inference rule: bottom conclusion, top hypothesis\n\n          ev n\n------  ----------\n ev 0    ev (n+2)\n\n*)\n\nInductive beautiful : nat -> Prop :=\n| b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(*\n                               beautiful n beautiful m\n-------- ---------   --------  ------------------------\n  b_0      b_3         b_5         beautiful(n+m)\n\n*)\n\nTheorem b_times2: forall n, beautiful n -> beautiful (2 * n).\nProof.\n  intros n beau. (* premises to a lemma *)\n  apply b_sum.\n  apply beau.\n  apply b_sum.\n  apply beau.\n  apply b_0.\nQed.\n\n(* when to use computational vs. inductive definitions? *)\n(* Inductive defs are more flexible than computational ones *)\n\n\n", "meta": {"author": "soojison", "repo": "Software-Foundations", "sha": "e27171399450b5f96fd31afcd974251c6cf2c7c1", "save_path": "github-repos/coq/soojison-Software-Foundations", "path": "github-repos/coq/soojison-Software-Foundations/Software-Foundations-e27171399450b5f96fd31afcd974251c6cf2c7c1/inclass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.8856314798554445, "lm_q1q2_score": 0.8258100038221161}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive exp: Type :=\n  | con (n: nat)\n  | add (a: exp) (b: exp)\n  | sub (a: exp) (b: exp).\n\nFixpoint eval (e: exp): nat :=\n  match e with\n  | con n => n\n  | add a b => eval a + eval b\n  | sub a b => eval a - eval b\n  end.\n\n\nInductive comm: Type :=\n  | addc\n  | subc\n  | push (n: nat).\n\nPrint list.\n\nFixpoint r (pr: list comm) (s: list nat): list nat :=\n  match pr, s with \n  | (cons addc pr'), (cons a (cons b  rest)) => r pr' (cons (a + b) rest)\n  | (cons subc pr'), (cons a (cons b  rest)) => r pr' (cons (a - b) rest)\n  | (cons (push n) pr'), stack => r pr' (cons n stack)\n  | [::], s => s\n  | _, _ => nil\n  end.\n\nFixpoint compile (e: exp): list comm :=\n    match e with \n    | con n => cons (push n) nil\n    | add a b => compile b ++ compile a ++  (cons addc nil) \n    | sub a b => compile b ++ compile a ++ (cons subc nil)\n    end.\n\n(* 20.3.1 *)\nLemma stepc: forall e rest stack, \n  r (compile e ++ rest) stack = r rest (cons (eval e) stack).\nProof.\n  elim => [n //| a IH b IH' | a IH b IH'] rest stack.\n  - rewrite /compile -/compile /eval -/eval.\n    rewrite -catA IH'.\n    rewrite -catA IH.\n    rewrite cat1s.\n    by rewrite /r -/r.\n  - rewrite /compile -/compile /eval -/eval.\n    rewrite -catA IH'.\n    rewrite -catA IH.\n    rewrite cat1s.\n    by rewrite /r -/r.\nQed.\n\n(* 20.3.2 *)\nTheorem correctc: forall e, r (compile e) [::] = [:: (eval e)].\nProof.\n  elim => [ n //= | a IH b IH' | a IH b IH' ].\n  - by rewrite /compile -/compile 2!stepc /r /eval -/eval.\n  - by rewrite /compile -/compile 2!stepc /r /eval -/eval.\nQed.\n\n(* 20.4 *)\nFixpoint d (pr: list comm) (exps: list exp): list exp :=\n  match pr, exps with \n  | [::], e => e\n  | [:: addc & rest], [:: e1, e2 & exps] => d rest [:: add e1 e2 & exps]\n  | [:: subc & rest], [:: e1, e2 & exps] => d rest [:: sub e1 e2 & exps]\n  | [:: push n & rest], exps => d rest [:: con n & exps]\n  | _, _ => [::]\n  end.\n\n(* 20.4.1 *)\nLemma stepd: forall e pr b, d (compile e ++ pr) b = d pr [:: e & b ].\nProof.\n  elim => [ n pr b // | e1 IH e2 IH' pr b | e1 IH e2 IH' pr b ].\n  - rewrite /compile -/compile -catA IH' -catA IH cat1s.\n    by rewrite /d -/d.\n  - rewrite /compile -/compile -catA IH' -catA IH cat1s.\n    by rewrite /d -/d.\nQed.\n\n(* 20.4.2 *)\nTheorem correctd: forall e, d (compile e) [::] = [:: e ].\nProof.\n  elim => [ n // | a IH b IH' | a IH b IH' ];\n    by rewrite /compile -/compile stepd stepd /d -/d.\nQed.\n  ", "meta": {"author": "cattingcat", "repo": "coq_lessons", "sha": "49ea5727398acddd5b347b234d6b4efcab305422", "save_path": "github-repos/coq/cattingcat-coq_lessons", "path": "github-repos/coq/cattingcat-coq_lessons/coq_lessons-49ea5727398acddd5b347b234d6b4efcab305422/model_and_prooving_CompTT/pt3/ch20_exp_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8688267745399465, "lm_q1q2_score": 0.8257425060888198}}
{"text": "\nRequire Export ZArith  List  Arith Bool.\n\n(* \n \nInductive month : Set :=\n| January : month | February : month | March : month\n| April : month   | May : month      | June : month\n| July : month    | August : month   | September : month\n| October : month | November : month | December : month.\n\n*)\n\n(** short form \n*)\nInductive month : Set :=\n| January | February | March     | April   | May      | June \n| July    | August   | September | October | November | December.\n\n(** Tests :\n\nCheck month_ind.\n\nCheck month_rec.\n*)\n\n\nTheorem month_equal :\nforall m:month, \n m=January \\/ m=February \\/ m=March \\/ m=April \\/ m=May \\/ m=June \\/\n m=July \\/ m=August \\/  m=September \\/ m=October \\/ m=November \\/\n m=December.\nProof.  \n destruct m; auto 12.\nQed.\n\n(** explicit use of maont_ind:\n\n*)\nTheorem month_equal' :\nforall m:month, \n m=January \\/ m=February \\/ m=March \\/ m=April \\/\n m=May \\/ m=June \\/ m=July \\/ m=August \\/ \n m=September \\/ m=October \\/ m=November \\/ m=December.\nProof.  \n intro m; pattern m; apply month_ind; auto 12.\nQed.\n\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_length' (leap:bool) :=\n  month_rec (fun m:month => nat)\n  31 (if leap then 29 else 28) 31 30 31 30 31 31 30 31 30 31.\n\n\nDefinition month_length'' (leap:bool)(m:month) :=\n match m with\n | February => if leap then 29 else 28\n | April  | June  | September | November => 30\n | _  => 31\n end.\n\n(** Tests :\n\nCompute  (fun leap => month_length leap November).\n*)\n\nExample  length_february : month_length false February = 28.\nProof. reflexivity. Qed.\n\n(* Definition with Record *)\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nDefinition in_diagonal (p:plane) :=\n  Z_eq_bool (abscissa p) (ordinate p).\n\n\nInductive vehicle : Set :=\n  bicycle : nat->vehicle | motorized : nat->nat->vehicle.\n\n(** \nCheck vehicle_ind.\n*)\n\nDefinition nb_wheels (v:vehicle) : nat :=\n  match v with\n  | bicycle x => 2\n  | motorized x n => n\n  end.\n\nDefinition nb_seats (v:vehicle) : nat :=\n  match v with\n  | bicycle x => x\n  | motorized x _ => x\n  end.\n\nTheorem at_least_28 :\n forall (leap:bool)(m:month), 28 <= month_length leap m.\nProof.\n intros leap m; case m; simpl; auto with arith.\n case leap; simpl; auto with arith.\nQed.\n\nDefinition next_month (m:month) :=\n  match m with\n  |  January => February  | February => March | March => April\n  | April => May         | May => June       | June => July\n  | July => August       | August => September\n  | September => October | October => November\n  | November => December | December => January\n  end.\n\nTheorem next_august_then_july :\n forall m:month, next_month m = August -> m = July.\nProof.\n intros m; case m; simpl; intros Hnext_eq;\n    (reflexivity || discriminate Hnext_eq).\nQed.\n \n\n\n(* Simulating discriminate (just for the fun) *)\n\nTheorem not_January_eq_February' : January <> February.\nProof.\n unfold not; intros H. \n change ((fun m:month =>\n          match m with | January => True | _ => False end)\n        February).\n rewrite <- H.\n trivial.\nQed.\n\n(* Using injection *)\n\nTheorem bicycle_eq_seats :\n forall x1 y1:nat, bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intros x1 y1 H.\n injection H.\n trivial.\nQed.\n\n(* Simulating injection (for the fun) *)\n\nTheorem bicycle_eq_seats' :\n forall x1 y1:nat, bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intros x1 y1 H.\n change (nb_seats (bicycle x1) = nb_seats (bicycle y1)).\n rewrite H; reflexivity.\nQed.\n\nTheorem next_march_shorter :\n forall (leap:bool)(m1 m2:month), next_month m1 = March ->\n   month_length leap m1 <= month_length leap m2.\nProof.\n intros leap m1 m2 H.\n case_eq m1; try  (intro H0; rewrite H0 in H; simpl in H; discriminate H).\n  case leap ; case m2 ; simpl; auto with arith.\nQed.\n\n(* A first, detailed, proof of associativity of + *)\n\nTheorem plus_assoc :\n forall x y z:nat, (x+y)+z = x+(y+z).\nProof.\n induction x as [ | x0 IHx0].\n -  simpl; reflexivity.\n - simpl; intros y z; rewrite IHx0; reflexivity.\nQed.\n\n\nFixpoint mult2 (n:nat) : nat :=\n   match n with \n   | 0 => 0\n   | S p => S (S (mult2 p))\n   end.\n\nInductive Z_btree : Set :=\n  Z_leaf : Z_btree | Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nFixpoint sum_all_values (t:Z_btree) : Z :=\n  (match t with\n   | Z_leaf => 0\n   | Z_bnode v t1 t2 =>\n       v + sum_all_values t1 + sum_all_values t2\n  end)%Z.\n \nFixpoint zero_present (t:Z_btree) : bool :=\n   match t with\n   | Z_leaf => false\n   | Z_bnode (0%Z)  t1 t2 => true\n   | Z_bnode _ t1 t2 =>\n        zero_present t1 ||  zero_present t2\n   end.\n\nFixpoint add_one (x:positive) : positive :=\n  match x with\n  | xI x' => xO (add_one x')\n  | xO x' => xI x'\n  | xH => 2%positive\n  end.\n\n\nInductive Z_fbtree : Set :=\n  Z_fleaf : Z_fbtree | Z_fnode : Z ->(bool->Z_fbtree)-> Z_fbtree.\n\nDefinition right_son (t:Z_btree) : Z_btree :=\n  match t with\n  | Z_leaf => Z_leaf\n  | Z_bnode a t1 t2 => t2\n  end.\n\n\nDefinition fright_son (t:Z_fbtree) : Z_fbtree :=\n  match t with\n  | Z_fleaf => Z_fleaf\n  | Z_fnode a f => f false\n  end.\n\n(**\n\nCheck Z_fbtree_ind. \n*)\n\nFixpoint fsum_all_values (t:Z_fbtree) : Z :=\n (match t with\n  | Z_fleaf => 0\n  | Z_fnode v f =>\n     v + fsum_all_values (f true) + fsum_all_values (f false)\n  end )%Z .\n\nInductive Z_inf_branch_tree : Set :=\n| Z_inf_leaf : Z_inf_branch_tree\n| Z_inf_node : Z->(nat->Z_inf_branch_tree)->Z_inf_branch_tree.\n\n\nFixpoint sum_f (n:nat)(f : nat -> Z) : Z\n := (match n with \n       | O => 0\n       | S p => f n + sum_f p f\n     end)%Z.\n\nFixpoint n_sum_all_values (n:nat)(t:Z_inf_branch_tree) : Z :=\n  (match t with\n    | Z_inf_leaf => 0\n    | Z_inf_node v f =>\n         v + sum_f n (fun x:nat => n_sum_all_values n (f x))\n    end )%Z.\n\n\n\nDefinition mult2' : nat->nat :=\n  fix f (n:nat) : nat :=\n    match n with 0 => 0 | S p => S (S (f p)) end.\n\n\n\nFixpoint app {A:Type}(l m:list A) : list A :=\n  match l with\n  | nil => m\n  | cons a l1 => cons a (app  l1 m)\n  end.\n\n\nDefinition pred_option (n:nat) : option nat :=\n  match n with O => None | S p => Some p end.\n\nDefinition pred2_option (n:nat) : option nat :=\n  match pred_option n with\n  | None => None\n  | Some p => pred_option p\n  end.\n\nFixpoint nth_option {A:Type} (n:nat)(l:list A) : option A :=\n  match n, l with\n  | O, cons a tl => Some a\n  | S p, cons a tl => nth_option  p tl\n  | _, nil => None\n  end.\n\n(** Some tests: \n\nPrint fst.\n\nCheck (sum nat bool). \n\nCheck (inl bool 4).\n\nCheck (inr nat false).\n*)\n\n\nInductive ltree (n:nat) : Set :=\n  | lleaf : ltree n\n  | lnode : forall p:nat, p <= n -> ltree n -> ltree n -> ltree n.\n\n\nInductive sqrt_data (n:nat) : Set :=\n  sqrt_intro : forall x:nat, x*x <= n -> n <  S x * S x -> sqrt_data n.\n\nInductive htree (A:Type) : nat->Type :=\n  | hleaf : A->htree A 0\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\n(**\n\nCheck htree_ind.\n\n*)\n\n\nFixpoint htree_to_btree (n:nat)(t:htree Z n){struct t} : Z_btree :=\n  match t with\n  | hleaf _ x => Z_bnode x Z_leaf Z_leaf\n  | hnode _ p v t1 t2 =>\n      Z_bnode v (htree_to_btree p t1)(htree_to_btree p t2)\n  end.\n\nFixpoint invert (A:Type)(n:nat)(t:htree A n){struct t} : htree A n :=\n  match t in htree _ x return htree A x with\n  | hleaf _ v => hleaf A v\n  | hnode _ p v t1 t2 => hnode A p v (invert A p t2)(invert A p t1)\n  end.\n\n(**\n\nPrint Empty_set.\n\nCheck Empty_set_ind. \n*)\n\nInductive strange : Set :=  cs : strange->strange.\n\n\nTheorem strange_empty : forall x:strange, False.\nProof.\n intro x; induction x.\n assumption.\nQed.\n\n(** attempt to prove falsehood\n\nTheorem nat_not_strange :  forall n:nat, False.\nProof.\n intros x; elim x.\nAbort.\n\n*)\n\nInductive even_line : nat->Set :=\n  | even_empty_line : even_line 0\n  | even_step_line : forall n:nat, even_line n -> even_line (S (S n)).\n\n(** Tests :\n\nCheck even_empty_line.\n\nCheck (even_step_line _ even_empty_line). \n\n\nCheck (even_step_line _ (even_step_line _ even_empty_line)). \n*)\n\n", "meta": {"author": "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/chap6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.9086179031191509, "lm_q1q2_score": 0.8255864859992382}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Recdef.\nRequire Import List.\nRequire Import Program.Tactics.\nImport ListNotations.\n\nSection Lecture6.\n\n  (* True iff the list\u2019s elements are in decreasing order *)\n  Inductive Dec : list nat -> Prop :=\n  | DNil : Dec []\n  | DCons : forall a l,\n      (forall b, In b l -> a <= b) ->\n      Dec l ->\n      Dec (a :: l).\n  Hint Constructors Dec.\n\n  (* True iff the list\u2019s elements are in INcreasing order *)\n  Inductive Inc : list nat -> Prop :=\n  | INil : Inc []\n  | ICons : forall a l,\n      (forall b, In b l -> b <= a) ->\n      Inc l ->\n      Inc (a :: l).\n  Hint Constructors Inc.\n\n  (* A fact about appending increasing lists *)\n  Lemma Inc_app xs ys:\n    Inc xs -> Inc ys ->\n    (forall x y, In x xs -> In y ys -> y <= x) ->\n    Inc (xs ++ ys).\n  Admitted.\n\n\n  Lemma Dec_rev xs: Dec (rev xs) -> Inc xs.\n    induction xs.\n    auto.\n    simpl.\n    intros.\n    apply ICons; intros.\n    (* Ugh! We could prove some lemmas about Dec, but instead\n       let\u2019s use a more convenient induction principle. *)\n  Abort.\n\n\n  (* Reverse induction on lists: *)\n  Lemma rev_ind {A} (P:list A -> Prop):\n      P [] ->\n      (forall a l, P l -> P (l ++ [a])) ->\n      (forall l, P l).\n    (* But this is difficult to prove from scratch.\n       We need one more helper induction principle. *)\n  Abort.\n\n  Lemma rev_ind' {A} (P:list A -> Prop):\n      P [] ->\n      (forall a l, P (rev l) -> P (rev (a :: l))) ->\n      (forall l, P (rev l)).\n    (* This induction principle is easier to prove\n       because, in the inductive hypotheses, `l` grows\n       in the normal way (from the front). *)\n    intros; induction l; auto.\n  Qed.\n\n  Lemma rev_ind {A} (P:list A -> Prop):\n      P [] ->\n      (forall a l, P l -> P (l ++ [a])) ->\n      (forall l, P l).\n    intros.\n    rewrite <- (rev_involutive l). (* `rev (rev l) = l` *)\n    apply rev_ind'; auto.\n    intros.\n    simpl.\n    apply H0.\n    auto.\n  Qed.\n\n\n  (* We\u2019ve proved the new induction principle correct,\n     so we can use it. *)\n  Lemma Dec_rev xs: Dec (rev xs) -> Inc xs.\n    induction xs using rev_ind; auto.\n    rewrite rev_unit. (* `rev (xs ++ [a]) = a :: rev xs` *)\n    intros; inversion H; subst.\n    apply Inc_app.\n    - auto. (* `auto` can apply inductive hypothesis *)\n    - apply ICons; intros.\n      + destruct H0.\n      + auto.\n    - intros; destruct H1.\n      + subst.\n        apply H2.\n        apply in_rev in H0.\n        auto.\n      + destruct H1.\n  Qed.\n\n\n  (* The proof gets easier if we tell Coq `auto` to\n     automatically resolve `In _ nil` hypotheses. *)\n  Hint Extern 1 => match goal with\n                   | [ H : In _ nil |- _ ] => destruct H\n                   end.\n\n  Lemma Dec_rev' xs: Dec (rev xs) -> Inc xs.\n    induction xs using rev_ind; auto.\n    rewrite rev_unit.\n    intros; inversion H; subst.\n    apply Inc_app; auto. (* !! *)\n    intros; destruct H1; auto.\n    apply in_rev in H0; subst; auto.\n  Qed.\n\nEnd Lecture6.\n", "meta": {"author": "readablesystems", "repo": "cs260r-17", "sha": "6275e4e7007b7a6af6f1031e80994a3043521256", "save_path": "github-repos/coq/readablesystems-cs260r-17", "path": "github-repos/coq/readablesystems-cs260r-17/cs260r-17-6275e4e7007b7a6af6f1031e80994a3043521256/l06sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8933094110250333, "lm_q1q2_score": 0.8255445867751751}}
{"text": "(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n    definitions from the previous chapter: *)\n\nFrom LF Require Export Basics.\n\n(** * Proof by Induction *)\n\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\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\n\n(** **** Exercise: 2 stars, standard, recommended (basic_induction)  \n\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, standard (double_plus)  \n\n    Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (evenb_S)  \n\n    One inconvenient aspect of our definition of [evenb n] is the\n    recursive call on [n - 2]. This makes proofs about [evenb n]\n    harder when done by induction on [n], since we may need an\n    induction hypothesis about [n - 2]. The following lemma gives an\n    alternative characterization of [evenb (S n)] that works better\n    with induction: *)\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (destruct_induction)  \n\n    Briefly explain the difference between the tactics [destruct]\n    and [induction].\n\n(* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_destruct_induction : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n). { reflexivity. }\n  rewrite -> H.\n  reflexivity.  Qed.\n\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* We just need to swap (n + m) for (m + n)... seems\n     like plus_comm should do the trick! *)\n  rewrite -> plus_comm.\n  (* Doesn't work...Coq rewrites the wrong plus! *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n    a local lemma stating that [n + m = m + n] (for the particular [m]\n    and [n] that we are talking about here), prove this lemma using\n    [plus_comm], and then use it to do the desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n\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(** - _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(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  \n\n    Translate your solution for [plus_comm] into an informal proof:\n\n    Theorem: Addition is commutative.\n\n    Proof: (* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_plus_comm_informal : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_refl_informal)  \n\n    Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = n =? n] for any [n].\n\n    Proof: (* FILL IN HERE *)\n\n    [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (mult_comm)  \n\n    Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\n\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, standard, optional (more_exercises)  \n\n    Take a piece of paper.  For each of the following theorems, first\n    _think_ about whether (a) it can be proved using only\n    simplification and rewriting, (b) it also requires case\n    analysis ([destruct]), or (c) it also requires induction.  Write\n    down your prediction.  Then fill in the proof.  (There is no need\n    to turn in your piece of paper; this is just to encourage you to\n    reflect before you hack!) *)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n  true = (n <=? n).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n  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  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n  (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, standard, optional (eqb_refl)  \n\n    Prove the following theorem.  (Putting the [true] on the left-hand\n    side of the equality may look odd, but this is how the theorem is\n    stated in the Coq standard library, so we follow suit.  Rewriting\n    works equally well in either direction, so we will have no problem\n    using the theorem no matter which way we state it.) *)\n\nTheorem eqb_refl : forall n : nat,\n  true = (n =? n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (plus_swap')  \n\n    The [replace] tactic allows you to specify a particular subterm to\n   rewrite and what you want it rewritten to: [replace (t) with (u)]\n   replaces (all copies of) expression [t] in the goal by expression\n   [u], and generates [t = u] as an additional subgoal. This is often\n   useful when a plain [rewrite] acts on the wrong part of the goal.\n\n   Use the [replace] tactic to do a proof of [plus_swap'], just like\n   [plus_swap] but without needing [assert (n + m = m + n)]. *)\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, standard, recommended (binary_commute)  \n\n    Recall the [incr] and [bin_to_nat] functions that you\n    wrote for the [binary] exercise in the [Basics] chapter.  Prove\n    that the following diagram commutes:\n\n                            incr\n              bin ----------------------> bin\n               |                           |\n    bin_to_nat |                           |  bin_to_nat\n               |                           |\n               v                           v\n              nat ----------------------> nat\n                             S\n\n    That is, incrementing a binary number and then converting it to\n    a (unary) natural number yields the same result as first converting\n    it to a natural number and then incrementing.\n    Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n    Before you start working on this exercise, copy the definitions\n    from your solution to the [binary] exercise here so that this file\n    can be graded on its own.  If you want to change your original\n    definitions to make the property easier to prove, feel free to\n    do so! *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_commute : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse)  \n\n    This is a further continuation of the previous exercises about\n    binary numbers.  You may find you need to go back and change your\n    earlier definitions to get things to work here.\n\n    (a) First, write a function to convert natural numbers to binary\n        numbers. *)\n\nFixpoint nat_to_bin (n:nat) : bin\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** Prove that, if we start with any [nat], convert it to binary, and\n    convert it back, we get the same [nat] we started with.  (Hint: If\n    your definition of [nat_to_bin] involved any extra functions, you\n    may need to prove a subsidiary lemma showing how such functions\n    relate to [nat_to_bin].) *)\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_a : option (nat*string) := None.\n\n(** (b) One might naturally expect that we should also prove the\n        opposite direction -- that starting with a binary number,\n        converting to a natural, and then back to binary should yield\n        the same number we started with.  However, this is not the\n        case!  Explain (in a comment) what the problem is. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_b : option (nat*string) := None.\n\n(** (c) Define a normalization function -- i.e., a function\n        [normalize] going directly from [bin] to [bin] (i.e., _not_ by\n        converting to [nat] and back) such that, for any binary number\n        [b], converting [b] to a natural and then back to binary yields\n        [(normalize b)].  Prove it.  (Warning: This part is a bit\n        tricky -- you may end up defining several auxiliary lemmas.\n        One good way to find out what you need is to start by trying\n        to prove the main statement, see where you get stuck, and see\n        if you can find a lemma -- perhaps requiring its own inductive\n        proof -- that will allow the main proof to make progress.) Don't\n        define thi using nat_to_bin and bin_to_nat! *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_c : option (nat*string) := None.\n(** [] *)\n\n", "meta": {"author": "anemoneflower", "repo": "Coq-study", "sha": "eafb63595e8773234fa3da4b93428a2a7ad17484", "save_path": "github-repos/coq/anemoneflower-Coq-study", "path": "github-repos/coq/anemoneflower-Coq-study/Coq-study-eafb63595e8773234fa3da4b93428a2a7ad17484/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.9304582526016021, "lm_q1q2_score": 0.8255068415201232}}
{"text": "Module IndPrinciples.\n\nPrint nat_ind.\nCheck nat_ind :\n  forall (P : nat -> Prop),\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\nTheorem mul_0_r' : forall (n : nat),\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity. Qed.\n\n\nTheorem plus_one_r' : forall (n : nat),\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros. simpl. rewrite -> H. reflexivity.\nQed.\n\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nCheck rgb_ind: \n  forall (P: rgb -> Prop),\n  P red ->\n  P green ->\n  P blue ->\n  forall (c : rgb), P c.\n\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\nCheck natlist_ind :\n  forall (P : natlist -> Prop),\n    P nnil ->\n    (forall (n : nat) (l : natlist),  P l -> P (ncons n l)) ->\n    forall (l : natlist), P l.\n\n\nInductive natlist' : Type :=\n  | nnil'\n  | nsnoc (l : natlist') (n : nat).\n\nCheck natlist'_ind :\n  forall (P : natlist' -> Prop),\n    P nnil' ->\n    (forall (l : natlist'), P l -> forall (n : nat), P (nsnoc l n)) ->\n    forall (n : natlist'), P n.\n\n\n\nInductive booltree : Type :=\n  | bt_empty\n  | bt_leaf (b : bool)\n  | bt_branch (b : bool) (t1 t2 : booltree).\n\nCheck booltree_ind: \n  forall (P : booltree -> Prop),\n    P bt_empty ->\n    (forall (b : bool), P (bt_leaf b)) ->\n    (forall (b : bool) (t1: booltree), P t1 -> forall (t2 : booltree), P t2 -> P (bt_branch b t1 t2)) ->\n    (forall (t : booltree), P t).\n\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\n\nCheck tree_ind: \n  forall (X: Type) (P: tree X -> Prop),\n    (forall (x: X), P (leaf X x)) ->\n    (forall (t1: tree X), P t1 -> forall (t2: tree X), P t2 -> P (node X t1 t2)) ->\n    (forall (t: tree X), P t).\n\n\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\nCheck foo'_ind: \n  forall (X: Type) (P: foo' X -> Prop),\n    (forall (l: list X) (f: foo' X), P f -> P (C1 X l f)) ->\n    P (C2 X ) ->\n    (forall (f: foo' X), P f).\n\n\n\nDefinition P_m0r' : nat -> Prop :=\n  fun n => n * 0 = 0.\n\nTheorem mul_0_r'' : forall (n: nat),\n  P_m0r' n.\nProof.\n  apply (nat_ind P_m0r').\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(* IndProp induction: *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS (n: nat) (H: ev n): ev (S (S n))\n.\n\nCheck ev_ind :\n  forall (P : nat -> Prop),\n    P 0 ->\n    (forall (n : nat), ev n -> P n -> P (S (S n)) ) ->\n    (forall (n : nat), ev n -> P n).\n\nInductive ev' : nat -> Prop :=\n  | ev'_0 : ev' 0\n  | ev'_2 : ev' 2\n  | ev'_sum n m (Hn : ev' n) (Hm : ev' m) : ev' (n + m).\n\nTheorem ev_ev' : forall n, ev n -> ev' n.\nProof.\n  apply (ev_ind ev').\n  - (* ev_0 *)\n    apply ev'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\n\n\n\nInductive le1 : nat -> nat -> Prop :=\n  | le1_n : forall n, le1 n n\n  | le1_S : forall n m, (le1 n m) -> (le1 n (S m)).\nNotation \"m <=1 n\" := (le1 m n) (at level 70).\n\nInductive le2 (n:nat) : nat -> Prop :=\n  | le2_n : le2 n n\n  | le2_S m (H : le2 n m) : le2 n (S m).\nNotation \"m <=2 n\" := (le2 m n) (at level 70).\n\nCheck le1_ind :\n  forall (P : nat -> nat -> Prop),\n    (forall (n : nat), P n n) ->\n    (forall (n m : nat), n <=1 m -> P n m -> P n (S m)) ->\n    (forall (n n0 : nat), n <=1 n0 -> P n n0).\n\nCheck le2_ind :\n  forall (n : nat) (P : nat -> Prop),\n    P n ->\n    (forall (m  : nat), n <=2 m -> P m -> P (S m)) ->\n    (forall (n0 : nat), n <=2 n0 -> P n0).\n\n\n(* induction lemma is just lemma *)\nFixpoint build_proof\n         (P : nat -> Prop)\n         (evPO : P 0)\n         (evPS : forall (n : nat), P n -> P (S n))\n         (n : nat) : P n :=\n  match n with\n  | 0   => evPO\n  | S k => evPS k (build_proof P evPO evPS k)\n  end.\n\n\n\nDefinition nat_ind2 :\n  forall (P : nat -> Prop),\n  P 0 ->\n  P 1 ->\n  (forall (n : nat), P n -> P (S(S n))) ->\n  (forall (n : nat), P n) :=\n    fun P P0 P1 PSS =>\n      fix f (n:nat) := match n with\n                       | 0        => P0\n                       | 1        => P1\n                       | S (S n') => PSS n' (f n')\n                       end.\n\nFixpoint even (n: nat): bool :=\n  match n with \n  | 0 => true\n  | S 0 => false\n  | S (S k) => even k\n  end.\n\nLemma even_ev : forall n, even n = true -> ev n.\nProof.\n  intros.\n  induction n as [ | |n'] using nat_ind2.\n  - apply ev_0.\n  - simpl in H.\n    inversion H.\n  - simpl in H.\n    apply ev_SS.\n    apply IHn'.\n    apply H.\nQed.\n\n\n\nInductive foo'' (X:Type) : Type :=\n  | C1' (l : list X) (f : foo'' X)\n  | C2'.\n\nCheck foo''_ind : \n  forall (X: Type) (P: foo'' X -> Prop),\n    (forall (l: list X) (f: foo'' X), P f -> P (C1' X l f)) ->\n    P (C2' X) ->\n    (forall (f: foo'' X), P f).\n\n\n\n\nEnd IndPrinciples.", "meta": {"author": "cattingcat", "repo": "coq_lessons", "sha": "49ea5727398acddd5b347b234d6b4efcab305422", "save_path": "github-repos/coq/cattingcat-coq_lessons", "path": "github-repos/coq/cattingcat-coq_lessons/coq_lessons-49ea5727398acddd5b347b234d6b4efcab305422/softwarefoundations/vol1/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.9136765175373274, "lm_q1q2_score": 0.8253187074714582}}
{"text": "Require Import Arith.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\nintros.\napply plus_permute_2_in_4.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\nintros.\nrewrite -> mult_plus_distr_r.\nrewrite -> mult_plus_distr_l.\nrewrite <- plus_assoc.\nrewrite <- plus_assoc.\napply NPeano.Nat.add_cancel_l.\nrewrite -> mult_plus_distr_l.\nreplace (m*n) with (n*m).\nrewrite -> plus_assoc.\nreplace (2*n*m) with (n*m+n*m).\nrewrite -> plus_comm.\nreflexivity.\nsimpl.\nrewrite -> mult_plus_distr_r.\napply NPeano.Nat.add_cancel_l.\nrewrite -> mult_plus_distr_r.\nrewrite -> mult_0_l.\nrewrite -> plus_0_r.\nreflexivity.\napply mult_comm.\nQed.", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/2/9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.8252651900065489}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  \n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n.\n  induction n.\n  simpl.\n  apply ev_0.\n  simpl.\n  apply ev_SS.\n  apply IHn.\n  Qed.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* Infinite, because you can destruct 8 as 0 + 8 as long as you want. *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nSearchAbout [\"_0\"].\n               \nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros n.\n  induction n.\n  simpl.\n  intros H.\n  apply H.\n  intros H.\n  apply b_sum. apply H.\n  rewrite plus_0_r.\n  apply H.\n  Qed.\n(** [] *)\nSearchAbout [\"S\"].\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros n m H.\n  induction m as [| m'].\n  simpl.\n  apply b_0.\n  rewrite <- plus_1_l.\n  rewrite mult_plus_distr_r.\n  apply b_sum.\n  simpl.\n  rewrite plus_0_r.\n  apply H.\n  apply IHm'.\n  Qed.\n  \n\n  \n  \n\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* --------- (g_0)\ngorgeous0\ngorgeous n\n-------------- (g_plus3)\ngorgeous (n+3)\ngorgeous n\n-------------- (g_plus5)\ngorgeous (n+5) *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros.\n  repeat apply g_plus5.\n  apply g_plus3.\n  apply H.\n  Qed.\n  \n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\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 H1 H2.\n  induction H1.\n  simpl.\n  apply H2.\n  simpl.\n  apply g_plus3.\n  apply IHgorgeous.\n  simpl.\n  apply g_plus5.\n  apply IHgorgeous.\n  Qed.\n(** [] *)\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.\n  apply g_0.\n  apply g_plus3.   apply g_0.\n  apply g_plus5.   apply g_0.\n  apply gorgeous_sum.\n  apply IHbeautiful1.\n  apply IHbeautiful2.\n  Qed.\n  \n(** [] *)\n\n\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n  intros x y z.\n  rewrite plus_swap.\n  rewrite plus_assoc.\n  reflexivity.\n  Qed.\n\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   simpl.\n   apply g_0.\n   rewrite  helper_g_times2;\n   rewrite plus_swap; simpl;\n   repeat apply g_plus3.\n   rewrite <- plus_assoc.\n   apply IHgorgeous.\n   rewrite  helper_g_times2.\n   rewrite plus_swap. simpl.\n   repeat apply g_plus5.\n   rewrite <- plus_assoc.\n   apply IHgorgeous.\n   Qed.\n   \n\n   \n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *) \n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* no, because induction on n can not really tell us information about the ev status. *)\n(** [] *)\n\n(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\nBecause we cannot prove some number that is not even to be even.\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\nSearchAbout [\"ev_\"].\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  intros n m H1 H2.\n  induction H1.\n  simpl. apply H2.\n  simpl.\n  apply ev_SS.\n  apply IHev.\n  Qed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we \n   can _look_ at that evidence for more information. For example, consider \n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead \n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** 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.\n  Qed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H3.\n  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nSearchAbout [\"_0\"].\n\nTheorem mytool1 : forall n m,\n                    n+m = 0 -> n=0.\nProof.\n  intros. induction m.\n  rewrite plus_0_r in H.\n  apply H.\n  inversion H.\n  induction n.\n  simpl.\n  simpl in H.\n  rewrite H. reflexivity.\n  inversion H.\n  Qed.\n\n  \n  \nSearchAbout [\"ev_\"].\n    \nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m H1 H2.\n  induction H2.\n  simpl in H1. apply H1.\n  apply IHev.\n  simpl in H1.\n  inversion H1.\n  apply H0.\n  Qed.\n  \n  \n  \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However, \n   we can define inductive predicates about any type of data. For example, \n   suppose we would like to characterize lists of _even_ length. We can \n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof. \n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H. \n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil. \n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l. \n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n    \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 [pal_app_rev] that \n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that \n       forall l, pal l -> l = rev l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\nInductive total_relation : nat -> nat -> Prop :=\n  tr : forall n m, total_relation n m.\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation : nat -> nat -> Prop :=\n  er : forall n m, 1+1=3 -> empty_relation n m.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nTheorem Sn_le_m__n_le_m : forall n m,\n  S n <= m -> n <= m.\nProof.\n  intros n m H. induction H.\n  Case \"le_n\". apply le_S. apply le_n.\n  Case \"le_S\". apply le_S. apply IHle.  Qed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros.\n  induction H.\n  apply H0.\n  apply IHle.\n  apply Sn_le_m__n_le_m.\n  apply H0. Qed.\n  \n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n.\n  apply le_n.\n  apply le_S.\n  apply IHn. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  intros.\n  induction H.\n  apply le_n.\n  apply le_S.\n  apply IHle.\n  Qed.\n  \n  \n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros.\n  inversion H.\n  apply le_n.\n  apply Sn_le_m__n_le_m in H1.\n  apply H1.\n  Qed.\n  \n  \n\n\n  \n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  intros.\n  induction a.\n  apply O_le_n.\n  simpl. apply n_le_m__Sn_le_Sm. apply IHa. Qed.\n  \nSearchAbout [\"plus\"].\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n intros.\n split.\n induction n2.\n rewrite plus_0_r in H.\n apply H.\n apply IHn2. \n apply Sn_le_m__n_le_m in H.\n rewrite plus_n_Sm. apply H.\n induction n1.\n simpl in H.\n apply H.\n apply IHn1. \n apply Sn_le_m__n_le_m in H.\n simpl in H.\n apply H.\n Qed.\n \n \n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros.\n  apply Sn_le_m__n_le_m in H.\n  apply n_le_m__Sn_le_Sm.\n  apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  intros n.\n  induction n.\n  intros.\n  apply O_le_n.\n  intros.\n  destruct m.\n  inversion H.\n  apply n_le_m__Sn_le_Sm.\n  apply IHn.\n  inversion H.\n  reflexivity. Qed.\n  \n  \nSearchAbout [\"ble\"].\n\n    \nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m.\n  intros.\n  inversion H.\n  reflexivity.\n  intros.\n  destruct n.\n  simpl.\n  reflexivity.\n  simpl.\n  apply IHm.\n  apply Sn_le_Sm__n_le_m in H. apply H. Qed.\n  \n  \n  \n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  intros.\n  apply ble_nat_true in H.\n  apply ble_nat_true in H0.\n  apply le_ble_nat.\n  generalize dependent H0.\n  apply le_trans.\n  apply H.\n  Qed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros n m.\n  generalize dependent n.\n  unfold not.\n  induction m as [| m'].\n  intros.\n  inversion H0.\n  rewrite H1 in H. inversion H.\n  intros.\n  destruct n as [| n'].\n  inversion H.\n  simpl in H.\n  apply IHm' in H. apply H.\n  apply Sn_le_Sm__n_le_m in H0. apply H0. Qed.\n  \n\n  \n \n \n  \n  \n\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is, \n      any list is a subsequence of itself.  \n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3], \n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is \n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2] \n      is a subsequence of [l3], then [l1] is a subsequence of [l3].  \n      Hint: choose your induction carefully!\n*)\n\n(* FILL IN HERE *)\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\nAnswer: 1 and 2 are provable\n*)\n\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n\n", "meta": {"author": "coderU", "repo": "CS565", "sha": "2c2a7a7c964171833419cbfe208311b55fcc7d1a", "save_path": "github-repos/coq/coderU-CS565", "path": "github-repos/coq/coderU-CS565/CS565-2c2a7a7c964171833419cbfe208311b55fcc7d1a/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8252590242116544}}
{"text": "Require Import FunInd.\n\nInductive is_even : nat -> Prop :=\n| is_even_O : is_even 0\n| is_even_S : forall n : nat, is_even n -> is_even (S (S n)).\n\n\nFixpoint even (n : nat) : Prop :=\n  match n with\n  | 0 => True\n  | 1 => False\n  | (S (S n)) => even n\n  end.\n\nFunctional Scheme even_ind := Induction for even Sort Prop.\n\nTheorem even_sound :\n  forall (n : nat) (v : Prop), (even n) = True -> is_even n.\n\nProof.\nintro.\nintro.\nfunctional induction (even n) using even_ind; intros.\napply is_even_O.\nelimtype False.\nrewrite H.\nauto.\napply is_even_S.\napply IHP.\nassumption.\nQed.\n\nTheorem even_complete : forall (n : nat) (v : Prop), is_even n -> (even n) = True.\nintro.\nintro.\nintro.\ninduction H.\nsimpl.\nreflexivity.\nsimpl.\nassumption.\nQed.\n\nInductive is_fact : nat -> nat -> Prop :=\n| is_fact_1 : is_fact 0 1\n| is_fact_S : forall (n : nat) (r : nat), is_fact n r -> is_fact (S n) ((S n) * r).\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | (S n) => (S n) * (fact n)\n  end.\n\nFunctional Scheme fact_ind := Induction for fact Sort Prop.\n\nTheorem fact_sound :\n  forall (n : nat) (r : nat), (fact n) = r -> is_fact n r.\n\nProof.\nintro.\nfunctional induction (fact n) using fact_ind; intros.\nrewrite <- H.\napply is_fact_1.\nelim H.\napply is_fact_S.\napply IHn0.\nreflexivity.\nQed.\n\nOpen Scope list_scope.\nInductive is_perm : list nat -> list nat -> Prop :=\n| perm_base : forall (l : list nat) (a : nat), is_perm (a :: l) (l ++ a::nil)\n| perm_ind  : forall (l1 : list nat) (l2 : list nat) (a : nat), is_perm l1 l2 -> is_perm (a :: l1) (a :: l2)\n| perm_ref  : forall (l1 : list nat) (l2 : list nat), l1 = l2 -> is_perm l1 l2\n| perm_tran : forall (l1 : list nat) (l2 : list nat) (l3 : list nat), (is_perm l1 l2) -> (is_perm l2 l3) -> is_perm l1 l3\n| perm_sem  : forall (l1 : list nat) (l2 : list nat), is_perm l1 l2 -> is_perm l2 l1.\n\nLemma trans_1 : is_perm (1::2::3::nil) (3::2::1::nil).\napply (perm_tran (1::2::3::nil) ((2::3::nil)++(1::nil)) (3::2::1::nil)).\napply perm_base.\nsimpl.\napply (perm_tran (2::3::1::nil) ((3::1::nil)++(2::nil)) (3::2::1::nil)).\napply perm_base.\nsimpl.\napply perm_ind.\napply (perm_tran (1::2::nil) ((1::nil)++(2::nil)) (2::1::nil)).\nsimpl.\napply perm_ref.\nreflexivity.\napply perm_base.\nQed.\n\nInductive sorted : list nat -> Prop :=\n| sorted_empty  : sorted nil\n| sorted_one    : forall n : nat, sorted (n::nil)\n| sorted_rec    : forall (n : nat) (m : nat) (l : list nat), n <= m -> sorted (m::l) -> sorted (n::m::l).\n\nLemma sort_1 : sorted (1::2::3::nil).\napply sorted_rec.\napply le_S.\napply le_n.\napply sorted_rec.\napply le_S.\napply le_n.\napply sorted_one.\nQed.\n\nRequire Import Compare_dec.\nFixpoint insert (x : nat) (l : list nat) : list nat :=\n  match l with\n  | nil => (x::nil)\n  | h::t => match (le_dec x h) with\n            | left _ => (x::h::t)\n            | right _ => (h::(insert x t))\n  end\nend.\n\nFixpoint sort (l : list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nFunctional Scheme sort_ind := Induction for sort Sort Prop.\nFunctional Scheme insert_ind := Induction for insert Sort Prop.\n\nRequire Export Omega.\nLemma perm_insert : forall (a : nat) (l : list nat), is_perm (a::l) (insert a l).\nintros.\nfunctional induction (insert a l) using insert_ind.\napply perm_ref.\nreflexivity.\napply perm_ref.\nreflexivity.\napply (perm_tran (a::h::t) (h::a::t) (h::insert a t)).\napply (perm_tran (a::h::t) ((h::t)++(a::nil)) (h::a::t)).\napply perm_base.\nsimpl.\napply perm_ind.\napply perm_sem.\napply perm_base.\napply perm_ind.\napply IHl0.\nQed.\n\nLemma sort_insert : forall (a : nat) (l : list nat), sorted l -> sorted (insert a l).\nintros.\nelim H.\nsimpl.\napply sorted_one.\nintros.\nsimpl.\nelim (le_dec a n).\nintros.\napply sorted_rec.\nomega.\napply sorted_one.\nintros.\napply sorted_rec.\nomega.\napply sorted_one.\nintros n m.\nsimpl.\nelim (le_dec a m).\nintros.\nelim (le_dec a n).\nintros.\napply sorted_rec.\nomega.\napply sorted_rec.\nomega.\napply H1.\nintros.\napply sorted_rec.\nomega.\napply sorted_rec.\nomega.\napply H1.\nintros.\nelim (le_dec a n).\nintros.\napply sorted_rec.\nomega.\napply sorted_rec.\nomega.\napply H1.\nintros.\napply sorted_rec.\nauto.\nauto.\nQed.\nTheorem sort_sound :\n  forall (l : list nat) (ls : list nat), sort l = ls -> (is_perm l ls) /\\ (sorted ls).\n\nProof.\nintro.\nfunctional induction (sort l) using sort_ind; intros.\nrewrite <- H.\nsplit.\napply perm_ref.\nreflexivity.\napply sorted_empty.\nrewrite <- H.\nsplit.\napply (perm_tran (h::t) (h::sort t) (insert h (sort t))).\napply perm_ind.\napply IHl0.\nreflexivity.\napply perm_insert.\napply sort_insert.\napply IHl0.\nreflexivity.\nQed.", "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/6induction_fonctionelle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.8840392695254318, "lm_q1q2_score": 0.8251894988834767}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Relations.Relations.\n\nClass TotalOrder {A : Type} (R : relation A) := {\n  reflexivity : forall (x : A), R x x;\n  antisymmetry : forall (x y : A), R x y -> R y x -> x = y;\n  transitivity : forall (x y z : A), R x y -> R y z -> R x z;\n  compare : forall (x y : A), { R x y } + { R y x };\n  eqdec : forall (x y : A), { x = y } + { x <> y }\n}.\n\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Peano_dec.\n\nInstance TotalOrder_nat : @TotalOrder nat le.\nProof with auto with arith.\n  split...\n  intros. eauto with arith.\n  intros.\n  assert ({ x <= y } + {x >= y}) as H.\n  { apply le_ge_dec. }\n  destruct H...\nQed.\n\nInductive PairOrdering \n  {A B : Type} \n  (AR : relation A) (BR : relation B) : (A * B) -> (A * B) -> Prop :=\n| MkPairOrdering1 : forall a b1 b2,\n  BR b1 b2 ->\n  PairOrdering AR BR (a,b1) (a,b2)\n| MkPairOrdering2 : forall a1 a2 b1 b2,\n  AR a1 a2 ->\n  a1 <> a2 ->\n  PairOrdering AR BR (a1,b1) (a2,b2).\n\nInductive SumOrdering  {A B : Type} \n  (AR : relation A) (BR : relation B) : relation (A + B) :=\n| MkSumOrdering1 : forall x y,\n  SumOrdering AR BR (inl x) (inr y)\n| MkSumOrdering2 : forall x y,\n  AR x y ->\n  SumOrdering AR BR (inl x) (inl y)\n| MkSumOrdering3 : forall x y,\n  BR x y ->\n  SumOrdering AR BR (inr x) (inr y).\n\nSection SumOrdering.\n\n  Hint Constructors SumOrdering.\n\n  Variable A B : Type.\n  Variable AR : relation A.\n  Variable BR : relation B.\n  Variable OrdA : TotalOrder AR.\n  Variable OrdB : TotalOrder BR.\n\n  Lemma SumOrdering_reflexivity : forall x, SumOrdering AR BR x x.\n  Proof with eauto.\n    destruct x...\n    apply MkSumOrdering2...\n    apply reflexivity.\n    apply MkSumOrdering3...\n    apply reflexivity.\n  Qed.\n\n  Lemma SumOrdering_antisymmetry : forall x y, \n    SumOrdering AR BR x y ->\n    SumOrdering AR BR y x ->\n    x = y.\n  Proof with eauto.\n    intros.\n    inversion H; subst.\n    - inversion H0; subst.\n    - inversion H0; subst.\n      f_equal.\n      apply antisymmetry...\n    - inversion H0; subst.\n      f_equal.\n      apply antisymmetry...\n  Qed.\n\n  Lemma SumOrdering_transitivity : forall x y z,\n    SumOrdering AR BR x y ->\n    SumOrdering AR BR y z ->\n    SumOrdering AR BR x z.\n  Proof with eauto.\n    intros.\n    destruct x.\n    destruct y.\n    destruct z.\n    inversion H; inversion H0; subst.\n    - apply MkSumOrdering2...\n      eapply transitivity...\n    - apply MkSumOrdering1...\n    - destruct z...\n      inversion H0.\n    - destruct y.\n      inversion H.\n      destruct z...\n      inversion H0.\n      eapply MkSumOrdering3...\n      inversion H; subst.\n      inversion H0; subst.\n      eapply transitivity...\n  Qed.\n\n  Lemma SumOrdering_compare : forall x y,\n    { SumOrdering AR BR x y } + { SumOrdering AR BR y x }.\n  Proof with eauto.\n    intros.\n    destruct x.\n    destruct y.\n    + assert ({AR a a0} + {AR a0 a})...\n      apply compare...\n      destruct H...\n    + left...\n    + destruct y.\n      - right...\n      - assert ({BR b b0} + {BR b0 b})...\n        apply compare...\n        destruct H...\n  Qed.\n\n  Lemma SumOrdering_eqdec : forall (x y : A + B), \n    { x = y } + { x <> y }.\n  Proof with eauto.\n    destruct x.\n    destruct y.\n    decide equality. \n    + apply eqdec. \n    + apply eqdec.\n    + right. unfold not. intros. inversion H.\n    + destruct y.\n      - right. unfold not. intros. inversion H.\n      - destruct (eqdec b b0); subst...\n        right. unfold not. intros. inversion H. subst. contradiction n...\n  Qed.\n\n  Instance TotalOrder_sum :  TotalOrder (SumOrdering AR BR) := {\n    reflexivity := SumOrdering_reflexivity;\n    antisymmetry := SumOrdering_antisymmetry;\n    transitivity := SumOrdering_transitivity;\n    compare := SumOrdering_compare;\n    eqdec := SumOrdering_eqdec\n  }.\n\nEnd SumOrdering.\n  \nSection PairOrdering.\n\n  Hint Constructors PairOrdering.\n\n  Variable A B : Type.\n  Variable AR : relation A.\n  Variable BR : relation B.\n  Variable OrdA : TotalOrder AR.\n  Variable OrdB : TotalOrder BR.\n\n  Lemma PairOrdering_reflexivity : forall x, PairOrdering AR BR x x.\n  Proof with eauto.\n    destruct x...\n    apply MkPairOrdering1...\n    apply reflexivity.\n  Qed.\n\n  Lemma PairOrdering_antisymmetry : forall x y, \n    PairOrdering AR BR x y ->\n    PairOrdering AR BR y x ->\n    x = y.\n  Proof with eauto.\n    intros.\n    inversion H; subst.\n    - inversion H0; subst.\n      assert (b1 = b2). apply antisymmetry...\n      subst...\n      contradiction H7...\n    - inversion H0; subst.\n      contradiction H2...\n      assert (a1 = a2). apply antisymmetry...\n      subst.\n      contradiction H2...\n  Qed.\n\n  Lemma PairOrdering_transitivity : forall x y z,\n    PairOrdering AR BR x y ->\n    PairOrdering AR BR y z ->\n    PairOrdering AR BR x z.\n  Proof with eauto.\n    intros.\n    destruct x.\n    destruct y.\n    destruct z.\n    inversion H; inversion H0; subst.\n    - apply MkPairOrdering1...\n      eapply transitivity...\n    - apply MkPairOrdering2...\n    - apply MkPairOrdering2...\n    - apply MkPairOrdering2...\n      eapply transitivity...\n      assert ({a = a1 } + { a <> a1 }). apply eqdec.\n      destruct H1...\n      subst.\n      assert (a0 = a1). apply antisymmetry...\n      subst...\n  Qed.\n\n  Lemma PairOrdering_compare : forall x y,\n    { PairOrdering AR BR x y } + { PairOrdering AR BR y x }.\n  Proof with eauto.\n    intros.\n    destruct x.\n    destruct y.\n    assert ({AR a a0} + {AR a0 a})...\n    apply compare...\n    assert ({BR b b0} + {BR b0 b})...\n    apply compare...\n    assert ({a = a0 } + { a <> a0 }). apply eqdec.\n    destruct H1; subst...\n    - destruct H0...\n    - destruct H...\n  Qed.\n\n  Lemma PairOrdering_eqdec : forall (x y : A * B), \n    { x = y } + { x <> y }.\n  Proof with eauto.\n    destruct x.\n    destruct y.\n    decide equality. \n    apply eqdec. \n    apply eqdec.\n  Qed.\n\n  Instance TotalOrder_pair :  TotalOrder (PairOrdering AR BR) := {\n    reflexivity := PairOrdering_reflexivity;\n    antisymmetry := PairOrdering_antisymmetry;\n    transitivity := PairOrdering_transitivity;\n    compare := PairOrdering_compare;\n    eqdec := PairOrdering_eqdec\n  }.\n\nEnd PairOrdering.\n\nExisting Instances TotalOrder_pair TotalOrder_sum.\n\nDefinition inverse (A B : Type) (f : A -> B) (g : B -> A) : Prop :=\n  forall x, g (f x) = x.\n\nInductive ProjectOrdering (A B : Type) (f : A -> B) (BR : relation B) : relation A :=\n  | MkProjOrdering : forall x y,\n    BR (f x) (f y) ->\n    ProjectOrdering f BR x y.\n  \nHint Constructors ProjectOrdering.\n\nLemma TotalOrder_Project : forall (A B : Type) (f : A -> B) \n   (g : B -> A)\n   (RB : relation B)\n   (OrdB : TotalOrder RB),\n   inverse f g ->\n   TotalOrder (ProjectOrdering f RB).\nProof with eauto.\n  intros.\n  destruct OrdB.\n  split; intros.\n  + eapply MkProjOrdering...\n  + unfold inverse in H.\n    inversion H0; inversion H1; subst...\n    assert (f x = f y) as X.\n    apply antisymmetry0...\n    rewrite <- H.\n    rewrite <- (H x).\n    rewrite -> X...\n  + inversion H0; inversion H1; subst...\n  + destruct (compare0 (f x) (f y))...\n  + destruct (eqdec0 (f x) (f y))...\n    - left.\n      rewrite <- H.\n      rewrite <- (H x).\n      rewrite -> e...\n    - right.\n      unfold not in *.\n      intros.\n      rewrite -> H0 in n.\n      apply n.\n      reflexivity.\nQed.\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/TotalOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.8249324979564109}}
{"text": "From mathcomp\n  Require Import ssreflect ssrnat.\n\nSection naturalNumber.\n\nLemma add0nEqn (n : nat) : 0 + n = n.\nProof. by []. Qed.\n\nLemma addn3Eq2n1 (n : nat) : n + 3 = 2 + n + 1.\nProof.\nrewrite addn1.\nrewrite add2n.\nrewrite addnC.\nby [].\nQed.\n\nFixpoint sum n := if n is m.+1 then sum m + n else 0.\n\nLemma sumGauss (n : nat) : sum n * 2 = (n + 1) * n.\nProof.\nelim: n => [// | n IHn].\nrewrite mulnC.\nrewrite (_ : sum (n.+1) = n.+1 + (sum n)); last first.\nrewrite /=.\nby rewrite addnC.\nrewrite mulnDr.\nrewrite mulnC in IHn.\nrewrite IHn.\nrewrite 2!addn1.\nrewrite [_ * n]mulnC.\nrewrite -mulnDl.\nby [].\nQed.\n\nEnd naturalNumber.\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/\u8429\u539f\u5b66, \u30a2\u30d5\u30a7\u30eb\u30c8\u30fb\u30ec\u30ca\u30eb\u30c9 (2018) Coq_SSReflect_MathComp\u306b\u3088\u308b\u5b9a\u7406\u8a3c\u660e/chap2-4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8248145158993879}}
{"text": "From mathcomp\n     Require Import ssreflect ssrnat.\n\nSection naturalNumber.\n\n  Lemma addOnEqn(n : nat) : 0 + n = n.\n  Proof. by []. Qed.\n\n  Lemma addn3Eq2n1 (n : nat) : n + 3 = 2 + n + 1.\n  Proof.\n    rewrite addn1.\n    rewrite add2n.\n    rewrite addnC.\n    by [].\n  Qed.\n\n  Fixpoint sum n := if n is m.+1 then sum m + n else 0.\n\n  Lemma sumGauss (n : nat) : sum n * 2 = (n + 1) * n.\n  Proof.\n    elim: n => [// | n IHn].\n    rewrite mulnC.\n    rewrite (_ : sum (n.+1) = n.+1 + (sum n)); last first.\n    rewrite /=.\n    by rewrite addnC.\n    rewrite mulnDr.\n    rewrite mulnC in IHn.\n    rewrite IHn.\n    rewrite 2!addn1.\n    rewrite [_ * n]mulnC.\n    rewrite -mulnDl.\n    by [].\n  Qed.\n\nEnd naturalNumber.\n", "meta": {"author": "depth401", "repo": "ssreflect", "sha": "0c8dc899dd47907ee9c54e25b743cb348f22269f", "save_path": "github-repos/coq/depth401-ssreflect", "path": "github-repos/coq/depth401-ssreflect/ssreflect-0c8dc899dd47907ee9c54e25b743cb348f22269f/2/NaturalNumber.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.824773040436997}}
{"text": "Require Import Arith.\n\n(* Exercise 6 *)\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\nintros x y H.\napply (plus_lt_compat_r x y 10). assumption.\nQed.\n\n(* Exercise 7 *)\n\nGoal forall P Q : nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\nintros P Q H1 H2.\napply (H2 0). assumption.\nQed.\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\nintros P H.\nexists 1. simpl. assumption.\nQed.\n\nGoal forall P : nat -> Prop, (forall n m, P n -> P m) -> (exists p, P p) -> forall q, P q.\nProof.\nintros P H1 H2 q.\ndestruct H2 as [p H3]. apply (H1 p q).\nassumption.\nQed.\n\n(* Exercise 8 *)\n\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nProof.\nintros m n.  \neapply NPeano.Nat.add_cancel_r.\neapply mult_comm.\nQed.\n\n(* Exercise 9 *)\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\nintros n m p q.\napply plus_permute_2_in_4.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\nintros n m.\nerewrite mult_plus_distr_l.\nrepeat erewrite mult_plus_distr_r.\nrewrite (plus_comm (n * m) (m * m)).\nerewrite <- plus_permute_2_in_4.\neapply NPeano.Nat.add_cancel_l.\nrewrite (mult_comm m n).\nsimpl. erewrite <- plus_n_O.\nerewrite mult_plus_distr_r.\nreflexivity.\nQed.\n\n(* Exercise 10 *)\n\nParameter G : Set.\nParameter mult : G -> G -> G.\nNotation \"x * y\" := (mult x y).\nParameter one : G.\nNotation \"1\" := one.\nParameter inv : G -> G.\nNotation \"/ x\" := (inv x).\n(* Notation \"x / y\" := (mult x (inv y)). *) (* \\u4f7f\\u3063\\u3066\\u3082\\u3088\\u3044 *)\n\nAxiom mult_assoc : forall x y z, x * (y * z) = (x * y) * z.\nAxiom one_unit_l : forall x, 1 * x = x.\nAxiom inv_l : forall x, /x * x = 1.\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\nintro x.\nassert(H: (/(/x) * (/x)) * x * (/x) = 1).\n rewrite <- (mult_assoc (/(/x) * (/x)) x (/x)).\n rewrite <- (mult_assoc (/(/x)) (/x) (x * /x)).\n rewrite (mult_assoc (/x) x (/x)).\n rewrite (inv_l x). rewrite one_unit_l.\n apply (inv_l (/x)).\nrewrite (inv_l (/x)) in H. rewrite one_unit_l in H.\nassumption.\nQed.\n\nLemma one_unit_r : forall x, x * 1 = x.\nProof.\nintros x.\nrewrite <- (one_unit_l (x * 1)).\nassert(H: (/(/x) * (/x)) * (x * (/x * x)) = x).\n rewrite <- (mult_assoc (/(/x)) (/x) (x* (/x * x))).\n rewrite (mult_assoc (/(/x)) (/x) (x*(/x * x))).\n rewrite <- mult_assoc.\n rewrite (mult_assoc (/x) x (/x * x)).\n replace (/x * x * (/x * x)) with (1 * (/x * x)).\n  rewrite one_unit_l. rewrite mult_assoc.\n  rewrite inv_l. rewrite one_unit_l. reflexivity.\n rewrite (inv_l x). reflexivity. \nrewrite (inv_l x) in H. rewrite (inv_l (/x)) in H.\nassumption.\nQed.\n\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/coqex2014/coqex2014_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.8247486872122404}}
{"text": "Require Import ZArith. \nRequire Import List.\nRequire Import Classical_Prop.\nOpen Scope Z_scope.\n\nFrom QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Open Scope qc_scope.\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import seq ssreflect ssrbool ssrnat eqtype.\n\n(****Expressoes sem Variaveis****)\n\n(*1*)\n\nInductive Op : Type :=\n  | P   : Op\n  | M   : Op\n  | MM  : Op.\n\nCheck forAll.\nRequire Import String. Open Scope string.\nInstance showOp : Show (Op) :=\n  {| show o := \n      match o with\n      | P => \"+\"\n      | M => \"-\"\n      | MM => \"*\"\n      end\n  |}.\n\nDefinition genOp : G Op :=\n  elems [P ; M ; MM].\n\nInductive aexp :=\n  | Leaf : Z -> aexp\n  | Node : aexp -> Op -> aexp -> aexp.\n\nInstance showAExp : Show (aexp) :=\n  {| show := \n      let fix aux a := \n        match a with\n        | Leaf z => show z\n        | Node l o r => \"(\" ++ aux l ++ \" \" ++ show o ++ \" \" ++ aux r ++ \")\"\n        end\n      in aux \n  |}.\n\nFixpoint genAExp (sz : nat) (gz : G Z) (go : G Op) :=\n  match sz with\n  | 0%nat => liftGen Leaf gz\n  | S sz' => freq [ (1%nat, liftGen Leaf gz)\n                  ; (sz, liftGen3 Node (genAExp sz' gz go) go (genAExp sz' gz go))\n                  ]\n  end.\n\nSample (genAExp 3 (choose(0,10)) genOp).\n\n(*2*)\n\nFixpoint aeval (a : aexp) : Z :=\n    match a with\n    | Leaf n => n \n    | Node L P R  => aeval L + aeval R\n    | Node L M R  => aeval L - aeval R\n    | Node L MM R => aeval L * aeval R\nend.\n\nModule TreeNotations.\nNotation \"( L ; + ; R )\" := (Node L P R).\nNotation \"( L ; - ; R )\" := (Node L M R).\nNotation \"( L ; * ; R )\" := (Node L MM R).\nNotation \"\u00ab x \u00bb\" := (Leaf x).\nEnd TreeNotations.\n\nImport TreeNotations.\n\nModule ListNotations.\nNotation \"[ ]\" := nil (format \"[ ]\") : list_scope.\nNotation \"[ x ]\" := (cons x nil) : list_scope.\nNotation \"[ x ; y ; .. ; z ]\" := (cons x (cons y .. (cons z nil) ..)) : list_scope.\nEnd ListNotations.\n\nImport ListNotations.\n\n(*3*)\n\nEval compute in (2*3)+(3*(4-2)).\n\nEval compute in aeval ((\u00ab2\u00bb;*;\u00ab3\u00bb);+;(\u00ab3\u00bb;*;(\u00ab4\u00bb;-;\u00ab2\u00bb))).\n\nEval compute in (20-40)*(30+(1*1)).\n\nEval compute in aeval ((\u00ab20\u00bb;-;\u00ab40\u00bb);*;(\u00ab30\u00bb;+;(\u00ab1\u00bb;*;\u00ab1\u00bb))).\n\n(*4*)\n\nFixpoint aevalR (a : aexp) (n : Z) : Prop :=\n  match a with\n  | Leaf z => z = n \n  | Node a1 op a2 => \n      match op with \n      | P =>\n          exists (n1 n2: Z),  aevalR a1 n1 /\\ aevalR a2 n2 /\\ n1 + n2 = n\n      | M => \n          exists (n1 n2: Z),  aevalR a1 n1 /\\ aevalR a2 n2 /\\ n1 - n2 = n\n      | MM => \n          exists (n1 n2: Z),  aevalR a1 n1 /\\ aevalR a2 n2 /\\ n1 * n2 = n\n     end\n  end.\n\n(*5*)\n\nTheorem RelEqFun : forall (a : aexp) (n : Z),\n                    (aevalR a n) <-> (aeval a = n).\nProof.\n  induction a.\n  - simpl. intros. reflexivity.\n  - red. intros. induction o.\n    + split.\n      * simpl. intros. \n        destruct H as [n1 H]. \n        destruct H as [n2 H]. \n        destruct H. destruct H0. \n        assert (IHa1 := (IHa1 n1)).\n        assert (IHa2 := (IHa2 n2)).\n        unfold iff in IHa1; destruct IHa1; clear H3.\n        unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H)).\n        assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6.\n        assumption.\n      * simpl. intros.\n        assert (IHa1 := (IHa1 (aeval a1))).\n        assert (IHa2 := (IHa2 (aeval a2))).\n        unfold iff in IHa1; destruct IHa1; clear H0.\n        unfold iff in IHa2; destruct IHa2; clear H0.\n        exists (aeval a1); exists (aeval a2).\n        auto 4.\n(*______________________________________________________________________________________________________________*)\n    + split.\n      * simpl. intros. \n        destruct H as [n1 H];destruct H as [n2 H];destruct H; destruct H0.   \n        assert (IHa1 := (IHa1 n1));assert (IHa2 := (IHa2 n2)).\n        unfold iff in IHa1; destruct IHa1; clear H3.\n        unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H));assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6;assumption.       \n      * simpl. intros.\n        assert (IHa1 := (IHa1 (aeval a1)));assert (IHa2 := (IHa2 (aeval a2))).\n        unfold iff in IHa1; destruct IHa1; clear H0;unfold iff in IHa2; destruct IHa2; clear H0.\n        eauto 7.\n    + split.\n      * simpl. intros. \n        destruct H as [n1 H];destruct H as [n2 H];destruct H; destruct H0.   \n        assert (IHa1 := (IHa1 n1));assert (IHa2 := (IHa2 n2)).\n        unfold iff in IHa1; destruct IHa1; clear H3.\n        unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H));assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6;assumption.       \n      * simpl. intros.\n        assert (IHa1 := (IHa1 (aeval a1)));assert (IHa2 := (IHa2 (aeval a2))).\n        unfold iff in IHa1; destruct IHa1; clear H0;unfold iff in IHa2; destruct IHa2; clear H0.\n        eauto 7.\nQed.\n\n(****Maquina de Stack****)\nLet stack     := list Z.\n\nInductive Exp : Type :=\n  | Num   : Z -> Exp\n  | Pls   : Exp\n  | Min   : Exp\n  | Mul   : Exp.\n\nDefinition stack_exp := list Exp.\n\nDefinition SPush (n : Z) (st : stack) : stack :=\n  cons n st.\n\nDefinition SPlus (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b+a) c)\n  end.\n\nDefinition SMinus (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b-a) c)\n  end.\n\n\nDefinition SMult (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b*a) c)\n  end.\n\n(*1*)\nFixpoint execute (s : stack) (a : stack_exp) : option stack :=\n  match a with\n  | nil => Some s \n  | cons (Num n) a' => execute (SPush n s) a'\n  | cons Pls a'     => \n      match SPlus s with\n      | Some s' => execute s' a'\n      | None => None\n      end\n  | cons Min a'     => \n      match SMinus s with\n      | Some s' => execute s' a'\n      | None => None\n      end\n  | cons Mul a'     => \n      match SMult s with\n      | Some s' => execute s' a'\n      | None => None\n      end\n  end.\n\nFixpoint stack_eq (st1 st2 : stack) : bool :=\n  match st1, st2 with\n  | nil, nil => true\n  | cons z1 st1', cons z2 st2' => Zeq_bool z1 z2 && stack_eq st1' st2'\n  | _, _ => false\n  end.\n\nDefinition option_stack_eq (o1 o2 : option stack) : bool :=\n  match o1, o2 with\n  | None, None => true\n  | Some st1, Some st2 => stack_eq st1 st2\n  | _, _ => false\n  end.\n\n(*2*)\n\nLet stack_machine : stack := nil. \n\nLet expression    : stack_exp  := [Num 2; Num 3; Mul; Num 3; Num 4; Num 2; Min; Mul; Pls].\n\nEval compute in execute stack_machine expression.\n\n(*3*)\n\n(*\n    Decidimos usar o option para saber se houve problema.\n    *)\n\n(****Compilador****)\nOpen Scope list.\nFixpoint compile (a : aexp) : stack_exp := \n  match a with\n  | Leaf z => cons (Num z) nil\n  | Node l P r => compile l ++ compile r ++ cons Pls nil\n  | Node l M r => compile l ++ compile r ++ cons Min nil\n  | Node l MM r => compile l ++ compile r ++ cons Mul nil\n  end.\n\n\nDefinition Correction' (a : aexp) :=\n  option_stack_eq (execute nil (compile a)) (Some (cons (aeval a) nil)).\n\n\nCheck forAll.\nSample (genAExp 3 (choose(0,10)) genOp).\nQuickChick (forAll (genAExp 3 (choose(0,10)) genOp) Correction').\n\n\n\n(*2*)\n\nEval compute in execute nil (compile ((\u00ab2\u00bb;*;\u00ab3\u00bb);+;(\u00ab3\u00bb;*;(\u00ab4\u00bb;-;\u00ab2\u00bb)))).\n\n(*3*)\n\nLemma Dinamic_Execute (z : Z) (se1 se2 : stack_exp):\n  forall (st st1 : stack),\n    execute st se1 = Some (z :: nil) -> \n    execute (st ++ st1) (se1 ++ se2) = execute (z :: st1) se2.\nProof.\n  induction se1.\n  - simpl.\n    intros.\n    inversion H.\n    simpl.\n    reflexivity.\n  - induction a.\n    + simpl.\n      intros.\n      apply (IHse1 (z0 :: st) st1).\n      assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 + a) :: st) st1).\n           assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 - a) :: st) st1).\n           assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 * a) :: st) st1).\n           assumption.\nQed. \n\nTheorem Correction : forall (a : aexp),\n                     (execute nil (compile a) = Some (cons (aeval a) nil)).\nProof.\n  intros.\n  induction a.\n  - simpl. reflexivity.\n  - induction o.\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1) (compile a1) (compile a2 ++ Pls :: nil) nil nil) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2) (compile a2) (Pls :: nil) nil (aeval a1 :: nil)) IHa2)); simpl in H1.\n      rewrite H.\n      rewrite H1.\n      reflexivity.\n(*______________________________________________________________________________________________________________*)\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1) (compile a1) (compile a2 ++ Min :: nil) nil nil) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2) (compile a2) (Min :: nil) nil (aeval a1 :: nil)) IHa2)); simpl in H1.\n      rewrite H; rewrite H1; reflexivity.\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1) (compile a1) (compile a2 ++ Mul :: nil) nil nil) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2) (compile a2) (Mul :: nil) nil (aeval a1 :: nil)) IHa2)); simpl in H1.\n      rewrite H; rewrite H1; reflexivity.\nQed.\n", "meta": {"author": "AJGQ", "repo": "trabalhoVF", "sha": "7c4f5679db8389f4b384c5d31a101092ac305cab", "save_path": "github-repos/coq/AJGQ-trabalhoVF", "path": "github-repos/coq/AJGQ-trabalhoVF/trabalhoVF-7c4f5679db8389f4b384c5d31a101092ac305cab/Nelson/semvars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8933094060543488, "lm_q1q2_score": 0.824559561955627}}
{"text": "Inductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\nDefinition next_weekday (d:day) : day :=\n    match d with\n      | monday => tuesday\n      | tuesday => wednesday\n      | wednesday => thursday\n      | thursday => friday\n      | friday => monday\n      | saturday => monday\n      | sunday => monday\n    end.\n\nEval compute in (next_weekday friday).\n\nEval compute in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\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_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\nCheck true.\n\n\n\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nCheck (negb true).\n\nEval compute in (negb true).\n\nCheck negb.\n\nModule Playground1.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nCheck O.\n\nDefinition pred (n:nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n      | O => O\n      | S O => O\n      | S (S n') => n'\n  end.\n\nCheck (S (S (S (S O)))).\n\nEval compute in (minustwo 3).\n\nEval compute in pred O.\nEval compute in pred (S (S O)).\n\nEval compute in (minustwo (S (S O))).\nEval compute in (minustwo (S (S (S (S O))))).\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n    | O => true\n    | S O => false\n    | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n:nat) (m:nat) : nat :=\n  match n with\n    | O => m\n    | (S n') => S (plus n' m)\n  end.\n\nEval compute in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nEval compute in (mult 3 3).\n\nFixpoint minus (n m: nat) : nat :=\n  match n, m with\n    | 0, _ => 0\n    | S _ , 0 => n\n    | S n' , S m' => minus n' m'\n  end.\n\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\nCheck ((0 +1) + 1).\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n,m with\n    | O,O => true\n    | O,(S n') => false\n    | S n',O => false\n    | S n',S m' => beq_nat n' m'\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n,m with\n    | O,O => true\n    | O,(S n') => true\n    | S n',O => false\n    | S n',S m' => ble_nat n' m'\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n  match n,m with\n    | O,O => false\n    | O,(S n') => true\n    | (S n'),O => false\n    | (S n'),(S m') => andb (ble_nat n' m') (negb (beq_nat n' m'))\n  end.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_n_O : forall n, n+0 = n.\nProof.\n  simpl.\nAbort.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. \n  simpl.\n  reflexivity. \nQed.\n\nTheorem plus_id_example : forall n m: nat,\n                            n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | zero : bin\n  | twice : bin -> bin\n  | twice_plus_one : bin -> bin.\n\nFixpoint twice_nat (n:nat) : nat :=\n  match n with\n    | O => O\n    | (S n') => S (S (twice_nat n'))\nend.\n\nFixpoint bin_to_nat (n:bin) : nat :=\n  match n with\n    | zero => O\n    | twice x => twice_nat (bin_to_nat x)\n    | twice_plus_one x => S (twice_nat (bin_to_nat x))\nend.\n\nFixpoint incr (n:bin) : bin :=\n    match n with\n      | zero => twice_plus_one zero\n      | twice x => twice_plus_one x\n      | twice_plus_one x => twice (incr x)\n    end.\n\nExample test_bin_incr1: (bin_to_nat(incr zero)) = (S O).\nProof.\nreflexivity.\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\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 test : nat := 3.\nCheck test.\n\nTheorem plus_n_O : forall n, n = n + 0.\nProof.\n  intros n.\n  simpl.\n  Abort.\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 andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c.\n  destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n", "meta": {"author": "psibi", "repo": "sf", "sha": "36d1f95b4d4ed894ecc2c55c81095c822f3e9c69", "save_path": "github-repos/coq/psibi-sf", "path": "github-repos/coq/psibi-sf/sf-36d1f95b4d4ed894ecc2c55c81095c822f3e9c69/chapter1/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.9086178876533446, "lm_q1q2_score": 0.8244001094602548}}
{"text": "Inductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1 : 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(* Complete specification for orb; a truth table *)\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Complete specification for andb *)\nExample test_andb1: (andb true false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb2: (andb false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb3: (andb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb4: (andb true true) = true.\nProof. simpl. reflexivity. Qed.\n\n(* Introducing infix notation via [Notation] *)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb5: true && true && false = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: nandb *)\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 true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: andb3 *)\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  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", "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/lf/basics/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.9059898254600903, "lm_q1q2_score": 0.8243664940121403}}
{"text": "Definition nandb (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n  | true => match b2 with\n    | true => false\n    | false => true\n    end\n  | false => true\n  end.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3: bool): bool :=\nmatch b1 with\n  | true => match b2 with\n    | true => match b3 with\n      | true => true\n      | false => false\n      end\n    | false => false\n    end\n  | false => false\n  end.\n\nFixpoint factorial (n: nat) : nat :=\n  match n with\n    | 0 => 1\n    | S n => S n * factorial n\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\" := (leb x y) (at level 70) : nat_scope.\n\nDefinition ltb (n m : nat) : bool :=\n\tmatch n <=? m with\n\t| false => false\n\t| true => negb(m <=? n)\n\tend.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof.\nreflexivity.\nQed.\n\nExample test_ltb2: (ltb 2 4) = true.\nProof.\nreflexivity.\nQed.\n\nExample test_ltb3: (ltb 4 2) = false.\nProof.\nreflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\nintros n m o.\nintros H.\nrewrite -> H.\nintros I.\nrewrite -> I.\nreflexivity.\nQed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\nintros n.\ndestruct n as [ | n'].\n- reflexivity.\n- reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice :\n\tforall (f : bool -> bool), (forall (x : bool), f x = x) ->\n\t\tforall (b : bool), f (f b) = b.\nProof.\nintros.\nrewrite H.\nrewrite H.\nreflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n\tforall (f : bool -> bool), (forall (x : bool), f x = negb x) ->\n\t\tforall (b : bool), f (f b) = b.\nProof.\nintros.\ndestruct b.\n\t(* case b = true *)\n\trewrite H.\n\trewrite H.\n\tsimpl.\n\treflexivity.\n\t(* case b = false *)\n\trewrite H.\n\trewrite H.\n\tsimpl.\n\treflexivity.\nQed.\n", "meta": {"author": "imel96", "repo": "logical-coq", "sha": "233e1424e277e7f8eb082b766a9d44d7b9c9b501", "save_path": "github-repos/coq/imel96-logical-coq", "path": "github-repos/coq/imel96-logical-coq/logical-coq-233e1424e277e7f8eb082b766a9d44d7b9c9b501/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.9046505338155469, "lm_q1q2_score": 0.8242992088821275}}
{"text": "From LF Require Export Induction.\nModule NatList.\n    Inductive natprod : Type :=\n        | pair (n1 n2 : nat).\n\n    Check (pair 3 5) : natprod.\n\n    Definition fst (p: natprod) : nat :=\n        match p with\n        | pair x _ => x\n        end.\n\n    Definition snd (p: natprod) : nat :=\n        match p with\n        | pair _ y => y\n        end.\n    \n    Compute (fst (pair 3 5)).\n\n    Notation \"( x , y )\" := (pair x y).\n    \n    Compute (fst (3, 5)).\n\n    Definition fst' (p : natprod) : nat :=\n        match p with\n        | (x, _) => x\n        end.\n\n    Definition snd' (p : natprod) : nat := \n        match p with\n        | (_, y) => y\n        end.\n\n    Definition swap_pair (p : natprod) : natprod :=\n        match p with\n        | (x, y) => (y, x)\n        end.\n    \n    Theorem surjective_pairing' : forall n m : nat,\n        (n, m) = (fst (n, m), snd (n, m)).\n    Proof.\n        reflexivity.\n    Qed.\n\n    Theorem surjective_pairing : forall p : natprod,\n        p = (fst p, snd p).\n    Proof.\n        intros p. destruct p as [n m]. reflexivity.\n    Qed.\n\n    Theorem snd_fst_is_swap: forall p : natprod,\n        (snd p, fst p) = swap_pair p.\n    Proof.\n        intros p. destruct p as [n m]. reflexivity.\n    Qed.\n    \n    Theorem fst_swap_is_snd: forall p : natprod,\n        fst (swap_pair p) = snd p.\n    Proof.\n        intros p. destruct p as [n m]. reflexivity.\n    Qed.\n    \n    Inductive natlist : Type :=\n        | nil\n        | cons (n : nat) ( l :  natlist).\n    \n    Notation \"x :: l\" :=\n        (cons x l)\n        (at level 60, right associativity).\n    \n    Notation \"[ ]\" := nil.\n    Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n    Fixpoint repeat (n count : nat) : natlist :=\n        match count with\n        | 0 => nil\n        | S count' => n :: (repeat n count')\n    end.\n\n    Fixpoint length (l: natlist) : nat :=\n        match l with\n        | nil => 0\n        | h :: t => S (length t)\n        end.\n\n    Fixpoint app (l1 l2 : natlist) : natlist :=\n        match l1 with\n        | nil => l2\n        | h :: t => h :: (app t l2)\n        end.\n\n    Notation \"x ++ y\" :=\n        (app x y)\n        (at level 60, right associativity).\n    \n    Definition hd (default : nat) (l : natlist) : nat := \n        match l with\n        | nil => default\n        | h :: _ => h\n        end.\n    \n    Definition tl (l : natlist) : natlist := \n        match l with\n        | nil => nil\n        | h :: t => t\n        end.\n    \n    Fixpoint nonzeros (l : natlist) : natlist :=\n        match l with\n        | nil => nil\n        | 0 :: t => nonzeros t\n        | h :: t => h :: (nonzeros t)\n        end.\n    \n    Example test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n    Proof. reflexivity. Qed.\n\n\n    Fixpoint oddmembers (l:natlist) : natlist :=\n        match l with\n        | nil => nil\n        | h :: t => let \n            t' := oddmembers t \n            in if odd h then h :: t' else t'\n        end.\n    \n    Example test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\n    Proof. reflexivity. Qed.\n\n    Definition countoddmembers (l:natlist) : nat := length (oddmembers l).\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        | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n        end.\n    \n    Example test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n    Proof. reflexivity. Qed.\n    Example test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n    Proof. reflexivity. Qed.\n    Example test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n    Proof. reflexivity. Qed.\n    Example test_alternate4: alternate [] [20;30] = [20;30].\n    Proof. reflexivity. Qed.\n\n    Definition bag := natlist.\n\n    Fixpoint count (v : nat) (s : bag) : nat :=\n        match s with\n        | nil => 0\n        | h :: t => let tc := count v t in if h =? v then 1 + tc else tc\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 : nat -> bag -> bag := cons.\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 := negb ((count v s) =? 0).\n\n    Example test_member1: member 1 [1;4;1] = true.\n    Proof. reflexivity. Qed.\n    Example test_member2: member 2 [1;4;1] = false.\n    Proof.  reflexivity. Qed.\n\n    (* Exercise: 3starts, standard, optional (bag_more_functions) \n\n    Here are some more bag functions for you to practice with.\n\n    When remove_one is applied to a bag without the number to remove, it should \n    return the same bag unchanged. (This exercise is optional, but students \n    following the advanced track will need to fill in the definition of remove_one\n    for a later exercise.) \n\n    *)\n\n    Fixpoint remove_one (v : nat) (s : bag) : bag :=\n        match s with\n        | nil => nil\n        | h :: t => if h =? v then t else h :: (remove_one v t)\n        end.\n\n    Example test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n    Proof. reflexivity. Qed.\n    Example test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n    Proof. reflexivity. Qed.\n    Example test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n    Proof. reflexivity. Qed.\n    Example test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n    Proof. reflexivity. Qed.\n\n    Fixpoint remove_all (v:nat) (s:bag) : bag :=\n        match s with\n        | nil => nil\n        | h :: t => let rem := remove_all v t in if h =? v then rem else h :: rem\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        | h :: t, s2' => (member h s2') && subset t (remove_one h s2')\n        end.\n\n    Example test_subset1: subset [1;2] [2;1;4;1] = true.\n    Proof. reflexivity. Qed.\n    Example test_subset2: subset [1;2;2] [2;1;4;1] = false.\n    Proof. reflexivity. Qed.\n\n    (* Exercise: 2 stars, standard especially useful (add_inc_count) \n    \n    Adding a value to a bag should increase the value's count by one. \n    State that as a theorem and prove it. \n    *)\n\n    Theorem eq_refl: forall n : nat,\n        n =? n = true.\n    Proof.\n        intros n. induction n as [|n' IHn'].\n        - reflexivity.\n        - simpl. rewrite -> IHn'. reflexivity.\n    Qed.\n    \n\n    Theorem bag_add_inc_count : forall v : nat, forall b : bag,\n        count v (add v b) = S (count v b).\n    Proof.\n        intros v b. \n        destruct b as [|bh' bt'].\n        - simpl. rewrite -> eq_refl. reflexivity.\n        - simpl. rewrite -> eq_refl. reflexivity.\n    Qed.\n\n    Fixpoint rev (l:natlist) : natlist :=\n        match l with\n        | nil => nil\n        | h :: t => rev t ++ [h]\n        end.\n\n    Example test_rev1: rev [1;2;3] = [3;2;1].\n    Proof. reflexivity. Qed.\n    Example test_rev2: rev nil = nil.\n    Proof. reflexivity. Qed.\n\n    Theorem app_length : forall l1 l2 : natlist,\n        length (l1 ++ l2) = (length l1) + (length l2).\n    Proof.\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. \n    Qed.\n\n    Theorem rev_length : forall l : natlist,\n        length (rev l) = length l.\n    Proof.\n        intros l. induction l as [| n l' IHl'].\n        - (* l = nil *)\n            reflexivity.\n        - (* l = cons *)\n            simpl. rewrite -> app_length.\n            simpl. rewrite -> IHl'. rewrite add_comm.\n            reflexivity.\n    Qed.\n  \n\n    (* Exercise: 3 stars, standard (list_exercises) \n    \n    More practice with lists:\n    *)\n\n    Theorem app_nil_r : forall l : natlist,\n        l ++ [] = l.\n    Proof.\n        intros l. induction l as [|lh' lt' IHl'].\n        - reflexivity.\n        - simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n\n    Theorem app_assoc: forall l1 l2 l3 : natlist,\n        l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\n    Proof.\n        intros l1 l2 l3. induction l1 as [|l1h l1t IHl1'].\n        - (* l1 = nil *)\n            reflexivity.\n        - (* l1 = cons l1h l1t *)\n            simpl. rewrite -> IHl1'. reflexivity.\n    Qed.\n    \n    Theorem rev_app_distr: forall l1 l2 : natlist,\n        rev (l1 ++ l2) = rev l2 ++ rev l1.\n    Proof.\n        intros l1 l2. induction l1 as [|l1h l1t IHl1'].\n        - (* l1 = nil *)\n            simpl. rewrite -> app_nil_r. reflexivity.\n        - (* l1 = cons l1h l1t *)\n            simpl. \n            rewrite -> IHl1'. \n            rewrite -> app_assoc. \n            reflexivity.\n    Qed.\n\n    Theorem rev_involutive : forall l : natlist,\n        rev (rev l) = l.\n    Proof.\n        intros l. induction l as [|lh lt IHl'].\n        - reflexivity.\n        - (* l = cons lh lt *)\n            simpl. \n            rewrite -> rev_app_distr.\n            rewrite -> IHl'.\n            reflexivity.\n    Qed.\n\n    (* There is a short solution to the next one. If you find yourself \n       getting tangled up, step back and try to look for a simpler way. \n    *)\n\n    Theorem app_assoc4: forall l1 l2 l3 l4 : natlist,\n        l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n    Proof.\n        intros l1 l2 l3 l4.\n        rewrite -> app_assoc.\n        rewrite -> app_assoc.\n        reflexivity.\n    Qed.\n    \n    (* An exercise about your implementation of nonzeros: *)\n\n    Lemma nonzeros_app: forall l1 l2 : natlist,\n        nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n    Proof.\n        intros l1 l2. induction l1 as [|l1h l1t IHl1'].\n        - reflexivity.\n        - induction l1h as [|l1h' IHl1h'].\n            -- simpl. rewrite -> IHl1'. reflexivity.\n            -- simpl. rewrite -> IHl1'. reflexivity.\n    Qed.\n    \n    (* Exercise: 2 stars, standard (eqblist) \n    \n    Fill in the definition of eqblist, which compares lists of numbers\n    for equality. Prove that eqblist l l yields true for every list l. \n\n    *)\n \n    Fixpoint eqblist (l1 l2 : natlist) : bool :=\n        match l1, l2 with\n        | nil, nil => true\n        | h1 :: t1, h2 :: t2 => (h1 =? h2) && eqblist t1 t2\n        | _, _ => false\n        end.  \n  \n    Example test_eqblist1 : (eqblist nil nil = true).\n    Proof. reflexivity. Qed.\n    Example test_eqblist2 : eqblist [1;2;3] [1;2;3] = true.\n    Proof. reflexivity. Qed.\n    Example test_eqblist3 : eqblist [1;2;3] [1;2;4] = false.\n    Proof. reflexivity. Qed.\n  \n    Theorem eqblist_refl : forall l:natlist,\n        eqblist l l = true.\n    Proof.\n        intros l. induction l as [|h t IHl'].\n        - reflexivity.\n        - simpl. rewrite -> IHl'. rewrite -> eq_refl. reflexivity.\n    Qed.\n\n    (* Exercise: 1 star, standard (count_member_nonzero) *)\n\n    Theorem count_member_nonzero: forall s : bag,\n        1 <=? (count 1 (1 :: s)) = true.\n    Proof.\n        intros s. induction s as [|h t IHs'].\n        - reflexivity.\n        - simpl. reflexivity.\n    Qed.\n\n    Theorem leb_n_Sn: forall n : nat,\n        n <=? (S n) = true.\n    Proof.\n        intros n. induction n as [| n' IHn'].\n        - reflexivity.\n        - simpl. rewrite -> IHn'. reflexivity.\n    Qed.\n    \n    (* Exercise: 3 stars, advanced (remove_does_not_increase_count) *)\n\n    Theorem remove_does_not_increase_count: forall s : bag,\n       (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\n    Proof.\n        intros s. induction s as [|h t IHs'].\n        - reflexivity.\n        - simpl. induction h as [|h' IHh'].\n            -- simpl. rewrite -> leb_n_Sn. reflexivity.\n            -- simpl. rewrite -> IHs'. reflexivity. \n    Qed.\n    \n    (* Exercise: 3 stars, standard, optional (bag_count_sum)\n    \n    Write down an interesting theorem bag_count_sum about bags involving\n    the functions count and sum, and prove it using Coq. (You may find that\n    the difficulty of the proof depends on how you defined count! Hint: If\n    you defined count using =? you may find it useful to know that destruct\n    works on arbitrary expressions, not just simple identifiers.)\n    *)\n\n    Theorem bag_count_sum: forall n : nat, forall b1 b2: bag,\n        count n b1 + count n b2 = count n (sum b1 b2).\n    Proof.\n        intros n b1 b2. induction b1 as [|b1h b1t IHb1].\n        - reflexivity.\n        - simpl. destruct (b1h =? n) as [].\n            -- simpl. rewrite -> IHb1. reflexivity.\n            -- rewrite -> IHb1. reflexivity.\n    Qed.\n    \n    (* Exercise: 4 stars, advanced (rev_injective) \n    \n    Prove that the rev function is injective. There is a hard way and an easy\n    way to do this. \n    *)\n\n    Theorem rev_injective: forall l1 l2 : natlist,\n        rev l1 = rev l2 -> l1 = l2.\n    Proof.\n        intros l1 l2.\n        intros H.\n        rewrite <- rev_involutive.\n        rewrite <- H.\n        rewrite -> rev_involutive.\n        reflexivity.\n    Qed.\n    \n    Inductive natoption : Type :=\n        | Some (n : nat)\n        | None.\n\n    Fixpoint nth_error (l : natlist) (n : nat) : natoption :=\n        match l, n with\n        | nil, _ => None\n        | a :: _, 0 => Some a\n        | _ :: l', S n' => nth_error l' n'\n        end.\n\n    Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\n    Proof. reflexivity. Qed.\n    Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\n    Proof. reflexivity. Qed.\n    Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.\n    Proof. reflexivity. Qed.\n\n    Definition option_elim (d : nat) (o : natoption) : nat := \n        match o with\n        | Some n' => n'\n        | None => d\n        end.\n    \n    (* Exercise: 2 stars, standard (hd_error)\n    \n    Using the same idea, fix the hd function from earlier so we\n    don't have to pass a default element for the nil case. \n    *)\n    \n    Definition hd_error (l : natlist) : natoption := \n        match l with\n        | nil => None\n        | h :: _ => Some h\n        end.\n    \n    Example test_hd_error1 : hd_error [] = None.\n    Proof. reflexivity. Qed.\n    Example test_hd_error2 : hd_error [1] = Some 1.\n    Proof. reflexivity. Qed.\n    Example test_hd_error3 : hd_error [5;6] = Some 5.\n    Proof. reflexivity. Qed.\n\n    (* Exercise: 1 star, standard, optional (option_elim_hd) \n    \n    This exercise relates your new hd_error to the old hd.\n    *)\n\n    Theorem option_elim_hd: forall (l : natlist) (default : nat),\n        hd default l = option_elim default (hd_error l).\n    Proof.\n        intros l d. destruct l as [].\n        - reflexivity.\n        - reflexivity.\n    Qed.\nEnd NatList.\n\nInductive id : Type := Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n    match x1, x2 with\n    | Id n1, Id n2 => n1 =? n2\n    end.\n\n(* Exercise: 1 star standard (eqb_id_refl) *)\n\nTheorem eqb_id_refl: forall x: id,\n    eqb_id x x = true.\nProof.\n    intros x. destruct x. simpl. rewrite -> NatList.eq_refl. reflexivity.\nQed.\n\nModule PartialMap.\n    Export NatList.\n\n    Inductive partial_map : Type :=\n        | empty\n        | record (i: id) (v : nat) (m : partial_map).\n\n    Definition update (d : partial_map) (x : id) (value : nat) : partial_map := \n        record x value d.\n    \n    Fixpoint find (x : id) (d : partial_map) : natoption :=\n        match d with\n        | empty => None\n        | record y v d' => if eqb_id x y\n                           then Some v\n                           else find x d'\n        end.\n\n    (* Exercise: 1 star, standard (update_eq) *)\n\n    Theorem update_eq: forall (d: partial_map) (x : id) (v : nat),\n        find x (update d x v) = Some v.\n    Proof.\n        intros d x v. destruct d as [].\n        - simpl. rewrite -> eqb_id_refl. reflexivity.\n        - simpl. rewrite -> eqb_id_refl. reflexivity.\n    Qed.\n    \n    (* Exercise: 1 star, standard (update-neq) *)\n\n    Theorem 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.\n    Proof.\n        intros d x y o H. destruct d as [].\n        - simpl. rewrite -> H. reflexivity.\n        - simpl.  rewrite -> H. reflexivity.\n    Qed.\nEnd PartialMap.\n", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume1/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.8242308911671369}}
{"text": "(** * Multiset:  Insertion sort with multisets *)\n\n(** We have seen how to specify algorithms on \"collections\", such as\n    sorting algorithms, using permutations.  Instead of using\n    permutations, another way to specify these algorithms is to use\n    multisets.  A _set_ of values is like a list with no repeats where\n    the order does not matter.  A _multiset_ is like a list, possibly\n    with repeats, where the order does not matter.  One simple\n    representation of a multiset is a function from values to [nat]. *)\n\nRequire Import Perm.\nRequire Import Sort.\nRequire Export FunctionalExtensionality.\n\n(** In this chapter we will be using natural numbers for two different\n    purposes: the values in the lists that we sort, and the\n    multiplicity (number of times occurring) of those values.  To keep\n    things straight, we'll use the [value] type for values, and [nat]\n    for multiplicities. *)\n\nDefinition value := nat.\n\nDefinition multiset := value -> nat.\n\n(** Just like sets, multisets have operators for [union], for the\n    [empty] multiset, and the multiset with just a single element. *)\n\nDefinition empty : multiset :=\n   fun x => 0.\n\nDefinition union (a b : multiset) : multiset :=\n   fun x => a x + b x.\n\nDefinition singleton (v: value) : multiset :=\n   fun x => if x =? v then 1 else 0.\n\n(** **** Exercise: 1 star (union_assoc)  *)\n(** Since multisets are represented as functions, to prove that one\n    multiset equals another we must use the axiom of functional\n    extensionality. *)\n\nLemma union_assoc: forall a b c : multiset, (* assoc stands for \"associative\" *)\n   union a (union b c) = union (union a b) c.\nProof.\n  intros.\n  extensionality x.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (union_comm)  *)\nLemma union_comm: forall a b : multiset,  (* comm stands for \"commutative\" *)\n   union a b = union b a.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Remark on efficiency:  These multisets aren't very efficient.  If\n  you wrote programs with them, the programs would run slowly. However,\n  we're using them for _specifications_, not for _programs_.  Our\n  multisets built with [union] and [singleton] will never really\n  _execute_ on any large-scale inputs; they're only used in the proof\n  of correctness of algorithms such as [sort].  Therefore, their\n  inefficiency is not a problem. *)\n\n(** Contents of a list, as a multiset: *)\n\nFixpoint contents (al: list value) : multiset :=\n  match al with\n  | a :: bl => union (singleton a) (contents bl)\n  | nil => empty\n  end.\n\n(** Recall the insertion-sort program from [Sort.v].  Note that it\n    handles lists with repeated elements just fine. *)\n\nExample sort_pi: sort [3;1;4;1;5;9;2;6;5;3;5] = [1;1;2;3;3;4;5;5;5;6;9].\nProof. simpl. reflexivity. Qed.\n\nExample sort_pi_same_contents:\n    contents (sort [3;1;4;1;5;9;2;6;5;3;5]) = contents [3;1;4;1;5;9;2;6;5;3;5].\nProof.\nextensionality x.\ndo 10 (destruct x; try reflexivity).\n  (* Why does this work? Try it step by step, without [do 10] *)\nQed.\n\n(* ################################################################# *)\n(** * Correctness *)\n\n(** A sorting algorithm must rearrange the elements into a list that\n    is totally ordered.  But let's say that a different way: the\n    algorithm must produce a list _with the same multiset of values_,\n    and this list must be totally ordered. *)\n\nDefinition is_a_sorting_algorithm' (f: list nat -> list nat) :=\n  forall al, contents al = contents (f al) /\\ sorted (f al).\n\n(** **** Exercise: 3 stars (insert_contents)  *)\n(** First, prove the auxiliary lemma [insert_contents], which will be\n    useful for proving [sort_contents] below.  Your proof will be by\n    induction.  You do not need to use [extensionality]. *)\n\nLemma insert_contents: forall x l, contents (x::l) = contents (insert x l).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (sort_contents)  *)\n(** Now prove that sort preserves contents. *)\n\nTheorem sort_contents: forall l, contents l = contents (sort l).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem insertion_sort_correct:\n  is_a_sorting_algorithm' sort.\nProof.\nsplit. apply sort_contents. apply sort_sorted.\nQed.\n\n(** **** Exercise: 1 star (permutations_vs_multiset)  *)\n(** Compare your proofs of [insert_perm, sort_perm] with your proofs\n    of [insert_contents, sort_contents].  Which proofs are simpler?\n\n      - [ ] easier with permutations,\n      - [ ] easier with multisets\n      - [ ] about the same.\n\n   Regardless of \"difficulty\", which do you prefer / find easier to\n   think about?\n      - [ ] permutations or\n      - [ ] multisets\n\n   Put an X in one box in each list. *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Permutations and multisets *)\n\n(** The two specifications of insertion sort are equivalent.  One\n    reason is that permutations and multisets are closely related.\n    We're going to prove:\n\n       [Permutation al bl <-> contents al = contents bl.] *)\n\n(** **** Exercise: 3 stars  *)\n(** The forward direction is easy, by induction on the evidence for\n    [Permutation]: *)\n\nLemma perm_contents:\n  forall al bl : list nat,\n   Permutation al bl -> contents al = contents bl.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The other direction,\n    [contents al = contents bl -> Permutation al bl],\n    is surprisingly difficult.  (Or maybe there's an easy way\n    that I didn't find.) *)\n\nFixpoint list_delete (al: list value) (v: value) :=\n  match al with\n  | x::bl => if x =? v then bl else x :: list_delete bl v\n  | nil => nil\n  end.\n\nDefinition multiset_delete (m: multiset) (v: value) :=\n   fun x => if x =? v then pred(m x) else m x.\n\n(** **** Exercise: 3 stars (delete_contents)  *)\nLemma delete_contents:\n  forall v al,\n   contents (list_delete al v) = multiset_delete (contents al) v.\nProof.\n  intros.\n  extensionality x.\n  induction al.\n  simpl. unfold empty, multiset_delete.\n  bdestruct (x =? v); auto.\n  simpl.\n  bdestruct (a =? v).\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars (contents_perm_aux)  *)\nLemma contents_perm_aux:\n forall v b, empty = union (singleton v) b -> False.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (contents_in)  *)\nLemma contents_in:\n  forall (a: value) (bl: list value) , contents bl a > 0 -> In a bl.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (in_perm_delete)  *)\nLemma in_perm_delete:\n  forall a bl,\n  In a bl -> Permutation (a :: list_delete bl a) bl.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars (contents_perm)  *)\nLemma contents_perm:\n forall al bl, contents al = contents bl -> Permutation al bl.\nProof.\n  induction al; destruct bl; intro.\n  auto.\n  simpl in H.\n  contradiction (contents_perm_aux _ _ H).\n  simpl in H. symmetry in H.\n  contradiction (contents_perm_aux _ _ H).\n  specialize (IHal (list_delete (v :: bl) a)).\n  remember (v::bl) as cl.\n  clear v bl Heqcl.\n\n  (** From this point on, you don't need induction.\n    Use the lemmas [perm_trans], [delete_contents], \n     [in_perm_delete], [contents_in].   At _certain points_\n     you'll need to unfold the definitions of \n     [multiset_delete], [union], [singleton]. *)\n\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The main theorem: equivalence of multisets and permutations *)\nTheorem same_contents_iff_perm:\n  forall al bl, contents al = contents bl <-> Permutation al bl.\nProof.\n  intros. split. apply contents_perm. apply perm_contents.\nQed.\n\n(** Therefore, it doesn't matter whether you prove your sorting\n    algorithm using the Permutations method or the multiset method. *)\n\nCorollary sort_specifications_equivalent:\n    forall sort, is_a_sorting_algorithm sort <->  is_a_sorting_algorithm' sort.\nProof.\n  unfold is_a_sorting_algorithm, is_a_sorting_algorithm'.\n  split; intros;\n  destruct (H al); split; auto;\n  apply same_contents_iff_perm; auto.\nQed.\n\n\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/SF/vfa/Multiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.824230887981536}}
{"text": "Require Import Arith.\n\nFixpoint sum_odd_n (n:nat) : nat :=\n  match n with\n    O => O\n  | S p => 1 + 2*p + sum_odd_n p\n  end.\nSearch (Nat.mul).\n\nLemma sum_odd_n_p : forall (n:nat), sum_odd_n (n:nat) = n*n.\n  induction n.\n  simpl. reflexivity.\n  simpl. rewrite IHn. ring.\nQed.\n\nFixpoint sum_n (n:nat) : nat :=\n  match n with\n    0 => 0\n  | S p => 1 + p + sum_n p\n  end.\n\nCompute sum_n 3.\nSearch mult.\n(*\nNat.mul_succ_r: forall n m : nat, n * S m = n * m + n\nNat.mul_succ_l: forall n m : nat, S n * m = n * m + m\n *)\n\nLemma sum_n_helper : forall n : nat,\n  2 * sum_n (S n) = 2 * (S n) + 2 * sum_n n.\nProof.\n  intros n. simpl. ring.\nQed.\n\nTheorem sum_n_formula : forall n, 2 * sum_n n = (n*(n+1)).\nProof.\n  intros n.\n  induction n as [| k IH].\n  - (* base case n = 0 *)\n    simpl. reflexivity.\n  - (* inductive case *)\n    rewrite -> sum_n_helper.\n    rewrite IH.\n    ring.\nQed.\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\n(* need to figure out how to do this without the ring tactic. *) \n(*Require Import QArith.*)\n\nTheorem sum_n_formula2 : forall n : nat , sum_n n = (n * (n+1)/2)%nat .\nProof.\n  intros n.\n  apply div_helper.\n  - discriminate.\n  - rewrite sum_n_formula.\n    simpl. reflexivity.\nQed.\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\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nTheorem sub_add_1 : forall a :Z, a -1 + 1 = a.\nProof.\n  intros a. ring.\nQed.\n\nClose Scope Z_scope.\n\nRequire Import Field.\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(*\nModule RealExample.\n\n  Require Import Reals.\n  Open Scope R_scope.\n\n  Theorem frac_r : forall x y z, z<>0 -> (x+y) / z = x/z + y/z.\n  Proof.\n    intros x y z z_not_0.\n    field. assumption.\n  Qed.\n\n  \n  Close Scope R_scope.\nEnd RealExample.\n*)\n(*\nOpen Scope R_scope.\n\nTheorem *)\nSearch (_:N N _:N).\nCompute Nat.pow 2 O.\n\nFixpoint pow_series_2_n (k: nat) : nat :=\n  match k with\n    O => O\n  | S p => (Nat.pow 2 p) + (pow_series_2_n p) \n  end.\n\nCompute pow_series_2_n 2.\nCompute O + O.\n\nTheorem sum_2_pow_n: forall n: ", "meta": {"author": "ihasson", "repo": "coq", "sha": "0da545a4966f48b1874183812f61f54eac7b1976", "save_path": "github-repos/coq/ihasson-coq", "path": "github-repos/coq/ihasson-coq/coq-0da545a4966f48b1874183812f61f54eac7b1976/sum_of_odd_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8705972549785203, "lm_q1q2_score": 0.8241044652712765}}
{"text": "(* Taken from Logical Foundatins *)\n\nInductive even : nat -> Prop :=\n| even_O : even 0\n| even_S n (H : even n) : even (S (S n)).\n\nFixpoint double n :=\n  match n with\n  | O => O\n  | S n => S (S (double n))\n  end.\n\nFact even_double n :\n  even (double n).\nProof.\n  induction n as [|n IH]; cbn.\n  - exact even_O.\n  - now apply even_S.\nQed.\n\nTheorem even_correct n :\n  even n <-> exists k, n = double k.\nProof.\n  split.\n  - intros H. induction H as [|n H [k IH]].\n    + now exists 0.\n    + exists (S k). cbn. now rewrite IH.\n  - intros [k H]. rewrite H. now apply even_double.\nQed.\n\nTheorem even_sum n m :\n  even n -> even m -> even (n + m).\nProof.\n  intros H1 H2.\n  induction H1 as [|n _ IH]; cbn.\n  - exact H2.\n  - now apply even_S.\nQed.\n\nTheorem not_even_S n :\n  even n -> ~ even (S n).\nProof.\n  induction n as [|n IH]; cbn.\n  - intros H1 H2. inversion H2.\n  - intros H1 H2. contradict H1. apply IH. now inversion H2.\nQed.\n\nTheorem even_inv n :\n  even (S (S n)) -> even n.\nProof.\n  intros H. now inversion H.\nQed.\n\nTheorem even_sum_inv n m :\n  even (n + m) -> even n -> even m.\nProof.\n  intros H H1.\n  induction H1 as [|n H1 IH].\n  - now cbn in H.\n  - apply even_inv in H. now apply IH.\nQed.\n", "meta": {"author": "archbung", "repo": "icl-ss19", "sha": "fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e", "save_path": "github-repos/coq/archbung-icl-ss19", "path": "github-repos/coq/archbung-icl-ss19/icl-ss19-fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e/indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8236853709862804}}
{"text": "Require Export ct16.\n\nSection DivConq.\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\n(* split_pivot:= \n * takes an input term as pivot and list l and split into two sublists where the\n * first sublist contains all element/s that is/are le_dec _ pivot and the\n * second sublist contains the rest of the element/s. \n *)\n\nFixpoint split_pivot (pivot : A) l : list A * list A :=\n  match l with\n  | nil => (nil, nil)\n  | a :: l' => let (l1, l2) := (split_pivot pivot l') in\n    if le_dec a pivot \n    then (a :: l1, l2) else (l1, a :: l2)\n  end.\n\n\n(* split_pivot_wf:\n * states that for any list ls, each of the sublists generated has length less\n * than or equal to its original list's.\n *)\n\nLemma split_pivot_wf1 : forall a l, length (fst (split_pivot a l)) <= length l.\nProof.\ninduction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l); \nsimpl in *; auto; apply le_n_S; auto.\nDefined.\n\nLemma split_pivot_wf2 : forall a l, length (snd (split_pivot a l)) <= length l.\nProof.\ninduction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l); \nsimpl in *; auto; apply le_n_S; auto.\nDefined.\n\n\n(* div_conq_pivot:\n * - another variation of div_conq_split, just that for this, it will use \n *   split_pivot instead.\n * - To prove some proposition P holds for all lists ls, one needs to prove the\n *   following:\n *   1. P holds for empty list, nil.\n *   2. If P hold fst(split_pivot a l) and snd(split_pivot a l), then P must\n *      also hold for (a :: l).\n *)\n\nTheorem div_conq_pivot : \n  forall (P : list A -> Type),\n    P nil\n    -> (forall a l, P (fst (split_pivot a l)) -> P (snd (split_pivot a l)) \n      -> P (a :: l))\n    -> forall l, P l.\nProof.\nintros; eapply well_founded_induction_type. eapply lengthOrder_wf.\ndestruct x; intros; auto; apply X0; apply X1; apply le_lt_n_Sm.\napply split_pivot_wf1. apply split_pivot_wf2.\nDefined.\n\n\n\nHypothesis notle_le: forall x y, ~ le x y -> le y x.\n\n\n(* Forall_snd_split_pivot:\n * le a x for every element, x, in snd(split_pivot a l).\n *)\n\nLemma Forall_snd_split_pivot : forall a l, Forall (le a) (snd(split_pivot a l)).\nProof.\ninduction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l);\nsimpl in *; auto.\nDefined.\n\nEnd DivConq.\n\nLtac div_conq_pivot := eapply div_conq_pivot.", "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/ct22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.907312229506029, "lm_q1q2_score": 0.8232154766947526}}
{"text": "(* boolean implementation and theorems.*)\n\n(* A value of type bool is one of a finite set of elements: either true or false.*)\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(* NOTE: functions here are named as <function>b; the b is used to indicate\n    that it is a boolean function.*)\n\n(* negb defines the negation of a boolean value.*)\nDefinition negb (b:bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nExample test_negb_true: (negb true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_negb_false: (negb false) = true.\nProof. simpl. reflexivity. Qed.\n\n(*\nBoolean \"and\".\n\nGiven two boolean values, a and b, andb returns true if both are true\nor false otherwise.\n\nTheorem:\n  If a is true, the result of andb depends on the value of a; returning the\n  value of b means that if b is true, andb returns true.\n\n  Otherwise, if a is false, there is no way for andb to return true.\n*)  \nDefinition andb (a:bool) (b:bool) : bool :=\n  match a with\n    | true => b\n    | false => false\n  end.\n\nExample test_andb_ff: (andb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb_ft: (andb false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb_tf: (andb true false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb_tt: (andb true true) = true.\nProof. simpl. reflexivity. Qed.\n\n(*\nBoolean \"or\".\n\nGiven two boolean values, a and b, orb returns true if either value is true\nor false otherwise.\n\nTheorem:\n  If a is true, then orb is true and no further evaluation needs to be done.\n\n  Otherwise, if a is false, the value of the or is dependent on b: if b is\n  false, the outcome is false as this implies both a and b are false. Otherwise,\n  the outcome is true.\n*)  \n\nDefinition orb (a:bool) (b:bool) : bool :=\n  match a with\n    | false => b\n    | true => true\n  end.\n\nExample test_orb_ff: (orb false false) = false.\nProof. reflexivity. Qed.\nExample test_orb_ft: (orb false true) = true.\nProof. reflexivity. Qed.\nExample test_orb_tf: (orb true false) = true.\nProof. reflexivity. Qed.\nExample test_orb_tt: (orb true true) = true.\nProof. reflexivity. Qed.\n\n(*\nExercise: 1 star (nandb)\nComplete the definition of the following function, then make sure that the\nExample assertions below can each be verified by Coq.\n *)\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n    | false => true\n    | true => negb b2\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. reflexivity. Qed.\n\n(*\nDo the same for the andb3 function below. This function should return true\nwhen all of its inputs are true, and false otherwise. \n *)\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (andb (andb b1 b2) b3).\n\nExample test_andb31: (andb3 true true true) = true.\nProof. 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(* proving the involution of the boolean negation *)\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  reflexivity. reflexivity.\nQed.\n\n(*\nExercise: 2 stars (boolean functions)\nUse the tactics you have learned so far to prove the following theorem about boolean\nfunctions.\n *)\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f x b.\n  rewrite -> x.\n  rewrite -> x.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\n(*\nNow state and prove a theorem negation_fn_applied_twice similar to the previous one\nbut where the second hypothesis says that the function f has the property that\nf x = negb x.\n *)\n\nTheorem identity_fn_applied_twice_neg :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = negb x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f x b.\n  rewrite -> x.\n  rewrite -> x.\n  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\n(*\nExercise: 2 stars (andb_eq_orb)\nProve the following theorem. (You may want to first prove a subsidiary lemma or two.)\n *)\n\nTheorem andb_eq_orb :\n  forall(b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros b c.\n  destruct b. destruct c.\n  reflexivity. simpl.\n  intros H1. rewrite H1.\n  reflexivity. simpl.\n  destruct c. intros H2. rewrite H2. reflexivity. reflexivity.\nQed.\n", "meta": {"author": "kisom", "repo": "sf", "sha": "36ec076f140a79a382f298b277f19d4d9dc236a2", "save_path": "github-repos/coq/kisom-sf", "path": "github-repos/coq/kisom-sf/sf-36ec076f140a79a382f298b277f19d4d9dc236a2/basics/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210671, "lm_q2_score": 0.8918110454379296, "lm_q1q2_score": 0.8231765239861268}}
{"text": "Require Import Coq.Program.Tactics.\n\nModule Type Monoid.\n  Parameter M: Type.\n  Parameter e: M.\n  Parameter mult: M -> M -> M.\n  Axiom mult_e_l:\n    forall x, mult e x = x.\n  Axiom mult_e_r:\n    forall x, mult x e = x.\n  Axiom mult_assoc:\n    forall x y z, mult x (mult y z) = mult (mult x y) z.\nEnd Monoid.\n\nModule list_bool_Monoid <: Monoid.\n  Definition M := list bool.\n  Definition e: M := nil.\n  Definition mult x y: M := app x y.\n  Proposition mult_e_l:\n    forall x, mult e x = x.\n    auto.\n  Qed.\n  Proposition mult_e_r:\n    forall x, mult x e = x.\n    induction x; auto.\n    unfold mult.\n    simpl.\n    unfold mult in IHx.\n    rewrite IHx.\n    reflexivity.\n  Qed.\n  Proposition mult_assoc:\n    forall x y z, mult x (mult y z) = mult (mult x y) z.\n    Require Import List.\n    apply app_assoc.\n  Qed.\nEnd list_bool_Monoid.\n\nPrint Monoid.\nPrint list_bool_Monoid.\n\nModule MonoidExponential (M: Monoid).\n  Fixpoint exp (x: M.M) (n: nat): M.M :=\n    match n with \n    | 0 => M.e\n    | S n' => M.mult x (exp x n')\n    end.\n  Proposition exp_law:\n    forall n m x, M.mult (exp x n) (exp x m) = exp x (n + m).\n  induction n.\n  simpl.\n  intros.\n  rewrite M.mult_e_l.\n  auto.\n  (* step *)\n  simpl.\n  intros.\n  rewrite <- M.mult_assoc.\n  rewrite IHn.\n  auto.\n  Qed.\nEnd MonoidExponential.\n\nModule list_bool_Exponential.\n  Include list_bool_Monoid.\n  Include MonoidExponential list_bool_Monoid.\nEnd list_bool_Exponential.\n\n", "meta": {"author": "koba-e964", "repo": "coqworks", "sha": "d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c", "save_path": "github-repos/coq/koba-e964-coqworks", "path": "github-repos/coq/koba-e964-coqworks/coqworks-d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c/coqex7/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8230496676059006}}
{"text": "Theorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\n  Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\n  Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  induction m.\n  reflexivity.\n  simpl.\n  rewrite <- IHm.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  rewrite -> plus_n_Sm.\n  reflexivity.\n  Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\n  Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  rewrite -> plus_n_Sm with n n.\n  reflexivity.\n  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\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  induction n.\n  reflexivity.\n  rewrite -> IHn.\n  assert(H: forall a : bool, a = negb (negb a)).\n  {\n    intros [].\n    reflexivity.\n    reflexivity.\n  }\n  rewrite <- H.\n  simpl.\n  reflexivity.\n  Qed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  assert(p + n = n + p).\n  {\n    rewrite -> plus_comm.\n    reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem mult_dist : forall n m p : nat,\n  p * (n + m) = p * n + p * m.\nProof.\n  intros n m p.\n  induction p.\n  reflexivity.\n  simpl.\n  rewrite -> IHp.\n  simpl.\n  rewrite -> plus_assoc with (n + m) (p * n) (p * m).\n  rewrite -> plus_assoc with (n + p * n) m (p * m).\n  rewrite <- plus_assoc with n (p * n) m.\n  rewrite -> plus_comm with (p * n) m.\n  rewrite -> plus_assoc with n m (p * n).\n  reflexivity.\n  Qed.\n\nLemma mult_one_same : forall n : nat,\n  n * 1 = n.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\n  Qed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\n  simpl.\n  rewrite -> IHm.\n  assert (H : n + n * m = n * 1 + n * m).\n  {\n    rewrite -> mult_one_same with n.\n    reflexivity.\n  }\n  rewrite -> H.\n  rewrite <- mult_dist with 1 m n.\n  simpl.\n  reflexivity.\n  Qed.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nTheorem leb_refl : forall n:nat,\n  true = (n <=? n).\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\n  Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  0 =? (S n) = false.\nProof.\n  induction n.\n  reflexivity.\n  reflexivity.\n  Qed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros [].\n  reflexivity.\n  reflexivity.\n  Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n  intros n m p.\n  intros H.\n  induction p.\n  - simpl. rewrite -> H. reflexivity.\n  - simpl. rewrite -> IHp. reflexivity.\n  Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  (S n) =? 0 = false.\nProof.\n  reflexivity.\n  Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  intros n.\n  simpl.\n  rewrite -> plus_comm with n 0.\n  reflexivity.\n  Qed.\n\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n               (negb c))\n  = true.\nProof.\n  intros [] [].\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  rewrite -> mult_comm with (n + m) p.\n  rewrite -> mult_comm with n p.\n  rewrite -> mult_comm with m p.\n  rewrite -> mult_dist with n m p.\n  reflexivity.\n  Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  rewrite -> mult_plus_distr_r with m (n * m) p.\n  reflexivity.\n  Qed.\n\nTheorem eqb_refl : forall n : nat,\n  true = (n =? n).\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\n  Qed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  replace (p + n) with (n + p).\n  reflexivity.\n  rewrite -> plus_comm.\n  reflexivity.\n  Qed.\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (m:bin) : bin :=\n  match m with\n  | Z => B Z\n  | A n => B n\n  | B n => A (incr n)\n  end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  | Z => O\n  | A n => 2 * bin_to_nat n\n  | B n => 1 + 2 * bin_to_nat n\n  end.\n\nTheorem bin_to_nat_pres_incr : forall (b : bin),\n  bin_to_nat (incr b) = S (bin_to_nat b).\nProof.\n  induction b.\n  reflexivity.\n  reflexivity.\n  simpl.\n  rewrite -> IHb.\n  simpl.\n  rewrite <- plus_n_Sm.\n  reflexivity.\n  Qed.\n\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with\n  | O => Z\n  | S n' => incr(nat_to_bin n')\n  end.\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> bin_to_nat_pres_incr with (nat_to_bin n).\n  rewrite -> IHn.\n  reflexivity.\n  Qed.\n", "meta": {"author": "akemimadoka", "repo": "software-foundations-exercises", "sha": "5acc814e7f0653de0d2e7bddaa7b8d34046821ec", "save_path": "github-repos/coq/akemimadoka-software-foundations-exercises", "path": "github-repos/coq/akemimadoka-software-foundations-exercises/software-foundations-exercises-5acc814e7f0653de0d2e7bddaa7b8d34046821ec/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8230125216805396}}
{"text": "Fixpoint plus (n:nat) (m:nat) :=\n  match n with\n  | O => m\n  | S n1 => S (plus n1 m)\n  end.\n\nExample test_plus_1: (plus (S O) (S O)) = (S (S O)).\nProof. simpl. reflexivity. Qed.\nExample test_plus_2: (plus O O) = O.\nProof. simpl. reflexivity. Qed.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n1 => plus m (mult n1 m) \n  end.\n\nExample test_mult_0: (mult O O) = O.\nProof. simpl. reflexivity. Qed.\nExample test_mult_1: (mult (S (S O)) (S (S O))) = (S (S (S (S O)))).\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m : nat) : nat :=\n  match n,m with\n  | O, _ => O\n  | n1, O => n1\n  | S n1, S m1 => minus n1 m1\n  end.\n\nExample test_minus_0: (minus O O) = O.\nProof. simpl. reflexivity. Qed.\n\nExample test_minus_1: (minus (S O) O) = S O.\nProof. simpl. reflexivity. Qed.\n\nExample test_minus_2: (minus (S (S O)) (S O)) = (S O).\nProof. simpl. reflexivity. Qed.\n\nExample test_minus_3: (minus O (S O)) = O.\nProof. simpl. reflexivity. Qed.\n\nExample test_minus_4: (minus (S (S O)) (S (S (S O)))) = O.\nProof. simpl. reflexivity. Qed.\n\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S power' => mult base (exp base power')\n  end.\n\nExample test_exp_1: (exp (S O) O) = S O.\nProof. simpl. reflexivity. Qed.\n\nExample test_exp_2: (exp (S (S O)) (S (S O))) = (S (S (S (S O)))).\nProof. simpl. reflexivity. Qed.\n\nInfix \"*\" := mult.\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => S O\n  | S n1 => n * fact n1\n  end.\n\nExample test_fact_1: (fact O) = (S O).\nProof. simpl. reflexivity. Qed.\n\nExample test_fact_2: (fact (S (S (S O)))) = (S (S (S (S (S (S O)))))).\nProof. simpl. reflexivity. Qed.\n\nExample test_fact_3: (fact (S O)) = (S O).\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial1: (fact 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_fact4: (fact 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\n\nFixpoint beq_nat (n m : nat) : bool := \n  match n, m with\n  | O, O => true\n  | S _, O => false\n  | O, S _ => false\n  | S n1, S m1 => beq_nat n1 m1\n  end.\n\nExample test_beq_nat1: (beq_nat 4 3) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_nat2: (beq_nat 3 3) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_nat3: (beq_nat 2 3) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint leq_nat (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | S _, O => false\n  | O, S _ => true\n  | S n1, S m1 => leq_nat n1 m1\n  end.\n\n\nExample test_leq_nat1: (leq_nat 4 3) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_leq_nat2: (leq_nat 3 3) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_leq_nat3: (leq_nat 2 3) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n  match (beq_nat n m) with\n  | true => false\n  | false => leq_nat n m\n  end.\n\nExample test_blt_nat1: (blt_nat 4 3) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat2: (blt_nat 3 3) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat3: (blt_nat 2 3) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat4: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat5: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat6: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition admit {T: Type} : T.  Admitted.\n\n\nTheorem plus_O_n : forall n : nat, (0 + n) = n.\nProof.\n  intros n. \n  reflexivity.  \nQed.\n\n\nTheorem plus_id_n_m : forall n m : nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  (* move n and m into the context *)\n  intros n m.\n  (* move the hypotesis into the context *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> \n  m = o -> \n  n + m = m + o.\nProof.\n  intros n m o.\n  intros H1.\n  intros H2.\n\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity.\n Qed.\n\nTheorem mult_0_plus: forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem plus_S_n : forall n : nat,\n  (1 + n) = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem mult_S_1: forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H1.\n  rewrite -> plus_S_n.\n  rewrite -> H1.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\nQed.\n\nTheorem andb_two_equals : forall b c : bool,\n  b = true ->\n  c = true ->\n  andb b c = true.\nProof.\n  intros b c.\n  intros H1.\n  intros H2.\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n  reflexivity.\n  rewrite <- H.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice: \n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n intros f x b.\n destruct b.\n rewrite -> x.\n rewrite -> x.\n reflexivity.\n rewrite -> x.\n rewrite -> x.\n reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice:\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = negb x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f x b.\n  destruct b.\n  rewrite -> x.\n  rewrite -> x.\n  reflexivity.\n  rewrite -> x.\n  rewrite -> x.\n  reflexivity.\nQed.\n  \nTheorem identity_fn_applied_twice': \n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n intros f H b.\n rewrite -> H.\n rewrite -> H.\n reflexivity.\n \nQed.\n\nTheorem identity_fn_applied_twice'' : \n  forall (f : bool -> bool),\n    (forall (x : bool), f x = x) -> forall (b : bool), f (f b) = b.\nProof.\n  intros f H b. (* Introduce our parameters *)\n  rewrite -> H.\n  apply H.\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,c;\n  intro H;\n  inversion H.\n  inversion H.\n  reflexivity.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | T : bin\n  | O : bin -> bin\n  | S : bin -> bin.\n\nExample construct: (S (S (S (S (O (S (S (O (S T))))))))) = (S (S (S (S (O (S (S (O (S T))))))))).\nProof. simpl. reflexivity. Qed.\n\nFixpoint incr (b : bin) : bin :=\n  match b with\n  | T => T\n  | S T => S (O T)\n  | O T => (S T)\n  | S n => S (incr n)\n  | O n => O (incr n)\n  end. \n\nExample zero_inc: incr (O T) = (S T).\nProof. reflexivity. Qed.\n\nExample one_inc: incr (S T) = (S (O T)).\nProof. reflexivity. Qed.\n\nExample two_inc: incr (S (O T)) = (S (S T)).\nProof. simpl. reflexivity. Qed.\n\nExample ten_inc: incr (S (O (S (O T)))) = (S (O (S (S T)))).\nProof. simpl. reflexivity. Qed.\n\nFixpoint bin_length (b : bin) : nat :=\n  match b with\n   | T => 0\n   | O n => 1 + (bin_length n)\n   | S n => 1 + (bin_length n)\n  end.\n\nExample bin_length_0: bin_length T = 0.\nProof. simpl. reflexivity. Qed.\n\nExample bin_length_1: bin_length (S T) = 1.\nProof. simpl. reflexivity. Qed.\n\nExample bin_length_3: bin_length (S (O (S T))) = 3.\nProof. simpl. reflexivity. Qed.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n   | T => 0\n   | S n => 1 * (exp 2 (bin_length n)) + (bin_to_nat n)\n   | O n => 0 + (bin_to_nat n)\n  end.\n\nExample bin_to_nat_110: bin_to_nat (S (S (O T))) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample bin_to_nat_11: bin_to_nat (S (S T)) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample bin_to_nat_incr: bin_to_nat (incr (S (S (O T)))) = 6+1.\nProof. simpl. reflexivity. Qed.\n\nInductive bin' : Type :=\n  | Z : bin'\n  | D : bin' -> bin'\n  | F : bin' -> bin'.\n\nFixpoint incr' (b: bin') : bin' :=\n  match b with\n    | Z => F Z\n    | D b' => F b'\n    | F b' => D (incr' b')\n  end.\n\nFixpoint bin_to_nat' (b: bin') : nat :=\n  match b with\n    | Z => 0\n    | D b' => 2 * (bin_to_nat' b')\n    | F b' => 1 + 2 * (bin_to_nat' b')\n  end.\n", "meta": {"author": "avatar29A", "repo": "SoftwareFoundationSolutions", "sha": "c8f6ab5a6a6ead61668ee800e49e578f303bf473", "save_path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions", "path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions/SoftwareFoundationSolutions-c8f6ab5a6a6ead61668ee800e49e578f303bf473/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.823012520071405}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** ** Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros. induction n as [| n'].\n  Case \"n = 0\". simpl. apply ev_0.\n  Case \"n = S n'\". simpl. apply ev_SS.\n  apply IHn'.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* No, induction is needed on [E]*)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* Induction was attempted on the n as opposed to the E. *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n   intros. induction H as [| n'].\n   Case \"H = 0\". apply H0.\n   Case \"H = ev_SS\". apply ev_SS. apply IHev.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* 3 + 5, 5 + 3, 8 + 0, 0 + 8\n   4 ways*)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. simpl.\n  apply b_sum.\n  apply H.\n  apply b_sum.\n  apply H.\n  apply b_0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   intros. induction m as [| m'].\n   Case \"m = 0\". simpl. apply b_0.\n   Case \"m = S m'\". simpl. apply b_sum.\n     apply H.\n     apply IHm'.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* [gorgeous] is any sum of any [gorgeous] numbers*)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n   intros. \n   apply g_plus5.\n   apply g_plus5.\n   apply g_plus3.\n   apply H.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros. induction H as [|n' |n'].\n  Case \"n = 0\". apply H0.\n  Case \"n = 3 + n'\". apply g_plus3. apply IHgorgeous.\n  Case \"m = 5 + n'\". apply g_plus5. apply IHgorgeous.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n intros. induction H as [|n' |n' |n'].\n Case \"0\". apply g_0.\n Case \"3\". apply g_plus3. apply g_0.\n Case \"5\". apply g_plus5. apply g_0.\n Case \"n\". apply gorgeous_sum.\n   SCase \"n'\". apply IHbeautiful1.\n   SCase \"m\". apply IHbeautiful2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   (* 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\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n  \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. inversion H. inversion H1. inversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros. induction H0.\n  simpl in H. apply H.\n  apply IHev. inversion H. apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X:Type} : (list X) -> Prop :=\n  |p_nil : pal[]\n  |p_one : forall x, pal [x]\n  |p_cons : forall x l, pal l -> pal (x :: snoc l x).\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(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\nInductive added_up : nat -> nat -> nat -> Prop :=\n  ad : forall n m : nat, added_up n m (n + m).\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\nInductive subbed_wrong : nat -> nat -> Prop :=\n  sb : forall n:nat, subbed_wrong n (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\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if oddb n then Podd n else Peven n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros. unfold combine_odd_even.\n  destruct (oddb n).\n  apply H. reflexivity.\n  apply H0. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros. unfold combine_odd_even in H.\n  rewrite H0 in H. apply H.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros. unfold combine_odd_even in H.\n  rewrite H0 in H. apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "Morales-BA", "repo": "csSoftFound_moralesb", "sha": "088c0f5780132649652593fdc3bee4766f011588", "save_path": "github-repos/coq/Morales-BA-csSoftFound_moralesb", "path": "github-repos/coq/Morales-BA-csSoftFound_moralesb/csSoftFound_moralesb-088c0f5780132649652593fdc3bee4766f011588/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8872045974451017, "lm_q1q2_score": 0.8227609793996074}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 3 *)\n\nRequire Import Frap.\n\n(* In this problem set, we'll get some experience with higher-order functions,\n * which are functions that themselves take functions as arguments!\n *)\n\n(*\n * First, we'll reproduce some definitions we need from Lecture 2,\n * [tree] and [flatten]:\n *)\n\nInductive tree {A} :=\n| Leaf\n| Node (l : tree) (d : A) (r : tree).\nArguments tree : clear implicits.\n\nFixpoint flatten {A} (t : tree A) : list A :=\n  match t with\n  | Leaf => []\n  | Node l d r => flatten l ++ d :: flatten r\n  end.\n\nModule Type S.\n\n  (* Define the identity function [id], which just returns its\n   * argument without modification.\n   *)\n  Parameter id : forall {A : Type}, A -> A.\n\n  (* [compose] is another higher-order function: [compose g f]\n   * applies [f] to its input and then applies [g]. Argument order\n   * follows the general convention of functional composition in\n   * mathematics denoted by the small circle.\n   *)\n  Parameter compose : forall {A B C : Type}, (B -> C) -> (A -> B) -> A -> C.\n\n  (* If we map the [id] function over any list, we get the\n   * same list back.\n   *)\n  Axiom map_id : forall {A : Type} (xs : list A),\n    map id xs = xs.\n\n  (* If we map the composition of two functions over the list,\n   * it's the same as mapping the first function over the whole list\n   * and then mapping the second function over that resulting list.\n   *)\n  Axiom map_compose : forall {A B C : Type} (g : B -> C) (f : A -> B)\n                             (xs : list A),\n    map (compose g f) xs = map g (map f xs).\n\n  (* Next we can show some classic properties that demonstrate a\n   * certain sense in which [map] only modifies the elements of\n   * a list but preserves its structure: [map_length] shows it \n   * preserves length, and [map_append] and [map_rev] show that\n   * it commutes with [++] and [rev], respectively.\n   * For each of [length], [++], and [rev], it doesn't matter\n   * whether we apply [map] before the operation or after.\n   *)\n  Axiom map_length : forall {A B : Type} (f : A -> B) (xs : list A),\n    length (map f xs) = length xs.\n\n  Axiom map_append : forall {A B : Type} (f : A -> B) (xs ys : list A),\n    map f (xs ++ ys) = map f xs ++ map f ys.\n\n  Axiom map_rev : forall {A B : Type} (f : A -> B) (xs : list A),\n    map f (rev xs) = rev (map f xs).\n\n  (* [fold] is a higher-order function that is even more general\n   * than [map]. In essence, [fold f z] takes as input a list\n   * and produces a term where the [cons] constructor is\n   * replaced by [f] and the [nil] constructor is replaced\n   * by [z].\n   *\n   * [fold] is a \"right\" fold, which associates the binary operation\n   * the opposite way as the [fold_left] function that we defined\n   * in lecture.\n   *)\n  Parameter fold : forall {A B : Type}, (A -> B -> B) -> B -> list A -> B.\n\n  (* For instance, we should have\n       fold plus 10 [1; 2; 3]\n     = 1 + (2 + (3 + 10))\n     = 16\n   *)\n  Axiom fold_example : fold plus 10 [1; 2; 3] = 16.\n\n  (* Prove that [map] can actually be defined as a particular\n   * sort of [fold].\n   *)\n  Axiom map_is_fold : forall {A B : Type} (f : A -> B) (xs : list A),\n    map f xs = fold (fun x ys => cons (f x) ys) nil xs.\n\n  (* Since [fold f z] replaces [cons] with [f] and [nil] with\n   * [z], [fold cons nil] should be the identity function.\n   *)\n  Axiom fold_id : forall {A : Type} (xs : list A),\n    fold cons nil xs = xs.\n\n  (* If we apply [fold] to the concatenation of two lists,\n   * it is the same as folding the \"right\" list, and using\n   * that as the starting point for folding the \"left\" list.\n   *)\n  Axiom fold_append : forall {A : Type} (f : A -> A -> A) (z : A)\n                        (xs ys : list A),\n    fold f z (xs ++ ys) =\n    fold f (fold f z ys) xs.\n\n  (* Using [fold], define a function that computes the\n   * sum of a list of natural numbers.\n   *)\n  Parameter sum : list nat -> nat.\n\n  (* Note that [simplify] fails to reduce [ sum [1; 2; 3] ].\n   * This is due to a quirk of [simplify]'s behavior: because\n   * unfolding [sum] does not present an immediate opportunity\n   * for reduction (since [fold] will still need to be unfolded\n   * to its fixpoint definition, no simplification is performed).\n   * A simple remedy is to use the tactic [unfold sum] prior to\n   * calling [simplify]. This should come in handy for future proofs\n   * involving definitions that use [fold], too.\n   *)\n  Axiom sum_example : sum [1; 2; 3] = 6.\n  \n  (* Using [fold], define a function that computes the\n   * conjunction of a list of Booleans (where the 0-ary\n   * conjunction is defined as [true]).\n   *)\n  Parameter all : list bool -> bool.\n\n  Axiom all_example : all [true; false; true] = false.\n\n  (* The following two theorems, [sum_append] and [all_append],\n   * say that the sum of the concatenation of two lists\n   * is the same as summing each of the lists first and then\n   * adding the result.\n   *)\n  Axiom sum_append : forall (xs ys : list nat),\n      sum (xs ++ ys) = sum xs + sum ys.\n\n  Axiom all_append : forall (xs ys : list bool),\n      all (xs ++ ys) = andb (all xs) (all ys).\n\n  (* Just like we defined [map] for lists, we can similarly define\n   * a higher-order function [tree_map] which applies a function on\n   * elements to all of the elements in the tree, leaving the tree\n   * structure intact.\n   *)\n  Parameter tree_map : forall {A B : Type}, (A -> B) -> tree A -> tree B.\n\n  Axiom tree_map_example :\n    tree_map (fun x => x + 1) (Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 (Node Leaf 4 Leaf)))\n    = (Node (Node Leaf 2 Leaf) 3 (Node Leaf 4 (Node Leaf 5 Leaf))).\n\n  (* [tree_map_flatten] shows that [map]\n   * and [tree_map] are related by the [flatten] function.\n   *)\n  Axiom tree_map_flatten : forall {A B : Type} (f : A -> B) (t : tree A),\n      flatten (tree_map f t) = map f (flatten t).\n\n  (* Using [fold], define a function that composes a list of functions,\n   * applying the *last* function in the list *first*.\n   *)\n  Parameter compose_list : forall {A : Type}, list (A -> A) -> A -> A.\n\n  Axiom compose_list_example :\n    compose_list [fun x => x + 1; fun x => x * 2; fun x => x + 2] 1 = 7.\n\n  (* Show that [sum xs] is the same as converting each number\n   * in the list [xs] to a function that adds that number,\n   * composing all of those functions together, and finally\n   * applying that large composed function to [0].\n   * Note that function [plus], when applied to just one number as an\n   * argument, returns a function over another number, which\n   * adds the original argument to it!\n   *)\n  Axiom compose_list_map_add_sum : forall (xs : list nat),\n    compose_list (map plus xs) 0 = sum xs.\n  \nEnd S.\n\n(* The template file Pset3.v also suggests some additional challenge problems,\n * which won't be graded but which provide extra practice with higher-order\n * functions. In these problems, you will implement the \"continuation monad\"\n * and prove a property about it.\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/pset3/Pset3Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8991213725394588, "lm_q1q2_score": 0.8226070107359654}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives.\n\n*)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions \n    ([forall x, P]).  \n*)\n\n\n(** In Coq, the type of things that can (potentially) \n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated \n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P]. \n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.  \nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on\nequality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat \n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that\ntakes evidence for [P] as input and produces evidence for [Q] as its\noutput.\n*)     \n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?  \n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other\n      datatype.\n\n    - Sometimes a proposition is declared to be true without\n      substantiating evidence.  Such propositions are called _axioms_.\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" conjunctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [destruct] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof. \n  intros P Q H.\n  destruct H as [\u03c01 \u03c02].\n  apply \u03c02.\nQed.\n  \n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  destruct H as [HP HQ]. \n  split.  \n    Case \"left\". apply HQ. \n    Case \"right\". apply HP.  Qed.\n  \n\n(** **** Exercise: 2 stars (and_assoc)  *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [destruct] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  destruct H as [HP [HQ HR]].\n  split. \n  split.\n  apply HP.\n  apply HQ.\n  apply HR.\nQed.\n\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) \n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  destruct H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  destruct H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  intro p.\n  split.\n  apply self_implication.\n  apply self_implication.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R bi1 bi2.\n  inversion bi1 as [PQ QP].\n  inversion bi2 as [QR RQ].\n  split.\n  intro HP. apply PQ in HP. apply QR in HP. apply HP.\n  intro HR. apply RQ in HR. apply QP in HR. apply HR.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [destruct] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. destruct H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2)  *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H. destruct H as [[HP0 | HQ] [HP1 | HR]].\n  left. apply HP0.\n  left. apply HP0.\n  left. apply HP1.\n  right. split. apply HQ. apply HR.\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  intros. \n  split. \n  apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\nQed.\n\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct H.\n  rewrite H. rewrite H0. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (andb_false)  *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  intros b c H.\n  destruct b,c.\n  inversion H.\n  right. reflexivity.\n  left. reflexivity.\n  left. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false)  *)\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b, c.\n  left. reflexivity.\n  left. reflexivity.\n  right. reflexivity.\n  inversion H.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false_elim)  *)\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  split.\n    destruct b. inversion H.\n                      reflexivity.\n    destruct c. destruct b. inversion H.\n                                       inversion H.\n                      reflexivity.\nQed.\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True)  *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := \n  Truth : True.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. destruct H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n   \n  By definition of P this is the same thing as proving\n    P -> ( P -> False) -> False\n    \n    By introducting P and applying it in P -> False, we have the hypothesis False from which we can prove anything.\n*)\n\n(** **** Exercise: 2 stars (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not. intros.\n  apply H in H1. apply H0 in H1. inversion H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  unfold not. \n  intros.\n  apply contradiction_implies_anything with (Q := False) in H.\n  apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(**\n  We can unfold the proposition into (P /\\ ~P) -> False\n  from  the Hypthesis we can conclude False by contradiction_implies_anything.\n  \n*)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [~P] \n     from evidence for [P]. *) \n  Abort.\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := forall P:Prop, \n  P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop, \n  ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop, \n  (P->Q) -> (~P\\/Q).\n  \nTheorem excluded_middle_classic: excluded_middle <-> classic.\n  Proof. \n  unfold classic.\n  unfold excluded_middle.\n  split. \n    intros. \n    destruct H with (P := P) as [PT | PF]. apply PT. \n                                                               apply H0 in PF. inversion PF.\n   unfold not. intros. apply H. intros. apply H0. left. intros. apply H. intros. apply H0. right. apply H1.\nQed.\n   \nTheorem peirce_excluded_middle : peirce <-> excluded_middle.\n  unfold peirce.\n  unfold excluded_middle.\n  split.\n    intros. apply H with (Q := False). intros. right. unfold not. intros. apply H0. left. apply H1.\n    intros EXC P. destruct EXC with (P := P) as [PT | PF]. intros. apply PT.\n                                                                                          intros. apply H. intros. apply PF in H0. inversion H0.\nQed.\n\nTheorem classic_de_morgan : classic <-> de_morgan_not_and_not.\nProof.\n  unfold classic.\n  unfold de_morgan_not_and_not.\n  split.\n  \n  unfold not. intros CLS P.\n    intros Q DMG. apply CLS. intros PDQ.  destruct DMG. split.\n           intro H. apply PDQ. left. apply H. \n           intro H. apply PDQ. right. apply H.\n  unfold not. intros DMG P NNP. destruct DMG with (P := P) (Q := P). intros H. destruct H as [H _].  apply NNP. apply H. apply H. apply H.\nQed.\n\nTheorem excluded_middle_implies_to_or : excluded_middle <-> implies_to_or.\nProof.\n  unfold excluded_middle.\n  unfold implies_to_or.\n  unfold not.\n  split.\n  intros EXC P Q PQ. destruct EXC with (P := P) as [PT | PF]. \n                                   right. apply PQ. apply PT. \n                                   left. apply PF.\n intros IMP P. apply or_commut. apply IMP. intro H. apply H.\nQed.\n  \n(** [] *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).  \nProof.\n  unfold not.\n  intros P H.\n  apply H.\n  right.\n  intro HP.\n  apply H.\n  left.\n  apply HP.\nQed.\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n    \nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** **** Exercise: 2 stars (false_beq_nat)  *)\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof. \n  intros n m Hnm.\n  destruct (beq_nat n m) eqn:eq.\n    unfold not in Hnm.\n    apply ex_falso_quodlibet.\n    apply Hnm.\n    apply beq_nat_true in eq.\n    apply eq.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_false)  *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  unfold not.\n  intros n m H0.\n  destruct (beq_nat n m) eqn:eq.\n    inversion H0.\n    intro H1. rewrite H1 in eq. rewrite <- beq_nat_refl in eq. inversion eq.\nQed.\n\n  \n(** [] *)\n\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "michaelblack", "repo": "SoftwareFoundations", "sha": "e49e488c443db95a95be2a564e559d29b6e5099f", "save_path": "github-repos/coq/michaelblack-SoftwareFoundations", "path": "github-repos/coq/michaelblack-SoftwareFoundations/SoftwareFoundations-e49e488c443db95a95be2a564e559d29b6e5099f/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.930458255976267, "lm_q1q2_score": 0.8225616426225462}}
{"text": "(* week_38b_induction.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Working file. *)\n\n(* ********** *)\n\nRequire Import Arith.\n\n(* ********** *)\n\nCheck nat_ind.\n(*\nnat_ind : forall P : nat -> Prop,\n            P 0 ->\n            (forall n : nat,\n               P n -> P (S n)) ->\n            forall n : nat,\n              P n\n*)\n\n(* ********** *)\n\n(* An induction principle with two steps\n   instead of one:\n*)\n\nLemma nat_ind2 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_P1 H_PSS n.\n  assert (consecutive :\n    forall x : nat,\n      P x /\\ P (S x)).\n    intro x.\n    induction x as [ | x' [IHx' IHSx']].\n\n    split.\n      exact H_P0.\n    exact H_P1.\n\n    split.\n      exact IHSx'.\n    exact (H_PSS x' IHx' IHSx').\n\n  destruct (consecutive n) as [ly _].\n  exact ly.\nQed.\n\n(* ********** *)\n\n(* Let us revisit evenp: *)\n\nDefinition specification_of_evenp (evenp : nat -> bool) :=\n  (evenp 0 = true)\n  /\\\n  (evenp 1 = false)\n  /\\\n  (forall n'' : nat,\n     evenp (S (S n'')) = evenp n'').\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_evenp :\n  forall f g : nat -> bool,\n    specification_of_evenp f ->\n    specification_of_evenp g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_evenp.\n  intros [Hf_0 [Hf_1 Hf_ij]] [Hg_0 [Hg_1 Hg_ij]] n.\n(* We could write\n     apply (nat_ind2 ... ... ... ... n).\n   but that would be notationally daunting.\n*)\n  induction n as [ | | n' IH_n' IH_Sn'] using nat_ind2.  \n\n  rewrite -> Hf_0.\n  rewrite -> Hg_0.\n  reflexivity.\n\n  rewrite -> Hf_1.\n  rewrite -> Hg_1.\n  reflexivity.\n\n  rewrite -> Hf_ij.\n  rewrite -> Hg_ij.\n  exact IH_n'.\nQed.\n\n(* ********** *)\n\n(* Let us revisit fibonacci: *)\n\nDefinition specification_of_the_fibonacci_function (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  forall n'' : nat,\n    fib (S (S n'')) = fib (S n'') + fib n''.\n\nTheorem there_is_only_one_fibonacci_function :\n  forall fib1 fib2 : nat -> nat,\n    specification_of_the_fibonacci_function fib1 ->\n    specification_of_the_fibonacci_function fib2 ->\n    forall n : nat,\n      fib1 n = fib2 n.\nProof.\n  intros fib1 fib2.\n  unfold specification_of_the_fibonacci_function.\n  intros [H_fib1_bc0 [H_fib1_bc1 H_fib1_ic]]\n         [H_fib2_bc0 [H_fib2_bc1 H_fib2_ic]].\n  intro n.\n  induction n as [ | | n' IH_n' IH_Sn'] using nat_ind2.\n      rewrite -> H_fib2_bc0.\n      exact H_fib1_bc0.\n    rewrite -> H_fib2_bc1.\n    exact H_fib1_bc1.\n  rewrite -> H_fib1_ic.\n  rewrite -> H_fib2_ic.\n  rewrite -> IH_n'.\n  rewrite -> IH_Sn'.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Let us revisit nat_ind: *)\n\nLemma nat_ind1 :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall i : nat,\n      P i -> P (S i)) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_bc H_ic n.\n  induction n as [ | | n'' IH_n'' IH_Sn''] using nat_ind2.\n\n  exact H_bc.\n\n  exact (H_ic 0 H_bc).\n\n  apply (H_ic (S n'') IH_Sn'').\n\n  Restart.\n  (* Replace \"Restart.\" with a proof. *)\n\n  intros P H_bc H_ic n.\n  induction n as [ | n' IHn'].\n\n  exact H_bc.\n\n  exact (H_ic n' IHn').\nQed.\n\n(* ********** *)\n\n(* Exercises:\n\n   (1) define nat_ind3 and\n       (a) prove it by induction\n       (b) prove it using nat_ind1\n       (c) prove it using nat_ind2\n\n   (2) using nat_ind3,\n       (a) prove nat_ind1\n       (b) prove nat_ind2\n*)\n\nLemma nat_ind3 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    P 2 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i)) -> P (S (S (S i)))) ->\n      forall n : nat,\n        P n.\nProof.\n  intros P H_P0 H_P1 H_P2 H_PSSS n.\n  assert (consecutive :\n    forall x : nat,\n      P x /\\ P (S x) /\\ P (S (S x))).\n    intro x.\n    induction x as [ | x' [IHx' [IHSx' IHSSx']]].\n      split.\n        exact H_P0.\n      split.\n        exact H_P1.\n      exact H_P2.\n    split.\n      exact IHSx'.\n    split.\n      exact IHSSx'.\n    apply (H_PSSS x' IHx' IHSx' IHSSx').\n  destruct (consecutive n) as [ly _].\n  exact ly.\n\n  Restart.\n\n  intros P H_P0 H_P1 H_P2 H_PSSS n.\n  assert (consecutive :\n    forall x : nat,\n      P x /\\ P (S x) /\\ P (S (S x))).\n    intro x.\n    induction x as [ | x' [IHx' [IHSx' IHSSx']]] using nat_ind1.\n      split.\n        exact H_P0.\n      split.\n        exact H_P1.\n      exact H_P2.\n    split.\n      exact IHSx'.\n    split.\n      exact IHSSx'.\n    apply (H_PSSS x' IHx' IHSx' IHSSx').\n  destruct (consecutive n) as [ly _].\n  exact ly.\n\n  Restart.\n\n  intros P H_P0 H_P1 H_P2 H_PSSS n.\n  assert (consecutive :\n    forall x : nat,\n      P x /\\ P (S x) /\\ P (S (S x))).\n    intro x.\n    induction x as [ | | x'' [IHx'' [IHSx'' IHSSx'']] [_ [_ IHSSSx'']]] using nat_ind2.\n        split.\n          exact H_P0.\n        split.\n          exact H_P1.\n        exact H_P2.\n      split.\n        exact H_P1.\n      split.\n        exact H_P2.\n      apply (H_PSSS 0 H_P0 H_P1 H_P2).\n    split.\n      exact IHSSx''.\n    split.\n      exact IHSSSx''.\n    apply (H_PSSS (S x'') IHSx'' IHSSx'' IHSSSx'').\n  destruct (consecutive n) as [ly _].\n  exact ly.\nQed.\n\nLemma nat_ind1_proved_using_nat_ind3 :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall i : nat,\n      P i -> P (S i)) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_PS.\n  induction n as [ | | | n''' _ _ IHSSn'''] using nat_ind3.\n        exact H_P0.\n      apply (H_PS 0 H_P0).\n    apply (H_PS (S 0) (H_PS 0 H_P0)).\n  apply (H_PS (S (S n''')) IHSSn''').\nQed.\n\nLemma nat_ind2_proved_using_nat_ind3 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_P1 H_PSS n.\n  assert (consecutive :\n    forall x : nat,\n      P x /\\ P (S x)).\n    intro x.\n    induction x as [ | | | x''' [IHx''' IHSx'''] [_ IHSSx'''] [_ IHSSSx''']] using nat_ind3.\n          split.\n            exact H_P0.\n          exact H_P1.\n        split.\n          exact H_P1.\n        apply (H_PSS 0 H_P0 H_P1).\n      split.\n        apply (H_PSS 0 H_P0 H_P1).\n      apply (H_PSS 1 H_P1 (H_PSS 0 H_P0 H_P1)).\n    split.\n      exact IHSSSx'''.\n    apply (H_PSS (S (S x''')) IHSSx''' IHSSSx''').\n  destruct (consecutive n) as [ly _].\n  exact ly.\n\n  Restart.\n\n  (* Hmm i guess i didn't need som of those assertions: *)\n  intros P H_P0 H_P1 H_PSS n.\n  induction n as [ | |\u00a0| n''' IHn''' IHSn''' IHSSn'''] using nat_ind3.\n        exact H_P0.\n      exact H_P1.\n    apply (H_PSS 0 H_P0 H_P1).\n  apply (H_PSS (S n''') IHSn''' IHSSn''').\n\nQed.\n\n(* ********** *)\n\n(* end of week_38b_induction.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w38/week_38b_Noergaard_Benjamin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.9207896829553821, "lm_q1q2_score": 0.8225500769356356}}
{"text": "(* by Evelyne Contejean *)\nSet Implicit Arguments. \n\nRequire Import Relations.\nRequire Import List.\n\nInductive trans_clos (A : Set) (R : relation A) : relation A:=\n  | t_step : forall x y, R x y -> trans_clos R x y\n  | t_trans : forall x y z, R x y -> trans_clos R y z -> trans_clos R x z.\n\nLemma trans_clos_is_trans :\n  forall (A :Set) (R : relation A) a b c, \n  trans_clos R a b -> trans_clos R b c -> trans_clos R a c.\nProof.\nintros A R a b c Hab; generalize c; clear c; induction Hab as [a b Hab | a b c Hab Hbc].\nintros c Hbc; apply t_trans with b; trivial.\nintros d Hcd; apply t_trans with b; trivial.\napply IHHbc; trivial.\nQed.\n\nLemma acc_trans :\n forall (A : Set) (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.\nQed.\n\nLemma wf_trans :\n  forall (A : Set) (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.\nQed.\n\nLemma inv_trans :\n  forall (A : Set) (R : relation A) (P : A -> Prop),\n  (forall a b, P a -> R a b -> P b) -> \n  forall a b, P a -> trans_clos R a b -> P b.\nProof.\nintros A R P Inv a b Pa a_Rp_b; induction a_Rp_b.\napply Inv with x; trivial.\napply IHa_Rp_b; apply Inv with x; trivial.\nQed.\n\n", "meta": {"author": "aarondroidbryce", "repo": "cyclic_peano", "sha": "fb0a713eb8ada20402c62a5953e1ccc800860605", "save_path": "github-repos/coq/aarondroidbryce-cyclic_peano", "path": "github-repos/coq/aarondroidbryce-cyclic_peano/cyclic_peano-fb0a713eb8ada20402c62a5953e1ccc800860605/theories/Casteran/closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8222280585454788}}
{"text": "Set Implicit Arguments.\nRequire Import ZArith.\n\nInductive plane : Set :=\n  | point : Z->Z-> plane.\n\nCheck plane_ind. \n(* forall P : plane -> Prop,\n   (forall x y : Z, P (point x y)) -> forall p : plane, P p\n*)\n\nDefinition plane_x (p:plane): Z := \n  match p with point x y => x end.\n\n\nDefinition plane_y (p:plane): Z := \n  match p with point x y => y end.\n\nReset plane.\nRecord plane : Set := point { point_x:Z ; point_y:Z }.\n\nPrint plane.\nPrint point_x.\n\nCheck Zabs_nat.\n\nDefinition manhattan_dist (p q: plane) : nat :=\n  Zabs_nat(point_x p - point_x q) +\n  Zabs_nat(point_y p - point_y q).\n\n\nInductive vehicle : Set :=\n  | bicycle : nat -> vehicle\n  | motorized : nat -> nat -> vehicle.\n\nCheck vehicle_ind.\n(*\nforall P : vehicle -> Prop,\n  (forall n : nat, P (bicycle n)) ->\n  (forall n n0 : nat, P (motorized n n0)) -> forall v : vehicle, P v\n*)\n\nDefinition nb_wheels (v:vehicle) : nat :=\n  match v with\n  | bicycle x     => 2\n  | motorized x n => n\n  end.\n\nDefinition nb_seats (v:vehicle) : nat :=\n  match v with\n  | bicycle x     => x\n  | motorized x _ => x\n  end.\n\nCheck vehicle_rec.\n(*\n forall P : vehicle -> Set,\n (forall n : nat, P (bicycle n)) ->\n (forall n n0 : nat, P (motorized n n0)) -> forall v : vehicle, P v\n*)\n\nDefinition nb_seats' := vehicle_rec (fun v => nat) (fun n => n) (fun n m => n).\n\nLemma Lemma_seats: forall v:vehicle, nb_seats v = nb_seats' v.\nProof.\n  intro v. pattern v. apply vehicle_ind. intro n. reflexivity. intros n m. reflexivity.\nQed.\n\nTheorem bicycle_not_motorized: forall n m p: nat, bicycle n <> motorized m p. \nProof.\n  intros n m p. unfold not. intro H. (* discriminate H. *)\n  pose (g:=fun (v:vehicle) => match v with bicycle x => True | motorized x y => False end).\n  change (g (motorized m p)). rewrite <- H. simpl. apply I.\nQed.\n\nTheorem bicycle_eq_seats: forall x y: nat, bicycle x = bicycle y -> x = y.\nProof.\n  intros x y H. change (x = nb_seats (bicycle y)). rewrite <- H. simpl. apply eq_refl.\nQed.\n\nTheorem bicycle_eq_seats': forall x y: nat, bicycle x = bicycle y -> x = y.\nProof.\n  intros x y H. injection H. trivial. \nQed.\n\nInductive south_west : plane -> plane -> Prop :=\n  south_west_def: \n    forall a1 a2 b1 b2:Z, (a1 <= b1)%Z -> (a2 <= b2)%Z ->\n      south_west (point a1 a2) (point b1 b2).\n\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/records.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.9046505440982948, "lm_q1q2_score": 0.8219816681219796}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export LF.Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    previous chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n   you read them in a .v file.  The inner brackets, around 3, indicate\n   a list, but the outer brackets, which are invisible in the HTML\n   rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  (* FILL IN HERE *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  (* FILL IN HERE *) Admitted.\n\nDefinition countoddmembers (l:natlist) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  (* FILL IN HERE *) Admitted.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n (* FILL IN HERE *) Admitted.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n (* FILL IN HERE *) Admitted.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n    all the elements of [a] and of [b].  (Mathematicians usually\n    define [union] on multisets a little bit differently, which\n    is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n (* FILL IN HERE *) Admitted.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_member1:             member 1 [1;4;1] = true.\n (* FILL IN HERE *) Admitted.\n\nExample test_member2:             member 2 [1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  (* FILL IN HERE *) Admitted.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  (* FILL IN HERE *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* FILL IN HERE *) Admitted.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* FILL IN HERE *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n (* FILL IN HERE *) Admitted.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommendedM (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the\n    \"scrutinee\" (the value being \"scrutinized\" by the match) in the\n    definition of [app], allowing the match itself to be\n    simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 starsM (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** There is a short solution to the next 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  (* FILL IN HERE *) Admitted.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n (* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\n(* FILL IN HERE *) Admitted.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n (* FILL IN HERE *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs)  *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optionalM (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it.  (You may\n    find that the difficulty of the proof depends on how you defined\n    [count]!) *)\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advancedM (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish.\n\n    We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 starsM (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?  (Answer in English\n    or the natural language of your choice.)\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** $Date: 2017-07-14 19:07:15 -0400 (Fri, 14 Jul 2017) $ *)\n\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/SF/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.9111797148356995, "lm_q1q2_score": 0.8218118248446075}}
{"text": "Require Import Bool List ZArith Arith.\nRequire Import CpdtTactics.\n\nInductive bit : Set :=\n| Zero\n| One.\n\nDefinition bitField := list bit.\n\nFixpoint numOnes (b : bitField) : nat :=\n  match b with\n    | nil => 0\n    | t :: rest =>\n      match t with\n        | Zero => numOnes rest\n        | One => 1 + (numOnes rest)\n      end\n  end.\n\nFixpoint numZeros (f : bitField) : nat :=\n  match f with\n    | nil => 0\n    | t :: rest =>\n      match t with\n        | Zero => 1 + (numZeros rest)\n        | One => numZeros rest\n      end\n  end.\n\nTheorem all_ones_or_zeros :\n  forall f : bitField, numOnes f + numZeros f = length f.\nProof.\n  intros; induction f.\n  simpl. reflexivity.\n\n  destruct a. simpl. rewrite plus_comm. rewrite -> plus_Sn_m.\n  rewrite plus_comm. apply eq_S. apply IHf.\n\n  simpl. rewrite -> IHf. reflexivity.\nQed.  \n\n(*eq_S: forall x y : nat, x = y -> S x = S y*)\n(*: forall n m : nat, S n + m = S (n + m)*)\n  SearchAbout (S _ = S _).\n\n(*crush.\n  simpl. crush.\nQed.*)\n\nTheorem num_ones_lte_bitField_length :\n  forall b : bitField, numOnes b <= (length b).\nProof.\n  intros b. induction b as [| b'].\n\n  simpl. reflexivity.\n\n  destruct b'.\n  simpl. rewrite IHb. apply le_n_Sn.\n\n  simpl. apply le_n_S. apply IHb.\nQed.\n\nFixpoint isZero (f : bitField) : bool :=\n  match f with\n    | nil => true\n    | Zero :: nil => true\n    | b :: f' =>\n      match b with\n        | Zero => isZero f'\n        | One => false\n      end\n  end.\n\n(*Lemma isZero_implies_all_zero :\n  forall f : bitField, isZero (Zero :: f) = true -> isZero f = true.\nProof.\n  intros. simpl isZero in H.\n  apply H.\nQed.*)\n\nLemma append_zero_gives_zero :\n  forall f : bitField, isZero (Zero :: f) = isZero f.\nProof.\n  intros.\n  simpl. destruct f; simpl; reflexivity.\nQed.\n\nLemma append_one_gives_non_zero : \n  forall f : bitField, isZero (One :: f) = false.\nProof.\n  intros. simpl; reflexivity.\nQed.\n\nTheorem isZero_correct :\n  forall f : bitField, (isZero f) = true -> numZeros f = length f.\nProof.\n  intros.\n  induction f. simpl. reflexivity.\n\n  destruct a.\n  simpl. rewrite append_zero_gives_zero in H.\n  apply eq_S. apply IHf in H. apply H.\n  discriminate.\nQed.\n\n(*  rewrite append_one_gives_non_zero in H.*)\n\nFixpoint halfAdd (carry left right : bit) : bitField :=\n  match numOnes (carry :: left :: right :: nil) with\n    | 0 => (Zero :: Zero :: nil)\n    | 1 => (One :: Zero :: nil)\n    | 2 => (Zero :: One :: nil)\n    | other => (One :: One :: nil)\n  end.\n\nTheorem halfAdd_possible_results :\n  forall c l r : bit, (halfAdd c l r) = (Zero :: Zero :: nil) \\/\n                      (halfAdd c l r) = (Zero :: One :: nil) \\/\n                      (halfAdd c l r) = (One :: Zero :: nil) \\/\n                      (halfAdd c l r) = (One :: One :: nil).\nProof.\n  intros c l r.\n  destruct c. destruct l. destruct r. simpl.\n  tauto. tauto.\n  destruct r. tauto. tauto.\n  destruct l. destruct r. tauto. tauto.\n  destruct r. tauto. tauto.\nQed.\n\n\nTheorem halfAdd_result_is_length_2 :\n  forall c l r : bit, length (halfAdd c l r) = 2.\nProof.\n  intros c l r.\n  pose proof halfAdd_possible_results as H.\n  specialize (H c l r).\n\n  inversion H.\n  rewrite H0.\n  simpl. reflexivity.\n\n  inversion H0.\n  rewrite H1. simpl. reflexivity.\n\n  inversion H1.\n  rewrite H2. simpl. reflexivity.\n\n  inversion H2.\n  rewrite H2. simpl. reflexivity.\nQed.\n\n\nOpen Scope Z_scope.\n\nFixpoint unsignedBitFieldToZRec (pow : Z) (f : bitField) : Z :=\n  match f with\n    | nil => 0\n    | b :: f' =>\n      match b with\n        | Zero => unsignedBitFieldToZRec (pow + 1) f'\n        | One => (2 ^ pow) + unsignedBitFieldToZRec (pow + 1) f'\n      end\n  end.\n\nDefinition unsignedBitFieldToZ (f : bitField) : Z :=\n  match f with\n    | nil => 0\n    | other => unsignedBitFieldToZRec 0 other\n  end.\n\nEval compute in unsignedBitFieldToZ nil.\nEval compute in unsignedBitFieldToZ (One :: nil).\nEval compute in unsignedBitFieldToZ (Zero :: One :: nil).\nEval compute in unsignedBitFieldToZ (Zero :: One :: One :: Zero :: nil).\n\nFixpoint addUnsignedRec (carry : bit) (l r : bitField) : bitField :=\n  match l with\n    | nil =>\n      match r with\n        | nil => carry :: nil\n        | other => nil\n      end\n    | b1 :: l' =>\n      match r with\n        | nil => nil\n        | b2 :: r' =>\n          let hadd := halfAdd carry b1 b2 in\n          match hadd with\n            | result :: newCarry :: nil => result :: (addUnsignedRec newCarry l' r')\n            | other => nil\n          end\n      end\n  end.\n\nDefinition addUnsigned (l r : bitField) : bitField :=\n  addUnsignedRec Zero l r.\n\nTheorem add_unsigned_correct :\n  forall l r : bitField,\n    (Zlength l) = (Zlength r) -> (Zlength r > 0) ->\n    unsignedBitFieldToZ (addUnsigned l r) =\n    (unsignedBitFieldToZ l) + (unsignedBitFieldToZ r).\nProof.\n  intros.\n  induction l.\n  simpl. rewrite Zlength_nil in H.\n  rewrite <- H in H0. crush.\n\n  destruct a.\n  \n(*rewrite Zlength_nil.*)\n\nSearchAbout (Zlength _).\n(*\nSearchAbout ((S _) <= (S _)).\nSearchRewrite (_ <= (S _)).\n*)\n", "meta": {"author": "dillonhuff", "repo": "Bit", "sha": "004c20c37eb201101bf10b55d488b67af242a5c5", "save_path": "github-repos/coq/dillonhuff-Bit", "path": "github-repos/coq/dillonhuff-Bit/Bit-004c20c37eb201101bf10b55d488b67af242a5c5/Bit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464115, "lm_q2_score": 0.8757870046160257, "lm_q1q2_score": 0.8215968189063886}}
{"text": "Fixpoint plus (n m: nat): nat :=\n  match n with\n  |O => m\n  |S n' => S (plus n' m)\n  end.\nNotation \"x + y\" := (plus x y).\n\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\nDefinition pred (n: nat): nat :=\n  match n with\n  |O => O\n  |S n' => n'\n  end.\n\nFixpoint gtb (n m: nat): bool :=\n  match m with\n  |O => true\n  |S m' =>\n    match n with\n    |O => false\n    |S n' => gtb n' m'\n    end\n  end.\n\nDefinition gtb2 (n m: nat): bool :=\n  match (minus n m) with\n  |O => false\n  |S p' => true\n  end.\n\nCompute (gtb 4 2).\nCompute (gtb 2 3).\nCompute (gtb2 4 2).\nCompute (gtb2 2 3).\n\nTheorem gtb_test : forall n : nat,  \n  gtb (n+1) 0 = true.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nFixpoint fibs (n: nat): nat :=\n  match n with\n  |O => O\n  |S n' =>\n    match n' with\n    |O => 1\n    |S n'' => plus (fibs n') (fibs n'')\n    end\n  end.\n\nCompute (fibs 0).\nCompute (fibs 1).\nCompute (fibs 2).\nCompute (fibs 3).\nCompute (fibs 4).\nCompute (fibs 5).", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.8215968188838115}}
{"text": "(* Intuitionistic logic is extended to classical logic\n   by assuming a classical axiom. There are different\n   possibilities for the choice of a classical axiom.\n   In this practical work we show the logical equivalence\n   of three different classical axioms. *)\n\n(* The following are three classical axioms *)\n\nDefinition excluded_middle := forall A:Prop, A \\/ ~A.\nDefinition peirce := forall A B:Prop, ((A -> B)-> A) -> A.\nDefinition double_negation := forall A:Prop, ~~A -> A.\n\n(* To show that these are equivalent,\n   we need to prove (at least) three implications.\n   As an example, the implication\n   excluded_middle implies peirce is given. *)\n\nLemma one : excluded_middle -> peirce.\nProof.\nunfold excluded_middle.\nunfold peirce.\nunfold not.\nintro EM.\nintro A.\nintro B.\nelim (EM A).\n\nintro x.\nintro y.\nassumption.\n\nintro x.\nintro y.\napply y.\nintro z.\nelimtype False.\napply x.\nassumption.\nQed.\n\n(* There is a new element in the syntax:\n   a universal quantification over propositions.\n   So in fact these formulas are second-order;\n   we come back to that later in the course. *)\n\n(* How to work with these universal quantifications ?\n   With \"intro\" and \"apply\". Explanation by example:\n\n   If the current goal is \"forall A:Prop, A -> A\",\n   then by doing \"intro A\" the new goal is A -> A\n   and a new hypothesis \"A:Prop\" appears.\n\n   If the current goal is \"C\" and there is a hypothesis\n   \"x: forall A:Prop, B -> A\"\n   then by \"apply x\" the current goal is transformed into \"B\".\n   The universally quantified A is instantiated by C.\n\n   Now suppose that the current goal is \"C\" and\n   there is a hypothesis \"x: forall A B:Prop, B -> A\".\n   Then \"apply x\" does not work because from the\n   current goal we can see how to instantiate A\n   (namely with C) but not how to instantiate B.\n   Therefore we should say \"apply x with something.\"\n   choosing something appropriately. *)\n\n(* exercise; you need the \"apply with\". *)\nLemma two : peirce -> double_negation.\nProof.\n\n\n\nunfold peirce .\n\nunfold double_negation .\nunfold not .\n\nintro x.\nintro y.\nintro z.\n\napply x with (A := y) (B := False) .\n\nintro w.\n\n\nelim z. \n\napply w.\n\n\nQed.\n\n(* exercise *)\nLemma three : double_negation -> excluded_middle.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise *)\nLemma four : excluded_middle -> double_negation.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise *)\nLemma everything_related :\n  excluded_middle -> forall A B : Prop , (A -> B) \\/ (B -> A).\nProof.\n(*! proof *)\n\nQed.\n\nLemma de_morgan :\n  excluded_middle -> forall A B : Prop , ~(~A/\\~B) -> A\\/B.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise\n   note that this lemma is true intuitionistically *)\nLemma about_implication : forall A B : Prop , (~A \\/ B) -> (A -> B).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise\n   for the converse of the previous lemma we need a classical axiom *)\nLemma classical_implication :\n  excluded_middle -> forall A B : Prop , (A -> B) -> (~A \\/ B).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise *)\nLemma about_classical_implication :\n  excluded_middle -> forall A B : Prop , ~B \\/ (A ->B).\nProof.\n(*! proof *)\n\nQed.\n\n\n", "meta": {"author": "danalvi", "repo": "imc010-type-theory-coq", "sha": "13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8", "save_path": "github-repos/coq/danalvi-imc010-type-theory-coq", "path": "github-repos/coq/danalvi-imc010-type-theory-coq/imc010-type-theory-coq-13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8/ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.8215968143273309}}
{"text": "\nModule NatPlayground.\n\nInductive nat:Type:=\n    |O\n    |S (n:nat).\n\nEnd NatPlayground.\n\nFixpoint oddn(n:nat):bool:=\n    match n with\n    |O=>false\n    |S O=>true\n    |S (S m)=>oddn m\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\n\nFixpoint plus (n m : nat):nat:=\n    match n with\n        |O => m\n        |S n' => S (plus n' m)\n    end.\n\nNotation \"x + y\" := (plus x y).\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.\nNotation \"x - y\" := (minus x y).\n\nFixpoint mult (n m : nat):nat:=\n    match n with\n        |O => O\n        |S n' => (mult n' m)+m\n    end.\n\nNotation \"x * y\" := (mult x y).\n\nFixpoint exp (base power : nat):nat:=\n    match power with\n        |O => O\n        |S O => base\n        |S power' => mult base (exp base power')\n    end.\n\nFixpoint factorial (n : nat):nat:=\n    match n with\n        |O => 1\n        |S n' => mult n (factorial(n'))\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.\n\nFixpoint less (n m : nat):bool:=\n    match n,m with\n        |O,O => false\n        |O,S m' => true\n        |S n',O => false\n        |S n',S m' => (less n' m')\n    end.\n\nNotation \"x <? y\" := (less x y) (at level 70) : nat_scope.\n\nDefinition less2 (n m : nat):bool:=\n    match n,m with\n        |O,O => false\n        |O,S m' => true\n        |S n',O => false\n        |_,_ => match n-m with\n                    |O => match m-n with\n                              |O => false\n                              |_ => true\n                          end\n                    |_ => false\n                end\n    end.\nCompute (less2 28 27).\n\nExample test_example:1+2=3.\nProof. Admitted.\n\nTheorem plus_0_n:forall n:nat,0+n=n.\nProof. intros n. simpl. reflexivity. Qed.\n\nExample plus_reverse:forall n m:nat,m=n->n+m=m+n.\nProof. \nintros n m. intros G. rewrite <- G.\nsimpl. reflexivity. Qed.\n\nTheorem plus_id_exercise:forall n m o:nat,\n    n=m -> m=o -> n+m=m+o.\nProof.\nintros n m o. intros H I. rewrite -> H. rewrite <- I.\nsimpl. reflexivity. Qed.\n\nTheorem t1:forall n m:nat,(0+n)*m = n*m.\nProof.\nintros n m. rewrite -> plus_0_n.\nsimpl. reflexivity. Qed.\n\n\nTheorem pre:forall n:nat,S n = 1+n.\nProof. simpl. reflexivity. Qed.\n\n\nTheorem mult_S_l:forall n m:nat,m=S n->m*(1+n)=m*m.\nProof.\nintros n m. intros H. rewrite <- pre. rewrite <- H.\nsimpl. reflexivity. Qed.\n\n\nTheorem plus_one_high_zero:forall n m:nat,0<?n+m+1=true.\nProof. intros n m. destruct n as [|n'] eqn:En.\n-destruct m as [|n''] eqn:Em.\n    +simpl. reflexivity.\n    +simpl. reflexivity.\n-destruct m as [|n''] eqn:Em.\n    +simpl. reflexivity.\n    +simpl. reflexivity.\nQed.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nTheorem andb_true_elim2:forall b c:bool,andb b c=true->c=true.\nProof. intros b c H.\ndestruct b eqn:Eb.\n-rewrite <- H. simpl. reflexivity.\n-destruct c eqn:Ec.\n    { simpl. reflexivity. }\n    { rewrite <- H. simpl. reflexivity. }\nQed.\n\nTheorem zero_nbeq_plus_1:forall n:nat,(0=?(n+1))=false.\nProof. intros n.\ndestruct n eqn:E.\n-simpl. reflexivity.\n-simpl. reflexivity.\nQed.\n\n\nTheorem identity_fn_applied_twice:\nforall (f:bool->bool),\n(forall (x:bool),f x=x)->forall (b:bool),f(f b)=b.\nProof.\nintros f H b.\nrewrite -> H.\nrewrite -> H.\nsimpl. reflexivity.\nQed.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n\nTheorem negation_fn_applied_twice:\nforall (f:bool->bool),\n(forall (x:bool),f x=negb x)->forall (b:bool),f(f b)=b.\nProof.\nintros f H b.\ndestruct b eqn:Eb.\n-rewrite -> H. rewrite -> H. simpl. reflexivity.\n-rewrite -> H. rewrite -> H. simpl. reflexivity.\nQed.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nTheorem andb_true_c_eq_c:forall c:bool,andb true c=c.\nProof. simpl. reflexivity. Qed.\n\nTheorem orb_true_c_eq_true:forall c:bool,orb true c=true.\nProof. simpl. reflexivity. Qed.\n\nTheorem andb_false_c_eq_false:forall c:bool,andb false c=false.\nProof. simpl. reflexivity. Qed.\n\nTheorem orb_false_c_eq_c:forall c:bool,orb false c=c.\nProof. simpl. reflexivity. Qed.\n\n\nTheorem andb_eq_orb:\nforall (b c:bool),andb b c=orb b c->b=c.\nProof.\nintros b c.\ndestruct b eqn:Eb.\n-rewrite -> andb_true_c_eq_c. rewrite->orb_true_c_eq_true.\nintros H. rewrite->H. simpl. reflexivity.\n-rewrite->andb_false_c_eq_false. rewrite->orb_false_c_eq_c.\nintros H. rewrite->H. simpl. reflexivity.\nQed.\n", "meta": {"author": "10ca1h0st", "repo": "LearnCoq", "sha": "3a9a5b7a4a9acd178c35510006da6f8fe6086a4b", "save_path": "github-repos/coq/10ca1h0st-LearnCoq", "path": "github-repos/coq/10ca1h0st-LearnCoq/LearnCoq-3a9a5b7a4a9acd178c35510006da6f8fe6086a4b/wjm01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.821568366330834}}
{"text": "Require Import ssreflect.\n\n\n(* We import the following library which gives us a notation for\n   the comparision between nat's   *)\nRequire Import Nat.\nCheck (leb 3 4).\nEval compute in (3 <=? 4).\nEval compute in (4 <=? 3).\n\n\n\n(* The library ssrbool adds a shortcut where booleans can be \n   viewed as propositions. If b is of type bool, it can be \n   viewd as the proposition b = true. *)\n\nRequire Import ssrbool.\n\nCheck true.\n\nCheck (is_true true).\n\nLemma ex_true : true.\nProof.\nreflexivity.\nQed.\n(* in general we will rather use the 'trivial' tactic though *)\n\n\n(* The following command is explained a few lines below *)\nSet Implicit Arguments.\n\n\n(* We define lists as seen; but this time the type of the arguments\n   is a parameter. We will be able to have lists for any type.   \n   So list : Type -> Type     *)\nInductive list (A : Type) :=\n| nil \n| cons : A -> list A -> list A.\n\nCheck nil.\nCheck cons.\n(* You see the type A is an argument of nil and cons *)\n\n(* The empty list of nat's  : *)\nCheck (nil nat).\n\n(* Because of implicit arguments, we can ommit the argument A for \n   cons - it is guessed by the system : *)\nCheck (cons 1 (cons 2 (nil nat))).\n\n(* We can also often let the system guess the argument of nil : *)\nCheck (cons 1 (cons 2 (nil _))).\n\n\n(* A pattern matching :  *)\n(* in some versions of Coq you may not have to mention \n   the argument of nil *)\n\nFixpoint app A (l1 : list A) l2 :=\n  match l1 with\n  | nil _ => l2  (* here *)\n  | cons n l => cons n (app l l2)\n  end.\n\n(* examples of adding commands into intro-patterns *)\n\nLemma app_nil : forall A (l : list A), app l (nil _) = l.\nProof.\nmove => A.\n(* try first \nelim => [ | n l hl].\n *)\n(* adding /= forces a 'simpl'\nelim => [ | n l hl] /=.\n *)\n(* adding //= does simpl + trivial + try discriminate : *)\nelim => [ | n l hl] //=.\nrewrite hl.\n\n(* The tactic 'done' corresponds to simpl+trivial+try discriminate *)\ndone.\nQed.\n\n(* one can replace \"rewrite hl; done\" by  \"by rewrite hl.\" *) \n\n(* Define the function which computes the length of a list *)\nFixpoint length A (l : list A) :=\n  match l with\n  | nil _ => 0\n  | cons _ m => S(length m)\n  end.\n  (* put correct code here *)\n\n\nLemma app_length : forall A (l1 : list A) l2,\n    length (app l1 l2) = (length l1) + (length l2).\nProof.\nmove => A.\nelim => [| x l hl] l2 //=.  \nby rewrite hl.\nQed.\n\n\n(* The following property states that a nat is less than the \n   first element of a list - if it exists. *)\nDefinition le_head (n:nat)(l : list nat) :=\n  match l with\n  | nil _ => True\n  | cons m _ => n <=? m\n  end.\n\n(* Use le_head to define what is means for a (list nat) to be \n   sorted in increasing order   *)\nFixpoint sorted (l : list nat) :=\n  match l with\n  | nil _ => True\n  | cons n l => (le_head n l) /\\ (sorted l)\n  end.\n\n\nDefinition l123 := (cons 1 (cons 2 (cons 3 (nil _)))).\n\nLemma s123 : sorted l123.\nProof.\ndo 4 (split; trivial).\nQed.\n\n\n(* Using the  <=?  construct, define a function \n   insert : nat -> list nat -> list nat\n   which inserts a nat in a sorted list  *)\n\nFixpoint insert (n:nat) (l : list nat) :=\n  match l with\n  | nil _ => cons n (nil _)\n  | cons m l' =>\n    if n <=? m then cons n l\n    else cons m (insert n l')\n  end.\n\n\n(* Use insert to define a simple sorting function *)\n(* insertion_sort : list nat -> list nat.  *)\n\n\nFixpoint insertion_sort (l : list nat) :=\n  (* put correct code here *)\n  match l with\n  | nil _ => nil _\n  | cons x l => insert x (insertion_sort l)\n  end.\n\n(* Test your function on an example *)\nEval compute in\n    (insertion_sort (cons 5 (cons 3 (cons 2 (cons 4 (cons 1 (nil _))))))).\n\n\n(* Try testing your function on a LARGE example *)\n\n           \nFixpoint revn n  :=\n  match n with\n  | O => nil _\n  | S n => cons n (revn n)\n  end.\n\nDefinition l1000 :=  (revn 1000).\n(* Eval compute in (insertion_sort l1000). *)\n(* you can interrupt by ctrl-c if necessary *)\n\n(* What is the complexity of insetion_sort ? *)\n(* answer in the comment *)\n\n\n(* Now we will do two things:\n 1 - prove that insertion_sort is indeed a sorting function\n 2 - define a more efficient sorting function\n*)\n\n\n(* 1-a : Insertion sort preserves the content of the list. \n   In this part we show that the elements are the same\n   at the end of the sorting *)\n\n\nFixpoint elem (n:nat) (l : list nat) :=\n  match l with\n  | nil _ => False\n  | cons m l => n = m \\/ elem n l\n  end.\n\nLemma ins_elem1 : forall l n m, elem m l -> elem m (insert n l).\nProof.\nelim => [| p l hl] n m //=.\nmove => [e | e]; case (_ <=? _); simpl; auto.\nQed.\n\nLemma eqn_refl : forall n, n =? n.\nelim => [|n e]//=.\nQed.\n\nLemma eqn_eq : forall n p, n =? p -> n=p.\nelim => [|n hn][| p]//= e.\nrewrite (hn p) //=.  \nQed.\n\nLemma ins_elem2 : forall l n, elem n (insert n l).\nProof.\nelim => [| p l hl] n //=.\n auto.\ncase (_ <=? _); simpl; auto.\nQed.\n\n\nLemma ins_elem3 : forall l n p, elem p (insert n l) -> p=n \\/ elem p l.\nProof.\nProof.\nelim => [| m l hl] n p //=.\ncase (_ <=? _); simpl; auto.\nmove => [e | e]; auto.\ncase: (hl n p e).\nauto. auto.\nQed.\n\n\n\n\nLemma insertion_sort_elem1 :\n  forall l n, elem n l -> elem n (insertion_sort l).\nProof.\nelim => [|m l hl] n //=.\nmove => [e | e]. rewrite e; apply ins_elem2.\napply ins_elem1; auto.\nQed.\n\nLemma insertion_sort_elem2 :\n  forall l n, elem n (insertion_sort l) -> elem n l.\nProof.\nelim => [|m l hl] n //= e.\ncase: (ins_elem3 _ m n e).\n  auto.\nby move => h; right; apply hl.\nQed.\n\n(* Question : is this property totally satisfying ? *)\n\n\n\n(* 1-b We now prove that the result of the sorting function is indeed\n   sorted *)\n\n(* this technical lemma we already saw in the previous class *)\nLemma leb_trans : forall n m p,\n    n <=? m -> m <=? p -> n<=? p.\nProof.\nelim => [|n hn][|m][|p]//=.\napply hn.\nQed.\n\n(* This one is easy too *)\nLemma leb_anti : forall n m, n <=? m = false -> m <=? n.\nProof.\nelim => [| n hn][| m]//=.\nby move => nm; apply hn.\nQed.\n\n(* We want to show that insert preserves the property sorted\n   One possibility is to prove first this stronger lemma which\n   is a good induction property *)\n\n(* We give the begining of the proof in order to show the use of\n   the case tactic here *)\nLemma ins_sorted_aux : forall l n,\n    sorted l ->\n    (sorted (insert n l))\n    /\\ (forall m, m<=? n ->\n                  le_head m l ->\n                  le_head m (insert n l)).\nProof.\n(* We do an induction over l, move n up *)\nelim => [| m l hl]//= n [h1 h2].\n\n\n(* we get the two induction hypotheses *)\nmove: (hl n h2) => [h3 h4].\n\n(* Now the trick : we do a case analysis over (n <=? m) but keep track\n  wether its value is true, resp. false *)\ncase nm : (_ <=? _) => /=.\nAdmitted.\n\n(* The lemma we wanted is now an easy consequence of the previous one *)\nLemma ins_sorted : forall l n,\n    sorted l ->\n    (sorted (insert n l)).\nProof.\nby move => l n sl; case (ins_sorted_aux l n sl).\nAdmitted.\n\nLemma insertion_sort_sorted : forall l, sorted (insertion_sort l).\nProof.\nelim => [|x l hl]//=.\nby apply ins_sorted.\nQed.\n\n\n(* 2 A more efficient sorting algorithm *)\n\n(* We use this function which merges two sorted lists into\n   one sorted list \n  We give the code because the syntex is a little tricky in order\n  to \"explain\" to Coq the it terminates  *)\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | nil _, t2 => t2\n  | t1, nil _ => t1\n  | cons n1 m1, cons n2 m2=>\n    if n1 <=? n2 then\n      cons n1 (merge m1 l2) \n    else \n      cons n2 (merge_aux m2)      \n  end\n  in merge_aux l2.\n\n\n\n\nEval compute in\n    merge (cons 1 (cons 3 (nil _)))(cons 2 (nil _)).\n\n\n(* This algorithm stores data in binary trees *)\nInductive tree :=\n| Leaf\n| Node : nat -> tree -> tree -> tree.\n\n\n(* such a tree is a heap if :\n   - the element at the root is smaller than the others\n   - the two subtrees are heaps\n\nThis property (being a heap) corresponds to the property of being\nsorted for lists.\n\nLet us define it :  *)\n\n(* The following prpoerty corresponds to le_head, but for trees: *) \nDefinition le_tree n t :=\n  match t with\n  | Leaf => True\n  | Node m _ _ => n <=? m = true\n  end.\n\n(* Now define the property \"being a heap\" *)\nFixpoint heap t :=\n  match t with\n  | Leaf => True\n  | Node n t1 t2 =>\n    le_tree n t1 /\\ le_tree n t2  /\\\n    heap t1 /\\ heap t2\n  end.\n\n\n(* What does this function do ? *)\nFixpoint ins_tree n t :=\n  match t with\n  | Leaf => (Node n Leaf Leaf)\n  | Node m t1 t2 =>\n    if n <=? m then\n      (Node n (ins_tree m t2) t1)\n    else\n      (Node m (ins_tree n t2) t1)\n  end.\n\n(* define a function which transforms an usorted list into a tree\n   which has the heap property (and is thus partly sorted)  *)\n\nFixpoint to_heap (l : list nat) :=\n  (* correct code here *) Leaf.\n\n\n\n(* define a function which transforms a heap into a sorted list \n   with the same elements *)\n\nFixpoint to_list (t : tree) :=\n  (* correct code here *)\n  nil nat.\n\n(* use the previous functions to define a new sorting function *)\n\nDefinition heap_sort (l : list nat) :=\n  (* correct code here *) nil nat.    \n\n(* test it *)\nEval compute in\n    heap_sort (cons 3 (cons 5 (cons 1 (cons 2 (cons 4 (nil _)))))).\n\n\n\nEval compute in (heap_sort l1000).\n\n\n\n(* Can you see or guess things about the complexity of this \n   new sorting function ? *)\n\n", "meta": {"author": "yubocai-poly", "repo": "Nim-Game", "sha": "cfda89d3ed187b07a43442ac1bb7ababc264c050", "save_path": "github-repos/coq/yubocai-poly-Nim-Game", "path": "github-repos/coq/yubocai-poly-Nim-Game/Nim-Game-cfda89d3ed187b07a43442ac1bb7ababc264c050/Tutorial_4/cse203_04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.9136765210631689, "lm_q1q2_score": 0.8215060944673169}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** ** Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros. induction n as [| n'].\n  Case \"n = 0\".\n  simpl. apply ev_0.\n  Case \"n = S n'\".\n  simpl. apply ev_SS. assumption.  Qed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\".\n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".\n    unfold even. apply IHE'.\nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.\n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful].\n       - Rule [b_5]: The number [5] is [beautiful].\n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n\n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5\n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)\n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n(** *** *)\n(**\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(**\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros. induction n as [| n'].\n  Case \"n = 0\".\n  simpl. apply g_plus5. apply g_plus5. apply g_plus3. apply H.\n  Case \"n = S n'\".\n  apply g_plus5. apply g_plus5. apply g_plus3. apply H.  Qed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous.\nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)\n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n\n    - Prove that\n       forall l, pal (l ++ rev l).\n    - Prove that\n       forall l, pal l -> l = rev l.\n*)\n\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.\n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.\n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.\n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(*\nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n", "meta": {"author": "B-Rich", "repo": "sf", "sha": "3ea9097e9723f082b9b954075d768a32e7d7696d", "save_path": "github-repos/coq/B-Rich-sf", "path": "github-repos/coq/B-Rich-sf/sf-3ea9097e9723f082b9b954075d768a32e7d7696d/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8991213671331905, "lm_q1q2_score": 0.8215060785089345}}
{"text": "(** Cantor's pairing function \n    (Originally  Russel O'Connors [goedel] contrib  *)\n\n\nRequire Import Arith Coq.Lists.List .\nFrom hydras Require Import extEqualNat primRec.\nFrom hydras Require Import Compat815.\nImport Nat.\n\n\n(**  * Bijection from [nat * nat] to [nat] *)\n\n(** ** Preliminary definitions *)\n\n(** Sum of all natural numbers upto [n] *)\n\n(* begin snippet sumToNDef:: no-out *)\nDefinition sumToN (n : nat) :=\n  nat_rec (fun _ => nat) 0 (fun x y : nat => S x + y) n.\n(* end snippet sumToNDef *)\n\n(* begin snippet sumToN1:: no-out *)\nLemma sumToN1 n : n <= sumToN n.\n(* end snippet sumToN1 *)\nProof.\n  induction n as [| n Hrecn]; [trivial |];\n    simpl in |- *; apply le_n_S, Nat.le_add_r.\nQed.\n\n(* begin snippet sumToN2:: no-out *)\nLemma sumToN2 b a :  a <= b -> sumToN a <= sumToN b.\n(* end snippet sumToN2 *)\nProof.\n  revert a; induction b as [| b Hrecb]; intros.\n  - simpl in |- *; rewrite  (Nat.le_0_r a) in H; now subst. \n  - rewrite  Nat.lt_eq_cases in H; destruct H as [H | H].\n    + transitivity (sumToN b).\n      * apply Hrecb; auto.\n        apply Compat815.lt_n_Sm_le; auto.\n      * cbn in |- *; apply le_S; rewrite Nat.add_comm.\n        apply le_add_r.\n    + subst a; reflexivity.  \nQed.\n\n(* begin snippet sumToNPR:: no-out *)\nLemma sumToNIsPR : isPR 1 sumToN.\nProof.\n  unfold sumToN in |- *.\n  apply indIsPR with (f := fun x y : nat => S x + y).\n  apply compose2_2IsPR\n    with (f := fun x y : nat => S x)\n         (g := fun x y : nat => y)\n         (h := plus).\n  - apply filter10IsPR, succIsPR.\n  - apply pi2_2IsPR.\n  - apply plusIsPR.\nQed.\n(* end snippet sumToNPR *)\n\n(** ** Definition and properties of [cPair] *)\n\n(**  The [cPair] function defined below is slightly different \n     from the \"usual\" Cantor pairing function shown in  a big part \n     of the litterature (and Coq's standard library). \n      Since both versions are equivalent upto a swap of the \n      rguments [a] and [b], we still use  Russel O'Connors notations *)\n\n(* begin snippet cPairDef *)\nDefinition cPair (a b : nat) := a + sumToN (a + b).\n\nCompute cPair 4 0. \n(* end snippet cPairDef *)\n\n(* begin snippet cPairIsPR:: no-out *)\nLemma cPairIsPR : isPR 2 cPair.\nProof.\n  unfold cPair; apply compose2_2IsPR\n    with\n    (f := fun x y : nat => x)\n    (g := fun x y : nat => sumToN (x + y))\n    (h := plus).\n  - apply pi1_2IsPR.\n  - apply compose2_1IsPR; [apply plusIsPR | apply sumToNIsPR].\n  - apply plusIsPR.\nQed.\n(* end snippet cPairIsPR *)\n\nSection CPair_Injectivity.\n\n  Remark cPairInjHelp :\n    forall a b c d : nat, cPair a b = cPair c d -> a + b = c + d.\n  Proof.\n    assert (H: forall a b : nat, a < b -> a + sumToN a < sumToN b).\n    {\n      simple induction b.\n      - intros H; elim (Nat.nlt_0_r _ H).\n      -  intros n H H0; simpl in |- *.\n         assert (H1: a <= n)\n         by (apply Compat815.lt_n_Sm_le; assumption).\n         rewrite Nat.lt_eq_cases in H1; destruct H1. \n        +  apply Nat.lt_trans with (sumToN n).\n            * auto.\n            * apply Compat815.le_lt_n_Sm.\n              rewrite Nat.add_comm; apply le_add_r.\n            +  rewrite H1.\n               apply Nat.lt_succ_diag_r .\n    }\n    unfold cPair in |- *; \n    assert\n      (H0: forall a b c d : nat,\n          a <= c -> b <= d -> a + sumToN c = b + sumToN d -> c = d).\n    { intros a b c d H0 H1 H2; induction (le_gt_cases c d).\n      - induction (Compat815.le_lt_or_eq _ _ H3).\n        + assert (H5: a + sumToN c < sumToN d).\n          { apply Nat.le_lt_trans with (c + sumToN c); [| auto].\n            now apply Nat.add_le_mono_r; auto. \n          }\n          rewrite H2 in H5; elim (Compat815.lt_not_le _ _ H5).\n          rewrite Nat.add_comm;apply le_add_r.\n        + auto.\n      - assert (H4: b + sumToN d < sumToN c).\n      { apply Nat.le_lt_trans with (d + sumToN d).\n        - apply Nat.add_le_mono_r; auto.\n        - auto.\n      }\n      rewrite <- H2 in H4;  elim (Compat815.lt_not_le _ _ H4).\n      rewrite add_comm; apply le_add_r.\n    }\n    intros; eapply H0.\n    - apply Nat.le_add_r.\n    - apply Nat.le_add_r.\n    - auto.\n  Qed.\n\n  (* begin snippet cPairInj1:: no-out *)\n  Lemma cPairInj1 a b c d: cPair a b = cPair c d -> a = c.\n  (* end snippet cPairInj1 *)\n  Proof.\n    intro H; assert (H0: a + b = c + d)\n      by (apply cPairInjHelp; auto).\n    unfold cPair in H; rewrite (Nat.add_comm a) in H; \n      rewrite (Nat.add_comm c) in H.\n    rewrite H0 in H; now rewrite Nat.add_cancel_l in H. \n  Qed.\n\n  (* begin snippet cPairInj2:: no-out *)\n  Lemma cPairInj2  a b c d : cPair a b = cPair c d -> b = d.\n  (* end snippet cPairInj2 *)\n  Proof.\n    intro H;  assert (H0: a + b = c + d) by\n      ( apply cPairInjHelp; auto ).\n    assert (H1: a = c) by (eapply cPairInj1; apply H).\n    rewrite H1 in H0; now rewrite Nat.add_cancel_l in H0. \n  Qed.\n\nEnd CPair_Injectivity.\n\nSection CPair_projections.\n\n  (* @todo document boundedSearch *)\n\n  (* begin snippet searchXY *)\n  Let searchXY (a : nat) :=\n        boundedSearch (fun a y : nat => ltBool a (sumToN (S y))) a.\n  (* end snippet searchXY *)\n\n  (* begin snippet cPairPi12 *)\n  Definition cPairPi1 (a : nat) := a - sumToN (searchXY a).\n  Definition cPairPi2 (a : nat) := searchXY a - cPairPi1 a.\n  (* end snippet cPairPi12 *)\n\nLemma cPairProjectionsHelp (a b: nat):\n  b < sumToN (S a) -> sumToN a <= b -> searchXY b = a.\nProof.\n  intros H H0; unfold searchXY in |- *.\n  induction (boundedSearch2 (fun b y : nat => ltBool b (sumToN (S y))) b).\n  - rewrite H1.\n    induction (eq_nat_dec b a).\n    + auto.\n    + elim (ltBoolFalse b (sumToN (S a))).\n      * apply (boundedSearch1\n                 (fun b y : nat => ltBool b (sumToN (S y))) b).\n        rewrite H1.\n        destruct (Nat.lt_gt_cases b a) as [H2 _]; specialize (H2 b0);\n          destruct H2 as [H2 | H2]. \n        -- rewrite Nat.lt_nge in H2. destruct H2. \n           apply Nat.le_trans with (sumToN a).\n           apply sumToN1.\n           auto.\n        -- auto.\n      * auto.\n  - set (c := boundedSearch (fun b y : nat => ltBool b (sumToN (S y))) b) in *.\n    induction (eq_nat_dec c a).\n    + auto.\n    + elim (ltBoolFalse b (sumToN (S a))).\n      apply (boundedSearch1 (fun b y : nat => ltBool b (sumToN (S y))) b).\n      fold c in |- *.\n      rewrite lt_gt_cases in b0; destruct b0 as [H2 | H2]; [trivial|].\n      rewrite Nat.le_ngt in H0; destruct H0.\n      * apply Nat.lt_le_trans with (sumToN (S c)).\n        -- apply ltBoolTrue.\n           auto.\n        -- assert (S c <= a).\n           { apply Compat815.lt_n_Sm_le.\n             now rewrite <- Nat.succ_lt_mono.\n           } apply sumToN2; auto.\n      * assumption.\n      * assumption.\nQed.\n\n(* begin snippet cPairProjections:: no-out *)\nLemma cPairProjections a: cPair (cPairPi1 a) (cPairPi2 a) = a.\n(* end snippet cPairProjections *)\nProof.\n  revert a; assert (H: \n        forall a b : nat, b < sumToN a ->\n                          cPair (cPairPi1 b) (cPairPi2 b) = b).\n  { intros a b H; induction a as [| a Hreca].\n    - simpl in H; elim (Nat.nlt_0_r _ H).\n    - induction (Nat.le_gt_cases (sumToN a) b).\n     assert (searchXY b = a)\n       by (apply cPairProjectionsHelp; auto).\n      unfold cPair in |- *.\n      replace (cPairPi1 b + cPairPi2 b) with a.\n      unfold cPairPi1 in |- *.\n      rewrite H1; now rewrite Nat.sub_add.\n      unfold cPairPi2 in |- *.\n      rewrite H1, Nat.add_comm,  Nat.sub_add.\n      auto.\n      unfold cPairPi1 in |- *.\n      rewrite H1.\n      simpl in H.\n      erewrite Nat.add_le_mono_l.\n      rewrite Nat.add_comm, sub_add. \n\n      apply Compat815.lt_n_Sm_le; auto.\n      rewrite add_comm;  apply H; auto.\n      auto.\n      apply Hreca.\n      auto.\n  }\n  intros a; apply H with (S a).\n  apply Nat.lt_le_trans with (S a).\n  apply Nat.lt_succ_diag_r .\n  apply sumToN1.\nQed.\n\nRemark searchXYIsPR : isPR 1 searchXY.\nProof.\n  unfold searchXY in |- *.\n  apply boundSearchIsPR with (P := fun a y : nat => ltBool a (sumToN (S y))).\n  unfold isPRrel in |- *.\n  apply\n    compose2_2IsPR\n    with\n    (h := charFunction 2 ltBool)\n    (f := fun a y : nat => a)\n    (g := fun a y : nat => sumToN (S y)).\n  - apply pi1_2IsPR.\n  - apply filter01IsPR with (g := fun y : nat => sumToN (S y)).\n    apply compose1_1IsPR.\n    + apply succIsPR.\n    + apply sumToNIsPR.\n - apply ltIsPR.\nQed.\n\n(* begin snippet  cPairPi1IsPR:: no-out *)\nLemma cPairPi1IsPR : isPR 1 cPairPi1.\n(* end snippet  cPairPi1IsPR *)\nProof.\n  unfold cPairPi1 in |- *.\n  apply compose1_2IsPR \n  with\n    (g := minus)\n    (f := fun x : nat => x)\n    (f' := fun a : nat => sumToN (searchXY a)).\n  - apply idIsPR.\n  - apply compose1_1IsPR.\n    + apply searchXYIsPR.\n    + apply sumToNIsPR.\n  - apply minusIsPR.\nQed.\n\n(* begin snippet  cPairProjections1:: no-out *)\nLemma cPairProjections1 (a b : nat): cPairPi1 (cPair a b) = a.\n(* end snippet  cPairProjections1 *)\nProof.\n  unfold cPair, cPairPi1  in |- *.\n  replace (searchXY (a + sumToN (a + b))) with (a + b).\n  now rewrite Nat.add_sub.\n  symmetry  in |- *; apply cPairProjectionsHelp.\n  - simpl in |- *; apply Nat.lt_succ_r.\n    apply Nat.add_le_mono_r, Nat.le_add_r.\n  - rewrite (Nat.add_comm a (sumToN (a + b))); apply le_add_r.\nQed.\n\n(* begin snippet  cPairProjections2:: no-out *)\nLemma cPairProjections2 (a b : nat): cPairPi2 (cPair a b) = b.\n(* end snippet  cPairProjections2 *)\nProof.\n  unfold cPairPi2 in |- *; rewrite cPairProjections1; unfold cPair in |- *.\n  replace (searchXY (a + sumToN (a + b))) with (a + b).\n  - rewrite Nat.add_comm; apply Nat.add_sub .\n  - symmetry  in |- *; apply cPairProjectionsHelp; simpl in |- *.\n    + rewrite Nat.lt_succ_r; apply Nat.add_le_mono_r, Nat.le_add_r.\n    + rewrite (Nat.add_comm a (sumToN (a + b)));apply le_add_r.\nQed.\n\n\n(* begin snippet  cPairPi2IsPR:: no-out *)\nLemma cPairPi2IsPR : isPR 1 cPairPi2.\n(* end snippet  cPairPi2IsPR *)\nProof.\n  unfold cPairPi2 in |- *.\n  apply compose1_2IsPR with (g := minus) (f := searchXY) (f' := cPairPi1).\n  - apply searchXYIsPR.\n  - apply cPairPi1IsPR.\n  - apply minusIsPR.\nQed.\n\n\nEnd CPair_projections.\n\nSection CPair_Order.\n\n  (* begin snippet cPairLe1:: no-out *)\n  Lemma cPairLe1 (a b : nat) : a <= cPair a b.\n  (* end snippet cPairLe1 *)\n  Proof. unfold cPair in |- *; apply Nat.le_add_r. Qed.\n\n\n  (* begin snippet cPairLe1A:: no-out *)\n  Lemma cPairLe1A (a : nat) : cPairPi1 a <= a.\n  (* end snippet cPairLe1A *)\n  Proof. \n    transitivity (cPair (cPairPi1 a) (cPairPi2 a)).\n    - apply cPairLe1.\n    - rewrite cPairProjections; apply le_n.\n  Qed.\n\n  (* begin snippet cPairLe2:: no-out *)\n  Lemma cPairLe2 ( a b : nat) : b <= cPair a b.\n  (* end snippet cPairLe2 *)\n  Proof.\n    unfold cPair in |- *; eapply Nat.le_trans with (b + a). \n    - apply Nat.le_add_r.\n    - rewrite (Nat.add_comm b a); transitivity (sumToN (a + b)).\n      + apply sumToN1.\n      + rewrite (Nat.add_comm _ (sumToN (a + b))); apply le_add_r.\n  Qed.\n\n  (* begin snippet cPairLe2A:: no-out *)\n  Lemma cPairLe2A (a: nat): cPairPi2 a <= a.\n  (* end snippet cPairLe2A *)\n  Proof.\n    transitivity (cPair (cPairPi1 a) (cPairPi2 a)).\n    - apply cPairLe2.\n    - rewrite cPairProjections; apply le_n.\n  Qed.\n\n  (* begin snippet cPairLe3:: no-out *)\n  Lemma cPairLe3 (a b c d : nat): a <= b -> c <= d -> cPair a c <= cPair b d.\n  (* end snippet cPairLe3 *)\n  Proof.\n    intros H H0; unfold cPair in |- *;\n      transitivity (a + sumToN (b + d)).\n    - apply Nat.add_le_mono_l, sumToN2; transitivity (a + d).\n      + now apply Nat.add_le_mono_l.\n      + now apply Nat.add_le_mono_r.\n    - now apply Nat.add_le_mono_r.\n  Qed.\n\n  (* begin snippet cPairLt1:: no-out *)\n  Lemma cPairLt1 (a b : nat): a < cPair a (S b).\n  (* end snippet cPairLt1 *)\n  Proof.\n    unfold cPair in |- *.\n    rewrite (Nat.add_comm a (S b)); simpl in |- *.\n    rewrite Nat.add_comm; simpl in |- *; rewrite Nat.add_comm.\n    apply le_n_S, Nat.le_add_r.\n  Qed.\n\n  (* begin snippet cPairLt2:: no-out *)\n  Lemma cPairLt2 (a b : nat): b < cPair (S a) b.\n  (* end snippet cPairLt2 *)\n  Proof.\n    unfold cPair in |- *; simpl in |- *;\n      unfold lt in |- *; apply le_n_S.\n    eapply Nat.le_trans.\n    - apply Nat.le_add_r. \n    - rewrite Nat.add_comm at 1. \n      apply Nat.add_le_mono_l.\n      apply le_S.\n      eapply Nat.le_trans.\n      + apply Nat.le_add_r.\n      + rewrite Nat.add_comm; apply Nat.le_add_r.\n  Qed.\n\nEnd CPair_Order.\n\nRequire Import Extraction. \nSection code_nat_list.\n\n(* begin snippet codeListDef:: no-out *)\nFixpoint codeList (l : list nat) : nat :=\n  match l with\n  | nil => 0\n  | n :: l' => S (cPair n (codeList l'))\n  end.\nCompute codeList (3::1::nil). \nCompute codeList (2::3::1::nil). \n(* end snippet codeListDef *)\n\n(* begin snippet codeListInj:: no-out *)\nLemma codeListInj (l m : list nat): codeList l = codeList m -> l = m.\nProof.\n  (* ... *)\n(* end snippet codeListInj *)\n\n  revert m; induction l as [| a l Hrecl].\n  - intros m H; destruct m as [| n l].\n   + reflexivity.\n   + discriminate H.\n  - intros m H; destruct m as [| n l0].\n    + discriminate H.\n    + (* begin snippet codeListInja:: no-in unfold *)\n      simpl in H.\n      (* end snippet codeListInja *) replace n with a.\n      * rewrite (Hrecl l0); [reflexivity |].\n        eapply cPairInj2; apply eq_add_S, H. \n      * eapply cPairInj1; apply eq_add_S, H.\nQed.\n\n\n(* begin snippet codeNthDef:: no-out  *)\n\n\nDefinition codeNth (n m:nat) : nat :=\n  let X := nat_rec (fun _ : nat => nat)\n             m\n             (fun _ Hrecn : nat => cPairPi2 (pred Hrecn)) n\n  in cPairPi1 (pred X).\n\n\n(* end snippet codeNthDef *)\n\n\n\n\n(** drops [n] first elements from [l] *)\nLet drop (n : nat) : forall (l : list nat), list nat.\nProof.\n  induction n as [| n Hrecn].\n  - exact (fun l => l).\n  - intros l; apply Hrecn; destruct l.\n   + exact (nil (A:=nat)).\n   + exact l.\nDefined.\n\n(* begin snippet codeNthCorrect:: no-out *)\nLemma codeNthCorrect :\n  forall (n : nat) (l : list nat), codeNth n (codeList l) = nth n l 0.\n(* end snippet codeNthCorrect *)\nProof.\n  unfold codeNth in |- *.\n  set\n    (A :=\n       fun l : list nat => match l with\n                           | nil => nil (A:=nat)\n                           | _ :: l0 => l0\n                           end) in *.\n  assert (H: forall l : list nat,\n             cPairPi2 (pred (codeList l)) = codeList (A l)).\n  { destruct l; simpl in |- *.\n    apply (cPairProjections2 0 0).\n    apply cPairProjections2.\n  }\n  assert\n    (H0: forall (n : nat) (l : list nat),\n        nat_rec (fun _ : nat => nat) (codeList l)\n          (fun _ Hrecn : nat => cPairPi2 (pred Hrecn)) n = \n          codeList (drop n l)).\n  {\n    simple induction n; simpl in |- *.\n    reflexivity.\n    intros n0 H0 l; rewrite H0, H. \n    unfold A in |- *; clear H0; revert l. \n    induction n0 as [| n0 Hrecn0]; simpl in |- *; intros.\n    - reflexivity.\n    - destruct l.\n      + apply (Hrecn0 nil).\n      + apply Hrecn0.\n  }\n  intros n l.\n  replace (nth n l 0) with match drop n l with\n                           | nil => 0\n                           | a :: _ => a\n                           end.  \n  rewrite H0; destruct (drop n l).\n  + simpl in |- *; apply (cPairProjections1 0 0).\n  + simpl in |- *;  apply cPairProjections1.\n  + revert l; induction n as [| n Hrecn].\n   * destruct l; reflexivity.\n   * destruct l.\n    -- simpl in Hrecn; destruct n; apply (Hrecn nil).\n    -- simpl in |- *; auto.\nQed.\n\n(* begin snippet codeNthIsPR:: no-out *)\nLemma codeNthIsPR : isPR 2 codeNth.\n(* end snippet codeNthIsPR *)\nProof.\n  unfold codeNth in |- *; apply compose2_1IsPR\n    with\n    (g := fun x : nat => cPairPi1 (pred x))\n    (f := fun n m : nat =>\n            nat_rec (fun _ : nat => nat) m\n              (fun _ Hrecn : nat => cPairPi2 (pred Hrecn)) n).\n  - apply ind1ParamIsPR\n    with\n    (g := fun m : nat => m)\n    (f := fun _ Hrecn m : nat => cPairPi2 (pred Hrecn)).\n    + apply filter010IsPR with (g := fun x : nat => cPairPi2 (pred x)).\n      apply compose1_1IsPR.\n      * apply predIsPR.\n      * apply cPairPi2IsPR.\n    + apply idIsPR.\n  - apply compose1_1IsPR.\n    + apply predIsPR.\n    + apply cPairPi1IsPR.\nQed.\n\nEnd code_nat_list.\n\nExtraction codeNth.\nPrint codeNth.\n\nSection Strong_Recursion.\n(* begin snippet evalStrongRecDef *)\nDefinition evalStrongRecHelp (n : nat) (f : naryFunc (S (S n))) :\n  naryFunc (S n) :=\n  evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil _) (codeList nil))\n    (evalComposeFunc (S (S n)) 2\n       (Vector.cons _ f _\n          (Vector.cons _ (evalProjFunc (S (S n)) n\n                            (Nat.lt_lt_succ_r _ _\n                               (Nat.lt_succ_diag_r  _))) _\n             (Vector.nil _))) \n       (fun a b : nat => S (cPair a b))).\n\nDefinition evalStrongRec (n : nat) (f : naryFunc (S (S n))) :\n  naryFunc (S n) :=\n  evalComposeFunc (S n) 1\n    (Vector.cons _\n       (fun z : nat => evalStrongRecHelp n f (S z)) _ (Vector.nil _))\n    (fun z : nat => cPairPi1 (pred z)).\n(* end snippet evalStrongRecDef *)\n\n(* begin snippet evalStrongRecPR:: no-out *)\nLemma evalStrongRecIsPR (n : nat) (f : naryFunc (S (S n))) :\n  isPR (S (S n))  f -> isPR (S n) (evalStrongRec n f).\n(* end snippet evalStrongRecPR *)\nProof.\n  intros; unfold evalStrongRec, evalStrongRecHelp in |- *.\n  fold (naryFunc (S n)) in |- *.\n  set\n    (A :=\n       evalPrimRecFunc n\n         (evalComposeFunc n 0 (Vector.nil (naryFunc n)) (codeList nil))\n         (evalComposeFunc (S (S n)) 2\n            (Vector.cons (naryFunc (S (S n))) f 1\n               (Vector.cons (naryFunc (S (S n)))\n                  (evalProjFunc (S (S n)) n\n                     (Nat.lt_lt_succ_r n (S n)\n                        (Nat.lt_succ_diag_r  n))) 0\n                  (Vector.nil (naryFunc (S (S n))))))\n            (fun a b : nat => S (cPair a b))))\n    in *.\n  assert (H0: isPR (S n) A).\n  { unfold A in |- *.\n    assert (isPR 2 (fun a b : nat => S (cPair a b))).\n    { apply compose2_1IsPR.\n      apply cPairIsPR.\n      apply succIsPR.\n    }\n    assert (H1: isPR 1 (fun z : nat => cPairPi1 (pred z))).\n    { apply compose1_1IsPR.\n      apply predIsPR.\n      apply cPairPi1IsPR.\n    }\n    induction H as (x, p).\n    induction H0 as (x0, p0).\n    induction H1 as (x1, p1).\n    exists\n      (primRecFunc n (composeFunc n 0 (PRnil _) zeroFunc)\n         (composeFunc (S (S n)) 2\n            (PRcons _ _ x\n               (PRcons _ _ (projFunc (S (S n)) n\n                              (Nat.lt_lt_succ_r n (S n)\n                                 (Nat.lt_succ_diag_r  n)))\n                  (PRnil _))) x0)).\n    apply\n      extEqualTrans\n      with\n      (evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil _) 0)\n         (evalComposeFunc (S (S n)) 2\n            (Vector.cons _ (evalPrimRec _ x) _\n               (Vector.cons _ (evalProjFunc (S (S n)) n\n                                 (Nat.lt_lt_succ_r n (S n)\n                                    (Nat.lt_succ_diag_r  n))) _\n                  (Vector.nil _))) (evalPrimRec _ x0))).\n    apply extEqualRefl.\n    apply extEqualPrimRec.\n    simpl in |- *.\n    apply extEqualRefl.\n    apply extEqualCompose.\n    unfold extEqualVector, extEqualVectorGeneral, Vector.t_rect in |- *.\n    repeat split; auto.\n    apply extEqualRefl.\n    auto.\n  }\n  assert (H1: isPR (S n) (fun z : nat => A (S z))).\n  { apply compose1_NIsPR; auto.\n    apply succIsPR.\n  }\n  clear H0; assert (H0: isPR 1 (fun z : nat => cPairPi1 (pred z))).\n  { apply compose1_1IsPR.\n    apply predIsPR.\n    apply cPairPi1IsPR.\n  }\n  induction H0 as (x, p).\n  induction H1 as (x0, p0).\n  exists (composeFunc (S n) 1 (PRcons _ _ x0 (PRnil _)) x).\n  simpl in |- *.\n  fold (naryFunc n) in |- *.\n  intros c; apply extEqualCompose.\n  unfold extEqualVector in |- *.\n  simpl in |- *; repeat split.\n  - apply (p0 c).\n  -  trivial.\nQed.\n\n(* begin snippet computeEvalStrongRecHelp:: no-out *)\nLemma computeEvalStrongRecHelp :\n  forall (n : nat) (f : naryFunc (S (S n))) (c : nat),\n    evalStrongRecHelp n f (S c) =\n      compose2 n (evalStrongRecHelp n f c)\n        (fun a0 : nat =>\n           evalComposeFunc n 2\n             (Vector.cons (naryFunc n) (f c a0) 1\n                (Vector.cons (naryFunc n) (evalConstFunc n a0) 0\n                   (Vector.nil (naryFunc n))))\n             (fun a1 b0 : nat => S (cPair a1 b0))).\n(* end snippet computeEvalStrongRecHelp:: no-out *)\nProof.\n  intros n f c; unfold evalStrongRecHelp at 1 in |- *; simpl in |- *.\n  fold (naryFunc n) in |- *.\n  induction (eq_nat_dec n (S n)).\n  - destruct (neq_succ_diag_r n a).\n  - induction (eq_nat_dec n n).\n    + replace\n        (evalPrimRecFunc n\n           (evalComposeFunc n 0 (Vector.nil (naryFunc n)) 0)\n           (fun a0 a1 : nat =>\n              evalComposeFunc n 2\n                (Vector.cons (naryFunc n) (f a0 a1) 1\n                   (Vector.cons (naryFunc n)\n                      (evalConstFunc n a1) 0 (Vector.nil (naryFunc n))))\n                (fun a2 b0 : nat => S (cPair a2 b0))) c)\n        with\n        (evalStrongRecHelp n f c).\n      reflexivity.\n      unfold evalStrongRecHelp at 1 in |- *.\n      simpl in |- *.\n      fold (naryFunc n) in |- *.\n      induction (eq_nat_dec n (S n)).\n      elim b; auto.\n      induction (eq_nat_dec n n).\n      * reflexivity.\n      * elim b1; auto.\n    + elim b0; auto.\nQed.\n\n\nFixpoint listValues  (f : naryFunc 2) (n : nat) : list nat :=\n  match n with\n    0 => nil\n  | S m => evalStrongRec _ f m :: listValues f m\n  end.\n\n\nLemma evalStrongRecHelp1 :\n forall (f : naryFunc 2) (n m : nat),\n   m < n ->\n   codeNth (n - S m) (evalStrongRecHelp _ f n) = evalStrongRec _ f m.\nProof.\n  assert\n    (H: forall (f : naryFunc 2) (n : nat),\n        evalStrongRecHelp _ f n = codeList (listValues f n)).\n  {\n    intros f n; induction n as [| n Hrecn].\n    - simpl in |- *; unfold evalStrongRecHelp in |- *; simpl in |- *.\n      reflexivity.\n    - unfold evalStrongRecHelp in |- *; simpl in |- *; \n        unfold evalStrongRecHelp in Hrecn; simpl in Hrecn; rewrite Hrecn.\n      unfold evalStrongRec in |- *; simpl in |- *.\n      now rewrite cPairProjections1, Hrecn.\n  }\n  intros f n m H0; rewrite H, codeNthCorrect.\n  induction n as [| n Hrecn].\n   - elim (Nat.nlt_0_r _ H0).\n   - induction (Compat815.le_lt_or_eq _ _ H0).\n     rewrite Nat.sub_succ_l; simpl in |- *.\n     rewrite Hrecn.\n     reflexivity.\n     apply Nat.succ_lt_mono; auto.\n     apply Compat815.lt_n_Sm_le; auto.\n     inversion H1.\n     rewrite  Nat.sub_diag; reflexivity. \nQed.\n\nLemma evalStrongRecHelpParam :\n  forall (a n c : nat) (f : naryFunc (S (S (S a)))),\n    extEqual a (evalStrongRecHelp (S a) f n c)\n      (evalStrongRecHelp a (fun x y : nat => f x y c) n).\nProof.\n  intros a n c f; unfold evalStrongRecHelp in |- *.\n  eapply extEqualTrans.\n  - apply extEqualSym.\n    apply evalPrimRecParam.\n  - assert\n    (H: extEqual (S a)\n       (evalPrimRecFunc a\n          (evalComposeFunc (S a) 0\n             (Vector.nil (naryFunc (S a))) (codeList nil) c)\n          (fun x y : nat =>\n             evalComposeFunc (S (S (S a))) 2\n               (Vector.cons (naryFunc (S (S (S a)))) f 1\n                  (Vector.cons (naryFunc (S (S (S a))))\n                     (evalProjFunc (S (S (S a))) (S a)\n                        (Nat.lt_lt_succ_r (S a) (S (S a))\n                           (Nat.lt_succ_diag_r  (S a)))) 0\n                     (Vector.nil (naryFunc (S (S (S a)))))))\n               (fun a0 b : nat => S (cPair a0 b)) x y c))\n       (evalPrimRecFunc a\n          (evalComposeFunc a 0 (Vector.nil (naryFunc a)) (codeList nil))\n          (evalComposeFunc (S (S a)) 2\n             (Vector.cons (naryFunc (S (S a))) (fun x y : nat => f x y c) 1\n                (Vector.cons (naryFunc (S (S a)))\n                   (evalProjFunc (S (S a)) a (Nat.lt_lt_succ_r a (S a)\n                                                (Nat.lt_succ_diag_r  a))) 0\n                   (Vector.nil (naryFunc (S (S a))))))\n             (fun a0 b : nat => S (cPair a0 b))))).\n    { apply\n        (extEqualPrimRec a\n           (evalComposeFunc (S a) 0\n              (Vector.nil (naryFunc (S a)))\n              (codeList nil) c)).\n      simpl in |- *; apply extEqualRefl.\n      - simpl in |- *; fold (naryFunc a) in |- *.\n        induction\n          (sumbool_rec\n             (fun _ : {a = S a} + {a <> S a} =>\n                {S a = S (S a)} + {S a <> S (S a)})\n             (fun a0 : a = S a => left (S a <> S (S a)) (f_equal S a0))\n             (fun b : a <> S a => right (S a = S (S a)) (not_eq_S a (S a) b))\n             (eq_nat_dec a (S a))).\n        + elim (Compat815.lt_not_le (S a) (S (S a))).\n          * apply Nat.lt_succ_diag_r.\n          * rewrite <- a0; auto.\n        + induction\n            (sumbool_rec (fun _ : {a = a} + {a <> a} =>\n                            {S a = S a} + {S a <> S a})\n               (fun a0 : a = a => left (S a <> S a) (f_equal S a0))\n               (fun b0 : a <> a => right (S a = S a) (not_eq_S a a b0)) \n               (eq_nat_dec a a)).\n            induction (eq_nat_dec a (S a)).\n          * elim (Compat815.lt_not_le a (S a)).\n            -- apply Nat.lt_succ_diag_r.\n            -- rewrite <- a1; auto.\n          * induction (eq_nat_dec a a).\n            -- intros;  apply extEqualRefl.\n            -- elim b1; auto.\n          * elim b0; auto.\n    }\n    apply (H n).\nQed.\n\nLemma evalStrongRecHelp2 :\n  forall (a : nat) (f : naryFunc (S (S a))) (n m : nat),\n    m < n ->\n    extEqual _\n      (evalComposeFunc _ 1\n         (Vector.cons _ (evalStrongRecHelp _ f n) 0 (Vector.nil _))\n         (fun b : nat => codeNth (n - S m) b)) (evalStrongRec _ f m).\nProof.\n  intro a; fold (naryFunc a) in |- *.\n  induction a as [| a Hreca].\n  - simpl in |- *.\n    apply evalStrongRecHelp1.\n  - simpl in |- *.\n  intros f n m H c; fold (naryFunc a) in |- *.\n  set (g := fun x y : nat => f x y c) in *.\n  assert\n    (H0: extEqual a\n       (evalComposeFunc a 1\n          (Vector.cons (naryFunc a)\n             (evalStrongRecHelp a g n) 0 (Vector.nil (naryFunc a)))\n          (fun b : nat => codeNth (n - S m) b)) (evalStrongRec a g m))\n      by (apply Hreca; auto).\n  unfold g in H0; clear g Hreca.\n  apply extEqualTrans with (evalStrongRec a (fun x y : nat => f x y c) m).\n  + apply\n    extEqualTrans\n    with\n    (evalComposeFunc a 1\n       (Vector.cons (naryFunc a)\n          (evalStrongRecHelp a (fun x y : nat => f x y c) n)\n          0 (Vector.nil (naryFunc a)))\n       (fun b : nat => codeNth (n - S m) b)).\n    * apply extEqualCompose; unfold extEqualVector in |- *.\n      simpl in |- *; repeat split.\n      apply evalStrongRecHelpParam.\n      apply extEqualRefl.\n    * apply H0.\n  + unfold evalStrongRec in |- *; simpl in |- *.\n    fold (naryFunc a) in |- *; apply extEqualCompose.\n    unfold extEqualVector in |- *; simpl in |- *; repeat split.\n    * apply extEqualSym.\n      apply evalStrongRecHelpParam.\n    * apply extEqualRefl.\nQed.\n\nLemma callIsPR (g : nat -> nat) :\n isPR 1 g -> isPR 2 (fun a recs : nat => codeNth (a - S (g a)) recs).\nProof.\n  intros H; apply  compose2_2IsPR\n    with (f := fun a recs : nat => a - S (g a))\n         (g := fun a recs : nat => recs).\n  - apply filter10IsPR with (g := fun a : nat => a - S (g a)).\n    apply compose1_2IsPR with\n      (f := fun a : nat => a)\n      (f' := fun a : nat => S (g a)).\n    + apply idIsPR.\n    + apply compose1_1IsPR.\n      * assumption.\n      * apply succIsPR.\n    + apply minusIsPR.\n  - apply pi2_2IsPR.\n  - apply codeNthIsPR.\nQed.\n\nEnd Strong_Recursion.\n\nLemma div2IsPR : isPR 1 div2.\nProof.\n  assert\n    (H: isPR 1\n          (evalStrongRec 0\n             (fun n recs : nat =>\n                switchPR n\n                  (switchPR (pred n)\n                     (S (codeNth (n - S (pred (pred n))) recs))\n                     0)\n                  0))).\n  { apply evalStrongRecIsPR.\n    assert (H : isPR 2 (fun n recs : nat => 0)).\n    { exists (composeFunc 2 0 (PRnil _) zeroFunc).\n      simpl in |- *; auto.\n    }\n    apply compose2_3IsPR with\n    (f1 := fun n recs : nat => n)\n    (f2 := fun n recs : nat =>\n             switchPR (pred n)\n               (S (codeNth (n - S (pred (pred n))) recs)) 0)\n    (f3 := fun n recs : nat => 0).\n    - apply pi1_2IsPR.\n    - apply compose2_3IsPR with\n        (f1 := fun n recs : nat => pred n)\n        (f2 := fun n recs : nat =>\n                 S (codeNth (n - S (pred (pred n))) recs))\n        (f3 := fun n recs : nat => 0).\n      + apply filter10IsPR.\n        apply predIsPR.\n      + apply compose2_1IsPR with\n            (f := fun n recs : nat =>\n                    codeNth (n - S (pred (pred n))) recs).\n        * apply compose2_2IsPR with\n            (f := fun n recs : nat => n - S (pred (pred n)))\n            (g := fun n recs : nat => recs).\n          apply filter10IsPR with\n            (g := fun n : nat => n - S (pred (pred n))).\n          apply compose1_2IsPR with\n            (f := fun n : nat => n)\n            (f' := fun n : nat => S (pred (pred n))).\n          apply idIsPR.\n          apply compose1_1IsPR with\n            (f := fun n : nat => pred (pred n)).\n          apply compose1_1IsPR; apply predIsPR.\n          apply succIsPR.\n          apply minusIsPR.\n          apply pi2_2IsPR.\n          apply codeNthIsPR.\n        * apply succIsPR.\n      + auto.\n      + apply switchIsPR.\n    - auto.\n    - apply switchIsPR.\n  }\n  destruct H as [x p]; exists x.\n  eapply extEqualTrans.\n  - apply p.\n  - clear p x; simpl in |- *; intro c.\n    set  (f := fun n recs : nat =>\n                 switchPR n (switchPR (pred n)\n                               (S (codeNth (n - S (pred (pred n)))\n                                     recs)) 0)  0) in *. \n    elim c using Compat815.ind_0_1_SS.\n    + unfold evalStrongRec in |- *; simpl in |- *; auto.\n    + unfold evalStrongRec in |- *; simpl in |- *;\n        apply cPairProjections1.\n    + intros n H; unfold evalStrongRec, evalComposeFunc,\n        evalOneParamList \n        in |- *.\n      rewrite computeEvalStrongRecHelp.\n      unfold f at 2 in |- *;\n        set (A := S (S n) - S (pred (pred (S (S n))))) in *.\n      simpl in |- *; rewrite cPairProjections1; apply eq_S.\n      rewrite <- H; unfold A in |- *; apply evalStrongRecHelp1.\n      auto.\nQed.\n\n(** abbreviations a la Lisp (to improve) *)\n\nModule LispAbbreviations.\n  #[global] Notation car n := (cPairPi1 n). \n  #[global] Notation caar n := (cPairPi1 (cPairPi1 n)). \n  #[global] Notation cadr n := (cPairPi1 (cPairPi2 n)). \n\n  #[global] Notation cdr n := (cPairPi2 n). \n  #[global] Notation cddr n := (cPairPi2 (cPairPi2 n)). \n  #[global] Notation cdddr n := (cPairPi2 (cPairPi2 (cPairPi2 n))). \n  #[global] Notation cddddr n := \n    (cPairPi2 (cPairPi2 (cPairPi2 (cPairPi2 n)))).\n\nEnd LispAbbreviations. \n\n\n(** ** Triples \n   (moved from codeSubFormula.v)\n*)\n\nDefinition cTriple (a b c : nat) : nat := cPair a (cPair b c).\n\nDefinition cTriplePi1 (n : nat) : nat := cPairPi1 n.\n\nDefinition cTriplePi2 (n : nat) : nat := cPairPi1  (cPairPi2 n).\n\nDefinition cTriplePi3 (n : nat) : nat := cPairPi2 (cPairPi2 n).\n\nLemma cTripleIsPR : isPR 3 cTriple.\nProof.\n  unfold cTriple; apply compose3_2IsPR with\n    (g := cPair)\n    (f1 := fun a b c : nat => a)\n    (f2 := fun a b c : nat => cPair b c).\n  - apply pi1_3IsPR. \n  - apply filter011IsPR with (g := fun b c : nat => cPair b c).\n    apply cPairIsPR.\n  - apply cPairIsPR.\nQed.\n\nLemma cTriplePi1IsPR : isPR 1 cTriplePi1.\nProof. apply cPairPi1IsPR. Qed.\n\nLemma cTriplePi2IsPR : isPR 1 cTriplePi2.\nProof.\n  unfold cTriplePi2; apply compose1_1IsPR.\n  - apply cPairPi2IsPR.\n  - apply cPairPi1IsPR.\nQed.\n\nLemma cTriplePi3IsPR : isPR 1 cTriplePi3.\nProof.\n  unfold cTriplePi3; apply compose1_1IsPR; apply cPairPi2IsPR.\nQed.\n\nLemma cTripleProj1 (a b c : nat) :  cTriplePi1 (cTriple a b c) = a.\nProof.  unfold cTriplePi1, cTriple; apply cPairProjections1. Qed.\n\nLemma cTripleProj2 (a b c : nat) : cTriplePi2 (cTriple a b c) = b.\nProof. \n  unfold cTriplePi2, cTriple; rewrite cPairProjections2; \n    apply cPairProjections1.\nQed.\n\nLemma cTripleProj3 (a b c : nat) : cTriplePi3 (cTriple a b c) = c.\nProof. \n  unfold cTriplePi3, cTriple; rewrite cPairProjections2.\n  apply cPairProjections2.\nQed.\n\nLemma cTripleProj (a: nat) :\n cTriple (cTriplePi1 a) (cTriplePi2 a) (cTriplePi3 a) = a.\nProof.\nunfold cTriple, cTriplePi1, cTriplePi2, cTriplePi3; \n  repeat rewrite cPairProjections; reflexivity.\nQed.\n", "meta": {"author": "coq-community", "repo": "hydra-battles", "sha": "2d211e0b5030d5f77aaaf6366b01fc64ed998c61", "save_path": "github-repos/coq/coq-community-hydra-battles", "path": "github-repos/coq/coq-community-hydra-battles/hydra-battles-2d211e0b5030d5f77aaaf6366b01fc64ed998c61/theories/ordinals/Ackermann/cPair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.8214704759886489}}
{"text": "Require Import Coq.Init.Nat.\nRequire Import Coq.Arith.PeanoNat.\n\nInductive tree : Type :=\n  | Nil\n  | Node (v : nat) (l r : tree).\n\nFixpoint insert (t : tree) (v : nat) : tree :=\n  match t with\n  | Nil => Node v Nil Nil\n  | Node v' l r => if v <? v'\n                   then Node v' (insert l v) r\n                   else if v' <? v\n                        then Node v' l (insert r v)\n                        else t\n  end.\n\nLemma insert_not_Nil : forall (t : tree) (v : nat),\n  insert t v <> Nil.\nProof.\n  intros t v. induction t as [| v' l IHl r IHr]; simpl;\n  (try destruct (v <? v'));\n  (try destruct (v' <? v));\n  intros H; discriminate H.\nQed.\n\nFixpoint search (t : tree) (v : nat) : bool :=\n   match t with\n   | Nil => false\n   | Node v' l r => if v <? v'\n                   then search l v\n                   else if v' <? v\n                        then search r v\n                        else true\n  end.\n\nFixpoint ForallT (t : tree) (P : nat -> Prop) : Prop :=\n  match t with\n  | Nil => True\n  | Node v' l r => P v' /\\ ForallT l P /\\ ForallT r P\n  end.\n\nInductive BST : tree -> Prop :=\n  | BST_Empty: BST Nil\n  | BST_Node (v : nat) (l r : tree) :\n    BST l ->\n    BST r ->\n    ForallT l (fun x => x < v) ->\n    ForallT r (fun x => x > v) ->\n    BST (Node v l r).\n\nLemma ForallT_insert : forall (t : tree) (P : nat -> Prop) (v : nat),\n  P v -> ForallT t P -> ForallT (insert t v) P.\nProof.\n intros t P v H1 H2. induction t as [| v' l IHr r IHl]; simpl.\n - repeat split. apply H1.\n - destruct (v <? v').\n  + simpl. simpl in H2. destruct H2 as [H2 [H3 H4]]. repeat split.\n    * apply H2.\n    * apply IHr. apply H3.\n    * apply H4.\n  + destruct (v' <? v).\n    * simpl. simpl in H2.\n      destruct H2 as [H2 [H3 H4]]. repeat split; auto.\n    * auto.\nQed.\n\nTheorem insertBST : forall (v : nat) (t : tree),\n  BST t -> BST (insert t v).\nProof.\n  intros v t H. induction H as [| v' l r H1 IHl H2 IHr H3 H4].\n  - simpl. constructor; try constructor.\n  - simpl. destruct (v<? v') eqn: E1.\n    + constructor; auto. apply ForallT_insert.\n      * apply Nat.ltb_lt. apply E1.\n      * auto.\n    + destruct (v'<? v) eqn: E2.\n      * constructor; auto. apply ForallT_insert.\n        -- unfold gt. apply Nat.ltb_lt. apply E2.\n        -- auto.\n      * constructor; auto.\nQed.\n\nFixpoint InT (t : tree) (v : nat) : Prop :=\n  match t with\n  | Nil => False\n  | Node v' l r => v = v' \\/ InT l v \\/ InT r v\n  end.\n\nLemma ForallT_InT : forall (t : tree) (v : nat) (P : nat -> Prop),\n  ForallT t P -> InT t v -> P v.\nProof.\n  intros t v P H H'. induction t as [| v' l IHl r IHr].\n  - inversion H'.\n  - simpl in H'. simpl in H. destruct H' as [H' | [H' | H']].\n    + destruct H as [H _]. rewrite H'. apply H.\n    + destruct H as [_ [H _]]. apply IHl; auto.\n    + destruct H as [_ [_ H]]. apply IHr; auto.\nQed.\n\nTheorem searchBST : forall (v : nat) (t : tree),\n  BST t -> search t v = true <-> InT t v.\nProof.\n  intros v t H. split; induction H as [| v1 l1 r1 H1 H3 H2 H4 IHl1 IHr1].\n  - intros H. discriminate.\n  - simpl. destruct (v <? v1) eqn: E1.\n    + intros H. right. left. auto.\n    + destruct (v1 <? v) eqn: E2.\n      * intros H. right. right. auto.\n      * intros H. left. clear H.\n        apply Nat.ltb_ge in E1. apply Nat.ltb_ge in E2.\n        apply Nat.le_antisymm; auto.\n  - simpl. auto.\n  - simpl. intros [H | [H | H]].\n    + rewrite H. rewrite Nat.ltb_irrefl. reflexivity.\n    + apply ForallT_InT with (v := v) in IHl1; auto.\n      apply Nat.ltb_lt in IHl1. rewrite IHl1. apply H3. apply H.\n    + apply ForallT_InT with (v := v) in IHr1; auto.\n      unfold gt in IHr1. apply Nat.ltb_lt in IHr1. rewrite IHr1.\n      apply Nat.ltb_lt in IHr1. apply Nat.lt_le_incl in IHr1.\n      apply Nat.ltb_ge in IHr1. rewrite IHr1. apply H4. apply H.\nQed.\n\n(* -------------- AVL -------------- *)\nFixpoint height (t : tree) : nat :=\n  match t with\n  | Nil => 0\n  | Node v l r => S (max (height l) (height r))\n  end.\n\n(* BT = Balanced Tree *)\nInductive BT : tree -> Prop :=\n  | BT_Empty: BT Nil\n  | BT_Node_Eq (v : nat) (l r : tree) : \n    BT l ->\n    BT r ->\n    height r = height l ->\n    BT (Node v l r)\n  | BT_Node_R (v : nat) (l r : tree) : \n    BT l ->\n    BT r ->\n    height r = S (height l) ->\n    BT (Node v l r)\n  | BT_Node_L (v : nat) (l r : tree) : \n    BT l ->\n    BT r ->\n    height l = S (height r) ->\n    BT (Node v l r).\n\nDefinition AVL (t : tree) : Prop :=\n  BST t /\\ BT t.\n\nDefinition left_rotate (t : tree) : tree :=\n  match t with\n  | Node v1 l1 (Node v2 l2 r2) => Node v2 (Node v1 l1 l2) r2\n  | _ => t\n  end.\n\nLemma ForallT_lt_trans : forall (n m : nat) (t : tree),\n  n < m -> ForallT t (fun x : nat => x < n) -> ForallT t (fun x : nat => x < m).\nProof.\n  intros n m t H1 H2. induction t as [| v l IHl r IHr];\n  simpl; auto.\n  repeat split.\n  - simpl in H2. destruct H2 as [H2 H3].\n    apply Nat.lt_trans with (m := n); auto.\n  - apply IHl. simpl in H2. destruct H2 as [H2 [H3 H4]].\n    auto.\n  - apply IHr. simpl in H2. destruct H2 as [H2 [H3 H4]].\n    auto.\nQed.\n\nLemma left_rotate_BST : forall (t : tree),\n  BST t -> BST (left_rotate t).\nProof.\n  intros t H. inversion H; unfold left_rotate.\n  - constructor.\n  - destruct r as [| v' l' r'].\n    + rewrite H4. apply H.\n    + constructor.\n      * inversion H1. constructor; auto.\n        simpl in H3. destruct H3 as [H3 [H12 H13]].\n        auto.\n      * inversion H1; auto.\n      * simpl in H3. destruct H3 as [H3 [H12 H13]].\n        simpl. repeat split.\n        -- auto.\n        -- apply ForallT_lt_trans with (n := v); auto.\n        -- inversion H1. auto.\n      * inversion H1. auto.\nQed.\n\nLemma ForallT_left_rotate : forall (P : nat -> Prop) (t : tree),\n  ForallT t P ->\n  ForallT (left_rotate t) P.\nProof.\n  intros P t H. induction t as [| v1 l1 IHl1 r1 IHr1]; auto.\n  unfold left_rotate. destruct r1 as [| l2 r2]; auto.\n  simpl. simpl in H. destruct H as [H1 [H2 [H3 [H4 H5]]]].\n  repeat split; auto.\nQed.\n\nDefinition right_rotate (t : tree) : tree :=\n  match t with\n  | Node v1 (Node v2 l2 r2) r1 => Node v2 l2 (Node v1 r2 r1)\n  | _ => t\n  end.\n\nLemma ForallT_gt_trans : forall (n m : nat) (t : tree),\n  n > m -> ForallT t (fun x : nat => x > n) -> ForallT t (fun x : nat => x > m).\nProof.\n  intros n m t H1 H2. induction t as [| v l IHl r IHr];\n  simpl; auto.\n  repeat split.\n  - simpl in H2. destruct H2 as [H2 H3].\n    apply Nat.lt_trans with (m := n); auto.\n  - apply IHl. simpl in H2. destruct H2 as [H2 [H3 H4]].\n    auto.\n  - apply IHr. simpl in H2. destruct H2 as [H2 [H3 H4]].\n    auto.\nQed.\n\nLemma right_rotate_BST : forall (t : tree),\n  BST t -> BST (right_rotate t).\nProof.\n  intros t H. inversion H; unfold right_rotate.\n  - constructor.\n  - destruct l as [| v' l' r'].\n    + rewrite H4. auto.\n    + constructor.\n      * inversion H0. auto.\n      * constructor; auto.\n        -- inversion H0. auto.\n        -- simpl in H2. destruct H2 as [H2 [H5 H6]]. auto.\n      * inversion H0. auto.\n      * simpl. repeat split. \n        -- simpl in H2. destruct H2 as [H2 [H5 H6]]. auto.\n        -- inversion H0. auto.\n        -- simpl in H2. destruct H2 as [H2 [H5 H6]].\n           apply ForallT_gt_trans with (n := v); auto.\nQed.\n\nLemma ForallT_right_rotate : forall (P : nat -> Prop) (t : tree),\n  ForallT t P ->\n  ForallT (right_rotate t) P.\nProof.\n  intros P t H. induction t as [| v1 l1 IHl1 r1 IHr1]; auto.\n  unfold right_rotate. destruct l1 as [| l2 r2]; auto.\n  simpl. simpl in H. destruct H as [H1 [[H2 [H3 H4]] H5]].\n  repeat split; auto.\nQed.\n\nInductive Diff : Type :=\n  | Zero\n  | One\n  | MinusOne\n  | Two\n  | MinusTwo\n  | Impossible.\n\nDefinition diff (t : tree) : Diff :=\n  match t with\n  | Nil => Zero\n  | Node _ l r => let hl := height l in\n                  let hr := height r in\n                    if hl =? hr\n                    then Zero\n                    else if hl =? (S hr)\n                    then One\n                    else if (S hl) =? hr\n                    then MinusOne\n                    else if hl =? (S (S hr))\n                    then Two\n                    else if (S (S hl)) =? hr\n                    then MinusTwo\n                    else Impossible\n  end.\n\nLemma diff_Zero : forall (v : nat) (l r : tree),\n  diff (Node v l r) = Zero <-> height l = height r.\nProof.\n  intros. split.\n  - intros H. unfold diff in H.\n    destruct (height l =? height r) eqn: E.\n    apply Nat.eqb_eq; apply E.\n    destruct (height l =? S (height r)). discriminate.\n    destruct (S (height l) =? height r). discriminate.\n    destruct (height l =? S (S (height r))). discriminate.\n    destruct (S (S (height l)) =? height r); discriminate.\n  - intros H. apply Nat.eqb_eq in H. unfold diff. rewrite H. auto.\nQed.\n\nLemma diff_One : forall (v : nat) (l r : tree),\n  diff (Node v l r) = One <-> height l = S (height r).\nProof.\n  intros. split.\n  - intros H. unfold diff in H.\n    destruct (height l =? height r). discriminate.\n    destruct (height l =? S (height r)) eqn: E. \n    apply Nat.eqb_eq; apply E.\n    destruct (S (height l) =? height r). discriminate.\n    destruct (height l =? S (S (height r))). discriminate.\n    destruct (S (S (height l)) =? height r); discriminate.\n  - intros H. unfold diff.\n    destruct (height l =? height r) eqn: E.\n    apply Nat.eqb_eq in E. rewrite H in E. apply Nat.neq_succ_diag_l in E.\n    inversion E.\n    apply Nat.eqb_eq in H. rewrite H. auto.\nQed.\n\nLemma neq_succ_2_diag_l : forall (n : nat),\n  S (S n) <> n.\nProof.\n  intros n H. induction n as [| n' IHn'].\n  - discriminate.\n  - apply Nat.succ_inj in H. apply IHn' in H. inversion H.\nQed.\n\nLemma diff_MinusOne : forall (v : nat) (l r : tree),\n  diff (Node v l r) = MinusOne <-> S (height l) = height r.\nProof.\n  intros. split.\n  - intros H. unfold diff in H.\n    destruct (height l =? height r). discriminate.\n    destruct (height l =? S (height r)). discriminate.\n    destruct (S (height l) =? height r) eqn: E.\n    apply Nat.eqb_eq; apply E.\n    destruct (height l =? S (S (height r))). discriminate.\n    destruct (S (S (height l)) =? height r); discriminate.\n  - intros H. unfold diff.\n    destruct (height l =? height r) eqn: E1.\n    apply Nat.eqb_eq in E1. rewrite E1 in H.\n    apply Nat.neq_succ_diag_l in H. inversion H.\n    destruct (height l =? S (height r)) eqn: E2.\n    apply Nat.eqb_eq in E2. rewrite E2 in H.\n    apply neq_succ_2_diag_l in H. inversion H.\n    apply Nat.eqb_eq in H. rewrite H. reflexivity.\nQed.\n\nLemma neq_succ_3_diag_l : forall (n : nat),\n  n <> S (S (S n)).\nProof.\n  intros n H. induction n as [| n' IHn'].\n  - discriminate.\n  - apply Nat.succ_inj in H. apply IHn' in H. inversion H.\nQed.\n\nLemma diff_Two : forall (v : nat) (l r : tree),\n  diff (Node v l r) = Two <-> height l = S (S (height r)).\nProof.\n  intros. split.\n  - intros H. unfold diff in H.\n    destruct (height l =? height r). discriminate.\n    destruct (height l =? S (height r)). discriminate.\n    destruct (S (height l) =? height r). discriminate.\n    destruct (height l =? S (S (height r))) eqn: E.\n    apply Nat.eqb_eq; apply E.\n    destruct (S (S (height l)) =? height r); discriminate.\n  - intros H. unfold diff.\n    destruct (height l =? height r) eqn: E1.\n    apply Nat.eqb_eq in E1. rewrite E1 in H.\n    symmetry in H. apply neq_succ_2_diag_l in H. inversion H.\n    destruct (height l =? S (height r)) eqn: E2.\n    apply Nat.eqb_eq in E2. rewrite E2 in H.\n    apply Nat.succ_inj in H. symmetry in H.\n    apply Nat.neq_succ_diag_l in H. inversion H.\n    destruct (S (height l) =? height r) eqn: E3.\n    apply Nat.eqb_eq in E3. rewrite <- E3 in H.\n    apply neq_succ_3_diag_l in H. inversion H.\n    apply Nat.eqb_eq in H. rewrite H. reflexivity.\nQed.\n\nLemma neq_succ_4_diag_l : forall (n : nat),\n  S (S (S (S n))) <> n.\nProof.\n  intros n H. induction n as [| n' IHn'].\n  - discriminate.\n  - apply Nat.succ_inj in H. apply IHn' in H. inversion H.\nQed.\n\nLemma diff_MinusTwo : forall (v : nat) (l r : tree),\n  diff (Node v l r) = MinusTwo <-> S (S (height l)) = height r.\nProof.\n  intros. split.\n  - intros H. unfold diff in H.\n    destruct (height l =? height r). discriminate.\n    destruct (height l =? S (height r)). discriminate.\n    destruct (S (height l) =? height r). discriminate.\n    destruct (height l =? S (S (height r))). discriminate.\n    destruct (S (S (height l)) =? height r) eqn: E.\n    apply Nat.eqb_eq; apply E. inversion H.\n  - intros H. unfold diff.\n    destruct (height l =? height r) eqn: E1.\n    apply Nat.eqb_eq in E1. rewrite E1 in H.\n    apply neq_succ_2_diag_l in H. inversion H.\n    destruct (height l =? S (height r)) eqn: E2.\n    apply Nat.eqb_eq in E2. rewrite E2 in H.\n    symmetry in H. apply neq_succ_3_diag_l in H. inversion H.\n    destruct (S (height l) =? height r) eqn: E3.\n    apply Nat.eqb_eq in E3. rewrite <- E3 in H.\n    apply Nat.succ_inj in H. apply Nat.neq_succ_diag_l in H. inversion H.\n    destruct (height l =? S (S (height r))) eqn: E4.\n    apply Nat.eqb_eq in E4. rewrite E4 in H.\n    apply neq_succ_4_diag_l in H. inversion H.\n    apply Nat.eqb_eq in H. rewrite H. reflexivity.\nQed.\n\n(* ---------- insert AVL ----------*)\nDefinition rebalance_right (t : tree) : tree :=\n  match t with\n  | Nil => Nil\n  | Node v l r => match diff l with\n                  | MinusOne => right_rotate (Node v (left_rotate l) r)\n                  | _ => right_rotate (Node v l r)\n                  end\n  end.\n\nLemma rebalance_right_BST : forall (t : tree),\n  BST t -> BST (rebalance_right t).\nProof.\n  intros t H. unfold rebalance_right. inversion H.\n  - constructor.\n  - destruct (diff l); apply right_rotate_BST; subst; auto.\n    constructor; auto.\n    + apply left_rotate_BST; auto.\n    + destruct l as [| v1 l1 r1]; auto.\n      simpl. destruct r1 as [| v2 l2 r2]; auto.\n      inversion H. simpl in H9.\n      destruct H9 as [H11 [H12 [H13 [H14]]]].\n      simpl in H2. destruct H2 as [H15 [H16]].\n      simpl. repeat split; assumption.\nQed.\n\nLemma ForallT_rebalance_right : forall (P : nat -> Prop) (t : tree),\n  ForallT t P ->\n  ForallT (rebalance_right t) P.\nProof.\n  intros P t H. induction t as [| v1 l1 IHl1 r1 IHr1]; auto.\n  unfold rebalance_right. destruct (diff l1);\n  apply ForallT_right_rotate; auto.\n  simpl. simpl in H. destruct H as [H1 [H2 H3]].\n  repeat split; auto.\n  apply ForallT_left_rotate. auto.\nQed.\n\nDefinition rebalance_left (t : tree) : tree :=\n  match t with\n  | Nil => Nil\n  | Node v l r => match diff r with\n                  | One => left_rotate (Node v l (right_rotate r))\n                  | _ => left_rotate (Node v l r)\n                  end\n  end.\n\nLemma rebalance_left_BST : forall (t : tree),\n  BST t -> BST (rebalance_left t).\nProof.\n  intros t H. unfold rebalance_left. inversion H.\n  - constructor.\n  - destruct (diff r); apply left_rotate_BST; subst; auto.\n    constructor; auto.\n    + apply right_rotate_BST; auto.\n    + unfold right_rotate. destruct r as [| v1 l1 r1];\n      auto. destruct l1 as [| v2 l2 r2]; auto.\n      simpl in H3. destruct H3 as [H5 [[H7 [H8]]]].\n      simpl. repeat split; assumption.\nQed.\n\nLemma ForallT_rebalance_left : forall (P : nat -> Prop) (t : tree),\n  ForallT t P ->\n  ForallT (rebalance_left t) P.\nProof.\n  intros P t H. induction t as [| v1 l1 IHl1 r1 IHr1]; auto.\n  unfold rebalance_left. destruct (diff r1);\n  apply ForallT_left_rotate; auto.\n  simpl. simpl in H. destruct H as [H1 [H2 H3]].\n  repeat split; auto.\n  apply ForallT_right_rotate. auto.\nQed.\n\nDefinition rebalance (t : tree) : tree :=\n  match diff t with\n  | Two => rebalance_right t\n  | MinusTwo => rebalance_left t\n  | _ => t\n  end.\n\nTheorem rebalance_BST : forall (t : tree),\n  BST t -> BST (rebalance t).\nProof.\n  intros t H. unfold rebalance. inversion H.\n  - constructor.\n  - destruct (diff (Node v l r)); subst; auto.\n    + apply rebalance_right_BST; auto.\n    + apply rebalance_left_BST; auto.\nQed.\n\nFixpoint insertAVL (t : tree) (v : nat) : tree :=\n  match t with\n  | Nil => Node v Nil Nil\n  | Node v' l r => if v <? v'\n                   then rebalance (Node v' (insertAVL l v) r)\n                   else if v' <? v\n                        then rebalance (Node v' l (insertAVL r v))\n                        else t\n  end.\n\nLemma max_Sn_n : forall (n : nat),\n  max (S n) n = S n.\nProof.\n  intros n. apply max_l. auto.\nQed.\n\nLemma max_n_Sn : forall (n : nat),\n  max n (S n) = S n.\nProof.\n  intros n. rewrite Nat.max_comm. apply max_Sn_n.\nQed.\n\nLemma max_SSn_n : forall (n: nat),\n  max (S (S n)) n = S ( S n).\nProof.\n  intros n. induction n as [| n' IHn']; auto.\n  simpl. destruct n'; auto.\nQed.\n\nLemma insertAVL_height : forall (t : tree) (v: nat),\n  BT t ->\n  height (insertAVL t v) = S (height t) \\/ height (insertAVL t v) = height t.\nProof.\n  intros. induction H as \n    [|\n     v' l r BTl IHl BTr IHr EQlr |\n     v' l r BTl IHl BTr IHr EQlr |\n     v' l r BTl IHl BTr IHr EQlr ].\n  - simpl. left. reflexivity.\n  - simpl. destruct (v <? v').\n    + unfold rebalance. destruct (diff (Node v' (insertAVL l v) r)) eqn:EQ;\n      try (simpl; destruct IHl as [IHl | IHl]; [\n        rewrite IHl; destruct (S (height l) <=? height r) eqn: EQ2; [\n           apply Nat.leb_le in EQ2; right; f_equal; rewrite max_r; auto;\n              symmetry; apply max_r; rewrite Nat.le_succ_l in EQ2;\n              apply Nat.lt_le_incl in EQ2; apply EQ2 |\n           rewrite Nat.leb_gt in EQ2; left; f_equal; rewrite max_l; [\n              f_equal; unfold lt in EQ2; apply le_S_n in EQ2;\n                 symmetry; apply max_l; apply EQ2 |\n             apply Nat.lt_le_incl; apply EQ2 ]]|\n        right; f_equal; rewrite IHl; reflexivity ]).\n     * unfold rebalance_right. destruct (diff (insertAVL l v)) eqn:EQ2;\n       try (unfold right_rotate; destruct (insertAVL l v); [\n            simpl; apply diff_Two in EQ; simpl in EQ; discriminate |\n            simpl; apply diff_Two in EQ; simpl in EQ; injection EQ as EQ;\n              destruct IHl; [\n              simpl in H; injection H as H; rewrite <- H; rewrite EQ;\n                 rewrite max_Sn_n;\n                 pose proof (Nat.max_spec (height t2) (height t1)) as H1;\n                 destruct H1 as [ [H1 H2] | [H1 H2]]; [\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     simpl; rewrite Nat.max_assoc; right; f_equal; f_equal;\n                     apply max_r; rewrite max_l; auto; rewrite EQ in H1; unfold lt in H1;\n                     apply le_S_n; auto |\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     rewrite max_Sn_n; left; f_equal; apply max_r; rewrite EQ in H1; auto ] |\n              simpl in H; rewrite EQ in H; rewrite EQlr in H; apply neq_succ_2_diag_l in H;\n                 inversion H ]]).\n        unfold right_rotate. destruct (insertAVL l v) eqn:EQ3.\n        -- simpl. rewrite EQlr. right. f_equal. rewrite Nat.max_id. reflexivity.\n        -- unfold left_rotate. destruct t2 eqn:EQ4.\n           ++ simpl. apply diff_MinusOne in EQ2. discriminate.\n           ++ simpl. apply diff_MinusOne in EQ2. simpl in EQ2. injection EQ2 as EQ2.\n              apply diff_Two in EQ. simpl in EQ. injection EQ as EQ. rewrite EQ2 in EQ.\n              rewrite Nat.max_comm in EQ. rewrite max_Sn_n in EQ. injection EQ as EQ.\n              assert (H: max (height t1) (height t3) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite EQ2. rewrite Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. clear H.\n              assert (H: max (height t4) (height r) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite <- EQ. rewrite <- Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. rewrite Nat.max_id. rewrite EQ. rewrite EQlr.\n              left. rewrite Nat.max_id. reflexivity.\n      * apply diff_MinusTwo in EQ. destruct IHl.\n        -- rewrite <- EQlr in H. rewrite H in EQ. symmetry in EQ.\n           apply neq_succ_3_diag_l in EQ. inversion EQ.\n        -- rewrite <- EQlr in H. rewrite H in EQ.\n           apply neq_succ_2_diag_l in EQ. inversion EQ.\n    +  destruct (v' <? v).\n       * unfold rebalance. destruct (diff (Node v' l (insertAVL r v))) eqn:EQ;\n         try ( simpl; destruct IHr as [IHr | IHr]; [\n            rewrite IHr; rewrite EQlr; left; rewrite Nat.max_id; rewrite Nat.max_comm;\n            rewrite max_Sn_n; reflexivity |\n            rewrite IHr; rewrite EQlr; right; reflexivity ]).\n         -- apply diff_Two in EQ. destruct IHr. \n            ++ rewrite EQlr in H. rewrite H in EQ.\n               apply neq_succ_3_diag_l in EQ. inversion EQ.\n            ++ rewrite EQlr in H. rewrite H in EQ. symmetry in EQ.\n               apply neq_succ_2_diag_l in EQ. inversion EQ. \n         -- apply diff_MinusTwo in EQ. destruct IHr.\n            ++ rewrite EQlr in H. rewrite H in EQ. apply Nat.neq_succ_diag_l in EQ.\n               inversion EQ.\n            ++ rewrite EQlr in H. rewrite H in EQ. apply neq_succ_2_diag_l in EQ.\n               inversion EQ.\n       * simpl. right. reflexivity.\n  - simpl. destruct (v <? v').\n    + unfold rebalance. destruct (diff (Node v' (insertAVL l v) r)) eqn:EQ;\n      try (simpl; destruct IHl as [IHl | IHl]; [\n        rewrite IHl; destruct (S (height l) <=? height r) eqn: EQ2; [\n           apply Nat.leb_le in EQ2; right; f_equal; rewrite max_r; auto;\n              symmetry; apply max_r; rewrite Nat.le_succ_l in EQ2;\n              apply Nat.lt_le_incl in EQ2; apply EQ2 |\n           rewrite Nat.leb_gt in EQ2; left; f_equal; rewrite max_l; [\n              f_equal; unfold lt in EQ2; apply le_S_n in EQ2;\n                 symmetry; apply max_l; apply EQ2 |\n             apply Nat.lt_le_incl; apply EQ2 ]]|\n        right; f_equal; rewrite IHl; reflexivity ]).\n     * unfold rebalance_right. destruct (diff (insertAVL l v)) eqn:EQ2;\n        try (unfold right_rotate; destruct (insertAVL l v); [\n            simpl; apply diff_Two in EQ; simpl in EQ; discriminate |\n            simpl; apply diff_Two in EQ; simpl in EQ; injection EQ as EQ;\n              destruct IHl; [\n              simpl in H; injection H as H; rewrite <- H; rewrite EQ;\n                 rewrite max_Sn_n;\n                 pose proof (Nat.max_spec (height t2) (height t1)) as H1;\n                 destruct H1 as [ [H1 H2] | [H1 H2]]; [\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     simpl; rewrite Nat.max_assoc; right; f_equal; f_equal;\n                     apply max_r; rewrite max_l; auto; rewrite EQ in H1; unfold lt in H1;\n                     apply le_S_n; auto |\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     rewrite max_Sn_n; left; f_equal; apply max_r; rewrite EQ in H1; auto ] |\n            simpl in H; rewrite EQ in H; rewrite EQlr in H; symmetry in H; apply neq_succ_3_diag_l in H;\n                 inversion H]]).\n        unfold right_rotate. destruct (insertAVL l v) eqn:EQ3.\n        -- simpl. rewrite EQlr. right. f_equal. rewrite Nat.max_comm. rewrite max_Sn_n.\n           reflexivity.\n        -- unfold left_rotate. destruct t2 eqn:EQ4.\n           ++ simpl. apply diff_MinusOne in EQ2. discriminate.\n           ++ simpl. apply diff_MinusOne in EQ2. simpl in EQ2. injection EQ2 as EQ2.\n              apply diff_Two in EQ. simpl in EQ. injection EQ as EQ. rewrite EQ2 in EQ.\n              rewrite Nat.max_comm in EQ. rewrite max_Sn_n in EQ. injection EQ as EQ.\n              assert (H: max (height t1) (height t3) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite EQ2. rewrite Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. clear H.\n              assert (H: max (height t4) (height r) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite <- EQ. rewrite <- Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. rewrite Nat.max_id. rewrite EQ. rewrite EQlr.\n              left. rewrite Nat.max_comm. rewrite max_Sn_n. reflexivity.\n      * apply diff_MinusTwo in EQ. destruct IHl.\n        -- rewrite <- EQlr in H. rewrite H in EQ.\n           apply neq_succ_2_diag_l in EQ. inversion EQ.\n        -- rewrite EQlr in EQ. rewrite H in EQ.\n           apply Nat.neq_succ_diag_l in EQ. inversion EQ.\n    +  destruct (v' <? v).\n       * unfold rebalance. destruct (diff (Node v' l (insertAVL r v))) eqn:EQ;\n         try (simpl; destruct IHr as [IHr | IHr]; [\n             rewrite IHr; rewrite EQlr; left; rewrite Nat.max_comm;\n             rewrite max_SSn_n; rewrite Nat.max_comm;\n            rewrite max_Sn_n; reflexivity |\n            rewrite IHr; rewrite EQlr; right; reflexivity ]).\n         -- apply diff_Two in EQ. destruct IHr. \n            ++ rewrite EQlr in H. rewrite H in EQ. symmetry in EQ.\n               apply neq_succ_4_diag_l in EQ. inversion EQ.\n            ++ rewrite EQlr in H. rewrite H in EQ.\n               apply neq_succ_3_diag_l in EQ. inversion EQ. \n         -- apply diff_MinusTwo in EQ. destruct IHr.\n            ++ unfold rebalance_left. Arguments max: simpl never.\n               destruct ( diff (insertAVL r v)) eqn:EQ2;\n               try (unfold left_rotate; destruct (insertAVL r v); [ discriminate |\n                    simpl in EQ; injection EQ as EQ;\n                      simpl in H; injection H as H; simpl;\n                      pose proof (Nat.max_spec (height t1) (height t2)) as H1;\n                 destruct H1 as [ [H1 H2] | [H1 H2]]; [\n                   rewrite H2 in EQ; rewrite <- EQ;\n                     rewrite <- EQ in H1; unfold lt in H1; apply le_S_n in H1; right;\n                     rewrite EQlr; rewrite max_n_Sn; f_equal; apply max_r; rewrite max_l; auto |\n                   rewrite H2 in EQ; rewrite <- EQ;\n                     rewrite max_n_Sn; left; f_equal; f_equal; rewrite EQlr; rewrite max_n_Sn;\n                     apply max_l; rewrite <- EQ in H1; auto ]]).\n                unfold left_rotate. destruct (insertAVL r v) eqn: EQ3.\n                ** inversion EQ2.\n                ** apply diff_One in EQ2. unfold right_rotate. destruct t1.\n                   --- discriminate.\n                   --- simpl in EQ2. simpl in EQ. rewrite EQ2 in EQ. rewrite max_Sn_n in EQ.\n                       injection EQ as EQ. simpl in H. injection H as H. rewrite EQ2 in H.\n                       rewrite max_Sn_n in H. injection EQ2 as EQ2.\n                       Arguments max : simpl nomatch. simpl.\n                       assert (H': max (height l) (height t1_1) = height l).\n                       { rewrite EQ. rewrite <- Nat.max_comm in EQ2. rewrite <- EQ2.\n                         rewrite <- Nat.max_assoc. rewrite Nat.max_id. reflexivity. }\n                       rewrite H'. clear H'.\n                       assert (H': max (height t1_2) (height t2) = height l).\n                       { rewrite Nat.max_comm. rewrite <- EQ2. rewrite <- Nat.max_assoc.\n                         rewrite Nat.max_id. rewrite <- EQ in EQ2. apply EQ2. }\n                       rewrite H'. rewrite EQlr. right. rewrite Nat.max_id. rewrite max_n_Sn.\n                       reflexivity.\n            ++ rewrite EQlr in H. rewrite H in EQ.\n               apply Nat.neq_succ_diag_l in EQ. inversion EQ.\n       * simpl. right. reflexivity.\n  - simpl. destruct (v <? v').\n    + unfold rebalance. destruct (diff (Node v' (insertAVL l v) r)) eqn:EQ;\n      try (simpl; destruct IHl as [IHl | IHl]; [\n        rewrite IHl; destruct (S (height l) <=? height r) eqn: EQ2; [\n           apply Nat.leb_le in EQ2; right; f_equal; rewrite max_r; auto;\n              symmetry; apply max_r; rewrite Nat.le_succ_l in EQ2;\n              apply Nat.lt_le_incl in EQ2; apply EQ2 |\n           rewrite Nat.leb_gt in EQ2; left; f_equal; rewrite max_l; [\n              f_equal; unfold lt in EQ2; apply le_S_n in EQ2;\n                 symmetry; apply max_l; apply EQ2 |\n             apply Nat.lt_le_incl; apply EQ2 ]]|\n        right; f_equal; rewrite IHl; reflexivity ]).\n     * unfold rebalance_right. destruct (diff (insertAVL l v)) eqn:EQ2;\n        try (unfold right_rotate; destruct (insertAVL l v); [\n            simpl; apply diff_Two in EQ; simpl in EQ; discriminate |\n            simpl; apply diff_Two in EQ; simpl in EQ; injection EQ as EQ;\n              destruct IHl; [\n              simpl in H; injection H as H; rewrite <- H; rewrite EQ;\n                 rewrite max_Sn_n;\n                 pose proof (Nat.max_spec (height t2) (height t1)) as H1;\n                 destruct H1 as [ [H1 H2] | [H1 H2]]; [\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     simpl; rewrite Nat.max_assoc; right; f_equal; f_equal;\n                     apply max_r; rewrite max_l; auto; rewrite EQ in H1; unfold lt in H1;\n                     apply le_S_n; auto |\n                  rewrite Nat.max_comm in H2; rewrite H2 in EQ; rewrite EQ;\n                     rewrite max_Sn_n; left; f_equal; apply max_r; rewrite EQ in H1; auto ] |\n            simpl in H; rewrite EQ in H; rewrite EQlr in H; apply Nat.neq_succ_diag_l in H;\n                 inversion H]]).\n        unfold right_rotate. destruct (insertAVL l v) eqn:EQ3.\n        -- simpl. rewrite EQlr. inversion EQ2.\n        -- unfold left_rotate. destruct t2 eqn:EQ4.\n           ++ simpl. apply diff_MinusOne in EQ2. discriminate.\n           ++ simpl. apply diff_MinusOne in EQ2. simpl in EQ2. injection EQ2 as EQ2.\n              apply diff_Two in EQ. simpl in EQ. injection EQ as EQ. rewrite EQ2 in EQ.\n              rewrite Nat.max_comm in EQ. rewrite max_Sn_n in EQ. injection EQ as EQ.\n              assert (H: max (height t1) (height t3) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite EQ2. rewrite Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. clear H.\n              assert (H: max (height t4) (height r) = max (height t3) (height t4)).\n              { rewrite Nat.max_comm. rewrite <- EQ. rewrite <- Nat.max_assoc.\n                rewrite Nat.max_id. reflexivity. }\n              rewrite H. rewrite Nat.max_id. rewrite EQ. rewrite EQlr.\n              right. rewrite max_Sn_n. reflexivity.\n      * apply diff_MinusTwo in EQ. destruct IHl.\n        -- rewrite EQlr in H. rewrite H in EQ.\n           apply neq_succ_4_diag_l in EQ. inversion EQ.\n        -- rewrite EQlr in H. rewrite H in EQ. symmetry in EQ.\n           apply neq_succ_3_diag_l in EQ. inversion EQ.\n    +  destruct (v' <? v).\n       * unfold rebalance. destruct (diff (Node v' l (insertAVL r v))) eqn:EQ;\n         try (simpl; destruct IHr as [IHr | IHr]; [\n             rewrite IHr; rewrite EQlr; right; rewrite Nat.max_id;\n            rewrite max_Sn_n; reflexivity |\n             rewrite IHr; rewrite EQlr; right; reflexivity]).\n         -- apply diff_Two in EQ. destruct IHr. \n            ++ rewrite <- EQlr in H. rewrite H in EQ. symmetry in EQ.\n               apply neq_succ_2_diag_l in EQ. inversion EQ.\n            ++ rewrite EQlr in EQ. rewrite H in EQ. symmetry in EQ.\n               apply Nat.neq_succ_diag_l in EQ. inversion EQ. \n         -- apply diff_MinusTwo in EQ. destruct IHr.\n            ++ rewrite <- EQlr in H. rewrite H in EQ. apply neq_succ_2_diag_l in EQ.\n               inversion EQ.\n            ++ rewrite EQlr in EQ. rewrite H in EQ. symmetry in EQ.\n               apply neq_succ_3_diag_l in EQ. inversion EQ.\n       * simpl. right. reflexivity.\nQed.\n\nLemma rebalance_right_BT : forall (l r : tree) (v : nat),\n  BT l -> BT r -> height l = S (S (height r)) ->\n  BT (rebalance_right (Node v l r)).\nProof.\n  intros. unfold rebalance_right. destruct l; try discriminate.\n  inversion H.\n  - symmetry in H7. apply diff_Zero with (v:= v0) in H7. rewrite H7.\n    unfold right_rotate. apply diff_Zero in H7. simpl in H1. injection H1 as H1.\n    rewrite H7 in H1. rewrite Nat.max_id in H1. apply BT_Node_R.\n    + auto.\n    + apply BT_Node_L; auto.\n    + simpl. rewrite H1. rewrite max_Sn_n. f_equal.\n      rewrite H7. rewrite H1. reflexivity.\n  - symmetry in H7. apply diff_MinusOne with (v:= v0) in H7. rewrite H7.\n    unfold right_rotate. unfold left_rotate. destruct l2.\n    + apply diff_MinusOne in H7. discriminate.\n    + apply diff_MinusOne in H7. simpl in H7. simpl in H1.\n      rewrite <- H7 in H1. rewrite max_n_Sn in H1. injection H1 as H1.\n      injection H7 as H7. inversion H6.\n      * rewrite H13 in H7. rewrite Nat.max_id in H7. apply BT_Node_Eq.\n        -- apply BT_Node_Eq; auto.\n        -- apply BT_Node_Eq; auto. rewrite <- H13 in H7. rewrite H7 in H1.\n           symmetry in H1. apply H1.\n        -- simpl. rewrite <- H1. rewrite H7. rewrite Nat.max_id. rewrite <- H13.\n           rewrite Nat.max_id. auto.\n      * rewrite H13 in H7. rewrite max_n_Sn in H7. apply BT_Node_Eq.\n        -- apply BT_Node_L; auto.\n        -- apply BT_Node_Eq; auto. rewrite <- H13 in H7. rewrite H7 in H1.\n           symmetry in H1. apply H1.\n        -- simpl. rewrite <- H1. rewrite H7. rewrite H13. rewrite Nat.max_id.\n           rewrite max_Sn_n. auto.\n      * rewrite H13 in H7. rewrite max_Sn_n in H7. apply BT_Node_Eq.\n        -- apply BT_Node_Eq; auto. rewrite H7. apply H13.\n        -- apply BT_Node_R; auto. rewrite <- H7. symmetry. apply H1.\n        -- simpl. rewrite <- H1. rewrite H7. rewrite H13. rewrite Nat.max_id.\n           rewrite max_n_Sn. reflexivity.\n  - apply diff_One with (v:= v0) in H7. rewrite H7.\n    apply diff_One in H7. simpl in H1. injection H1 as H1. unfold right_rotate.\n    rewrite H7 in H1. rewrite max_Sn_n in H1. injection H1 as H1. apply BT_Node_Eq.\n    + auto.\n    + apply BT_Node_Eq; auto.\n    + simpl. rewrite H1. rewrite Nat.max_id.\n      rewrite H7. rewrite H1. reflexivity.\nQed.\n\nLemma rebalance_left_BT : forall (l r : tree) (v : nat),\n  BT l -> BT r -> S (S (height l)) = height r ->\n  BT (rebalance_left (Node v l r)).\nProof.\n  intros. unfold rebalance_left. destruct r; try discriminate.\n  inversion H0.\n  - symmetry in H7. apply diff_Zero with (v:= v0) in H7. rewrite H7.\n    unfold left_rotate. apply diff_Zero in H7. simpl in H1. rewrite H7 in H1.\n    rewrite Nat.max_id in H1. injection H1 as H1. apply BT_Node_L.\n    + rewrite <- H1 in H7. apply BT_Node_R; auto.\n    + auto.\n    + simpl. f_equal. rewrite H7. rewrite <- H1. rewrite max_n_Sn. reflexivity.\n  - symmetry in H7. apply diff_MinusOne with (v:= v0) in H7. rewrite H7.\n    unfold left_rotate. apply diff_MinusOne in H7. simpl in H1.\n    rewrite <- H7 in H1. rewrite max_n_Sn in H1. injection H1 as H1.\n    apply BT_Node_Eq.\n    + apply BT_Node_Eq; auto.\n    + auto.\n    + simpl. rewrite H1. rewrite Nat.max_id. symmetry. apply H7.\n  - apply diff_One with (v:= v0) in H7. rewrite H7.\n    unfold left_rotate. unfold right_rotate. destruct r1.\n    + apply diff_One in H7. discriminate.\n    + apply diff_One in H7. simpl in H1. simpl in H7. injection H7 as H7.\n      rewrite H7 in H1. rewrite max_Sn_n in H1. injection H1 as H1. inversion H5.\n      * rewrite H13 in H7.\n        rewrite Nat.max_id in H7. apply BT_Node_Eq.\n        -- rewrite <- H7 in H1. apply BT_Node_Eq; auto.\n        -- rewrite <- H13 in H7. apply BT_Node_Eq; auto.\n        -- simpl. rewrite H1. rewrite <- H7. rewrite H13. reflexivity.\n      * rewrite H13 in H7.\n        rewrite max_n_Sn in H7. apply BT_Node_Eq.\n        -- rewrite <- H7 in H1. apply BT_Node_L; auto.\n        -- rewrite H7 in H13. apply BT_Node_Eq; auto.\n        -- simpl. rewrite H1. rewrite <- H7. rewrite H13.\n           rewrite Nat.max_id. rewrite max_Sn_n. reflexivity.\n      * rewrite H13 in H7. rewrite max_Sn_n in H7. apply BT_Node_Eq.\n        -- rewrite <- H13 in H7. rewrite <- H7 in H1. apply BT_Node_Eq; auto.\n        -- apply BT_Node_R; auto.\n        -- simpl. rewrite H1. rewrite <- H7. rewrite H13. rewrite Nat.max_id.\n           f_equal. apply max_n_Sn.\nQed.\n\nTheorem insertAVL_BT : forall (t : tree) (v : nat),\n  BT t -> BT (insertAVL t v).\nProof.\n  intros t v H. induction H.\n  - simpl. apply BT_Node_Eq; try apply BT_Empty. reflexivity.\n  - simpl. destruct (v <? v0).\n    + unfold rebalance. destruct (diff (Node v0 (insertAVL l v) r)) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height l v) in H. destruct H.\n           ++ rewrite <- H1 in H. apply diff_One with (v := v0) in H.\n              rewrite H in EQ. discriminate.\n           ++ rewrite <- H1 in H. apply diff_Zero with (v := v0) in H.\n              rewrite H in EQ. discriminate.\n    + destruct (v0 <? v).\n      * unfold rebalance. destruct (diff (Node v0 l (insertAVL r v))) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height r v) in H0. destruct H0.\n           ++ rewrite H1 in H0. symmetry in H0. apply diff_MinusOne with (v := v0) in H0.\n              rewrite H0 in EQ. discriminate.\n           ++ rewrite H1 in H0. symmetry in H0. apply diff_Zero with (v := v0) in H0.\n              rewrite H0 in EQ. discriminate.\n     * apply BT_Node_Eq; auto.\n  - simpl. destruct (v <? v0).\n    + unfold rebalance. destruct (diff (Node v0 (insertAVL l v) r)) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height l v) in H. destruct H.\n           ++ rewrite <- H1 in H. apply diff_Zero with (v := v0) in H.\n              rewrite H in EQ. discriminate.\n           ++ rewrite <- H in H1. symmetry in H1. apply diff_MinusOne with (v := v0) in H1.\n              rewrite H1 in EQ. discriminate.\n    + destruct (v0 <? v).\n      * unfold rebalance. destruct (diff (Node v0 l (insertAVL r v))) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height r v) in H0. destruct H0.\n           ++ rewrite H1 in H0. symmetry in H0. apply diff_MinusTwo with (v := v0) in H0.\n              rewrite H0 in EQ. discriminate.\n           ++ rewrite H1 in H0. symmetry in H0. apply diff_MinusOne with (v := v0) in H0.\n              rewrite H0 in EQ. discriminate.\n     * apply BT_Node_R; auto.\n  - simpl. destruct (v <? v0).\n    + unfold rebalance. destruct (diff (Node v0 (insertAVL l v) r)) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height l v) in H. destruct H.\n           ++ rewrite H1 in H. apply diff_Two with (v := v0) in H.\n              rewrite H in EQ. discriminate.\n           ++ rewrite H1 in H. apply diff_One with (v := v0) in H.\n              rewrite H in EQ. discriminate.\n    + destruct (v0 <? v).\n      * unfold rebalance. destruct (diff (Node v0 l (insertAVL r v))) eqn:EQ.\n        -- apply diff_Zero in EQ. apply BT_Node_Eq; auto.\n        -- apply diff_One in EQ. apply BT_Node_L; auto.\n        -- apply diff_MinusOne in EQ. apply BT_Node_R; auto.\n        -- apply diff_Two in EQ. apply rebalance_right_BT; auto.\n        -- apply diff_MinusTwo in EQ. apply rebalance_left_BT; auto.\n        -- apply (insertAVL_height r v) in H0. destruct H0.\n           ++ rewrite <- H1 in H0. symmetry in H0. apply diff_Zero with (v := v0) in H0.\n              rewrite H0 in EQ. discriminate.\n           ++ rewrite <- H0 in H1. apply diff_One with (v := v0) in H1.\n              rewrite H1 in EQ. discriminate.\n     * apply BT_Node_L; auto.\nQed.\n\nLtac detruct_contradiction exp :=\n  try destruct exp; try contradiction; try (repeat (intros H; discriminate H)).\n\nLemma insertAVL_not_Nil : forall (t : tree) (v : nat),\n  insertAVL t v <> Nil.\nProof.\n  intros t v. induction t as [| v' l IHl r IHr]; simpl.\n  - intros H. discriminate H.\n  - destruct (v <? v').\n    + unfold rebalance. detruct_contradiction (diff (Node v' (insertAVL l v) r)).\n      * unfold rebalance_right. destruct (diff (insertAVL l v));\n        unfold right_rotate; try detruct_contradiction (insertAVL l v);\n        try detruct_contradiction (left_rotate (Node v0 t1 t2)).\n      * unfold rebalance_left. destruct (diff r);\n        unfold left_rotate; try detruct_contradiction r;\n        try detruct_contradiction (right_rotate (Node v0 r1 r2)).\n    + destruct (v' <? v); try (intros H; discriminate H).\n      unfold rebalance. destruct (diff (Node v' (insertAVL l v) r));\n      try detruct_contradiction (diff (Node v' l (insertAVL r v)));\n      unfold rebalance_right; try detruct_contradiction (diff l);\n      unfold right_rotate; try detruct_contradiction l;\n      try detruct_contradiction (left_rotate (Node v0 l1 l2));\n      unfold rebalance_left; try detruct_contradiction (diff (insertAVL r v));\n      unfold left_rotate; try detruct_contradiction (insertAVL r v);\n      try detruct_contradiction (right_rotate (Node v0 t1 t2));\n      try detruct_contradiction (right_rotate (Node v1 t1 t2));\n      try detruct_contradiction (right_rotate (Node v2 t3 t4)).\nQed.\n\nLemma ForallT_rebalance : forall (P : nat -> Prop) (t : tree),\n  ForallT t P ->\n  ForallT (rebalance t) P.\nProof.\n  intros P t H1. induction t as [| v1 l1 IHl1 r1 IHr1]; auto.\n  unfold rebalance. destruct (diff (Node v1 l1 r1)); auto.\n  - apply ForallT_rebalance_right. auto.\n  - apply ForallT_rebalance_left. auto.\nQed.\n\nLemma ForallT_insertAVL : forall (P : nat -> Prop) (t : tree) (v : nat),\n  P v ->\n  ForallT t P ->\n  ForallT (insertAVL t v) P.\nProof.\n  intros P t v H1 H2. induction t as [| v1 l1 IHl1 r1 IHr1]; simpl.\n  - repeat split; auto.\n  - simpl in H2. destruct H2 as [H2 [H3 H4]].\n    destruct (v <? v1).\n    + apply ForallT_rebalance. simpl.\n      repeat split; auto.\n    + destruct (v1 <? v).\n      * apply ForallT_rebalance. simpl.\n        repeat split; auto.\n      * simpl. repeat split; auto.\nQed.\n\nLemma ltb_symm : forall (n m : nat),\n  (n < m) -> (m > n).\nProof.\n  intros n m H. induction n as [| n'];\n  destruct m as [| m']; auto.\nQed.\n\nTheorem insertAVL_BST : forall (t : tree) (v : nat),\n  BST t -> BST (insertAVL t v).\nProof.\n  intros t v H. induction H as [| v1 l1 r1 H1 IHl1 H2 IHr1 H3 H4]; simpl.\n  - repeat constructor.\n  - destruct (v <? v1) eqn: Ev1.\n    + apply rebalance_BST. constructor; auto.\n      apply ForallT_insertAVL; auto.\n      apply Nat.ltb_lt in Ev1. auto.\n    + destruct (v1 <? v) eqn: Ev2.\n      * apply rebalance_BST. constructor; auto.\n        apply ForallT_insertAVL; auto.\n        apply Nat.ltb_lt in Ev2. apply ltb_symm in Ev2. auto.\n      * constructor; auto.\nQed.\n\nTheorem insertAVL_AVL : forall (t : tree) (v : nat),\n  AVL t -> AVL (insertAVL t v).\nProof.\n  unfold AVL. intros. destruct H. split.\n  - apply insertAVL_BST. apply H.\n  - apply insertAVL_BT. apply H0.\nQed.\n", "meta": {"author": "ccal2", "repo": "coqProject", "sha": "a9908a3d0da39927807e5024fb8b114740e9058e", "save_path": "github-repos/coq/ccal2-coqProject", "path": "github-repos/coq/ccal2-coqProject/coqProject-a9908a3d0da39927807e5024fb8b114740e9058e/project.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8213022727343463}}
{"text": "Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\nFixpoint nonzeros (l:natlist) : natlist := \n    match l with \n    | nil => nil \n    | O :: t => nonzeros t\n    | n :: t => n :: nonzeros t\n    end.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof. Admitted.\n\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof. Admitted.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof. Admitted. \n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof. Admitted.\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\nDefinition and (b1 b2 : bool) : bool := \n    match b1 with \n    | false => false \n    | true => match b2 with \n        | false => false \n        | true => true\n        end \n    end.\n\nLemma eqb_n_n_true : forall n : nat,\n  eqb n n = true.\nProof. Admitted.\n\n(* EXERCISE *)\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n    match l1 with \n    | nil => match l2 with \n        | nil => true \n        | _ => false\n        end\n    | h :: t => match l2 with \n        | nil => false \n        | m :: n => and (eqb h m) (eqblist t n)\n        end \n    end.\n\nExample test_eqblist1 :\n    (eqblist nil nil = true).\nProof. simpl. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\n(* EXERCISE *)\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n    intros l. induction l as [| n l' IHl'].\n    - simpl. reflexivity. \n    - simpl. \n      rewrite -> IHl'. \n      rewrite -> eqb_n_n_true. \n      rewrite <- IHl'. simpl. \n      reflexivity.\n    Qed.", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/exercises/eqblist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.8213021464883807}}
{"text": "(*Sidorets Kirill et Ait gueni ssaid Abderrahmane*)\n(* 1.2 \u03bb-calcul simplement typ\u00e9*)\n  (* 1. Bool\u00e9ens (codage des constantes et des op\u00e9rations de base) *)\n  Section type_booleen. \n    (*1.2.1*)\n    Variable T : Set. \n    Definition cbool := T -> T -> T.\n    (*bool\u00e9ens de Church vrai: \u03bbx y.x*)\n    Definition ctr : cbool := fun x y => x.\n    Print ctr.\n    (*bool\u00e9ens de Church faux: \u03bbx y.y*)\n    Definition cfa : cbool := fun x y => y.\n    Print cfa.\n    (*if b then m else n : \u03bb b m n .b m n*)    \n    Definition cif: cbool -> T ->T ->T :=fun (b : cbool) (t : T) (e : T) =>b t e.\n    Variables F V : T.\n    Compute cif ctr V F.\n    Compute cif cfa V F.\n    (* a and  b : \u03bb a b.\u03bbx y. a (b x y) y *)\n    Definition cand:cbool->cbool->cbool := fun (a:cbool) (b:cbool) =>fun (x:T) (y:T) =>a (b x y) y.\n    Compute cand ctr ctr.\n    Compute cand ctr cfa.\n    Compute cand cfa cfa.\n    Compute cand cfa ctr.\n    (* a or  b : \u03bb a b.\u03bbx y. a x (b x y) *)\n    Definition cor :cbool->cbool->cbool:= fun (a:cbool) (b:cbool) =>fun (x:T)(y:T)=>a x (b x y).\n    Compute cor ctr ctr.\n    Compute cor ctr cfa.\n    Compute cor cfa cfa.\n    Compute cor cfa ctr.\n    (*not b :\u03bb b.\u03bb x y . b y x*)\n    Definition cnot:cbool->cbool := fun (b:cbool) => fun (x:T) (y:T)=> b y x.\n    Compute cnot ctr.\n    Compute cnot cfa.\n  End type_booleen.\n  (* 2. Entiers naturels (codage de quelques constantes, des op\u00e9rations\n   successeur, addition et multiplication, et du test \u00e0 0) *)\n  Section type_nat.\n  Variable T: Set.\n    Definition compo : (T->T) -> (T->T) -> (T->T) :=fun g f => fun x => g (f x).\n\n    Notation \"g \u00b0 f\" := (compo g f) (at level 10).\n    Fixpoint iter (f:T->T) (n: nat) :=\n    match n with\n    | O => fun x => x\n    | S p => f \u00b0 (iter f p)\n    end.\n    Definition cnat := (T->T) -> (T->T).\n    Definition cnat_of : nat -> cnat := fun n => fun f => (iter f n).\n    Notation \"[ X ]N \" := (cnat_of X) (at level 5).\n    Definition test := [3]N.\n    (* 0 :\u03bb f x .x *)  \n    Definition c0: cnat := fun (f:T->T) (x:T) => x.\n    (* 1 :\u03bb f x . f x *)  \n    Definition c1: cnat := fun (f:T->T) (x:T) => f x.\n    (* 2 :\u03bb f x . f (f x) *)  \n    Definition c2: cnat := fun (f:T->T) (x:T) => f (f x).\n    (* 3 :\u03bb f x . f (f (f x)) *)  \n    Definition c3: cnat := fun (f:T->T) (x:T) => f (f (f x)).\n    (* csucc(n)=n+1 : \u03bb n.\u03bb f x. f (n f x)*)\n    Definition cS:= fun (n:cnat)=> fun (f:T->T) (x:T)  => ( f (n f x )).\n    Compute c0.\n    Compute c1.\n    Compute c2.\n    Compute c3.\n    Compute cS c0.\n    Compute cS c1.\n    Compute cS c2.\n    Compute cS c3.\n    (* cadd (a,b)=a+b :\u03bb n m.\u03bb f x. n f (m f x) *)\n    Definition cadd := fun (n:cnat) (m:cnat) => fun (f:T->T) (x:T) =>  n f (m f x).\n    Compute cadd c1 c2.\n    Compute cadd c0 c2.\n    Compute cadd c3 c2.\n    Compute cadd c3 c3.\n    (* cmult (a,b)=a*b :\u03bb n m.\u03bb f . n (m f) *)\n    Definition cmult := fun (n:cnat) (m:cnat) => fun (f:T->T)=>  n (m f).\n    Compute cmult c1 c3.\n    Compute cmult c2 c2.\n    Compute cmult c2 c3.\n    Compute cmult c1 c1.\n    Compute cmult c2 c0.\n    Compute cmult c0 c3.\n    (* ceq0(n) = {si n =0 true sinon false}:\u03bb n .\u03bb x y . n (\u03bb z.y ) x*)\n    Definition cseq0 := fun (n:cnat)=> fun (x:T) (y:T)=> n (fun (z:T)=>y) x.\n    Compute cseq0 c0.\n    Compute cseq0 c1.\n    Compute cseq0 c3.\n  End type_nat.\n", "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_1.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.8212758230731508}}
{"text": "Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\nFixpoint nonzeros (l:natlist) : natlist := \n    match l with \n    | nil => nil \n    | O :: t => nonzeros t\n    | n :: t => n :: nonzeros t\n    end.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof. Admitted.\n\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof. Admitted.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof. Admitted. \n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof. Admitted.\n\n(* EXERCISE *)\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n    intros l. induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n\n(* EXERCISE *)\nTheorem rev_app_distr : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\n  Qed.\n\n(* An involution is a function that is its own inverse. That is, applying the function twice yield the original input. *)\n(* EXERCISE *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n    intros l. induction l as [| n l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. simpl. reflexivity. \n    Qed.\n\n(* EXERCISE *)\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n    intros l1 l2 l3 l4. induction l1 as [| n l1' IHl1'].\n    - simpl. rewrite -> app_assoc. reflexivity.\n    - simpl. rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\n    Qed.\n\n(* ADDITIONAL LEMMAS *)\nLemma app_assoc_with_nat : forall n : nat, forall l1 l2 : natlist,\n    (n :: l1) ++ l2 = n :: (l1 ++ l2).\nProof. \n    intros n. intros l1 l2. simpl. reflexivity.\n    Qed.\n\nLemma nonzeros_Sn_l1 : forall n : nat, forall l1 : natlist, \n    nonzeros(S n :: l1) = S n :: nonzeros l1.\nProof.\n    intros n. intros l1. simpl. reflexivity. Qed.\n\nLemma nonzeros_Sn_l1_l2 : forall n : nat, forall l1 l2 : natlist,\n    nonzeros(S n :: l1 ++ l2) = S n :: nonzeros(l1 ++ l2).\nProof. \n    intros n. intros l1 l2. simpl. reflexivity. Qed.\n\nLemma Sn_app_l1_l2_assoc : forall n : nat, forall l1 l2 : natlist, \n    (S n :: l1) ++ l2 = S n :: (l1 ++ l2).\nProof. \n    intros n. intros l1 l2. simpl. reflexivity. Qed.\n\n(* EXERCISE *)\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' IHl'].\n    - simpl. reflexivity.\n    - rewrite -> app_assoc_with_nat. destruct n.\n     + simpl. rewrite -> IHl'. reflexivity.\n     + rewrite -> nonzeros_Sn_l1_l2. \n       rewrite -> nonzeros_Sn_l1. \n       rewrite -> IHl'.\n       rewrite -> Sn_app_l1_l2_assoc.\n       reflexivity.\n    Qed.\n", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/exercises/list_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8211703982366798}}
{"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   : auxiliary library for nat.\n  author    : ZhengPu Shi\n  date      : 2021.05\n *)\n\nFrom Coq Require Export Init.Nat.\nFrom Coq Require Export Arith.\nFrom Coq Require Export PeanoNat.\nFrom Coq Require Export Lia.\nFrom Coq Require Export Bool.Bool.\n\n(* From Coq Require Export Lra. *)\n(* From Coq Require Export Setoid. (* R ==> R', Morphisms.respectful R R' *) *)\n\n\n(* ######################################################################### *)\n(** * More properties for nat *)\n\n(** a natural number must be odd or even *)\nLemma nat_split : forall (n : nat), exists (x : nat),\n    n = 2 * x \\/ n = 2 * x + 1.\nProof.\n  induction n.\n  - exists 0. auto.\n  - destruct IHn. destruct H.\n    + exists x. right. subst. lia.\n    + exists (x+1). left. subst. lia.\nQed.\n\n(** Two step induction principle for natural number *)\nTheorem nat_ind2 : forall (P : nat -> Prop),\n    (P 0) -> (P 1) -> (forall n, P n -> P (S (S n))) -> (forall n, P n).\nProof.\n  intros. destruct (nat_split n). destruct H2; subst; induction x; auto.\n  - replace (2 * S x) with (S (S (2 * x))); [apply H1; auto | lia].\n  - replace (2 * S x + 1) with (S (S (2 * x + 1))); [apply H1; auto | lia].\nQed.\n\n(** Connect induction principle between nat and list *)\nLemma ind_nat_list {A} : forall (P : list A -> Prop) ,\n    (forall n l, length l = n -> P l) -> (forall l, P l).\nProof.\n  intros. apply (H (length l)). auto.\nQed.\n\n\n\n(* ######################################################################### *)\n(** * Extension for nat from (Verified Quantum Computing). *)\n\n(* https://www.cs.umd.edu/~rrand/vqc/index.html *)\n\n(*******************************)\n(* Automation *)\n(*******************************)\n\nLemma double_mult : forall (n : nat), (n + n = 2 * n).\nProof.\n  intros. lia.\nQed.\n\nLemma pow_two_succ_l : forall x, 2^x * 2 = 2 ^ (x + 1).\nProof.\n  intros. rewrite Nat.mul_comm. rewrite <- Nat.pow_succ_r'. rewrite Nat.add_1_r. auto.\nQed.\n\nLemma pow_two_succ_r : forall x, 2 * 2^x = 2 ^ (x + 1).\nProof.\n  intros. rewrite <- Nat.pow_succ_r'. rewrite Nat.add_1_r. auto.\nQed.\n\nLemma double_pow : forall (n : nat), 2^n + 2^n = 2^(n+1). \nProof.\n  intros. rewrite double_mult. rewrite pow_two_succ_r. reflexivity.\nQed.\n\nLemma pow_components : forall (a b m n : nat), a = b -> m = n -> a^m = b^n.\nProof.\n  intuition.\nQed.\n\nLtac unify_pows_two :=\n  repeat match goal with\n    (* NB: this first thing is potentially a bad idea, do not do with 2^1 *)\n    | [ |- context[ 4%nat ]]                  => replace 4%nat with (2^2)%nat \n        by reflexivity\n    | [ |- context[ (0 + ?a)%nat]]            => rewrite Nat.add_0_l \n    | [ |- context[ (?a + 0)%nat]]            => rewrite Nat.add_0_r \n    | [ |- context[ (1 * ?a)%nat]]            => rewrite Nat.mul_1_l \n    | [ |- context[ (?a * 1)%nat]]            => rewrite Nat.mul_1_r \n    | [ |- context[ (2 * 2^?x)%nat]]          => rewrite <- Nat.pow_succ_r'\n    | [ |- context[ (2^?x * 2)%nat]]          => rewrite pow_two_succ_l\n    | [ |- context[ (2^?x + 2^?x)%nat]]       => rewrite double_pow \n    | [ |- context[ (2^?x * 2^?y)%nat]]       => rewrite <- Nat.pow_add_r \n    | [ |- context[ (?a + (?b + ?c))%nat ]]   => rewrite Nat.add_assoc \n    | [ |- (2^?x = 2^?y)%nat ]                => apply pow_components; try lia \n    end.\n\n(** Restoring Matrix dimensions *)\nLtac is_nat_equality :=\n  match goal with \n  | |- ?A = ?B => match type of A with\n                | nat => idtac\n                end\n  end.\n\n(* ######################################################################### *)\n(** * Useful bdestruct tactic with the help of reflection *)\n(** Use this tactic, the proposition of natural number comparision and the boolean\n    calculation of natural number comparison are connected. *)\n\n(** There havn't GT and GE in standard library. *)\n\nNotation  \"a >=? b\" := (Nat.leb b a) (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a) (at level 70) : nat_scope.\n\n(** Proposition and boolean are reflected. *)\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(** These theorems are automatic used. *)\nGlobal Hint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\n(** bool-destruct\uff0cuseful for boolean inequality of natural number *)\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. *)\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", "meta": {"author": "zhengpushi", "repo": "CoqExt", "sha": "f800fd509d80bd973ccc85b7a238359fa9ee1145", "save_path": "github-repos/coq/zhengpushi-CoqExt", "path": "github-repos/coq/zhengpushi-CoqExt/CoqExt-f800fd509d80bd973ccc85b7a238359fa9ee1145/CoqExt/NatExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8962513703624558, "lm_q1q2_score": 0.8210645027400373}}
{"text": "From Coq Require Import Arith.\n\n\nFixpoint fib (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | 1 => 1\n  | S (S n as n') => fib n' + fib n\n  end.\n\nFixpoint fib_aux (a b n : nat) : nat :=\n  match n with\n  | 0 => a\n  | S n => fib_aux b (a + b) n\n  end.\n\nDefinition fib2 (n : nat) : nat := fib_aux 0 1 n.\n\n\nTheorem fib_eq (n : nat) : fib2 n = fib n.\nProof.\n  intros.\n  induction n.\n  trivial.\n  unfold fib2.\n  assert (forall m a b, fib_aux a b (S m) = a * fib m + fib (S m) * b ).\n    induction m.\n    intros.\n    simpl.\n    simpl Nat.mul.\n    rewrite (Nat.mul_comm a 0).\n    simpl Nat.mul.\n    simpl Nat.add.\n    rewrite (Nat.add_comm b 0).\n    simpl Nat.add.\n    reflexivity.\n    simpl in *.\n    intros.\n    rewrite IHm.\n    ring.\n  rewrite (H n 0 1).\n  ring.\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/fibonacci.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.8210367177349954}}
{"text": "Require Export P01.\n(** **** Problem #2: 2 stars (blt_nat) *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Use [Fixpoint] to define it. *)\n\nFixpoint blt_nat (n m : nat) : bool :=\n  match n with\n  | O =>\n    match m with\n    | O => false\n    | S m' => true\n    end\n  | S n' =>\n    match m with\n    | O => false\n    | S m' => blt_nat n' m'\n    end\n  end.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n", "meta": {"author": "norangLemon", "repo": "plHW", "sha": "ca142b892b3dcb25cd7a3a29c14233061bca4c84", "save_path": "github-repos/coq/norangLemon-plHW", "path": "github-repos/coq/norangLemon-plHW/plHW-ca142b892b3dcb25cd7a3a29c14233061bca4c84/01/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8207816981721218}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat ssrfun eqtype.\n\n(* Three Color Triangle Problem (TCTP) *)\nSection TCTP_definitions.\n  (* Color: the type for the three colors in TCTP *)\n  (* red, blu (=blue), and yel (=yellow) *)\n  Inductive Color : Set := red | yel | blu.\n\n  (* The mix operation produces a next color by mixing two given colors *)\n  Definition mix c0 c1 :=\n    match c0, c1 with\n    | red, red => red\n    | red, yel => blu\n    | red, blu => yel\n    | yel, red => blu\n    | yel, yel => yel\n    | yel, blu => red\n    | blu, red => yel\n    | blu, yel => red\n    | blu, blu => blu\n    end.\n  Lemma mixcut c0 c1 c2 c3: mix (mix (mix c0 c1) (mix c1 c2)) (mix (mix c1 c2) (mix c2 c3)) = mix c0 c3.\n  Proof. by move: c0 c1 c2 c3 => [] [] [] []. Qed.\n\n  Definition coloring := nat -> nat -> Color.\n  \n  (* Meaning: The color of the node (x,y+1) is the mixure of those of the nodes (x,y) and (x+1,y). *)\n  Definition CFun colfun := forall x y, colfun x y.+1 = mix (colfun x y) (colfun x.+1 y).\n  \n  (* Meaning: The color of the node (x,y+n) is the mixure of those of the nodes (x,y) and (x+n,y). *)\n  Definition WellColoredVertices colfun x y n := colfun x (y + n) = mix (colfun x y) (colfun (x + n) y).\n\n  (* Meaning: The triangle (x,0)-(x+n,0)-(x,n) makes a well-colored triangle for any expected coloring. *)\n  Definition WellColoredTriangle x y n := forall colfun, CFun colfun -> WellColoredVertices colfun x y n.\n  \n  (* Lifting of top-level coloring functions (This will be applied to coloringYBBY and coloringBYB defined later) *)\n  Fixpoint liftcoloring (topcoloring : nat -> Color) x y :=\n    if y is y'.+1 then mix (liftcoloring topcoloring x y') (liftcoloring topcoloring x.+1 y') else topcoloring x.\nEnd TCTP_definitions.\n\nSection TCTP.\n(* Proof of the sufficient conditions ------------------------------------*)\n  Theorem TCTP_suf (k x y : nat) : WellColoredTriangle x y (3 ^ k).\n  Proof.\n    move=> colfun H.\n    elim: k x y => [|k IHk] x y; first by rewrite expn0 /WellColoredVertices !addn1; exact /H.\n    rewrite /WellColoredVertices -(mixcut _ (colfun (x + 3 ^ k) y) (colfun (x + (3 ^ k).*2) y)).\n    have <- : WellColoredVertices colfun x y (3 ^ k) by exact: IHk.\n    rewrite -addnn addnA.\n    have <- : WellColoredVertices colfun (x + 3 ^ k) y (3 ^ k) by exact: IHk.\n    have <- : WellColoredVertices colfun x (y + 3 ^ k) (3  ^k) by exact: IHk.\n    have -> : 3 ^ k.+1 = (3 ^ k).*2 + 3 ^ k by rewrite expnS (mulnDl 1 2) mul1n mul2n addnC.\n    rewrite -!addnA addnn !addnA.\n    have <- : WellColoredVertices colfun (x + (3 ^ k).*2) y (3 ^ k) by exact: IHk.\n    rewrite -addnn !addnA.\n    have <- : WellColoredVertices colfun (x + 3 ^ k) (y + 3 ^ k) (3 ^ k) by exact: IHk. \n    rewrite -!addnA addnn !addnA.\n    have <- : WellColoredVertices colfun x (y + (3 ^ k).*2) (3  ^k) by exact: IHk.\n    by rewrite addnAC.\n  Qed.\n\n(* Proof of the necessary condition ------------------------------------*)\nSection Allred.\n  (* allred: The lower most cell is red if there is a line whose all cells are red *)    \n  Variables (colfun : coloring) (x y n : nat).\n  Hypothesis H : CFun colfun.\n  Hypothesis redline : forall i, i <= n -> colfun (x + i) y = red.\n\n  Lemma allred : colfun x (y + n) = red.\n  Proof.\n    suff bottom q p : p + q <= n -> colfun (x + p) (y + q) = red by rewrite -(addn0 x); exact: bottom. \n    elim: q p => [p|q IHq p pqn]; first by rewrite !addn0; apply redline.\n    by rewrite addnS H IHq ?(leq_trans _ pqn)// -?addnS ?IHq// ?addnS// addSnnS.\n  Qed.\nEnd Allred.\n\n(* Begin: TCTP_nec_even --------------------*)\n(* coloringYB x n: paint cells from x to x+n alternatively (like yellow, blue, ..) (paint yellow for cells out of the range) *)\nDefinition coloringYB n i := if (i <= n) && ~~ odd i then yel else blu.\n\nSection TCTP_nec_even.\nVariables (colfun : coloring) (n : nat).\nHypotheses (n_gt_0 : n > 0) (H : CFun colfun).\nHypothesis topcolor : forall i, i <= n -> colfun i 0 = coloringYB n i.\n\nLemma even_bottom : colfun 0 n = red.\nProof.\n  suff even_next_red i : i <= n.-1 -> colfun i 1 = red; first by rewrite -(prednK n_gt_0) -add1n allred//.\n  move=> i_leq_pn.\n  have i_leq_n : i <= n by rewrite (leq_trans i_leq_pn) // leq_pred.\n  have i_lt_n : i < n by rewrite -add1n -leq_subRL ?subn1.\n  have -> : colfun i 1 = mix (colfun i 0) (colfun i.+1 0); first exact/H.\n  have -> : colfun i 0 = coloringYB n i by rewrite topcolor.\n  have -> : colfun i.+1 0 = coloringYB n i.+1 by rewrite topcolor //. \n  have YB_yel m j : j <= m -> ~~ odd j -> coloringYB m j = yel.\n  by move=> m_gt_j oj; rewrite /coloringYB m_gt_j oj.\n  have YB_blu m j : odd j -> coloringYB m j = blu by move=> oj; rewrite /coloringYB oj andbF.\n  have [oi|ei] := boolP (odd i).\n  - have -> : coloringYB n i = blu by exact: YB_blu.\n    have ->// : coloringYB n i.+1 = yel by rewrite YB_yel //= oi.\n  - have -> : coloringYB n i = yel by exact: YB_yel.\n    have ->// : coloringYB n i.+1 = blu by exact: YB_blu.\nQed.\nEnd TCTP_nec_even.\n\nLemma TCTP_nec_even n : n > 0 -> ~~ odd n -> ~ WellColoredTriangle 0 0 n.\nProof.\n  move=> n_gt_0 en WCT.\n  have H: CFun (liftcoloring (fun z => coloringYB n z)) by rewrite /=.\n  have := WCT _ H; rewrite /WellColoredVertices addnC addn0.\n  have <- : coloringYB n 0 = liftcoloring (fun z => coloringYB n z) 0 0 by rewrite//=.\n  have <- : coloringYB n n = liftcoloring (fun z => coloringYB n z) n 0 by rewrite //=.\n  have -> : coloringYB n 0 = yel by rewrite /=.\n  have -> : coloringYB n n = yel by rewrite /coloringYB leqnn en.\n  have -> // : liftcoloring (fun z => coloringYB n z) 0 n = red.\n  exact: even_bottom => //.  \nQed.\n  \n(* End: TCTP_nec_even --------------------*)\n\n(* Begin: TCTP_nec_shortodd --------------------*)\nDefinition coloringYBBY n i := if ((i <= n./2) && odd i) || ((n./2.+1 <= i <= n) && ~~ odd i) then blu else yel.\n\n(* Some properties of coloringYBBY *)\nLemma YBBY_yel_even n i : i <= n./2 -> ~~ odd i -> coloringYBBY n i = yel.\nProof. by move=> i_leq_hn /negbTE oi; rewrite /coloringYBBY oi /= !(andbF,andbT)/= ltnNge i_leq_hn. Qed.\nLemma YBBY_yel_odd n i : n./2.+1 <= i -> odd i -> coloringYBBY n i = yel.\nProof. by move=> r oi; rewrite /coloringYBBY oi !(andbF,andbT) leqNgt orbF r. Qed.\nLemma YBBY_blu_odd n i : i <= n./2 -> odd i -> coloringYBBY n i = blu.\nProof. by move=> ni oi; rewrite /coloringYBBY ni oi. Qed.\nLemma YBBY_blu_even n i : n./2.+1 <= i <= n -> ~~ odd i -> coloringYBBY n i = blu.\nProof. by move=> ni /negbTE oi; rewrite /coloringYBBY oi !(andbT,andbF) ni. Qed.\nLemma YBBY_both n : odd n -> coloringYBBY n 0 = coloringYBBY n n.\nProof.\n  move=> on; rewrite /coloringYBBY leq0n on/= !(andbF,andbT) orbF.\n  rewrite ifF //; apply/negbTE; rewrite -ltnNge.\n  by rewrite -{2}(odd_double_half n) on add1n ltnS -addnn leq_addl.\nQed.\n\nSection TCTP_nec_shortodd.\nVariables (colfun : coloring) (k n : nat).\nHypotheses (n_range : 3 ^ k < n <= (3 ^ k).*2) (on : odd n).\nHypothesis H : CFun colfun.\nHypothesis vertices : forall x y, WellColoredVertices colfun x y (3 ^ k).\nHypothesis topcolor : forall i, i <= n -> coloringYBBY n i = colfun i 0.\n\nLet shortodd_coloringYB i : i <= n - 3 ^ k -> coloringYB (n - 3 ^ k) i = colfun i (3 ^ k).\nProof.\n  move=> i_range.\n  have i_range' : i + 3 ^ k <= n by rewrite addnC -leq_subRL// ltnW//; move/andP : n_range => [].\n  have i_leq_n : i <= n by rewrite (leq_trans i_range)// leq_subr.\n  have n_range_lt : n < (3 ^ k).*2.\n  move: n_range => /andP[_]; rewrite leq_eqVlt => /predU1P[n_range_eq|//].\n  by move: on; rewrite n_range_eq odd_double.\n  have hn_range_lt : n./2 < 3 ^ k.\n  rewrite -(@ltn_pmul2l 2)// !mul2n (leq_trans _ n_range_lt)// ltnS.\n  by rewrite -{2}(odd_double_half n) on add1n.\n  have hn_range_lt' : n./2 < i + 3 ^ k by rewrite ltn_addl //.\n  have hn_geq_i : i <= n./2. apply: (leq_trans i_range).\n  by rewrite leq_subCl -{1}(odd_double_half n) on add1n -addnn subSn ?leq_addr// -addnBA// subnn addn0.\n  have -> : colfun i (3 ^ k) = mix (colfun i 0) (colfun (i + 3 ^ k) 0) by rewrite -vertices.\n  have <- : coloringYBBY n i = colfun i 0 by exact /topcolor /i_leq_n.\n  have <- : coloringYBBY n (i + 3 ^ k) = colfun (i + 3 ^ k) 0 by rewrite topcolor.\n  have [oi|ei] := boolP (odd i).\n  - have -> : coloringYBBY n i = blu by exact: YBBY_blu_odd.\n    have -> : coloringYBBY n (i + 3 ^ k) = blu.\n    by rewrite YBBY_blu_even// ?hn_range_lt'// oddD oddX orbT oi.\n    have ->// : coloringYB (n - 3 ^ k) i = blu by rewrite /coloringYB oi i_range //.\n  - have -> : coloringYBBY n i = yel by exact: YBBY_yel_even.      \n    have -> : coloringYBBY n (i + 3 ^ k) = yel.\n    by rewrite YBBY_yel_odd// ?hn_range_lt'// oddD oddX orbT /= addbT ei.\n    have ->// : coloringYB (n - 3 ^ k) i = yel by rewrite /coloringYB ei i_range //.\nQed.\n\nLemma shortodd_bottom : colfun 0 n = red.\nProof.\n  have shortodd_coloringYB_next_red i : i <= (n - 3 ^ k).-1 -> colfun i (3 ^ k).+1 = red.\n  have n_gt_0: 0 < n - 3 ^ k by rewrite ltn_subCr subn0; move /andP : n_range => [].\n  move=> i_range.\n  have i_range_leq : i <= n - 3 ^ k by rewrite (leq_trans i_range)// leq_pred.\n  have i_range_lt : i.+1 <= n - 3 ^ k by rewrite (leq_ltn_trans i_range)// ltn_predL.\n  suff : mix (colfun i (3 ^ k)) (colfun i.+1 (3 ^ k)) = red by move=> <-.\n  have [oi|ei] := boolP (odd i).\n  - rewrite -shortodd_coloringYB// (_ : coloringYB _ _ = blu).\n    by rewrite -shortodd_coloringYB// /coloringYB i_range_lt /= oi.\n    by rewrite /coloringYB i_range_leq oi.    \n  - rewrite -(shortodd_coloringYB i)// (_ : coloringYB _ _ = yel).\n    by rewrite -shortodd_coloringYB// /coloringYB i_range_lt /= ei.\n    by rewrite /coloringYB ei i_range_leq.\n  have -> : n = 3 ^ k + 1 + (n - 3 ^ k).-1.\n  have n_gt_0 : 0 < n - 3^k by rewrite ltn_subCr subn0; case /andP : n_range. \n  by rewrite -addnA addnC add1n prednK// ?subnK// ?subn_gt0// ltnW// -subn_gt0.\n  by rewrite allred// => i ?; rewrite addn1 shortodd_coloringYB_next_red.\nQed.\nEnd TCTP_nec_shortodd.\n\nLemma TCTP_nec_shortodd n k : 3 ^ k < n <= (3 ^ k).*2 -> odd n -> ~ WellColoredTriangle 0 0 n.\nProof.\n  move=> n_range on WCT.\n  have [colfun [H lift]] : exists colfun, CFun colfun /\\ forall x y, colfun x y = liftcoloring (fun z => coloringYBBY n z) x y\n  by exists (liftcoloring (fun z => coloringYBBY n z)).\n  have := WCT colfun H; rewrite /WellColoredVertices addnC addn0.\n  have topcolor i : coloringYBBY n i = colfun i 0 by rewrite lift //=.\n  have <- : colfun 0 0 = colfun n 0; first by rewrite lift -topcolor -YBBY_both//= subnn.\n  have -> : colfun 0 0 = yel by rewrite lift//=.\n  have -> // : colfun 0 n = red.\n  apply: (shortodd_bottom _ k) => // ? ?; exact: TCTP_suf.\nQed.\n(* End: TCTP_nec_shortodd --------------------*)\n\n(* Begin: TCTP_nec_longodd --------------------*)\n(* colorBYB x n k z : paint the topmost cells from x to x+n \n   - blue for the left-most 3^k cells + the right-most 3^k cells\n   - yellow for other cells\n  (- blue for cells out of the range)\n*)\nDefinition coloringBYB n k i := if 3 ^ k <= i <= n - 3 ^ k then yel else blu.\n\n(* Some properties of colorBYB *)\nLemma BYB_blu_left n k i : i <= (3 ^ k).-1 -> coloringBYB n k i = blu.\nProof.\n  move=> range; rewrite /coloringBYB ifF//; apply/negbTE.\n  by rewrite negb_and -ltnNge (leq_ltn_trans range)//= prednK// expn_gt0.\nQed.\nLemma BYB_yel_center n k i : 3 ^ k <= i <= n - 3 ^ k -> coloringBYB n k i = yel.\nProof. by move=> range; rewrite /coloringBYB range. Qed.\nLemma BYB_blu_right n k i : (n - 3 ^ k).+1 <= i -> coloringBYB n k i = blu.\nProof. by move=> range; rewrite /coloringBYB ifF//; apply/negbTE;rewrite negb_and orbC -ltnNge range. Qed.\n\nSection TCTP_nec_longodd.\nVariables (colfun : coloring) (k n : nat).\nHypotheses (n_range : (3 ^ k).*2.+1 <= n < 3 ^ k.+1) (H : CFun colfun).\nHypothesis vertices : forall x y, WellColoredVertices colfun x y (3 ^ k).\nHypothesis topcolor : forall i, i <= n -> coloringBYB n k i = colfun i 0.\n\n(* An inequality obtained from the range of n *)\nLet inequality : prod (3 ^ k <= n) (prod ((3 ^ k).*2 <= n) (n - (3 ^ k).*2 <= (3 ^ k).-1)).\nProof.\n  move: n_range => /andP[n_range_left n_range_right]; split.\n  - by rewrite (leq_trans _ n_range_left)// -addnn -addnS leq_addr.\n  - rewrite (ltnW n_range_left); split => [//|].\n    rewrite leq_subLR -addnn -ltnS -addnS prednK// ?expn_gt0//.\n    move: n_range_right; rewrite expnSr; move/leq_trans; apply.\n    by rewrite {2}(_ : 3 = 1 + 1 + 1)// 2!mulnDr !muln1.\nQed.\n\nLet longodd_red_both_sides :\n  (forall i, i <= n - (3 ^ k).*2 -> colfun i (3 ^ k) = red) /\\\n  (forall i, 3 ^ k <= i <= n - 3 ^ k -> colfun i (3 ^ k) = red).\nProof.\n  split=> [i i_range_right|i /andP[i_range_left i_range_right]];\n  have i_leq_n : i <= n by rewrite (leq_trans i_range_right)// leq_subr.\n  - have i_range_right' : 3 ^ k + i <= n - 3 ^ k.\n    by rewrite leq_subRL// ?inequality// addnA addnn -leq_subRL// inequality.\n    have n_range_geq : 3 ^ k + i <= n by rewrite (leq_trans i_range_right')// leq_subr.\n    have -> := vertices i 0; rewrite /WellColoredVertices. \n    have -> : colfun i 0 = blu.\n    rewrite -topcolor//; apply: BYB_blu_left => //.\n    by rewrite (leq_trans i_range_right) // inequality.\n    have ->// : colfun (i + (3 ^ k)) 0 = yel.\n    by rewrite -topcolor// (addnC i) // BYB_yel_center// leq_addr i_range_right'//.\n  - have ni_range : n - 3 ^ k < 3 ^ k + i.\n    rewrite ltn_subLR// ?(leq_trans i_range_left)// addnA addnn.\n    case /andP: n_range => _ /leq_trans ->//.\n    by rewrite expnS (mulnDl 1 2) addnC mul2n mul1n leq_add2l.\n    have -> := vertices i 0; rewrite /WellColoredVertices.\n    have -> : colfun i 0 = yel\n    by rewrite -topcolor // ?(BYB_yel_center n k i)// i_range_left i_range_right.\n    have ->// : colfun (i + 3 ^ k) 0 = blu; rewrite -topcolor// addnC; first by apply BYB_blu_right.\n    by rewrite -leq_subRL// inequality.\nQed.\n\nLemma longodd_bottom : colfun 0 n = red.\nProof.\n  have longodd_redline i : i <= n - (3 ^ k).*2 -> colfun i (3 ^ k).*2 = red.\n  move=> i_range; rewrite -addnn.\n  have in_range : i + 3 ^ k <= n - 3 ^ k.\n  by rewrite leq_subRL// ?inequality// addnCA addnn addnC -leq_subRL// inequality.\n  have ->// := vertices i (3 ^ k); rewrite /WellColoredVertices. \n  have ->// : colfun i (3 ^ k) = red by exact: longodd_red_both_sides.1.\n  have ->// : colfun (i + 3 ^ k) (3 ^ k) = red.\n  by apply: longodd_red_both_sides.2; rewrite leq_addl.    \n  have // : colfun 0 ((3^k).*2 + (n - (3^k).*2)) = red by rewrite allred//.\n  by rewrite addnC subnK// inequality.\nQed.\nEnd TCTP_nec_longodd.\n  \nLemma TCTP_nec_longodd n k :\n  (3 ^ k).*2.+1 <= n < 3 ^ k.+1 -> ~ WellColoredTriangle 0 0 n.\nProof.\n  move=> n_range WCT.\n  have [colfun [H lift]] : exists colfun, CFun colfun /\\ forall x y, colfun x y = liftcoloring (fun z => coloringBYB n k z) x y\n  by exists (liftcoloring (fun z => coloringBYB n k z)).\n  have := WCT colfun H; rewrite /WellColoredVertices addnC addn0.\n  have topcolor i : i <= n -> coloringBYB n k i = colfun i 0; first by rewrite lift /=.\n  rewrite /WellColoredTriangle in WCT.\n  have triangle x y : WellColoredVertices colfun x y (3 ^ k); first exact: TCTP_suf.\n  have -> : colfun 0 n = red; first by exact: (longodd_bottom _ k).\n  have -> : colfun 0 0 = blu by rewrite -(addn0 0) -topcolor// BYB_blu_left.\n  have ->// : colfun n 0 = blu.\n  rewrite -topcolor// BYB_blu_right// -ltn_subCl// ?subnn ?expn_gt0//.\n  by move /andP : n_range => [+ _]; apply: leq_trans; rewrite leqW// -addnn leq_addl. \nQed.\n(* End: TCTP_nec_longodd --------------------*)\n       \nLemma nat_case n : exists k, n = 0 \\/ n = 3 ^ k \\/ 3 ^ k < n <= (3 ^ k).*2 \\/ (3 ^ k).*2.+1 <= n < 3 ^ k.+1.\nProof.\n  elim: n => [|n [k [IH0|[IH1|[|]]]]]; first by exists 0; left.\n  - exists 0; right; left; by rewrite IH0.\n  - exists k; right; right; left; by rewrite -IH1 -addnn -addn1 !leq_add2l IH1 expn_gt0.\n  - case /andP => IH2L; rewrite leq_eqVlt => /predU1P[->|IH2R].\n    case: k IH2L => [|k]; first by exists 1 ; right; left; rewrite expn0 expn1.\n    exists (k.+1); right; right; right; apply /andP; split; first by[].\n    rewrite (expnSr 3 k.+1) {3}(_:3 = 2+1)// -(addn1 ((3^k.+1).*2)) mulnDr muln2 ltn_add2l muln1.\n    by rewrite expnS (ltn_trans (ltnSn 1))// -{1}(muln1 3) leq_pmul2l//expn_gt0.\n    by exists k; right; right; left; apply/andP; split; [exact:ltnW|].\n  - case /andP => IH3L; rewrite leq_eqVlt => /predU1P[|IH3R]; first by exists (k.+1); right; left.\n    by exists k; right; right; right; apply/andP; split; [rewrite (ltn_trans IH3L)|].\nQed. \n \nTheorem TCTP_nec n :\n  n > 0 -> WellColoredTriangle 0 0 n -> exists k, n = 3 ^ k.\nProof.\n  move=> + WCT; case: (nat_case n) => k [->//|n_case n_gt0]. \n  have [on|en] := boolP (odd n).\n  - case: n_case => [n_is_exp3k|[shortodd|longodd]]; first by exists k.\n    + by exfalso; exact: (TCTP_nec_shortodd n k).\n    + by exfalso; exact: (TCTP_nec_longodd n k).\n  - by exfalso; exact: (TCTP_nec_even n).\nQed.\n\n(* Main Theorem *)\nTheorem TCTP n :\n  n > 0 -> (exists k, n = 3 ^ k) <-> WellColoredTriangle 0 0 n.\nProof.\n  move=> n_gt0; split => [[k] n_is_exp3k|]; first rewrite n_is_exp3k.\n  - exact: TCTP_suf k 0 0.\n  - exact: TCTP_nec.\nQed.\n\nEnd TCTP.\n", "meta": {"author": "SyotaHashimoto", "repo": "ThreeColor", "sha": "ea60d3af9461bb2064783eab2a0c1a4d2bb59bc6", "save_path": "github-repos/coq/SyotaHashimoto-ThreeColor", "path": "github-repos/coq/SyotaHashimoto-ThreeColor/ThreeColor-ea60d3af9461bb2064783eab2a0c1a4d2bb59bc6/threecolor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8199928323313982}}
{"text": "(* Exercise coq_nat_04 *)\n\n(* Let us prove that addition is commutative. *)\n\n(* For this we may need the facts that '0' is a neutral element for\n   addition and that 'S (n + m) = n + S m' - the facts that we proved \n   before. However, those results are also available in the standard \n   library. First we need to make them available with the\n   'Require Import' command. *)\n   \nRequire Import Plus.\nCheck Nat.add_0_l.\nCheck Nat.add_0_r.\nCheck plus_n_Sm.\n\nLemma plus_comm : forall m n, m + n = n + m.\n\nProof.\nintros.\ninduction m.\nsimpl.\nrewrite Nat.add_0_r.\nreflexivity.\n(*step*)\nsimpl.\nrewrite -> IHm.\nrewrite plus_n_Sm.\nreflexivity.\n \nQed.\n", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_nat_04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.8199309478246557}}
{"text": "(**---\ncontent_type: md\nlayout: main\nheader_style: max-height:50px;\nclick: download('/')\ntitle: \"Konstantin Weitz: (Dis)advantages of using Abstract Data Types in Proof Assistants\"\ncomments: true\ninfo:\n---\n\n(Dis)advantages of using Abstract Data Types in Proof Assistants\n----------------------------------------------------------------\n\nThis blog post explains the advantages and disadvantages of using \nAbstract Data Types (ADTs, see TaPL Chapter 24) in a Proof Assistant. \nOn the plus side, ADTs promote data representation independence, code reuse, \nand clean code extraction; but they also do not support fix/match syntax,\nhave to expose derived operations, and prohibit computational reasoning.\n\n<!--more-->\n\nDownload this blog post's code [here][dl].\n\n[dl]: /assets/posts/coq-adts/CoqADT.v\n\n### Represenation Independence\n\nConsider Coq's standard library implementation of natural number addition `add`:\n**)\n\n    Print Nat.add.\n    (*\n    Fixpoint add (n m : nat) : nat :=\n      match n with\n      | 0 => m\n      | S n' => S (add n' m)\n      end\n    *)\n\n(**\nThis implementation is unsatisfactory, as it exposes the data representation details of the\n`nat` datatype. For example, this implementation of `add` will not work with a more \nspace efficient binary representation of natural numbers.\n\nThe standard solution to this problem is to **hide the data representation using an ADT**. ADTs can be\nimplemented using either Modules ([see][mod]), Sigma/Existential Types (see TaPL Chapter 24),\nRecords ([see][agda]), or Type Classes ([see][tc]).\nIn this blog post, we choose to implement ADTs in the Coq Proof\nAssistants using Type Classes.\n\nOur ADT for natural numbers `NatADT` consists of: \na type `Nat` whose representation is hidden,\noperations on the type (`zero`, `succ`, `natRect`), and\nequations that describe the operation's behavior (`natRectZero`, `natRectSucc`).\n\nThe operation `natRect` is the [eliminator for natural numbers][cmb]. \nThe equations describe the computational behavior of `natRect`.\n\n[tc]: http://www.labri.fr/perso/casteran/CoqArt/TypeClassesTut/typeclassestut.pdf\n[agda]: https://stackoverflow.com/questions/26888499/how-to-define-abstract-types-in-agda\n[mod]: http://www.cs.princeton.edu/~appel/vfa/ADT.html\n[cmb]: https://www.quora.com/In-type-theory-what-is-an-eliminator-and-what-is-its-opposite\n**)\n\n    Class NatADT := {\n      Nat : Type;\n      zero : Nat;\n      succ : Nat -> Nat;\n      natRect : forall P, P zero -> (forall n, P n -> P (succ n)) -> forall n, P n;\n      natRectZero : forall P z s, natRect P z s zero = z;\n      natRectSucc : forall P z s n, natRect P z s (succ n) = s n (natRect P z s n)\n    }.\n\n(**\nGiven this ADT, we can now implement an `add` function that is **independent \nof any particular implementation** of the natural numbers (hurray). \n\nUnfortunately, this also means that we have to implement the code in\nterms of the eliminator, and **cannot use fix/match syntax**\n(sigh). However, getting around this syntactic restriction would be trivial\nfor eliminator based languages like Lean.\n**)\n\n    Definition add `{NatADT} (n m:Nat) : Nat :=\n      natRect _ m (fun _ rec => succ rec) n.\n\n(**\n\n### Code Reuse\n\nWe can instantiate the ADT using Coq's standard library\nnatural numbers, ...\n**)\n\n    Instance natNat : NatADT := {|\n      Nat := nat;\n      zero := 0;\n      succ := S;\n      natRect := nat_rect\n    |}.\n    Proof.\n      - reflexivity.\n      - reflexivity.\n    Defined.\n\n(**\n... and call the `add` function as we please.\n**)\n\n    Compute (@add natNat 5 7).\n\n(**\nWe can even prove that our implementation of `add` is \nequivalent to the standard library operation `Nat.add` (`+`).\n**)\n\n    Lemma eqAddAdd (n m : nat) : n + m = add n m.\n      induction n; cbn in *; congruence.\n    Qed.\n\n(**\nWe can also instantiate the ADT using Coq's binary natural numbers `N`, ...\n**)\n\n    Require Import NArith.\n    \n    Open Scope N.\n    \n    Instance NNat : NatADT := {|\n      Nat := N;\n      zero := N.zero;\n      succ := N.succ;\n      natRect := N.peano_rect\n    |}.\n    Proof.\n      - apply N.peano_rect_base.\n      - apply N.peano_rect_succ.\n    Defined.\n\n(**\n... and call the `add` function as we please.\n**)\n\n    Compute (@add NNat 5 7).\n\n(**\n\nADTs thus **enable code reuse**, because a function has to only be implemented \nonce for an ADT, instead of every single instatiation of the ADT.\n\nWhile this instantiation of `add` is exponentially more space efficient \nthan the instantiation with `natNat`, the computation still requires \ntime exponential in the number of `n`'s bits.\n\nThe problem of ADTs is that they hide implementation details, and thus\ndeny opportunities for optimization. \nTo overcome this problem, ADT implementers have to guess and **expose all the operations\nthat some future instatiation of the ADT can implement more efficiently** \n(even if they can be implemented \nless efficiently using other operations of the ADT). The result is an ADT that \nis hard to understand (because the essential operations are swamped by derived operations)\nand inefficient (because some optimization opportunity will inevitably be lost for lack of precognition).\n**)\n\n(**\n\n### Extracting ADTs\n\n**ADTs are also useful for extraction**. We can instantiate an ADT using opaque terms\nthat will be implemented on extraction. \n**)\n\n    Parameter HsNat : Type.\n    Parameter hsZero : HsNat.\n    Parameter hsSucc : HsNat -> HsNat.\n    Parameter hsNatRect : forall P, P hsZero -> (forall n, P n -> P (hsSucc n)) -> forall n, P n.\n    Axiom hsNatRectZero : forall P z s, hsNatRect P z s hsZero = z.\n    Axiom hsNatRectSucc : forall P z s n, hsNatRect P z s (hsSucc n) = s n (hsNatRect P z s n).\n    \n    Extraction Language Haskell.\n    \n    Extract Constant HsNat => \"Prelude.Integer\".\n    Extract Constant hsZero => \"0\".\n    Extract Constant hsSucc => \"Prelude.succ\".\n    Extract Constant hsNatRect => \"(\\z s -> let f n = if n Prelude.== 0 \n                                                     then z \n                                                     else s (Prelude.pred n) \n                                                            (f (Prelude.pred n)) in f)\".\n    \n    Instance HsNatNat : NatADT := {|\n                                   Nat := HsNat;\n                                   zero := hsZero;\n                                   succ := hsSucc;\n                                   natRect := hsNatRect\n                                 |}.\n    Proof.\n      - apply hsNatRectZero.\n      - apply hsNatRectSucc.\n    Defined.\n\n    Definition hsAdd : HsNat := @add HsNatNat (hsSucc (hsSucc hsZero)) (hsSucc hsZero).\n    Extraction \"src/Add.hs\" hsAdd.\n\n(** \nThis approach clearly documents all the terms that have to be implemented \nby extraction (`Parameter`) and the assumptions about their behavior \n(`Axiom`), and is thus cleaner than the common alternative of \nsyntactically replacing arbitrary Coq terms and data types:\n**)\n\n    Extract Inductive nat => \"Prelude.Integer\" [\"0\" \"Prelude.succ\"] \n                                            \"(\\z s n -> if n Prelude.== 0 \n                                                        then z () \n                                                        else s (Prelude.pred n))\".\n    \n    Definition hsAddNat : nat := 2 + 1.\n    Extraction \"src/AddNat.hs\" hsAddNat.\n\n(** \n\n### Reasoning About ADTs\n\nThere is another major downside to using ADTs \u2014 they severely impact \ntheorem proving. Consider the following proof that `0 + n = n + 0` using\nCoq's standard library natural numbers. After the induction, the proof\nis almost automatic due to Coq's ability to computationally simplify (`cbn`)\nthe goal.\n**)\n\n    Open Scope nat.\n    \n    Lemma natAddZero (n : nat) : 0 + n = n + 0.\n      induction n as [|n' IHn'].\n      - reflexivity.\n      - cbn in IHn'.         (* A *)\n        rewrite IHn' at 1.   (* B *)\n        cbn.                 (* C *)\n        reflexivity.\n    Qed.\n\n(**\nCompare this to the proof which uses the ADT, where we have to \n**perform equational reasoning instead of computational reasoning**.\nThis is extremely burdensome, especially for more complicated proofs.\n**)\n\n    Lemma addZero `{Nat} n : add zero n = add n zero.\n      refine (natRect (fun n => add zero n = add n zero) _ (fun n' IHn' => _) n).\n      - reflexivity.\n      - unfold add in IHn'.             (* A *)\n        rewrite natRectZero in IHn'.    (* A *)\n        rewrite IHn' at 1.              (* B *)\n        unfold add.                     (* C *)\n        rewrite natRectSucc.            (* C *)\n        rewrite natRectZero.            (* C *)\n        reflexivity.\n    Qed.\n\n(**\n\n### Summary\n\nIn summary, there are several advantages to using ADTs:\n\n- ADTs are data representation independent.\n- ADTs enable code reuse.\n- ADTs enable clean extraction.\n\nBut there are also drawbacks:\n\n- ADTs do not support fix/match syntax.\n- ADTs have to expose derived operations.\n- ADTs prohibit computational reasoning.\n\n**)\n", "meta": {"author": "konne88", "repo": "konne88.github.io", "sha": "49d8d6d2860606df95e061beb1fc623ba9a990b9", "save_path": "github-repos/coq/konne88-konne88.github.io", "path": "github-repos/coq/konne88-konne88.github.io/konne88.github.io-49d8d6d2860606df95e061beb1fc623ba9a990b9/assets/posts/coq-adts/CoqADT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.8199100682466146}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** ** Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros.\n  induction n as [|n']. \n  simpl. apply ev_0. \n  simpl. apply ev_SS. apply IHn'. \nQed. \n\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E.\n induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  intros. \n  induction H as [|n' H']. \n  simpl.  apply H0. \n  simpl. apply ev_SS.  apply IHH'. \nQed. \n(** [] *)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* 2 ways *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. \n  simpl.\n  apply b_sum. \n  apply H. \n  rewrite -> plus_0_r. \n  apply H. \nQed. \n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   intros. \n   induction m as [|m']. \n   simpl. apply b_0. \n   apply b_sum.  apply H.\n   apply IHm'. \nQed. \n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n        -------------- g_0\n            gorgeous 0\n\n           gorgeous n\n        -------------- g_plus3\n           gorgeous (3+n)\n\n          gorgeous n\n        -------------- g_plus5\n          gorgeous(5+n)\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros. \n  simpl. apply g_plus5. apply g_plus5. apply g_plus3. apply H. \nQed. \n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros.\n  induction H as [|n'|n'].\n  simpl. apply H0. apply g_plus3.  apply IHgorgeous. \n  apply g_plus5. apply IHgorgeous. \nQed. \n  \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros. \n  induction H.\n  \nAdmitted. \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. \n  inversion H as [|n' H'].\n  inversion H' as [|n'' H''].\n  apply H''. \nQed. \n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros. \n  inversion H. \n  inversion H1. \n  inversion H3. \nQed. \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n*)\n\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\nInductive total_rel: nat -> nat -> Prop := \n  tot_rel : forall (n m:nat), total_rel n m. \n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_rel: nat -> nat -> Prop := \n  emp_rel : forall (n m:nat), empty_rel 0 0. \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_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\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if evenb n then Peven n else Podd n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros podd peven n.\n  unfold oddb.\n  intros H1 H2. \n  induction n as [|n']. \n  unfold combine_odd_even. simpl. apply H2.  reflexivity. \n  unfold combine_odd_even. \n  destruct evenb. \n\n    apply H2. reflexivity. \n    apply H1. 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  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "a3storm", "repo": "softwarefoundation", "sha": "c8245bf3179ff75373bc6b1d7eff77b92a1296f6", "save_path": "github-repos/coq/a3storm-softwarefoundation", "path": "github-repos/coq/a3storm-softwarefoundation/softwarefoundation-c8245bf3179ff75373bc6b1d7eff77b92a1296f6/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418252018901, "lm_q2_score": 0.8872046019186954, "lm_q1q2_score": 0.8199028801446596}}
{"text": "(** * Logic: Logic in Coq *)\n\n(*Require Export MoreCoq. \n*)\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives.\n\n*)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions \n    ([forall x, P]).  \n*)\n\n\n(** In Coq, the type of things that can (potentially) \n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated \n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P]. \n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.  \nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on\nequality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat \n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that\ntakes evidence for [P] as input and produces evidence for [Q] as its\noutput.\n*)     \n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?  \n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other\n      datatype.\n\n    - Sometimes a proposition is declared to be true without\n      substantiating evidence.  Such propositions are called _axioms_.\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" conjunctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  (*Case \"left\".*) reflexivity.\n  (*Case \"right\".*) reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    (*Case \"left\".*) reflexivity.\n    (*Case \"right\".*) reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [destruct] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  intros. destruct H as [HP HQ].\n  apply HQ.\nQed.\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  destruct H as [HP HQ]. \n  split.  \n    (*Case \"left\".*) apply HQ. \n    (*Case \"right\".*) apply HP.  Qed.\n  \n\n(** **** Exercise: 2 stars (and_assoc)  *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [destruct] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  destruct H as [HP [HQ HR]].\n  split. split. apply HP. apply HQ. apply HR.\nQed.\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) \n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  destruct H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  destruct H as [HAB HBA].\n  split.\n    (*Case \"->\".*) apply HBA.\n    (*Case \"<-\".*) apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  intros. split. 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. split. destruct H. destruct H0.\n  intros. apply H0. apply H. apply H3.\n  intros. destruct H. destruct H0.\n  apply H2. apply H3. apply H1.\nQed.  \n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [destruct] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    (*Case \"left\".*) apply or_intror. apply HP.\n    (*Case \"right\".*) apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    (*Case \"left\".*) right. apply HP.\n    (*Case \"right\".*) left. apply HQ.  Qed.\n\n\n\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. destruct H as [HP | [HQ HR]]. \n    (*Case \"left\".*) split.\n      (*SCase \"left\".*) left. apply HP.\n      (*SCase \"right\".*) left. apply HP.\n    (*Case \"right\".*) split.\n      (*SCase \"left\".*) right. apply HQ.\n      (*SCase \"right\".*) right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2)  *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros. inversion H as [HPQ HPR]. inversion HPQ. left. apply H0.\n  inversion HPR. left. apply H1. \n  right. split. apply H0. apply H1. \nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros. split. apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    (*Case \"b = true\".*) destruct c.\n      (*SCase \"c = true\".*) apply conj. reflexivity. reflexivity.\n      (*SCase \"c = false\".*) inversion H.\n    (*Case \"b = false\".*) inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct H.\n  rewrite H. rewrite H0. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (andb_false)  *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  intros. destruct b.\n  destruct c. inversion H.\n  right. reflexivity.\n  left. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false)  *)\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros. destruct b. left. reflexivity.\n  destruct c. right. reflexivity.\n  left. inversion H.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false_elim)  *)\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros. destruct b. destruct c. inversion H.\n  split. inversion H. reflexivity.\n  destruct c. split. reflexivity. inversion H.\n  split. auto. auto.\nQed.\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True)  *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := \n  I : True.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. destruct H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not in H0. unfold not. intros. apply H0. apply H.\n  apply H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  intros. unfold not. intros. destruct H.\n  apply H0. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [~P] \n     from evidence for [P]. *) \n  Abort.\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := forall P:Prop, \n  P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop, \n  ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop, \n  (P->Q) -> (~P\\/Q). \n\n(** [] *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).  \nProof.\n  intros. unfold not. intros. apply H. right. intros. apply H.\n  left. apply H0.\nQed.\n \n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  (*Case \"b = true\".*) reflexivity.\n  (*Case \"b = false\".*)\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** **** Exercise: 2 stars (false_beq_nat)  *)\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof.\n  induction n. destruct m. intros. apply ex_falso_quodlibet.\n  unfold not in H. apply H. reflexivity.\n  intros. unfold not in H. split.\n  destruct m. intros. unfold not in H. split.\n  simpl. intros. apply IHn. revert H. unfold not.\n  intros. apply H. apply f_equal. apply H0.\nQed. \n\n(** **** Exercise: 2 stars, optional (beq_nat_false)  *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  induction n. unfold not. intros. destruct m. inversion H.\n  inversion H0.\n  unfold not. intros. destruct m. inversion H0. inversion H. inversion H0.\n  revert H2 H3. apply IHn.\nQed.\n(** [] *)\n\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n", "meta": {"author": "Sooram", "repo": "Software-Foundations", "sha": "9c668f5c8395919645406855cdc78a214afdafd1", "save_path": "github-repos/coq/Sooram-Software-Foundations", "path": "github-repos/coq/Sooram-Software-Foundations/Software-Foundations-9c668f5c8395919645406855cdc78a214afdafd1/6. Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.9241418236349501, "lm_q1q2_score": 0.8199028766873456}}
{"text": "From LF Require Export Induction.\nModule NatList.\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\n\nCheck (pair 3 5) : natprod.\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\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. (* \u5565\u4e5f\u6ca1\u6709\u5f52\u7ea6\uff01 *)\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 : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros p. destruct p as [n m].\n  simpl. reflexivity. \nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros p. destruct p as [n m].\n  simpl. reflexivity. \nQed.\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nNotation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\nCompute tl [0;1;0;2;3;0;0].\nFixpoint nonzeros (l:natlist) : natlist :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l with\n  |[]=>[]\n  |h::t => if h=0 then (nonzeros t) else [h]++(nonzeros t)\nend.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l with\n  |[]=>[]\n  |h::t=> if evenb h then (oddmembers t) else [h]++(oddmembers t)\nend.\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l with\n  |[]=>0\n  |h::t=> if evenb h then (countoddmembers t) else 1+(countoddmembers t)\nend.\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l1,l2 with\n  |[],[] => []\n  |[],_ => l2\n  |_,[]=> l1\n  |h1::t1 , h2::t2 => [h1;h2]++(alternate t1 t2)\nend.\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\n  simpl. reflexivity.\nQed.\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof.\n  simpl. reflexivity.\nQed.\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof.\n  simpl. reflexivity.\nQed.\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof.\n  simpl. reflexivity.\nQed.\n\nDefinition bag := natlist.\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\nCheck beq_nat.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s with\n  |[]=>0\n  |h::t=>(if beq_nat h v then 1 else 0) + (count v t)\nend.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n  simpl. reflexivity.\nQed.\n\nDefinition sum : bag -> bag -> bag :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  app.\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof.\n  simpl. reflexivity.\nQed.\nDefinition add (v:nat) (s:bag) : bag :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s with\n  |[]=>[v]\n  |h::t=>[v]++h::t\nend.\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\nDefinition member (v:nat) (s:bag) : bool:=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s with\n  |[]=>false\n  |h::t=>if h=v then true else false\nend.\nExample test_member1: member 1 [1;4;1] = true.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_member2: member 2 [1;4;1] = false.\nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag:=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s with\n  |[]=>[]\n  |h::t=>if h=v then t else h::(remove_one v t)\nend.\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof.\n  simpl. reflexivity.\nQed.\nFixpoint remove_all (v:nat) (s:bag) : bag:=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s with\n  |[]=>[]\n  |h::t=>if h=v then (remove_all v t) else h::(remove_all v t)\nend.\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool:=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match s1 with\n  |[]=>true\n  |h::t=>if (count h s2)=0 then false\n                           else subset t (remove_one h s2)\nend.\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof.\n  simpl. reflexivity.\nQed. \n\nTheorem bag_count_add : forall s : bag,\n  count 1 (add 1 s) = S (count 1 s).\nProof.\n  intros s. destruct s as [].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity. \nQed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* \u8fd9\u79cd\u60c5\u51b5\u6bd4\u8f83\u68d8\u624b\u3002\u6211\u4eec\u4ece\u4e00\u822c\u7684\u5316\u7b80\u5f00\u59cb\u3002 *)\n    simpl.\n    (* \u73b0\u5728\u6211\u4eec\u597d\u50cf\u5361\u4f4f\u4e86\uff1a\u76ee\u6807\u662f\u8981\u8bc1\u660e\u6d89\u53ca ++ \u7684\u7b49\u5f0f\uff0c\n       \u4f46\u662f\u6211\u4eec\u5728\u4e0a\u4e0b\u6587\u548c\u5168\u5c40\u73af\u5883\u4e0b\u5e76\u6ca1\u6709\u4efb\u4f55\u6709\u7528\u7684\u7b49\u5f0f\uff01\n       \u901a\u8fc7\u7528 IH \u6765\u91cd\u5199\u76ee\u6807\uff0c\u6211\u4eec\u53ef\u4ee5\u63a8\u8fdb\u4e00\u70b9... *)\n    rewrite <- IHl'.\n    (* ...\u4f46\u4e5f\u4ec5\u6b64\u800c\u5df2\u3002 *)\nAbort.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* \u8bfe\u4e0a\u5df2\u5b8c\u6210 *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length.\n    simpl. rewrite -> IHl'. rewrite plus_comm.\n    reflexivity.\nQed.\n\nSearch app.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l. induction l as [].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl. reflexivity.\nQed.\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l1 l2. induction l1 as [].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1. rewrite -> app_assoc. reflexivity.\nQed.\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l. induction l as [].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. simpl.\n    rewrite -> IHl. reflexivity.\nQed. \n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l1 l2 l3 l4. rewrite -> app_assoc.\n  rewrite -> app_assoc. reflexivity.\nQed.\n\nSearch nonzeros.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l1 l2. induction l1 as [].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1. \n    destruct n as [].\n    * simpl. reflexivity.\n    * simpl. reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : bool:=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l1,l2 with\n  |[],[]=>true\n  |[],_ =>false\n  |_ ,[]=>false\n  |h1::t1,h2::t2=>if h1=h2 then eqblist t1 t2 \n                           else false\nend.\nExample test_eqblist1 :\n  (eqblist nil nil = true).\n (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \nProof.\n  reflexivity.\nQed.\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\n(* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \nProof.\n  reflexivity.\nQed.\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\n (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) Proof.\n  reflexivity.\nQed.\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  intros l. induction l as [].\n  - simpl. reflexivity.\n  - simpl. induction n as [].\n    * simpl. rewrite <- IHl. reflexivity.\n    * simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  (1 <= (count 1 (1 :: s))) = true.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros s. simpl. reflexivity.\nQed.\n\nTheorem leb_n_Sn : forall n,\n  (n <= (S n)) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n  ((count 0 (remove_one 0 s)) <= (count 0 s)) = true.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros s. induction s as [].\n  - simpl. reflexivity.\n  - simpl. induction n as [].\n    * simpl. rewrite -> leb_n_Sn. reflexivity.\n    * simpl. rewrite -> IHs. reflexivity.\nQed.\n\n(*Theorem app_nil_r : forall l : natlist,\n  l ++ [] = l.*)\nTheorem bag_count_sum : forall (n : nat) (s1 s2 : bag),\n  count n (sum s1 s2) = count n s1 + count n s2.\nProof.\n  intros n s1 s2. induction s1 as [|h1 t1 IHs1].\n  - simpl. reflexivity.\n  - induction s2 as [|h2 t2 IHs2].\n    * simpl. rewrite <- plus_n_O. rewrite -> app_nil_r. reflexivity.\n    * simpl. rewrite -> IHs1. simpl. rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem rev_injective : forall (l1 l2 : natlist), \n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 eq.\n  rewrite <- rev_involutive. \n  rewrite <- eq. rewrite -> rev_involutive. \n  reflexivity.\nQed.\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' n'\n               end\n  end.\n\nCompute nth_bad [1;4;5;6] 4.\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof.\n  simpl. reflexivity.\nQed.\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\n(*Definition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.*)\nDefinition hd_error (l : natlist) : natoption :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *)\n  match l with\n  | nil => None\n  | a::l => Some a\nend.\nExample test_hd_error1 : hd_error [] = None.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof.\n  simpl. reflexivity.\nQed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof.\n  simpl. reflexivity.\nQed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros l default. destruct l as [].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\nEnd NatList.\n\nInductive id : Type :=\n  | Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 = n2\n  end.\n\nCompute eqb_id (Id 2) (Id 2).\n\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros x. destruct x as []. simpl. \n  induction n as [].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\nCheck record (Id 1) 4 empty.\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nCompute update (record (Id 1) 1 empty) (Id 2) 2.\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.\nCompute find (Id 0) (record (Id 2) 2 (record (Id 1) 1 empty)).\n\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros d x v.\n  simpl. rewrite <- eqb_id_refl. reflexivity.\nQed.\n\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o eq.\n  simpl. rewrite -> eq. reflexivity.\nQed.\n\nEnd PartialMap.\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n\n\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": "Doughnut09", "repo": "sf_proof", "sha": "7cd8f950b2dd3ed2845bc502ffaaa02c72dc42a4", "save_path": "github-repos/coq/Doughnut09-sf_proof", "path": "github-repos/coq/Doughnut09-sf_proof/sf_proof-7cd8f950b2dd3ed2845bc502ffaaa02c72dc42a4/coq-sf-prove-main/LF/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.8199028729680368}}
{"text": "(* Pr\u00e1ctica 4 *)\n\n(* Ejercicio 1 *)\nSection Ejercicio1.\n\n(* 1.1 *)\nInductive list (A: Set) :  Set :=\n    nil\n  | cons : A -> list A -> list A. (* se puede hacer: forall A:Set...? solo si se definio como list: Set -> Set *)\n\nCheck nil.\nCheck cons.\n\nInductive bintree(A:Set):Set :=\n    btree_nil\n  | node: bintree A -> A -> bintree A -> bintree A.\n\nCheck bintree_ind.\n\n(* 1.2 *)\nInductive Array (A:Set): nat -> Set :=\n    array_nil : Array A 0\n  | array_cons : forall n:nat, A -> Array A n -> Array A (S n).\n\nInductive Matrix (A:Set): nat -> nat -> Set :=\n    matrix_nil : Matrix A 0 0\n  | ins_fila : forall n m:nat, Array A m -> Matrix A n m -> Matrix A (S n) m.\n\n(* 1.3 *)\nInductive leq : nat -> nat -> Prop :=\n    leq0 : forall n:nat, leq 0 n\n  | leqS : forall n m:nat, leq n m -> leq (S n) (S m).\n\n(* 1.4 *)\nInductive eq_list (A:Set):list A -> list A -> Prop :=\n    eq0 : eq_list A (nil A) (nil A)\n  | eqS : forall (a b:A) (l1 l2:list A), eq_list A l1 l2 -> a = b -> eq_list A (cons A a l1) (cons A b l2).\n(* Alternativamente podr\u00eda hacer forall (a:A) (l1 l2:list A), eq_list A l1 l2 -> eq_list A (cons A a l1) (cons A a l2),\npero deja \"implicita\" la igual, hay casos donde NO podr\u00eda aplicarse, dado que la igualdad no es obvia *)\n\n(* 1.5 *)\nInductive sorted (A:Set):(A->A->Prop) -> list A -> Prop :=\n  | sortedBNil : forall R:A->A->Prop, sorted A R (nil A)\n  | sortedBUnit : forall (R:A->A->Prop) (a:A) (l:list A), sorted A R (cons A a (nil A))\n  | sortedI : forall (R:A->A->Prop) (a b : A) (l:list A),\n      sorted A R (cons A b l) -> R a b -> sorted A R (cons A a (cons A b l)).\n\n(* 1.6 *)\nInductive mirror(A:Set):bintree A -> bintree A -> Prop :=\n    mirror0 : mirror A (btree_nil A) (btree_nil A) \n  | mirrorS : forall (t1 t2 t1' t2':bintree A) (a b : A), a = b -> mirror A t1 t2' -> mirror A t2 t1' -> mirror A (node A t1 a t2) (node A t1' b t2').\n\n(* 1.7 *)\n(* isomorfismo entre arboles binarios *)\nInductive isomorfismo(A:Set):bintree A -> bintree A -> Prop :=\n    isomorfismo0 : isomorfismo A (btree_nil A) (btree_nil A)\n  | isomorfismoS : forall (t1 t2 t1' t2':bintree A) (a b : A), isomorfismo A t1 t1' -> isomorfismo A t2 t2' -> isomorfismo A (node A t1 a t2) (node A t1' b t2').\n\n(* 1.8 *)\n(* est\u00e1 bien? *)\nInductive\n Gtree(A:Set):Set :=\n     empty_gtree : Gtree A\n   | node_gtree : A -> Forest A -> Gtree A\nwith\n Forest(A:Set):Set :=\n    empty_forest : Forest A\n  | branch_forest : Gtree A -> Forest A -> Forest A.\n\nEnd Ejercicio1.\n\n\n(* Ejercicio 2 *)\nSection Ejercicio2.\n\n(* 2.1 *)\nDefinition Or (a:bool) (b:bool):bool :=\n  match a with\n  | false => b\n  | _ => true\n  end.\n\nDefinition And (a:bool) (b:bool):bool :=\n  match a with\n  | true => b\n  | _ => false\n  end.\n\nDefinition Not (a:bool):bool :=\n  match a with\n  | true => false\n  | _ => true\n  end.\n\nDefinition Xor (a:bool) (b:bool):bool :=\n  match b with\n  | false => a\n  | _ => Not a\n  end.\n\n(* 2.2 *)\nDefinition is_nil (A:Set)(a:list A):bool :=\n  match a with\n  | nil => true\n  | _ => false\n  end.\nEnd Ejercicio2.\n\n\n(* Ejercicio 3 *)\nSection Ejercicio3.\n(* 3.1 *)\n(* El \"struc\" indica el argumento que ser\u00e1 estructuralmente menor\nen la llamada recursiva, en general no es necesario. *)\nFixpoint sum (n m:nat) {struct n}: nat :=\n  match n with\n  | 0 => m\n  | S k => S (sum k m)\n  end.\n\n(* 3.2 *)\nFixpoint prod (n m:nat) {struct n}: nat :=\n  match n with\n  | 0 => 0\n  | S k => sum m (prod k m)\n  end.\n\n(* 3.3 *)\nFixpoint pot (n m:nat) {struct m}: nat :=\n  match m with\n  | 0 => 1\n  | S k => prod n (pot n k)\n  end.\n\n(* 3.4 *)\nFixpoint leBool (n m:nat): bool :=\n  match n , m with\n  | 0 , _ => true\n  | S k , 0 => false\n  | S k, S j => leBool k j\n  end.\nEnd Ejercicio3.\n\n\n(* Ejercicio 4 *)\nSection Ejercicio4.\n\n(* 4.1 *)\nFixpoint length (A:Set) (l:list A):nat :=\n  match l with\n  | nil => 0\n  | cons _ l => 1 + length A l\n  end.\n\n(* 4.2 *)\nFixpoint append (A:Set) (l1:list A) (l2:list A):list A :=\n  match l1, l2 with\n  | nil, ll => ll\n  | ll, nil => ll\n  | cons a ll, lll => cons A a (append A ll lll)\n  end.\n\n(* 4.3 *)\nFixpoint reverse (A:Set) (l:list A):list A :=\n  match l with\n  | nil => nil A\n  | cons a ll => append A (reverse A ll) (cons A a (nil A)) \n  end.\n\n(* 4.4 *)\nFixpoint filter (A:Set) (f:A -> bool) (l:list A):list A :=\n  match l with\n  | nil => nil A\n  | cons a l' => if f a then cons A a (filter A f l') else filter A f l'\n  end.\n\n(* 4.5 *)\nFixpoint map (A B:Set) (f:A -> B) (l:list A):list B :=\n  match l with\n  | nil => nil B\n  | cons a l' => cons B (f a) (map A B f l')\n  end.\n\n(* 4.6 *)\nFixpoint exists_ (A: Set) (f:A -> bool) (l:list A):bool :=\n  match l with\n  | nil => false\n  | cons a l' => if f a then true else exists_ A f l'\n  end.\nEnd Ejercicio4.\n\n\n(* Ejercicio 5 *)\nSection Ejercicio5.\n\n(* 5.1 *)\nFixpoint inverse (A:Set) (t:bintree A):bintree A :=\n  match t with\n  | btree_nil => btree_nil A\n  | node t1 a t2 => node A (inverse A t2) a (inverse A t1)\n  end.\n\n(* 5.2 *)\nFixpoint nodos_internos (A:Set) (t:Gtree A) :nat :=\n  match t with\n    empty_gtree => 0\n  | node_gtree a f => S (nodos_internos' A f)\n  end\nwith nodos_internos' (A:Set) (f:Forest A):nat :=\n  match f with\n   empty_forest => 0\n  | branch_forest t f' => plus (nodos_internos A t) (nodos_internos' A f')\n  end.\n\nFixpoint nodos_externos (A:Set) (t:Gtree A) :nat :=\n  match t with\n    empty_gtree => 0\n  | node_gtree a f => nodos_externos' A f\n  end\nwith nodos_externos' (A:Set) (f:Forest A):nat :=\n  match f with\n   empty_forest => 1\n  | branch_forest t f' => plus (nodos_externos A t) (nodos_externos' A f')\n  end.\n\n(* Est\u00e1 bien? *)\nDefinition hayMas_nodos_internos (A:Set) (t:Gtree A):bool :=\n  Not (leBool (nodos_internos A t) (nodos_externos A t)).\n\nEnd Ejercicio5.\n\n\n(* Ejercicio 6 *)\nSection Ejercicio6.\n\n(* 6.1 *)\nRequire Import Coq.Arith.EqNat.\nDefinition listN := list nat.\n\nPrint listN.\n\n(* Puedo importar librerias? S\u00ed *)\nFixpoint member (n:nat) (l:listN):bool :=\n  match l with\n  | nil => false\n  | cons a l' => if beq_nat a n then true else member n l'\n  end.\n\n(* 6.2 *)\nFixpoint delete (l:listN) (n:nat):listN :=\n  match l with\n  | nil => nil nat\n  | cons a l' => if beq_nat a n then delete l' n else cons nat a (delete l' n)\n  end.\n\n(* 6.3 *)\nRequire Import Coq.Arith.Compare_dec.\n\nFunction insert' (n:nat) (l:listN):listN :=\n  match l with\n  | nil => cons nat n (nil nat)\n  | cons a l' => if leb a n then cons nat a (insert' n l') else cons nat n (cons nat a l')\n  end.\n\nFunction insert_sort (l:listN):listN :=\n  match l with\n  | nil => nil nat\n  | cons a l' => insert' a (insert_sort l')\n  end.\n\n(* Generalizaci\u00f3n *)\nFixpoint memberG (A:Set) (eqA:A->A->bool) (x:A) (l:list A):bool :=\n  match l with\n  | nil => false\n  | cons a l' => if eqA a x then true else memberG A eqA x l'\n  end.\n\nFixpoint deleteG (A:Set) (eqA:A->A->bool) (l:list A) (x:A):list A :=\n  match l with\n  | nil => nil A\n  | cons y l' => if (eqA x y) then deleteG A eqA l' x else cons A y (deleteG A eqA l' x)\n  end.\n\nFixpoint insertG' (A:Set) (leA:A->A->bool) (x:A) (l:list A):list A :=\n  match l with\n  | nil => nil A\n  | cons a l' => if leA a x then insertG' A leA a l' else cons A x (cons A a l')\n  end.\n\nFixpoint insert_sortG (A:Set) (leA:A->A->bool) (l:list A):list A :=\n  match l with\n  | nil => nil A\n  | cons a l' => insertG' A leA a (insert_sortG A leA l')\n  end.\n\nEnd Ejercicio6.\n\n\n(* Ejercicio 7 *)\nSection Ejercicio7.\n\n(* 7.1 *)\nInductive Exp (A:Set):Set :=\n    mas: A -> A -> Exp A\n  | producto: A -> A -> Exp A\n  | menos_unario: A -> Exp A.\n\n(* 7.2 *)\nDefinition expNat (e:Exp nat):nat :=\n  match e with\n  | mas x y => plus x y\n  | producto x y => prod x y\n  | menos_unario x => x\n  end.\n\n(* 7.3 *)\nDefinition expBool (e:Exp bool):bool :=\n  match e with\n  | mas x y =>\n    match x with\n    | true => true\n    | _ => x\n    end\n  | producto x y =>\n    match x with\n    | false => false\n    | _ => y\n    end\n  | menos_unario x =>\n    match x with\n    | true => false\n    | false => true\n    end\n  end.\n\nEnd Ejercicio7.\n\n\n(* Ejercicio 8 *)\nSection Ejercicio8.\n\n(* 8.1 *)\n(* Uso induction o case? En este caso son lo mismo *)\nLemma conmutatividadAnd : forall a b:bool, And a b = And b a.\nProof.\n  intros x y.\n  unfold And.\n  case x; case y; reflexivity.\nQed.\n\nLemma conmutatividadOr : forall a b:bool, Or a b = Or b a.\nProof.\n  intros x y.\n  unfold Or.\n  case x; case y; reflexivity.\nQed.\n\nLemma asociatidadAnd : forall a b c:bool, And (And a b) c = And a (And b c).\nProof.\n  intros x y c.\n  unfold And.\n  case x; reflexivity.\nQed.\n\nLemma asociatividadOr : forall a b c:bool, Or (Or a b) c = Or a (Or b c).\nProof.\n  intros x y c.\n  unfold Or.\n  case x; reflexivity.\nQed.\n\n(* 8.2 *)\nLemma LAnd : forall a b : bool, And a b = true <-> a = true /\\ b = true.\nProof.\n  intros x y.\n  unfold iff, And.\n  split.\n    intro H; split.\n      destruct x.\n        reflexivity.\n\n        assumption.\n      destruct x.\n        assumption.\n     \n        discriminate H.\n    intro H; elim H.\n    intros H' H''; clear H.\n    induction x; assumption.\nQed.\n\n(* 8.3 *)\nLemma LOr1 : forall a b : bool, Or a b = false <-> a = false /\\ b = false.\nProof.\n  intros x y; unfold iff, Or; split; intro H.\n    split; destruct x.\n      discriminate H.\n    \n      reflexivity.\n\n      discriminate H.\n  \n      assumption.\n    elim H; intros H' H''; clear H.\n    destruct x.\n      discriminate H'.\n  \n      assumption.\nQed.\n\n(* 8.4 *)\n(* Por qu\u00e9 cuando aplico \"induction x\", tambien modifica las hipotesis que tiene a x?\nPor que cuando cambia las expresiones que tienen x en el gol, tambien deber\u00eda modificar\nlas expresiones que est\u00e1n en las hip\u00f3tesis.\n Por qu\u00e9 \"case x\" NO modifica las hip\u00f3tesis, pero \"destruct x\" si lo hace? *)\nLemma LOr2 : forall a b : bool, Or a b = true <-> a = true \\/ b = true.\nProof.\n  intros x y; unfold iff, Or.\n  split; intro H.\n    destruct x.\n      left; reflexivity.\n  \n      right; assumption.\n    elim H; intro H'; clear H; destruct x.\n      reflexivity.\n\n      discriminate H'.\n\n      reflexivity.\n\n      assumption.\nQed.\n\n(* 8.5 *)\nLemma LXor : forall a b : bool, Xor a b = true <-> a <> b.\nProof.\n  intros x y; unfold iff, Xor, Not, not; split.\n    intros H H'.\n    destruct y, x.\n        discriminate H.  \n        discriminate H'.\n        discriminate H'.\n        discriminate H.\n    intro H.\n    destruct y, x.\n        elim (H (eq_refl true)).\n        reflexivity.\n        reflexivity.\n        elim (H (eq_refl false)).\nQed.\n\n\n(* 8.6 *)\nLemma LNot : forall b : bool, Not (Not b) = b.\nProof.\n  intro x; unfold Not.\n  case x; reflexivity.\nQed.\n\nEnd Ejercicio8.\n\n\n(* Ejercicio 9 *)\nSection Ejercicio9.\n\n(* 9.1 *)\n(* Est\u00e1 bien usar \"induction\" para probar sobre Fixpoint? Si*)\nLemma SumO : forall n : nat, sum n 0 = n.\nProof.\n  intro x.\n  induction x.\n    simpl.\n    reflexivity.\n\n    simpl.\n    rewrite -> IHx.\n    reflexivity.\nQed.\n\n(* 9.2 *)\nLemma SumS : forall n m : nat, sum n (S m) = sum (S n) m.\nProof.\n  intros x y.\n  induction x.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite -> IHx.\n    reflexivity.\nQed.\n\n(* 9.3 *)\n(* Hay una t\u00e1ctica que sirva como \u00e9ste lema? Si, apply f_equal. O sino, usar \"rewrite\". *)\n(* No lo uso, se puede BORRAR *)\nLemma aux:forall n m:nat, n=m -> S n = S m.\nProof.\n  intros x y H.\n  induction x; induction y.\n  reflexivity.\n  rewrite <- H.\n  reflexivity.\n  rewrite -> H.\n  reflexivity.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(* Est\u00e1 bien hacer induction sobre una variable de un para todo? S\u00ed*)\n(* Por qu\u00e9 si primero hago intros, y luego doble induccion, el \u00faltimo caso tiene\nuna hipotesis inductiva con un implica? *)\nLemma SumConm : forall n m : nat, sum n m = sum m n.\nProof.\n  induction n.\n    induction m.\n      simpl; reflexivity.\n      simpl; rewrite <- IHm; reflexivity.\n    induction m.\n      simpl.\n      rewrite (IHn 0).\n      simpl; reflexivity.\n\n      rename m into m'.\n      simpl.\n      rewrite <- IHm.\n      rewrite (IHn (S m')).\n      simpl.\n      rewrite (IHn m').\n      reflexivity.\nQed.\n\n\n(* 9.4 *)\nLemma SumAsoc : forall n m p : nat, sum n (sum m p) = sum (sum n m) p.\nProof.\n  intros x y z.\n  induction x.\n    simpl.\n    reflexivity.\n  \n    simpl.\n    rewrite -> IHx.\n    reflexivity.\nQed.\n\n(* 9.5 *)\nLemma ProdConm : forall n m : nat, prod n m = prod m n.\nProof.\n  induction n; induction m.\n    reflexivity.\n\n    simpl.\n    rewrite <- IHm; simpl; reflexivity.\n  \n    simpl.\n    rewrite (IHn 0).\n    simpl; reflexivity.  (* Cuando hago doble inducci\u00f3n, en el \u00faltimo caso tengo \"dos m\", hace falta que renombre? No. *)\n\n    simpl; rewrite <- IHm.\n    rewrite (IHn (S m)).\n    simpl.\n    rewrite (IHn m).\n    rewrite -> (SumAsoc m n (prod m n)).\n    rewrite -> (SumAsoc n m (prod m n)).\n    rewrite (SumConm n m).\n    reflexivity.\nQed.\n\n(* 9.7 *)\n(* Puedo hacer \u00e9ste ejercicio antes del 9.6? S\u00ed *)\nLemma ProdDistr : forall n m p : nat, prod n (sum m p) = sum (prod n m) (prod n p).\nProof.\n  induction n.\n    intros; simpl; reflexivity.\n\n    intros m' p'; simpl.\n    rewrite <- (SumAsoc m' (prod n m') (sum p' (prod n p'))).\n    rewrite (SumAsoc (prod n m') p' (prod n p')).\n    rewrite (SumConm (prod n m') p').\n    rewrite <- (SumAsoc p' (prod n m') (prod n p')).\n    rewrite (SumAsoc m' p' (sum (prod n m') (prod n p'))).\n    rewrite (IHn m' p').\n    reflexivity.\nQed.\n\n(* 9.6 *)\nLemma ProdAsoc : forall n m p : nat, prod n (prod m p) = prod (prod n m) p.\nProof.\n  induction n.\n    intros; simpl; reflexivity.\n\n    simpl.\n    intros m' p'.\n    rewrite (IHn m' p').\n    rewrite (ProdConm m' p').\n    rewrite (ProdConm (prod n m') p').\n    rewrite (ProdConm (sum m' (prod n m')) p').\n    symmetry; exact(ProdDistr p' m' (prod n m')).\nQed.\n\nEnd Ejercicio9.\n\n\n(* Ejercicio 10 *)\nSection Ejercicio10.\n\n(* 10.1 *)\nLemma L1 : forall (A : Set) (l : list A), append A l (nil A) = l.\nProof.\n  intros; destruct l; simpl; reflexivity.\nQed.\n\n(* 10.2 *)\n(* Est\u00e1 bien usar \"discriminate\"? S\u00ed *)\nLemma L2 : forall (A : Set) (l : list A) (a : A), ~(cons A a l) = nil A.\nProof.\n  intros; unfold not; intro H.\n  discriminate H.\nQed.\n\n(* 10.3 *)\nLemma L3 : forall (A : Set) (l m : list A) (a : A), cons A a (append A l m) = append A (cons A a l) m.\nProof.\n  destruct l; intros; destruct m; simpl; reflexivity.\nQed.\n\n(* 10.4 *)\nLemma L4 : forall (A : Set) (l m : list A),\nlength A (append A l m) = sum (length A l) (length A m).\nProof.\n  induction l; intro m'.\n    simpl; reflexivity.\n\n    destruct m'.\n      simpl.\n      rewrite (SumConm (length A l) 0).\n      simpl; reflexivity.\n    \n      simpl.\n      rewrite (IHl (cons A a0 m')).\n      simpl; reflexivity.\nQed.\n\n(* 10.5 *)\nLemma L5:forall (A : Set) (l : list A), length A (reverse A l) = length A l.\nProof.\n  induction l.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite <- IHl.\n    rewrite (L4 A (reverse A l) (cons A a (nil A))).\n    simpl.\n    rewrite (SumConm (length A (reverse A l)) 1).\n    simpl; reflexivity.\nQed.\n\n(* 11.3 *)\n(* Puedo usar \u00e9ste lema antes? S\u00ed *)\nLemma L9 : forall (A : Set) (l m n : list A),\nappend A l (append A m n) = append A (append A l m) n.\nProof.\n  induction l.\n    intros; simpl; reflexivity.\n\n    intros m' n'.\n    rewrite <- (L3 A l m' a).\n    rewrite <- (L3 A (append A l m') n' a).\n    rewrite <- (IHl m' n').\n    rewrite -> (L3 A l (append A m' n') a).\n    reflexivity.\nQed.\n\n(* 10.6 *)\nLemma L6 : forall (A : Set) (l m : list A),\nreverse A (append A l m) = append A (reverse A m) (reverse A l).\nProof.\n  induction l.\n    intro m'.\n    simpl.\n    rewrite (L1 A (reverse A m')); reflexivity.\n\n    intro m'; rewrite <- (L3 A l m').\n    simpl.\n    rewrite (L9 A (reverse A m') (reverse A l) (cons A a (nil A))).\n    rewrite (IHl m'); reflexivity.\nQed.\n\nEnd Ejercicio10.\n\n\n\n(* Ejercicio 11  *)\nSection Ejercicio11.\n\n(* 11.1 *)\nLemma L7 : forall (A B : Set) (l m : list A) (f : A -> B), map A B f (append A l m) = append B (map A B f l) (map A B f m).\nProof.\n  induction l.\n    simpl; reflexivity.\n\n    intros m' f'.\n    destruct m'.\n      simpl; reflexivity.\n\n      simpl.\n      assert(map A B f' (append A l (cons A a0 m')) = append B (map A B f' l) (map A B f' (cons A a0 m'))); [exact(IHl (cons A a0 m') f') | idtac].\n      rewrite H.\n      simpl; reflexivity.\nQed.\n\n(* 11.2 *)\nLemma L8 : forall (A : Set) (l m : list A) (P : A -> bool),\nfilter A P (append A l m) = append A (filter A P l) (filter A P m).\nProof.\n  induction l.\n    intros; simpl; reflexivity.\n\n    intros m' P'.\n    rewrite <- (L3 A l m' a).\n    simpl.\n    destruct (P' a).\n      rewrite <- (L3 A (filter A P' l) (filter A P' m')).\n      rewrite (IHl m' P'); reflexivity.\n\n      rewrite (IHl m' P'); reflexivity.\nQed.\n\n(* 11.3, est\u00e1 echo en la secci\u00f3n Ejercicio10 *)\n\n(* 11.4 *)\nLemma L10 : forall (A : Set) (l : list A), reverse A (reverse A l) = l.\nProof.\n  induction l.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite (L6 A (reverse A l) (cons A a (nil A))).\n    rewrite IHl.\n    simpl reverse.\n    rewrite <- (L3 A (nil A) l a).\n    simpl; reflexivity.\nQed.\n\nEnd Ejercicio11.\n\n\n(* Ejercicio 12 *)\nSection Ejercicio12.\n\nFixpoint filterMap (A B : Set) (P : B -> bool) (f : A -> B) (l : list A) {struct l} : list B :=\n  match l with\n  | nil => nil B\n  | cons a l1 =>\n    match P (f a) with\n    | true => cons B (f a) (filterMap A B P f l1)\n    | false => filterMap A B P f l1\n    end\n  end.\n\nLemma FusionFilterMap : forall (A B : Set) (P : B -> bool) (f : A -> B) (l : list A),\n  filter B P (map A B f l) = filterMap A B P f l.\nProof.\n  induction l.\n    simpl; reflexivity.\n\n    simpl.\n    destruct (P (f a)); rewrite IHl; reflexivity.\nQed.\n\nEnd Ejercicio12.\n\n(* Ejercicio 13 *)\nSection Ejercicio13.\n\n(* Puedo interpretar a \u00e9ste lema como: inverse cumple su especificaci\u00f3n? Si *)\nLemma arbol_espejo : forall (A:Set) (b:bintree A), mirror A (inverse A b) b.\nProof.\n  induction b.\n    simpl.\n    exact (mirror0 A).\n\n    simpl.\n    exact(mirrorS A (inverse A b2) (inverse A b1) b1 b2 a a (eq_refl a) IHb2 IHb1).\nQed.\n\nEnd Ejercicio13.\n\n\n(* Ejercicio 14 *)\nSection Ejercicio14.\n\n(* 14.1 *)\nDefinition arbol_id (A:Set) (b:bintree A):bintree A := b.\n\nLemma arbol_id_isomorfo : forall (A:Set) (b:bintree A), isomorfismo A (arbol_id A b) b.\nProof.\n  induction b.\n    unfold arbol_id.\n    exact (isomorfismo0 A).\n\n    unfold arbol_id.\n    exact (isomorfismoS A b1 b2 b1 b2 a a IHb1 IHb2).\nQed.\n\n(* 14.2 *)\nLemma isomorfismo_reflexividad : forall (A:Set) (b:bintree A), isomorfismo A b b.\nProof.\n  induction b.\n    exact (isomorfismo0 A).\n\n    exact(isomorfismoS A b1 b2 b1 b2 a a IHb1 IHb2).\nQed.\n\nLemma ismorfismo_simetria : forall (A:Set) (b b':bintree A), isomorfismo A b b' -> isomorfismo A b' b.\nProof.\n  intros.\n  induction H.\n  (* Si tuviese (node ..) en lugar de b', est\u00e1 bien aplicar induction H, y que (node ..) se pise?\n     Si no lo necesito esta bien. Para preservar el (node ..), hago una nueva hipotesis: b'' = node .., y\n     hago induccion sobre \" isomorfismo A b b'' \", dejando el isomorfismo lo mas generico posible.*)\n    exact (isomorfismo0 A).\n\n    exact (isomorfismoS A t1' t2' t1 t2 b a IHisomorfismo1 IHisomorfismo2).\nQed.\n\nEnd Ejercicio14.\n\n\n(* Ejercicio 15 *)\nSection Ejercicio15.\n\nInductive Tree (A:Set):Set :=\n    leaf : A -> Tree A\n  | tnode : Tree A -> Tree A -> Tree A.\n\n\n(* 15.1 *)\nFixpoint mapTree (A B:Set) (t:Tree A) (f:A->B) {struct t}:Tree B :=\n  match t with\n  | leaf x => leaf B (f x)\n  | tnode t1 t2 => tnode B (mapTree A B t1 f) (mapTree A B t2 f)\n  end.\n\n(* 15.2 *)\nFixpoint num_hojas (A:Set) (t:Tree A) {struct t}:nat :=\n  match t with\n  | leaf x => 1\n  | tnode t1 t2 => sum (num_hojas A t1) (num_hojas A t2)\n  end.\n\n(* 15.3 *)\nLemma ej15_3 : forall (A B:Set) (f:A->B) (t:Tree A), num_hojas A t = num_hojas B (mapTree A B t f).\nProof.\n  induction t.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite <- IHt1, IHt2; reflexivity.\nQed.\n\n(* 15.4 *)\nFixpoint hojas (A:Set) (t:Tree A):list A :=\n  match t with\n  | leaf x => cons A x (nil A)\n  | tnode t1 t2 => append A (hojas A t1) (hojas A t2)\n  end.\n\nLemma ej15_4 : forall (A:Set) (t:Tree A), num_hojas A t = length A (hojas A t).\nProof.\n  induction t.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite (L4 A (hojas A t1) (hojas A t2)).\n    rewrite <- IHt1, IHt2; reflexivity.\nQed.\n\nEnd Ejercicio15.\n\nSection Ejercicio16.\n\n(* 16.1 *)\n(* posfijo l1 l2 <-> l1 es un posfijo de l2 *)\nInductive posfijo (A:Set):list A -> list A -> Prop :=\n    posfijoB : forall (l :list A), posfijo A l l\n  | posfijoC : forall (l1 l2:list A) (a:A), posfijo A l1 l2 -> posfijo A l1 (cons A a l2).\n\n(* 16.2 *)\nLemma ej16_2a : forall (A:Set) (l1 l2 l3:list A), l2 = append A l3 l1 -> posfijo A l1 l2.\nProof.\n  induction l2.\n    intros; simpl.\n    destruct l1.\n      exact (posfijoB A (nil A)).\n      destruct l3.\n        simpl in H; discriminate H.\n        rewrite <- (L3 A l3 (cons A a l1) a0) in H; discriminate H.\n\n   intros l3' H.\n   destruct l3'.\n     simpl in H; rewrite H; exact (posfijoB A l1).\n     rewrite <- (L3 A l3' l1 a0) in H.\n     injection H; intros; clear H.\n     exact (posfijoC A l1 l2 a ((IHl2 l3') H0)).\nQed.\n\n(* En \u00e9sta forma se hace induccion sobre l3, pero antes de hacer induccion se reescribe l2 y se borra la igualdad *)\nLemma ej16_2a' : forall (A:Set) (l1 l2 l3:list A), l2 = append A l3 l1 -> posfijo A l1 l2.\nProof.\n  intros.\n  rewrite H; clear H.\n  induction l3.\n    simpl; exact (posfijoB A l1).\n\n    rewrite <- (L3 A l3 l1 a).\n    apply (posfijoC A l1 (append A l3 l1)).\n    assumption.\nQed.\n\n\nLemma ej16_2b : forall (A:Set) (l1 l2:list A), posfijo A l1 l2 -> exists (l3:list A), l2 = append A l3 l1.\nProof.\n  intros.\n  induction H.\n    exists (nil A).\n    simpl; reflexivity.\n\n    elim IHposfijo; intros; clear IHposfijo.\n    exists (cons A a x).\n    rewrite <- (L3 A x l1).\n    (* otra forma seria hacer: rewrite H0 *)\n    apply f_equal. (* puedo usar f_equal? Si*)\n    assumption.\nQed.\n\n(* 16.3 *)\nFixpoint ultimo (A:Set) (l:list A):list A :=\n  match l with\n  | nil => nil A\n  | cons x nil => cons A x (nil A)\n  | cons x l'' => ultimo A l''  (* est\u00e1 bien? Si *)\n  end.\n\n(* 16.4 *)\nLemma ej16_4aux : forall (A:Set) (l:list A) (a a':A), ultimo A (cons A a (cons A a' l)) = ultimo A (cons A a' l).\nProof.\n  intros; simpl; reflexivity.\nQed.\n\nLemma ej16_4 : forall (A:Set) (l:list A), posfijo A (ultimo A l) l.\nProof.\n  induction l.\n    simpl.\n    exact (posfijoB A (nil A)).\n\n    destruct l.\n      simpl.\n      exact (posfijoB A (cons A a (nil A))).\n      rewrite (ej16_4aux A l a a0).\n      exact ((posfijoC A (ultimo A (cons A a0 l)) (cons A a0 l) a) IHl).\nQed.\n\nEnd Ejercicio16.\n\n\n(* Ejercicio 17 *)\nSection Ejercicio17.\n\n(* 17.1 *)\n(* Es un arbol completo, pues las hojas siempre tienen un elemento *)\nInductive ABin (A B:Set):Set :=\n  | ABLeaf : B -> ABin A B\n  | ABCons : forall (_:A) (ab1 ab2:ABin A B), ABin A B.\n\n(* 17.2 *)\nFixpoint ABhojas (A B:Set) (ab:ABin A B) {struct ab}:nat :=\n  match ab with\n  | ABLeaf _ => 1\n  | ABCons _ ab1 ab2 => sum (ABhojas A B ab1) (ABhojas A B ab2)\n  end.\n\n(* 17.3 *)\nFixpoint ABnodos (A B:Set) (ab:ABin A B) {struct ab}:nat :=\n  match ab with\n  | ABLeaf _ => 0\n  | ABCons _ ab1 ab2 => S (sum (ABnodos A B ab1) (ABnodos A B ab2))\n  end.\n\n(* 17.4 *)\nLemma ej17_4 : forall (A B:Set) (ab:ABin A B), ABhojas A B ab = S (ABnodos A B ab).\nProof.\n  induction ab.\n    simpl; reflexivity.\n\n    simpl.\n    rewrite IHab1, IHab2; simpl.\n    rewrite -> (SumConm (ABnodos A B ab1) (S (ABnodos A B ab2))); simpl.\n    rewrite -> (SumConm (ABnodos A B ab2) (ABnodos A B ab1)); reflexivity.\nQed.\n\nEnd Ejercicio17.\n\n\n\n(* Ejercicio 18 *)\nSection Ej_18.\n\nVariable A : Set.\n\nInductive Tree_ : Set :=\n  | nullT : Tree_\n  | consT : A -> Tree_ -> Tree_ -> Tree_.\n\n(* 18.1 *)\n(* Por que si uso un \\/, el principio de inducci\u00f3n sale mal?\nEs conveniente NO hacer definiciones inductivas que tengan \\/. *)\nInductive isSubTree : Tree_ -> Tree_ -> Prop :=\n  | sb_iguales : forall (t:Tree_), isSubTree t t\n  | sb_izq : forall (t t1 t2:Tree_ ) (a:A), isSubTree t t1 -> isSubTree t (consT a t1 t2)\n  | sb_der : forall (t t1 t2:Tree_ ) (a:A), isSubTree t t2 -> isSubTree t (consT a t1 t2).\n\n(* 18.2 *)\nLemma isSubTree_ref : forall (t:Tree_), isSubTree t t.\nProof.\n  exact (sb_iguales).\nQed.\n\n(* 18.3 *)\nLemma isSubTree_tran : forall (t1 t2 t3:Tree_), isSubTree t1 t2 /\\ isSubTree t2 t3 -> isSubTree t1 t3.\nProof.\n  intros.\n  elim H; intros; clear H.\n  Print isSubTree_ind.\n  induction H1.\n    assumption.\n    apply (sb_izq t1 t0 t2 a); exact (IHisSubTree H0).\n    apply (sb_der t1 t0 t2 a); exact (IHisSubTree H0).\nQed.\n\nEnd Ej_18.\n\n\n(* Ejercicio 19 *)\nSection Ejercicio19.\n\n(* 19.1 *)\nInductive ACom (A:Set): nat -> Set :=\n  | AComB : A -> ACom A 0\n  | AComI : forall (n :nat) (_:A) (ac1 ac2:ACom A n), ACom A (S n).\n \n(* 19.2 *)\nFixpoint h (A:Set) (n:nat) (ac:ACom A n) {struct ac}:nat :=\n  match ac with\n  | AComB _ => 1\n  | AComI n _ _ _ => sum (pot 2 n) (pot 2 n)  (* est\u00e1 bien el match? si *)\n  end.\n\n(* 19.3 *)\n(* Parameter pot: nat -> nat -> nat. *)\nAxiom potO : forall n : nat, pot (S n) 0 = 1.\nAxiom potS : forall m: nat, pot 2 (S m) = sum (pot 2 m) (pot 2 m).\n\nLemma ej19_3 : forall (A:Set) (n:nat) (ac:ACom A n), h A n ac = pot 2 n.\nProof.\n  intros.\n  induction ac.\n    simpl h; rewrite (potO 1); reflexivity.\n    Check ACom_ind.\n    simpl h; rewrite (potS n).\n    reflexivity.\nQed.\n\nEnd Ejercicio19.\n\n\n(* Ejercicio 20 *)\nSection Ejercicio20.\n\n(* 20.1 *)\nInductive AB (A:Set):nat->Set :=\n    ABNil : AB A 0\n  | ABC : forall (n m:nat) (_:A) (t1:AB A n) (t2:AB A m), AB A (S (max n m)).\n\n(* 20.2 *)\n(* Por qu\u00e9 tengo que usar gt_dec, en el if then else? *)\nRequire Import Coq.Arith.Compare_dec.\n\nFixpoint camino (A:Set) (n:nat) (ab:AB A n):list A :=\n  match ab with\n  | ABNil => nil A\n  | ABC n m x t1 t2 => if gt_dec m n then cons A x (camino A m t2) else cons A x (camino A n t1)\n  end.\n\n(* 20.3 *)\nRequire Import Coq.Arith.Lt.\n\nLemma ej20_3 : forall (A:Set) (n:nat) (ab:AB A n), length A (camino A n ab) = n.\nProof.\n  induction ab.\n    simpl; reflexivity.\n\n    simpl.\n      destruct (gt_dec m n).\n        simpl.\n        rewrite IHab2.\n        rewrite (max_r n m (lt_le_weak n m g)).\n        reflexivity.\n\n        simpl.\n        rewrite IHab1.\n        rewrite (max_l n m (not_gt m n n0)).\n        reflexivity.\nQed.\n\nEnd Ejercicio20.\n", "meta": {"author": "JoelCa", "repo": "CFPTT", "sha": "55f6aca270d7ffba9069ed1033aca474f1d3df9b", "save_path": "github-repos/coq/JoelCa-CFPTT", "path": "github-repos/coq/JoelCa-CFPTT/CFPTT-55f6aca270d7ffba9069ed1033aca474f1d3df9b/practico4/plantilla4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8872045966995028, "lm_q1q2_score": 0.8199028725409925}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** ** Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros.\n  induction n.\n  Case \"n=0\". simpl. apply ev_0.\n  Case \"n=Sn\". simpl. apply ev_SS. apply IHn.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\".\n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".\n    unfold even. apply IHE'.\nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n(** Unable to prove the case (S n') by induction -- no rule for this case *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\nThere's no rule of ev to match the case ev (S n), attempts to apply won't unify.\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 E F. induction E.\n  Case \"E = ev_0\". simpl. apply F.\n  Case \"E = ev_SS\". simpl. apply ev_SS. apply IHE.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.\n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful].\n       - Rule [b_5]: The number [5] is [beautiful].\n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n\n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5\n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)\n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n(** *** *)\n(**\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(** Many more than the 2 presented, consider that 0+8 = 8 -- we could have an infinite proof tree. *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(**\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    intros n H. simpl. apply b_sum. apply H. apply b_sum. apply H. apply b_0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   intros n m B. induction m as [|m'].\n   Case \"m = 0\". simpl. apply b_0.\n   Case \"m = S m'\". simpl. apply b_sum. apply B. apply IHm'.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n   ---------- (g_0)\n   gorgeous 0\n\n   gorgeous n\n   ---------------- (g_plus3)\n   gorgeous (3 + n)\n\n   gorgeous n\n   ---------------- (g_plus5)\n   goregous (5 + n)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros n H. apply g_plus5. apply g_plus5. apply g_plus3. apply H.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous.\nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)\n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros. induction H as [|n'|n'].\n  Case \"g_0\". simpl. apply H0.\n  Case \"g_3\". apply g_plus3. apply IHgorgeous.\n  Case \"g_5\". apply g_plus5. apply IHgorgeous.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros. induction H.\n  Case \"b_0\". apply g_0.\n  Case \"b_3\". apply g_plus3. apply g_0.\n  Case \"b_5\". apply g_plus5. apply g_0.\n  Case \"b_sum\". apply gorgeous_sum. apply IHbeautiful1. apply IHbeautiful2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n  intros. rewrite plus_comm. rewrite <- plus_assoc. assert (y+x=x+y). apply plus_comm. rewrite H. apply plus_assoc.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   induction H.\n   Case \"g_0\". simpl. apply g_0.\n   Case \"g_plus3\". apply g_plus3. fold plus.\n                   rewrite helper_g_times2.\n                   apply g_plus3. fold plus.\n                   rewrite <- plus_assoc.\n                   apply IHgorgeous.\n   Case \"g_plus5\". apply g_plus5. fold plus.\n                   rewrite helper_g_times2.\n                   apply g_plus5. fold plus.\n                   rewrite <- plus_assoc.\n                   apply IHgorgeous.\nQed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(** Destruct on n would be stupid, and fail, but\nThe proof is identical if we destruct on E...\n  destruct E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS\". simpl. apply E'. Qed. *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H. inversion H. inversion H1. apply H3. Qed.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros H. inversion H. inversion H1. inversion H3. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m E F. induction F.\n  Case \"F = ev_0\". simpl in E. apply E.\n  Case \"F = ev_SS\". inversion E. apply IHF. apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p E.\n  apply ev_ev__ev.\n  rewrite plus_swap. rewrite <- plus_assoc. rewrite plus_assoc.\n  apply ev_sum. rewrite plus_comm. apply E.\n  rewrite <- double_plus. apply double_even.\nQed.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n\n    - Prove that\n       forall l, pal (l ++ rev l).\n    - Prove that\n       forall l, pal l -> l = rev l.\n*)\n\n\nInductive pal {X:Type} : list X -> Prop :=\n  pal_nil  : pal [ ]\n| pal_sing : forall x, pal [x]\n| pal_rec  : forall l x, pal l -> pal (x :: l ++ [x]).\n\nTheorem pal_app_rev : forall (X:Type) (l : list X),\n  pal (l ++ rev l).\nProof.\n  intros. induction l as [|x l'].\n  Case \"l=[]\". simpl. apply pal_nil.\n  Case \"l=x::l'\". simpl.\n    rewrite <- snoc_with_append.\n    rewrite snoc_append.\n    apply pal_rec.\n    apply IHl'.\nQed.\n\nTheorem pal_rev : forall X (l:list X),\n  pal l -> l = rev l.\nProof.\n  intros X l H.\n  induction H.\n  Case \"pal []\". reflexivity.\n  Case \"pal [x]\". reflexivity.\n  Case \"pal_rec\".\n    rewrite <- cons_app_assoc.\n    rewrite <- rev_app. simpl.\n    rewrite <- IHpal.\n    rewrite snoc_append.\n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\nTheorem app_assoc : forall X (l1 l2 l3:list X),\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros. induction l1.\n  Case \"[]\". reflexivity.\n  Case \"l1=x::l1'\". simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem app_singletons : forall X (x y : X),\n  [x;y] = [x] ++ [y].\nProof. reflexivity. Qed.\n\nTheorem nil_app_after : forall X (l : list X),\n  l ++ [] = l.\nProof. induction l. reflexivity. simpl. rewrite IHl. reflexivity. Qed.\n\nLemma cons_app_head : forall X (l : list X) x,\n  x :: l = [x] ++ l.\nProof. reflexivity. Qed.\n\nTheorem length_app_dist : forall X (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof. intros. induction l1. reflexivity. simpl. rewrite IHl1. reflexivity. Qed.\n\nTheorem plus_injective : forall (n m o : nat),\n  n + m = n + o -> m = o.\nProof. induction n. simpl. intros.  apply H. simpl. intros. inversion H. apply IHn. apply H1. Qed.\n\nLemma list_append_length_contra : forall X x (l1 l2 : list X),\n  l1 = (x::l2) ++ l1 -> 1 = 0.\nProof.\n  intros. apply f_equal with (f:=length) in H.\n  simpl in H. rewrite length_app_dist in H.\n  rewrite <- plus_1_l in H. rewrite plus_comm in H. rewrite <- plus_assoc in H. rewrite plus_comm in H.\n  symmetry in H. rewrite <- plus_0_r in H. rewrite <- plus_assoc in H.\n  apply plus_injective with (n:=length l1) (m:=1 + length l2) (o:=0) in H.\n  inversion H.\nQed.\n\nTheorem app_injective : forall X (l1 l2 l : list X),\n  l1 ++ l = l2 ++ l -> l1 = l2.\nProof.\n  induction l1. induction l2.\n  Case \"l1=[]\".\n    SCase \"l2=[]\". reflexivity.\n    SCase \"l2=::\". intros. simpl in H. apply list_append_length_contra in H. inversion H.\n  Case \"l1=::\". induction l2.\n    SCase \"l2=[]\". simpl. intros. symmetry in H. apply list_append_length_contra in H. inversion H.\n    SCase \"l2=::\".\n      intros. inversion H. apply IHl1 in H2. rewrite H2. reflexivity.\nQed.\n\nLemma length_0 : forall X (l : list X),\n  length l = 0 -> l = [].\nProof. intros. destruct l. reflexivity. inversion H. Qed.\n\nTheorem palindrome_converse : forall X (l:list X),\n  l = rev l -> pal l.\nProof.\n(*\n  intros X l E.\n  induction l as [|x l'].\n  Case \"l=[]\". apply pal_nil.\n  Case \"l=x::l'\". destruct l' as [|y l''].\n  SCase \"l=[x]\". apply pal_sing.\n  SCase \"l=x::y::l''\".\n    simpl in H. rewrite snoc_append in H. rewrite snoc_append in H.\n    rewrite app_assoc in H. simpl in H.\n    destruct (rev l'') as [|z l3] eqn:L2.\n    SSCase \"[]\".\n      simpl in H. inversion H. assert ([y] = [] ++ [y]) as A. reflexivity. rewrite A. apply pal_rec. apply pal_nil.\n    SSCase \"rev l''=x0::l\".\n      inversion H. rewrite H2.\n      apply f_equal with (f:=rev) in L2. rewrite rev_involutive in L2. rewrite L2 in H2. simpl in H2. rewrite snoc_append in H2.\n      rewrite app_singletons in H2.\n      rewrite <- app_assoc in H2. rewrite <- cons_app_assoc in H2.\n      apply app_injective with (l2:=l3 ++ [y]) (l:=[z]) in H2.\n      destruct l3 as [|z' l4] eqn:L3.\n      SSSCase  \"l3=[]\".\n        simpl. rewrite app_singletons. apply pal_rec. apply pal_sing.\n      SSSCase \"l3=::\".\n        simpl. inversion H2. rewrite snoc_append in H4. apply app_injective in H4.\n        rewrite app_singletons. rewrite <- app_assoc. rewrite <- cons_app_assoc. apply pal_rec.\n        apply pal_rec.\n        (* consistent names please *)\n        symmetry in H3. rewrite H3 in H2. rewrite H3 in H. rewrite H3 in L2.\n        (* tidy up the ind hyp *)\n        rewrite L2 in IHl'. simpl in IHl'. rewrite ?snoc_append in IHl'. rewrite ?app_assoc in IHl'.\n        rewrite <- ?app_singletons in IHl'.\n*)\n(** Bad induction hypothesis, requires y :: rev l4 ++ [y;z] = z :: y :: l4 ++ [y]\n    Note z is flipped from one end to the other.\n    This is because the inductive step fails to require that the list has the form x :: l' ++ [x]\n    If I could use pal as the inductive step, then things would be great...\n*)\n(* GIVE UP *) Admitted.\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*)\nInductive subseq : list nat -> list nat -> Prop :=\n  subseq_nil   : forall l, subseq [] l\n| subseq_match : forall n l l', subseq l l' -> subseq (n :: l) (n :: l')\n| subseq_else  : forall m n l l', subseq (n::l) l' -> subseq (n :: l) (m :: l').\n\nExample subseq_test1 : subseq [1;2;3] [1;2;3].\nProof. apply subseq_match. apply subseq_match. apply subseq_match. apply subseq_nil. Qed.\n\nExample subseq_test2 : subseq [1;2;3] [1;1;2;2;3].\nProof. apply subseq_else. apply subseq_match. apply subseq_match. apply subseq_else. apply subseq_match. apply subseq_nil. Qed.\n\n(** - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.\n*)\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  induction l.\n  apply subseq_nil.\n  apply subseq_match. apply IHl.\nQed.\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\nTheorem subseq_extends : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros l1 l2 l3 H. induction H.\n  apply subseq_nil.\n  simpl. apply subseq_match. apply IHsubseq.\n  simpl. apply subseq_else. apply IHsubseq.\nQed.\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\nTheorem subseq_trans : forall l1 l2 l3,\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3. generalize dependent l1.  generalize dependent l2.\n  induction l3.\n  Case \"l3=[]\". intros. inversion H0; inversion H; subst.\n    apply subseq_nil.\n    inversion H5. (* contra *)\n    inversion H5. (* contra *)\n  Case \"l3=x::l3\".  intros. inversion H0.\n    SCase \"l2=[]\". subst. inversion H. apply H0.\n    subst. inversion H.\n      apply subseq_nil.\n      apply subseq_match. apply IHl3 with (l2:=l). apply H4. apply H3.\n      apply subseq_else. apply IHl3 with (l2:=l). apply H4. apply H3.\n    subst. inversion H.\n      apply subseq_nil.\n      subst. apply subseq_else. apply IHl3 with (l2:=(n::l)). apply H. apply H3.\n      subst. apply subseq_else. apply IHl3 with (l2:=(n::l)). apply H. apply H3.\nQed.\n(* Phew! *)\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\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    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n      yes\n    - [R 1 [1,2,1,0]]\n      yes\n    - [R 6 [3,2,1,0]]\n      no\n*)\nTheorem r_1 : R 2 [1;0]. repeat constructor. Qed.\nTheorem r_2 : R 1 [1;2;1;0]. repeat constructor. Qed.\nTheorem r_3 : R 6 [3;2;1;0]. Abort.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n  | tr : forall n m:nat, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros. induction H0.\n  Case \"m=n\". apply H.\n  Case \"Sm0=n\". apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n. apply le_n. apply le_S. apply IHn. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros. induction H.\n  Case \"n=m\". apply le_n.\n  Case \"Sm0=m\". 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  induction m,n; intros.\n  apply O_le_n.\n  inversion H. inversion H1.\n  apply O_le_n.\n  inversion H. apply le_n.\n  subst. apply le_S. apply IHm. apply H1.\nQed.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  induction b.\n  rewrite plus_0_r. apply le_n.\n  rewrite plus_S_assoc. apply le_S. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt. intros. split; induction H.\n  rewrite <- plus_comm. rewrite <- plus_S_assoc. rewrite plus_comm. apply le_plus_l.\n  apply le_S. apply IHle.\n  rewrite <- plus_S_assoc. rewrite plus_comm. apply le_plus_l.\n  apply le_S. apply IHle.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply le_S. apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  induction n; intros.\n  Case \"n=0\". apply O_le_n.\n  Case \"n=Sn\". destruct m.\n    SCase \"m=0\". inversion H. (* absurd *)\n    SCase \"m=Sm\". apply n_le_m__Sn_le_Sm. apply IHn. simpl in H. apply H.\nQed.\n\nLemma ble_nat_Sl : forall n m,\n  ble_nat m n = true -> ble_nat m (S n) = true.\nProof.\n  induction n; intros.\n  Case \"n=0\". destruct m.\n    SCase \"m=0\". reflexivity.\n    SCase \"m=Sm\". simpl in H. inversion H. (* contra *)\n  Case \"n=Sn\". destruct m.\n    SCase \"m=0\". reflexivity.\n    SCase \"m=Sm\". simpl. apply IHn. simpl in H. apply H.\n Qed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros n m. generalize dependent n. induction m; intros.\n  Case \"m=0\". destruct n.\n    SCase \"n=0\". reflexivity.\n    SCase \"n=Sn\". inversion H. (* absurd *)\n  Case \"m=Sm\". inversion H.\n    SCase \"n=Sm\". symmetry. apply ble_nat_refl.\n    SCase \"n<=m\". apply IHm in H1. apply ble_nat_Sl. apply H1.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  intros.\n  apply le_ble_nat. apply ble_nat_true in H. apply ble_nat_true in H0.\n  apply le_trans with (m:=n) (n:=m). apply H. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  unfold not. intros. apply le_ble_nat in H0. rewrite H0 in H. inversion H.\nQed.\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        Yes, c1 c3 c2.\n      - [R 2 2 6]\n        No?\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n      No, c2 and c3 permit adjustment of one of the first two params\n      respectively, c4 operates same on both. All acions can be performed by all.\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      I don't think so. c2.c3 and c3.c2 equiv to opposite of c4.\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n\n    Addition\n*)\n\nTheorem R_plus : forall m n o,\n  R m n o -> m + n = o.\nProof.\n  intros. induction H.\n  Case \"c1\". reflexivity.\n  Case \"c2\". simpl. rewrite IHR. reflexivity.\n  Case \"c3\". rewrite plus_S_assoc. rewrite IHR. reflexivity.\n  Case \"c4\". rewrite plus_S_assoc in IHR. simpl in IHR. inversion IHR. reflexivity.\n  Case \"c5\". rewrite plus_comm. apply IHR.\nQed.\n\nTheorem plus_R : forall o m n,\n  m + n = o -> R m n o.\nProof.\n  induction o; intros; destruct m; simpl in H.\n  Case \"o=0\".\n    SCase \"m=0\". rewrite H. apply c1.\n    SCase \"m=Sm\". inversion H. (* contra *)\n  Case \"o=So\".\n    SCase \"m=0\". rewrite H. apply c3. apply IHo. reflexivity.\n    SCase \"m=Sm\". apply c2. apply IHo. simpl in H. inversion H. reflexivity.\nQed.\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.\n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.\n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if (oddb n) then Podd n else Peven n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros. unfold combine_odd_even. destruct (oddb n).\n  Case \"true\". apply H. reflexivity.\n  Case \"false\". apply H0. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  unfold combine_odd_even. intros. rewrite H0 in H. apply H.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  unfold combine_odd_even. intros. rewrite H0 in H. apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n : nat) (f : nat->Prop) : Prop :=\n  match n with\n  | O    => forall m : nat, f m\n  | S n' => f n -> true_upto_n__true_everywhere n' f\n  end.\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n", "meta": {"author": "IgnoredAmbience", "repo": "software-foundations", "sha": "e1e75f8bdfd83979b13f5ce7574659c7925a6cf6", "save_path": "github-repos/coq/IgnoredAmbience-software-foundations", "path": "github-repos/coq/IgnoredAmbience-software-foundations/software-foundations-e1e75f8bdfd83979b13f5ce7574659c7925a6cf6/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8199028563826232}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Rework your last proof using the full syntax of ssreflect. *)\n\n(* Solve the following equations. Search is your best friend. *)\nLemma ex5_arit1 n m : n + (m * n + 0) = n * m.+1.\nProof.\n  by rewrite addn0 -add1n mulnDr muln1 mulnC.\nQed.\n\nLemma ex5_arit2 n m : n %/ 2 + m = (2 * m + n) %/ 2.\nProof.\n  by rewrite mulnC divnMDl // addnC.\nQed.\n\nLemma ex5_arit3 n m p : 0 < p ->  p %| n -> n %/ p + m = (p * m + n) %/ p.\nProof.\n  move=> Hp Hpn.\n  rewrite divnDr //=.\n  rewrite mulKn //=.\n  by rewrite addnC.\nQed.\n\n(* Prove this by induction. *)\nLemma size_iota_sumn l : sumn (map (addn 1) l) = size l + sumn l.\nProof.\n  elim l => //= x xs IH.\n  by rewrite !addSn [x + _]addnC addnA IH add0n addnC.\nQed.\n\n(* Prove the following Theorem by induction. *)\nTheorem ex5_gauss n : (n * n.-1) %/ 2 = sumn (iota 0 n).\nProof.\n  elim n => //= n' IH.\n    rewrite (iota_addl 1 0) add0n size_iota_sumn -IH{IH} size_iota.\n    rewrite -{3}[n'](@mulnK _ 2) // -divnDl ?dvdn_mull //.\n    by rewrite [_ * _.-1]mulnC !mulnS muln0 addn0 -addnA; case: n'.\nQed.\n\n(* Advanced part *)\n\n(* Read the documentation of the wlog tactic *)\n\n(* Prove the following lemma without using dvdn_pexp2r following one the two informal\n   proofs. The first one is more detailed, the second one is more challenging.\n   If you want to try the second one, just skip ahead without reading the\n   following informal proof. *)\nLemma ex5_dvdn : forall m n k, k > 0 -> (m ^ k %| n ^ k) -> (m %| n).\nProof.\n\n(* Without loss of generality n is positive, since any number divides 0 *)\n\n(* Given d := gcdn m n, n can be written as n' * d and m as m' * d *)\n\n\n\n\n(* We also have d > 0 *)\n\n(* We can now refine our assumption to m' ^ k %| n' ^ k\n   since for b positive, a * b %| c * b -> a %| c     *)\n\n\n\n\n(* We can also prove that (m' ^ k) and (n' ^ k) are coprime since\n   the gcdn of m' and n' is 1, or equivalently (gcdn m' n') * d = d *)\n\n\n\n\n(* From this coprimality and the refiner hypothesis follows that\n   m' ^ k = 1 = gcdn (m' ^ k) (n' ^ k). Hint: gcdn a (a %% b) = gcdn a b *)\n\n\n\n(* Since m'^k = 1 also m' = 1. Thus m = d and d %| n *)\n\n\n\nQed.\n\nLemma ex5_dvdn_advanced : forall m n k, k > 0 -> (m ^ k %| n ^ k) -> (m %| n).\nProof.\n(* Without loss of generality we can assume (m ^ k) and (n ^ k) are coprime\n   (i.e. dividing n and m by their gcdn).\n   Since (m ^ k) also divides (n ^ k), (m ^ k) is 1, thus m is 1,\n   thus it trivially divides n. *)\n\n\n\n\n\n\n\n\n\n\nQed.\n\n", "meta": {"author": "daoo", "repo": "formalization-of-mathematics", "sha": "7f87baab942cc053e446396c69817e98483d6db5", "save_path": "github-repos/coq/daoo-formalization-of-mathematics", "path": "github-repos/coq/daoo-formalization-of-mathematics/formalization-of-mathematics-7f87baab942cc053e446396c69817e98483d6db5/exercises/map/exercises-05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.8196056392545796}}
{"text": "Require Import Arith.\n\nSearch (_ =? _).\n\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  destruct n.\n  - (* zero *) intros m. intros eq1. destruct m.\n    + (* zero *) reflexivity.\n    + (* S m *) apply beq_nat_true. exact eq1.\n  - (* S n *) intros m. intros eq1. destruct m.\n    + (* zero *) inversion eq1.\n    + (* S m *) apply beq_nat_true. exact eq1.\nQed.", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/5_Tactics/11_beq_nat_true.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.8196056377269856}}
{"text": "Inductive List :=\n|nil : List\n|cons : nat -> List -> List.\n\nPrint List_ind.\n\nFixpoint append (l1 l2 : List) : List :=\n  match l1 with\n  | nil => l2\n  | cons n l => cons n (append l l2)\nend.\n\nDefinition list1 := (cons 3 (cons 2 nil)).\nDefinition list2 := (cons 4 (cons 7 nil)).\n\nCompute (append list1 list2).\nCompute (append list2 list1).\n\nLemma append_nil_left:\n  forall l, append nil l = l.\nProof.\n  trivial.\nQed.\n\nLemma append_nil_right:\n  forall l, append l nil = l.\nProof.\n  induction l.\n  - trivial.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nLemma append_assoc :\n  forall l1 l2 l3,\n    append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n  induction l1.\n  - trivial.\n  - intros l2 l3.\n    simpl.\n    rewrite IHl1.\n    reflexivity.\nQed.\n\nFixpoint reverse(l : List) : List :=\n  match l with\n  |nil => nil\n  |(cons n l1) => append (reverse l1) (cons n nil)\nend.\n\nLemma helper:\n  forall l l2,\n     reverse ( append l l2) = \n     append (reverse l2) (reverse l).\nProof.\n  induction l.\n  - intros. simpl.\n    rewrite append_nil_right.\n    reflexivity.\n  - intros.\n    simpl.\n    rewrite IHl.\n    rewrite append_assoc.\n    reflexivity.\nQed.\n\nLemma involutive_reverse:\n  forall l, reverse (reverse l) = l.\nProof.\n  induction l.\n  - trivial.\n  - simpl.\n    rewrite helper.\n    rewrite IHl.\n    simpl.\n    reflexivity.\nQed. \n\n\n\n\n\n\n\n\n", "meta": {"author": "IonitaCatalin", "repo": "programming-language-principle", "sha": "e6a5b4f5284f28127707dc1b8838bad29f215c69", "save_path": "github-repos/coq/IonitaCatalin-programming-language-principle", "path": "github-repos/coq/IonitaCatalin-programming-language-principle/programming-language-principle-e6a5b4f5284f28127707dc1b8838bad29f215c69/coq_arc/curs2_liste.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.9046505331728751, "lm_q1q2_score": 0.8196041763553681}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                   Solange Coupet-Grimal & Line Jakubiec                  *)\n(*                                                                          *)\n(*                                                                          *)\n(*              Laboratoire d'Informatique de Marseille                     *)\n(*               CMI-Technopole de Chateau-Gombert                          *)\n(*                   39, Rue F. Joliot Curie                                *)\n(*                   13453 MARSEILLE Cedex 13                               *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lim.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*                              May 30th 1996                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                               Lib_Minus.v                                *)\n(****************************************************************************)\n\n\nRequire Export Lib_Pred.\n\n\nLemma minus_SS_n : forall n : nat, S (S n) - n = 2.\nintros n.\nelim minus_Sn_m.\napply eq_S.\nelim minus_Sn_m.\napply eq_S.\nelim minus_n_n; auto with arith.\nauto with arith.\nauto with arith.\nQed.\nHint Resolve minus_SS_n.\n\n\n\nLemma minus_S : forall n m : nat, n - m = S n - S m.\nintros; simpl in |- *; auto with arith.\nQed.\nHint Resolve minus_S.\n\n\n\nLemma pred_minus_minus : forall n m : nat, pred (n - m) = n - S m.\nsimple induction n; simple induction m; auto with arith.\nintros; elim minus_S.\nelim minus_S; auto with arith.\nQed.\nHint Resolve pred_minus_minus.\n\n\n\nLemma minus_pred_S : forall n m p : nat, n = m - p -> pred n = m - S p.\nintros n m p H.\nrewrite H; auto with arith.\nQed.\nHint Resolve minus_pred_S.\n\n\n\nLemma pred_minus : forall n : nat, pred n = n - 1.\nsimple induction n; auto with arith.\nQed.\nHint Resolve pred_minus.\n\n\n\nLemma O_minus_S : forall n m : nat, 0 = n - m -> 0 = n - S m.\nintros n m H.\nelim pred_minus_minus.\nelim H; auto with arith.\nQed.\nHint Resolve O_minus_S.\n\n\n\nLemma minus_minus_plus : forall n m p : nat, n - m - p = n - (m + p).\nsimple induction n; simple induction m; auto with arith.\nintros; elim minus_S.\nchange (n0 - n1 - p = S n0 - S (n1 + p)) in |- *.\nelim minus_S; apply H.\nQed.\nHint Resolve minus_minus_plus.\n\n\n\nLemma lt_O_minus : forall n m : nat, n < m -> 0 < m - n.\nsimple induction n; simple induction m; simpl in |- *; auto with arith.\nintro.\napply lt_trans with (S n0); auto with arith.\nQed.\nHint Resolve lt_O_minus.\n\n\n\nLemma le_minus : forall n m : nat, n - m <= n.\nsimple induction n; auto with arith.\n  intros. \t \n  case m; simpl in |- *; auto with arith.\nQed.\nHint Resolve le_minus.\n\n\n\nLemma le_minus_n_Sn : forall n m : nat, n - m <= S n - m.\nsimple induction n; simple induction m; auto with arith.\nintros.\nelim minus_S.\nelim minus_S; apply H. \nQed.\nHint Resolve le_minus_n_Sn.\n\n\n\nLemma le_reg_minus : forall n m p : nat, n <= m -> n - p <= m - p.\nintros.\nelim H; auto with arith.\nintros.\napply le_trans with (m0 - p).\nassumption.\napply le_minus_n_Sn.\nQed.\nHint Resolve le_reg_minus.\n\n\n\nLemma lt_transp_r : forall n m p : nat, 0 < n -> p < n + m -> p - m < n.\nsimple induction m; simple induction p.\nelim plus_n_O; auto with arith.\nelim plus_n_O; auto with arith.\nauto with arith.\nintros.\nsimpl in |- *.\napply H.\nauto with arith.\napply lt_S_n.\nreplace (S (n + n0)) with (n + S n0).\nauto with arith.\nelim plus_comm; simpl in |- *; auto with arith.\nQed.\n\n\n\nLemma lt_neq_O_pred : forall n m : nat, S n < m -> pred (m - n) <> 0.\nintros.\nelim H.\nrewrite minus_SS_n; auto with arith.\nintros.\nelim minus_Sn_m.\nsimpl in |- *.\nauto with arith.\napply le_trans with (S (S n)); auto with arith.\nQed.\nHint Resolve lt_neq_O_pred.\n\n\n\nLemma minus_Sn_n : forall n : nat, S n - n = 1.\nsimple induction n; auto with arith.\nQed.\nHint Resolve minus_Sn_n.\n\n\n\nLemma eq_minus_plus : forall n m : nat, m <= n -> n - m + m = n.\nintros n m.\ngeneralize n.\nelim m.\nclear n.\nintro n.\nintro lenO.\nelim plus_n_O. \nauto with arith.\nclear n m.\nintros m H_rec n leSmn.\nelim plus_n_Sm.\nreplace (S (n - S m + m)) with (S (n - S m) + m); auto with arith.\nrewrite minus_Sn_m; auto with arith.\napply (H_rec n).\nauto with arith.\nQed.\nHint Immediate eq_minus_plus.\n\n\n(************************************************************************)\n\n", "meta": {"author": "coq-contribs", "repo": "hardware", "sha": "cc92b5cb860fd857da744cc39628c6ad1508ddf9", "save_path": "github-repos/coq/coq-contribs-hardware", "path": "github-repos/coq/coq-contribs-hardware/hardware-cc92b5cb860fd857da744cc39628c6ad1508ddf9/Libraries/Lib_Arithmetic/Lib_Minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8856314707995588, "lm_q1q2_score": 0.8194127659013203}}
{"text": "\nRequire Import Arith.\n\nFixpoint sum_up_to (n : nat) :=\n  match n with\n  | 0 => 0\n  | S n' => n + sum_up_to n'\n  end.\n\nTheorem fact : forall n, 2 * sum_up_to n = n * (n + 1).\nProof.\n  intros.\n  induction n.\n  {\n    (* Prove the base case. *)\n    reflexivity.\n  }\n  {\n    (* Prove the inductive case. *)\n    (* Unfold the definition of sum_up_to and refold it once,\n       to effectively pull the +1 out of its argument. *)\n    unfold sum_up_to.\n    fold sum_up_to.\n    (* Distribute multiplication once, so our inductive\n       hypothesis exactly fits a subterm. *)\n    rewrite mult_plus_distr_l.\n    (* Rewrite using our inductive hypothesis. *)\n    rewrite IHn.\n    (* Now that sum_up_to is eliminated, simple\n       semi-ring properties suffice. *)\n    ring.\n  }\nQed.\n\nPrint fact.", "meta": {"author": "petersn", "repo": "calculus", "sha": "d5e9aee31cc9cb4b8baef7ebb223fd474ab5494a", "save_path": "github-repos/coq/petersn-calculus", "path": "github-repos/coq/petersn-calculus/calculus-d5e9aee31cc9cb4b8baef7ebb223fd474ab5494a/coq_tests/sum_fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.8723473630627234, "lm_q1q2_score": 0.8191558307771848}}
{"text": "Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nDefinition bag := natlist.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n  end.\n\n\nFixpoint count (v : nat) (s : bag) : nat :=\n    match s with \n    | nil => O \n    | h :: t => match eqb v h with \n        | true => 1 + count v t\n        | false => count v t\n        end\n    end.\n\nFixpoint remove_one (v : nat) (s: bag) : bag :=\n    match s with \n    | nil => nil \n    | h :: t => match eqb v h with\n        | true => t\n        | false => h :: remove_one v t\n        end\n    end.\n\nExample test_remove_one1:\n    count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n    match s with \n    | nil => nil \n    | h :: t => match eqb v h with\n        | true => remove_all v t\n        | false => h :: remove_all v t\n        end\n    end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nFixpoint member (v : nat) (s : bag) : bool :=\n  match s with \n  | nil => false \n  | h :: t => match eqb h v with\n    | true => true\n    | false => member v t\n    end\n  end.\n  \nFixpoint included (s1 : bag) (s2 : bag) : bool :=\n    match s1 with\n    | nil => 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\n(* Question: is there a more precise syntax than  \n  match true|false with   \n  | true => ... \n  | false => ... \n\n*)\n\n\nExample test_included1: included [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_included2: included [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/exercises/bag_more_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.8191108319388163}}
{"text": "Require Import Arith Lia.\n\n\nDefinition inj {X Y} (f : X -> Y) :=\n  forall x x', f x = f x' -> x = x'.  \nDefinition inv {X Y} (g : Y -> X) (f : X -> Y) :=\n  forall x, g (f x) = x.\nDefinition bijection X Y :=\n  { f : X -> Y & { g & inv g f /\\ inv f g }}.\n\nLemma size_rect {X} \u03c3 f : \n  (forall x, (forall y : X, \u03c3 y < \u03c3 x -> f y) -> f x) -> forall x, f x.\nProof.\n  intros H x. apply H.\n  induction (\u03c3 x).\n  - now intros ??%PeanoNat.Nat.nlt_0_r. \n  - intros. apply H.\n    intros. apply IHn. lia.\nDefined.\n\n\nSection Cantor.\n\n  Definition next '(x,y) := \n    match x with\n    | O => (S y, O)\n    | S x' => (x', S y)\n    end.\n\n  Fact n00_next : forall p, (0,0) <> next p.\n  Proof. intros [[] ]; intuition discriminate. Qed.\n\n  Fact inj_next : inj next.\n  Proof. intros [[] ][[] ]; cbn; congruence. Qed.\n\n  Fixpoint decode n := \n    match n with\n    | 0 => (0,0)\n    | S x => next (decode x)\n    end.\n\n  Lemma inj_decode : inj decode.\n  Proof.\n    intros n. induction n; intros []; auto.\n    - now intros ?%n00_next.\n    - now intros ?%eq_sym%n00_next.\n    - intros [=?%inj_next%IHn]. congruence.\n  Qed.\n\n  (* Shows that the function \"next\" is almost surjective *)\n  Fact zero_or_next : forall p, {a | p = next a} + {p = (0,0)}.\n  Proof.\n    intros [x []].\n    - destruct x. now right. left; now exists (0, x).\n    - left; now exists (S x, n).\n  Defined.\n\n\n  Fixpoint \u03a3 n := match n with 0 => 0 | S x => n + \u03a3 x end. \n\n  Definition code '(x,y) := \u03a3(x+y)+y.\n\n  Lemma code_next p : code(next p) = S(code p).\n  Proof.\n    destruct p as [[|x] y]; cbn.\n    - rewrite <-!plus_n_O, Nat.add_comm. reflexivity.\n    - rewrite !Nat.add_succ_r. reflexivity.\n  Qed.\n\n\n  Lemma inv_dc : inv decode code.\n  Proof.\n    unfold inv.\n    apply (size_rect code). intros p rec.\n    destruct (zero_or_next p) as [[? ->] | ->].\n    - rewrite code_next. cbn. f_equal. apply rec.\n      rewrite code_next; auto.\n    - reflexivity.\n  Qed.\n\n  Fact inv_cd : inv code decode.\n  Proof.\n    intros ?. apply inj_decode. now rewrite inv_dc.\n  Qed.\n\n\n  Corollary Bij_Nat_NatNat : bijection nat (nat * nat).\n  Proof.\n    exists decode, code. split. apply inv_cd. apply inv_dc.\n  Qed.\n\n\n  Fact CantorBound x y n : code (x, y) = n -> y < S n.\n  Proof. cbn; lia. Qed.\n\nEnd Cantor.\n", "meta": {"author": "HermesMarc", "repo": "Tennenbaum-CTT", "sha": "6e5b15df59f35cad91a0c6de679a31374a160cf0", "save_path": "github-repos/coq/HermesMarc-Tennenbaum-CTT", "path": "github-repos/coq/HermesMarc-Tennenbaum-CTT/Tennenbaum-CTT-6e5b15df59f35cad91a0c6de679a31374a160cf0/CantorPairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8190489791317874}}
{"text": "Add LoadPath \"$COQ_PROOFS\" as Path.\nLoad unit_1_006_numbers.\n\nTheorem plus_O_n : \n  forall n : nat, 0 + n = n. (* Proposition *)\n(* We manipulate the goal and context with tactics (intros, simpl and reflexivity)) *)\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l: forall n: nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nTheorem mult_0_l: forall n:nat, 0*n = 0.\nProof. intros n. reflexivity. Qed.\n", "meta": {"author": "kino6052", "repo": "coq-course", "sha": "57de05e6eca44d8617794be1d8b41803af0a7cda", "save_path": "github-repos/coq/kino6052-coq-course", "path": "github-repos/coq/kino6052-coq-course/coq-course-57de05e6eca44d8617794be1d8b41803af0a7cda/unit_1_007_simplification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8188934465028821}}
{"text": "Require Import Bool Arith List.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* Comments and source code are derived from the book Certified Programming with Dependent Types by Professor Adam Chlipala available for free at http://adam.chlipala.net/cpdt/. *)\n\n(* We define an inductive datatype binop to stand for the binary operators of our source language *)\nInductive binop : Set := Plus | Times.\n\n(* We write that a constant may be built from one argument, a natural number; and a binary operation may be built from a choice of operator and two operand expressions. *)\nInductive exp : Set := \n    | Const : nat -> exp\n    | Binop : binop -> exp -> exp -> exp.\n\n(* The meaning of a binary operator is a binary function over nat referring to the\nfunctions plus and mult from the Coq standard library. *)\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n    match b with\n        | Plus => plus\n        | Times => mult\n    end.\n\n(* A simple recursive definition of the meaning of an expression. *)\nFixpoint expDenote (e : exp) : nat := \n    match e with\n    | Const n => n\n    | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n    end.\n\n(* An instruction either pushes a constant onto the stack or pops two arguments, applies a binary operator to them, and pushes the result onto the stack.*)\nInductive instr : Set :=\n    | iConst : nat -> instr\n    | iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\n\n(* We can give instructions meanings as functions from stacks to optional stacks, where running an instruction results in None in case of a stack underflow and results in Some s\u2019 when the result of execution is the new stack s\u2019 *)\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n    match i with\n        | iConst n => Some (n :: s)\n        | iBinop b => match s with\n            | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n            | _ => None\n        end\n    end.\n\n(* Iterates application of instrDenote through a whole program. *)\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n    match p with\n        | nil => Some s\n        | i :: p' => match instrDenote i s with\n            | None => None\n            | Some s' => progDenote p' s'\n            end\n        end.\n\n(* Compiler itself. *)\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(* How can we be sure the compiler operates correctly for all input\nprograms? *)\nTheorem compile_correct : forall e, progDenote (compile e) nil\n    = Some (expDenote e :: nil).\n\nAbort.\n\nLemma compile_correct' : forall e p s,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n\ninduction e.\n\nintros.\n\nunfold compile.\n\nunfold expDenote.\n\nunfold progDenote at 1.\n\nsimpl.\n\nfold progDenote.\n\nreflexivity.\n\nintros.\n\nunfold compile.\n\nfold compile.\n\nunfold expDenote.\n\nfold expDenote.\n\nCheck app_assoc_reverse.\n\nrewrite app_assoc_reverse.\n\nrewrite IHe2.\n\nrewrite app_assoc_reverse.\n\nrewrite IHe1.\n\nunfold progDenote at 1.\n\nsimpl.\n\nfold progDenote.\n\nreflexivity.\n\nQed.", "meta": {"author": "syedtaz", "repo": "discrete-math", "sha": "98b89a146aa946a74ed3348bed29f89297d58eea", "save_path": "github-repos/coq/syedtaz-discrete-math", "path": "github-repos/coq/syedtaz-discrete-math/discrete-math-98b89a146aa946a74ed3348bed29f89297d58eea/src/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8188888705221187}}
{"text": "(* \"especially useful\" *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint nonzeros (l:natlist) : natlist := \n    match l with \n    | nil => nil \n    | O :: t => nonzeros t\n    | S n :: t => S n :: nonzeros t\n    end.\n\nExample test_nonzeros:\n    nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nsimpl. reflexivity. Qed.\n\n\nFixpoint even (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => even n'\n  end.\n\nDefinition odd (n:nat) : bool :=\n    negb (even n).\n\nFixpoint oddmembers (l:natlist) : natlist :=\n    match l with \n    | nil => nil\n    | O :: t => oddmembers t \n    | S n :: t => match odd(S n) with\n        | true => S n :: oddmembers t \n        | false => oddmembers t \n        end\n    end.\n\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.", "meta": {"author": "Kevin-TD", "repo": "coq_learning", "sha": "2c725a27ff6c930010e217f505923f9207b070d6", "save_path": "github-repos/coq/Kevin-TD-coq_learning", "path": "github-repos/coq/Kevin-TD-coq_learning/coq_learning-2c725a27ff6c930010e217f505923f9207b070d6/lists/exercises/list_funs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8188838311234533}}
{"text": "Module Type LocalNat.\n\nInductive nat : Set :=\n | O : nat\n | S : nat->nat.\nCheck nat.\nCheck O.\nCheck S.\n\nEnd LocalNat.\n\nPrint nat.\n\n\nPrint le.\n\nTheorem zero_leq_three: 0 <= 3.\n\nProof.\n constructor 2.\n constructor 2.\n constructor 2.\n constructor 1.\n\nQed.\n\nPrint zero_leq_three.\n\n\nLemma zero_leq_three': 0 <= 3.\n repeat constructor.\nQed.\n\n\nLemma zero_lt_three : 0 < 3.\nProof.\n unfold lt.\n repeat constructor.\nQed.\n\n\nRequire Import List.\n\nPrint list.\n\nCheck list.\n\nCheck (nil (A:=nat)).\n\nCheck (nil (A:= nat -> nat)).\n\nCheck (fun A: Set => (cons (A:=A))).\n\nCheck (cons 3 (cons 2 nil)).\n\n\n\n\nRequire Import Bvector.\n\nPrint Vector.t.\n\nCheck (Vector.nil nat).\n\nCheck (fun (A:Set)(a:A)=> Vector.cons _ a _ (Vector.nil _)).\n\nCheck (Vector.cons _ 5 _ (Vector.cons _ 3 _ (Vector.nil _))).\n\n\n\n\n\n\n\n\n\n\n\n\n\nLemma eq_3_3 : 2 + 1 = 3.\nProof.\n reflexivity.\nQed.\nPrint eq_3_3.\n\nLemma eq_proof_proof : refl_equal (2*6) = refl_equal (3*4).\nProof.\n reflexivity.\nQed.\nPrint eq_proof_proof.\n\nLemma eq_lt_le : ( 2 < 4) = (3 <= 4).\nProof.\n reflexivity.\nQed.\n\nLemma eq_nat_nat : nat = nat.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Set_Set : Set = Set.\nProof.\n reflexivity.\nQed.\n\nLemma eq_Type_Type : Type = Type.\nProof.\n reflexivity.\nQed.\n\n\nCheck (2 + 1 = 3).\n\n\nCheck (Type = Type).\n\nGoal Type = Type.\nreflexivity.\nQed.\n\n\nPrint or.\n\nPrint and.\n\n\nPrint sumbool.\n\nPrint ex.\n\nRequire Import ZArith.\nRequire Import Compare_dec.\n\nCheck le_lt_dec.\n\nDefinition max (n p :nat) := match le_lt_dec n p with\n                             | left _ => p\n                             | right _ => n\n                             end.\n\nTheorem le_max : forall n p, n <= p -> max n p = p.\nProof.\n intros n p ; unfold max ; case (le_lt_dec n p); simpl.\n trivial.\n intros; absurd (p < p); eauto with arith.\nQed.\n\nRequire Coq.extraction.Extraction.\nExtraction max.\n\n\n\n\n\n\nInductive tree(A:Set)   : Set :=\n    node : A -> forest A -> tree A\nwith\n  forest (A: Set)    : Set :=\n    nochild  : forest A |\n    addchild : tree A -> forest A -> forest A.\n\n\n\n\n\nInductive\n  even    : nat->Prop :=\n    evenO : even  O |\n    evenS : forall n, odd n -> even (S n)\nwith\n  odd    : nat->Prop :=\n    oddS : forall n, even n -> odd (S n).\n\nLemma odd_49 : odd (7 * 7).\n simpl; repeat constructor.\nQed.\n\n\n\nDefinition nat_case :=\n fun (Q : Type)(g0 : Q)(g1 : nat -> Q)(n:nat) =>\n    match n return Q with\n    | 0 => g0\n    | S p => g1 p\n    end.\n\nEval simpl in (nat_case nat 0 (fun p => p) 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 34).\n\nEval simpl in (fun g0 g1 => nat_case nat g0 g1 0).\n\n\nDefinition pred (n:nat) := match n with O => O | S m => m end.\n\nEval simpl in pred 56.\n\nEval simpl in pred 0.\n\nEval simpl in fun p => pred (S p).\n\n\nDefinition xorb (b1 b2:bool) :=\nmatch b1, b2 with\n | false, true => true\n | true, false => true\n | _ , _       => false\nend.\n\n\n Definition pred_spec (n:nat) := {m:nat | n=0 /\\ m=0  \\/ n = S m}.\n\n\n Definition predecessor : forall n:nat, pred_spec n.\n  intro n;case n.\n  unfold pred_spec;exists 0;auto.\n  unfold pred_spec; intro n0;exists n0; auto.\n Defined.\n\nPrint predecessor.\n\nExtraction predecessor.\n\nTheorem nat_expand :\n  forall n:nat, n = match n with 0 => 0 | S p => S p end.\n intro n;case n;simpl;auto.\nQed.\n\nCheck (fun p:False => match p return 2=3 with end).\n\nTheorem fromFalse : False -> 0=1.\n intro absurd.\n contradiction.\nQed.\n\nSection equality_elimination.\n Variables (A: Type)\n           (a b : A)\n           (p : a = b)\n           (Q : A -> Type).\n Check (fun H : Q a =>\n  match p in (eq _  y) return Q y with\n     refl_equal => H\n  end).\n\nEnd equality_elimination.\n\n\nTheorem trans : forall n m p:nat, n=m -> m=p -> n=p.\nProof.\n intros n m p eqnm.\n case eqnm.\n trivial.\nQed.\n\nLemma Rw :  forall x y: nat, y = y * x -> y * x * x = y.\n intros x y e; do 2 rewrite <- e.\n reflexivity.\nQed.\n\n\nRequire Import Arith.\n\nCheck mult_1_l.\n(*\nmult_1_l\n     : forall n : nat, 1 * n = n\n*)\n\nCheck mult_plus_distr_r.\n(*\nmult_plus_distr_r\n     : forall n m p : nat, (n + m) * p = n * p + m * p\n\n*)\n\nLemma mult_distr_S : forall n p : nat, n * p + p = (S n)* p.\n simpl;auto with arith.\nQed.\n\nLemma four_n : forall n:nat, n+n+n+n = 4*n.\n intro n;rewrite <- (mult_1_l n).\n\n Undo.\n intro n; pattern n at 1.\n\n\n rewrite <- mult_1_l.\n repeat rewrite   mult_distr_S.\n trivial.\nQed.\n\n\nSection Le_case_analysis.\n Variables (n p : nat)\n           (H : n <= p)\n           (Q : nat -> Prop)\n           (H0 : Q n)\n           (HS : forall m, n <= m -> Q (S m)).\n Check (\n    match H in (_ <= q) return (Q q)  with\n    | le_n _ => H0\n    | le_S _ m Hm => HS m Hm\n    end\n  ).\n\n\nEnd Le_case_analysis.\n\n\nLemma predecessor_of_positive : forall n, 1 <= n ->  exists p:nat, n = S p.\nProof.\n intros n  H; case H.\n exists 0; trivial.\n intros m Hm; exists m;trivial.\nQed.\n\nDefinition Vtail_total\n   (A : Set) (n : nat) (v : Vector.t A n) : Vector.t A (pred n):=\nmatch v in (Vector.t _ n0) return (Vector.t A (pred n0)) with\n| Vector.nil _ => Vector.nil A\n| Vector.cons _ _ n0 v0 => v0\nend.\n\nDefinition Vtail' (A:Set)(n:nat)(v:Vector.t A n) : Vector.t A (pred n).\n case v.\n simpl.\n exact (Vector.nil A).\n simpl.\n auto.\nDefined.\n\n(*\nInductive Lambda : Set :=\n  lambda : (Lambda -> False) -> Lambda.\n\n\nError: Non strictly positive occurrence of \"Lambda\" in\n \"(Lambda -> False) -> Lambda\"\n\n*)\n\nSection Paradox.\n Variable Lambda : Set.\n Variable lambda : (Lambda -> False) ->Lambda.\n\n Variable matchL  : Lambda -> forall Q:Prop, ((Lambda ->False) -> Q) -> Q.\n (*\n  understand matchL Q l (fun h : Lambda -> False => t)\n\n  as match l return Q with lambda h => t end\n *)\n\n Definition application (f x: Lambda) :False :=\n   matchL f False (fun h => h x).\n\n Definition Delta : Lambda := lambda (fun x : Lambda => application x x).\n\n Definition loop : False := application Delta Delta.\n\n Theorem two_is_three : 2 = 3.\n Proof.\n  elim loop.\n Qed.\n\nEnd Paradox.\n\n\nRequire Import ZArith.\n\n\n\nInductive itree : Set :=\n| ileaf : itree\n| inode : Z-> (nat -> itree) -> itree.\n\nDefinition isingle l := inode l (fun i => ileaf).\n\nDefinition t1 := inode 0 (fun n => isingle (Z.of_nat (2*n))).\n\nDefinition t2 := inode 0\n                      (fun n : nat =>\n                               inode (Z.of_nat n)\n                                     (fun p => isingle (Z.of_nat (n*p)))).\n\n\nInductive itree_le : itree-> itree -> Prop :=\n  | le_leaf : forall t, itree_le  ileaf t\n  | le_node  : forall l l' s s',\n                       Z.le l l' ->\n                      (forall i, exists j:nat, itree_le (s i) (s' j)) ->\n                      itree_le  (inode  l s) (inode  l' s').\n\n\nTheorem itree_le_trans :\n  forall t t', itree_le t t' ->\n               forall t'', itree_le t' t'' -> itree_le t t''.\n induction t.\n constructor 1.\n\n intros t'; case t'.\n inversion 1.\n intros z0 i0 H0.\n intro t'';case t''.\n inversion 1.\n intros.\n inversion_clear H1.\n constructor 2.\n inversion_clear H0;eauto with zarith.\n inversion_clear H0.\n intro i2; case (H4 i2).\n intros.\n generalize (H i2 _ H0).\n intros.\n case (H3 x);intros.\n generalize (H5 _ H6).\n exists x0;auto.\nQed.\n\n\n\nInductive itree_le' : itree-> itree -> Prop :=\n  | le_leaf' : forall t, itree_le'  ileaf t\n  | le_node' : forall l l' s s' g,\n                       Z.le l l' ->\n                      (forall i, itree_le' (s i) (s' (g i))) ->\n                       itree_le'  (inode  l s) (inode  l' s').\n\n\n\n\n\nLemma t1_le_t2 : itree_le t1 t2.\n unfold t1, t2.\n constructor.\n auto with zarith.\n intro i; exists (2 * i).\n unfold isingle.\n constructor.\n auto with zarith.\n exists i;constructor.\nQed.\n\n\n\nLemma t1_le'_t2 :  itree_le' t1 t2.\n unfold t1, t2.\n constructor 2  with (fun i : nat => 2 * i).\n auto with zarith.\n unfold isingle;\n intro i ; constructor 2 with (fun i :nat => i).\n auto with zarith.\n constructor .\nQed.\n\n\nRequire Import List.\n\nInductive ltree  (A:Set) : Set :=\n          lnode   : A -> list (ltree A) -> ltree A.\n\nInductive prop : Prop :=\n prop_intro : Prop -> prop.\n\nLemma prop_inject: prop.\nProof prop_intro prop.\n\n\nInductive ex_Prop  (P : Prop -> Prop) : Prop :=\n  exP_intro : forall X : Prop, P X -> ex_Prop P.\n\nLemma ex_Prop_inhabitant : ex_Prop (fun P => P -> P).\nProof.\n  exists (ex_Prop (fun P => P -> P)).\n trivial.\nQed.\n\n\n\n\n\nFail Check (fun (P:Prop->Prop)(p: ex_Prop P) =>\n      match p with exP_intro X HX => X end).\n(*\nError:\nIncorrect elimination of \"p\" in the inductive type\n\"ex_Prop\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n*)\n\n\nFail Check (match prop_inject with (prop_intro p) => p end).\n(*\nError:\nIncorrect elimination of \"prop_inject\" in the inductive type\n\"prop\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n*)\nPrint prop_inject.\n\n(*\nprop_inject =\nprop_inject = prop_intro prop\n     : prop\n*)\n\n\nInductive  typ : Type :=\n  typ_intro : Type -> typ.\n\nDefinition typ_inject: typ.\nsplit.\nFail exact typ.\n(*\nError: Universe Inconsistency.\n*)\nAbort.\n\nFail Inductive aSet : Set :=\n  aSet_intro: Set -> aSet.\n(*\nUser error: Large non-propositional inductive types must be in Type\n*)\n\nInductive ex_Set  (P : Set -> Prop) : Type :=\n  exS_intro : forall X : Set, P X -> ex_Set P.\n\n\nModule Type Version1.\n\nInductive comes_from_the_left (P Q:Prop): P \\/ Q -> Prop :=\n  c1 : forall p, comes_from_the_left P Q (or_introl (A:=P) Q p).\n\nGoal (comes_from_the_left _ _ (or_introl True I)).\nsplit.\nQed.\n\nGoal ~(comes_from_the_left _ _ (or_intror True I)).\n red;inversion 1.\n (* discriminate H0.\n *)\nAbort.\n\nEnd Version1.\n\nFail Definition comes_from_the_left (P Q:Prop)(H:P \\/ Q): Prop :=\n  match H with\n         |  or_introl p => True\n         |  or_intror q => False\n  end.\n\n(*\nError:\nIncorrect elimination of \"H\" in the inductive type\n\"or\", the return type has sort \"Type\" while it should be\n\"Prop\"\n\nElimination of an inductive object of sort \"Prop\"\nis not allowed on a predicate in sort \"Type\"\nbecause proofs can be eliminated only to build proofs\n*)\n\nDefinition comes_from_the_left_sumbool\n            (P Q:Prop)(x:{P}+{Q}): Prop :=\n  match x with\n         |  left  p => True\n         |  right q => False\n  end.\n\n\n\n\nClose Scope Z_scope.\n\n\n\n\n\nTheorem S_is_not_O : forall n, S n <> 0.\n\nSet Nested Proofs Allowed.\n\nDefinition Is_zero (x:nat):= match x with\n                                     | 0 => True\n                                     | _ => False\n                             end.\n Lemma O_is_zero : forall m, m = 0 -> Is_zero m.\n Proof.\n  intros m H; subst m.\n  (*\n  ============================\n   Is_zero 0\n  *)\n  simpl;trivial.\n Qed.\n\n red; intros n Hn.\n apply O_is_zero with (m := S n).\n assumption.\nQed.\n\nTheorem disc2 : forall n, S (S n) <> 1.\nProof.\n intros n Hn; discriminate.\nQed.\n\n\nTheorem disc3 : forall n, S (S n) = 0 -> forall Q:Prop, Q.\nProof.\n  intros n Hn Q.\n  discriminate.\nQed.\n\n\n\nTheorem inj_succ  : forall n m, S n = S m -> n = m.\nProof.\n\n\nLemma inj_pred : forall n m, n = m -> pred n = pred m.\nProof.\n intros n m eq_n_m.\n rewrite eq_n_m.\n trivial.\nQed.\n\n intros n m eq_Sn_Sm.\n apply inj_pred with (n:= S n) (m := S m); assumption.\nQed.\n\nLemma list_inject : forall (A:Set)(a b :A)(l l':list A),\n                     a :: b :: l = b :: a :: l' -> a = b /\\ l = l'.\nProof.\n intros A a b l l' e.\n injection e.\n auto.\nQed.\n\n\nTheorem not_le_Sn_0 : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H.\n case H.\nUndo.\n\nLemma not_le_Sn_0_with_constraints :\n  forall n p , S n <= p ->  p = 0 -> False.\nProof.\n intros n p H; case H ;\n   intros; discriminate.\nQed.\n\neapply not_le_Sn_0_with_constraints; eauto.\nQed.\n\n\nTheorem not_le_Sn_0' : forall n:nat, ~ (S n <= 0).\nProof.\n red; intros n H ; inversion H.\nQed.\n\nDerive Inversion le_Sn_0_inv with (forall n :nat, S n <=  0).\nCheck le_Sn_0_inv.\n\nTheorem le_Sn_0'' : forall n p : nat, ~ S n <= 0 .\nProof.\n intros n p H;\n inversion H using le_Sn_0_inv.\nQed.\n\nDerive Inversion_clear le_Sn_0_inv' with (forall n :nat, S n <=  0).\nCheck le_Sn_0_inv'.\n\n\nTheorem le_reverse_rules :\n forall n m:nat, n <= m ->\n                   n = m \\/\n                   exists p, n <=  p /\\ m = S p.\nProof.\n  intros n m H; inversion H.\n  left;trivial.\n  right; exists m0; split; trivial.\nRestart.\n  intros n m H; inversion_clear H.\n  left;trivial.\n  right; exists m0; split; trivial.\nQed.\n\nInductive ArithExp : Set :=\n     Zero : ArithExp\n   | Succ : ArithExp -> ArithExp\n   | Plus : ArithExp -> ArithExp -> ArithExp.\n\nInductive RewriteRel : ArithExp -> ArithExp -> Prop :=\n     RewSucc  : forall e1 e2 :ArithExp,\n                  RewriteRel e1 e2 -> RewriteRel (Succ e1) (Succ e2)\n  |  RewPlus0 : forall e:ArithExp,\n                  RewriteRel (Plus Zero e) e\n  |  RewPlusS : forall e1 e2:ArithExp,\n                  RewriteRel e1 e2 ->\n                  RewriteRel (Plus (Succ e1) e2) (Succ (Plus e1 e2)).\n\n\n\nFixpoint plus (n p:nat) {struct n} : nat :=\n  match n with\n          | 0 => p\n          | S m => S (plus m p)\n end.\n\nFixpoint plus' (n p:nat) {struct p} : nat :=\n    match p with\n          | 0 => n\n          | S q => S (plus' n q)\n    end.\n\nFixpoint plus'' (n p:nat) {struct n} : nat :=\n  match n with\n          | 0 => p\n          | S m => plus'' m (S p)\n end.\n\nModule Type even_test_v1.\n\nFixpoint even_test (n:nat) : bool :=\n  match n\n  with 0 =>  true\n     | 1 =>  false\n     | S (S p) => even_test p\n  end.\n\nEnd even_test_v1.\n\nModule even_test_v2.\n\nFixpoint even_test (n:nat) : bool :=\n  match n\n  with\n      | 0 =>  true\n      | S p => odd_test p\n  end\nwith odd_test (n:nat) : bool :=\n  match n\n  with\n     | 0 => false\n     | S p => even_test p\n end.\n\nEval simpl in even_test.\n\nEval simpl in (fun x : nat => even_test x).\n\nEval simpl in (fun x : nat => plus 5 x).\nEval simpl in (fun x : nat => even_test (plus 5 x)).\n\nEval simpl in (fun x : nat => even_test (plus x 5)).\n\nEnd even_test_v2.\n\n\nSection Principle_of_Induction.\nVariable    P               : nat -> Prop.\nHypothesis  base_case       : P 0.\nHypothesis  inductive_step   : forall n:nat, P n -> P (S n).\nFixpoint nat_ind  (n:nat)    : (P n) :=\n   match n return P n with\n          | 0 => base_case\n          | S m => inductive_step m (nat_ind m)\n   end.\n\nEnd Principle_of_Induction.\n\nScheme Even_induction := Minimality for even Sort Prop\nwith   Odd_induction  := Minimality for odd  Sort Prop.\n\nTheorem even_plus_four : forall n:nat, even n -> even (4+n).\nProof.\n intros n H.\n elim H using Even_induction with (P0 := fun n => odd (4+n));\n simpl;repeat constructor;assumption.\nQed.\n\n\nSection Principle_of_Double_Induction.\nVariable    P               : nat -> nat ->Prop.\nHypothesis  base_case1      : forall x:nat, P 0 x.\nHypothesis  base_case2      : forall x:nat, P (S x) 0.\nHypothesis  inductive_step   : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_ind (n m:nat){struct n} : P n m :=\n  match n, m return P n m with\n         |  0 ,     x    =>  base_case1 x\n         |  (S x),    0  =>  base_case2 x\n         |  (S x), (S y) =>  inductive_step x y (nat_double_ind x y)\n     end.\nEnd Principle_of_Double_Induction.\n\nSection Principle_of_Double_Recursion.\nVariable    P               : nat -> nat -> Set.\nHypothesis  base_case1      : forall x:nat, P 0 x.\nHypothesis  base_case2      : forall x:nat, P (S x) 0.\nHypothesis  inductive_step   : forall n m:nat, P n m -> P (S n) (S m).\nFixpoint nat_double_rec (n m:nat){struct n} : P n m :=\n  match n, m return P n m with\n         |   0 ,     x    =>  base_case1 x\n         |  (S x),    0   => base_case2 x\n         |  (S x), (S y)  => inductive_step x y (nat_double_rec x y)\n     end.\nEnd Principle_of_Double_Recursion.\n\nDefinition min : nat -> nat -> nat  :=\n  nat_double_rec (fun (x y:nat) => nat)\n                 (fun (x:nat) => 0)\n                 (fun (y:nat) => 0)\n                 (fun (x y r:nat) => S r).\n\nEval compute in (min 5 8).\nEval compute in (min 8 5).\n\n\n\nLemma not_circular : forall n:nat, n <> S n.\nProof.\n intro n.\n apply nat_ind with (P:= fun n => n <> S n).\n discriminate.\n red; intros n0 Hn0 eqn0Sn0;injection eqn0Sn0;auto.\nQed.\n\nDefinition eq_nat_dec : forall n p:nat , {n=p}+{n <> p}.\nProof.\n intros n p.\n apply nat_double_rec with (P:= fun (n q:nat) => {q=p}+{q <> p}).\nUndo.\n pattern p,n.\n elim n using nat_double_rec.\n destruct x; auto.\n destruct x; auto.\n intros n0 m H; case H.\n intro eq; rewrite eq ; auto.\n intro neg; right; red ; injection 1; auto.\nDefined.\n\nDefinition eq_nat_dec' : forall n p:nat, {n=p}+{n <> p}.\n decide equality.\nDefined.\n\nPrint Acc.\n\n\nRequire Import Minus.\n\nFail Fixpoint div (x y:nat){struct x}: nat :=\n if eq_nat_dec x 0\n  then 0\n  else if eq_nat_dec y 0\n       then x\n       else S (div (x-y) y).\n(*\nError:\nRecursive definition of div is ill-formed.\nIn environment\ndiv : nat -> nat -> nat\nx : nat\ny : nat\n_ : x <> 0\n_ : y <> 0\n\nRecursive call to div has principal argument equal to\n\"x - y\"\ninstead of a subterm of x\n\n*)\n\nLemma minus_smaller_S: forall x y:nat, x - y < S x.\nProof.\n intros x y; pattern y, x;\n elim x using nat_double_ind.\n destruct x0; auto with arith.\n simpl; auto with arith.\n simpl; auto with arith.\nQed.\n\nLemma minus_smaller_positive : forall x y:nat, x <>0 -> y <> 0 ->\n                                     x - y < x.\nProof.\n destruct x; destruct y;\n ( simpl;intros; apply minus_smaller_S ||\n   intros; absurd (0=0); auto).\nQed.\n\nDefinition minus_decrease : forall x y:nat, Acc lt x ->\n                                         x <> 0 ->\n                                         y <> 0 ->\n                                         Acc lt (x-y).\nProof.\n intros x y H; case H.\n intros Hz posz posy.\n apply Hz; apply minus_smaller_positive; assumption.\nDefined.\n\nPrint minus_decrease.\n\n\n\nFixpoint div_aux (x y:nat)(H: Acc lt x):nat.\n  refine (if eq_nat_dec x 0\n         then 0\n         else if eq_nat_dec y 0\n              then y\n              else div_aux (x-y) y _).\n apply (minus_decrease x y H);assumption.\nDefined.\n\n\nPrint div_aux.\n(*\ndiv_aux =\n(fix div_aux (x y : nat) (H : Acc lt x) {struct H} : nat :=\n   match eq_nat_dec x 0 with\n   | left _ => 0\n   | right _ =>\n       match eq_nat_dec y 0 with\n       | left _ => y\n       | right _0 => div_aux (x - y) y (minus_decrease x y H _ _0)\n       end\n   end)\n     : forall x : nat, nat -> Acc lt x -> nat\n*)\n\nRequire Import Wf_nat.\nDefinition div x y := div_aux x y (lt_wf x).\n\nExtraction div.\n(*\nlet div x y =\n  div_aux x y\n*)\n\nExtraction div_aux.\n\n(*\nlet rec div_aux x y =\n  match eq_nat_dec x O with\n    | Left -> O\n    | Right ->\n        (match eq_nat_dec y O with\n           | Left -> y\n           | Right -> div_aux (minus x y) y)\n*)\n\nLemma vector0_is_vnil : forall (A:Set)(v:Vector.t A 0), v = Vector.nil A.\nProof.\n intros A v;inversion v.\nAbort.\n\n\nFail Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:Vector.t A n),\n                                  n= 0 -> v = Vector.nil A.\n(*\nError: In environment\nA : Set\nn : nat\nv : Vector.t A n\nThe term \"[]\" has type \"Vector.t A 0\" while it is expected to have type\n \"Vector.t A n\"\n*)\n Require Import JMeq.\n\nLemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:Vector.t A n),\n                                  n= 0 -> JMeq v (Vector.nil A).\nProof.\n destruct v.\n auto.\n intro; discriminate.\nQed.\n\nLemma vector0_is_vnil : forall (A:Set)(v:Vector.t A 0), v = Vector.nil A.\nProof.\n intros a v;apply JMeq_eq.\n apply vector0_is_vnil_aux.\n trivial.\nQed.\n\n\nArguments Vector.cons [A] _ [n].\nArguments Vector.nil [A].\nArguments Vector.hd [A n].\nArguments Vector.tl [A n].\n\nDefinition Vid : forall (A : Type)(n:nat), Vector.t A n -> Vector.t A n.\nProof.\n destruct n; intro v.\n exact Vector.nil.\n exact (Vector.cons  (Vector.hd v) (Vector.tl v)).\nDefined.\n\nEval simpl in (fun (A:Set)(v:Vector.t A 0) => (Vid _ _ v)).\n\nEval simpl in (fun (A:Set)(v:Vector.t A 0) => v).\n\n\n\nLemma Vid_eq : forall (n:nat) (A:Type)(v:Vector.t A n), v=(Vid _ n v).\nProof.\n destruct v.\n reflexivity.\n reflexivity.\nDefined.\n\nTheorem zero_nil : forall A (v:Vector.t A 0), v = Vector.nil.\nProof.\n intros.\n change (Vector.nil (A:=A)) with (Vid _ 0 v).\n apply Vid_eq.\nDefined.\n\n\nTheorem decomp :\n  forall (A : Set) (n : nat) (v : Vector.t A (S n)),\n  v = Vector.cons (Vector.hd v) (Vector.tl v).\nProof.\n intros.\n change (Vector.cons (Vector.hd v) (Vector.tl v)) with (Vid _  (S n) v).\n apply Vid_eq.\nDefined.\n\n\n\nDefinition vector_double_rect :\n    forall (A:Set) (P: forall (n:nat),(Vector.t A n)->(Vector.t A n) -> Type),\n        P 0 Vector.nil Vector.nil ->\n        (forall n (v1 v2 : Vector.t A n) a b, P n v1 v2 ->\n             P (S n) (Vector.cons a v1) (Vector.cons  b v2)) ->\n        forall n (v1 v2 : Vector.t A n), P n v1 v2.\n induction n.\n intros; rewrite (zero_nil _ v1); rewrite (zero_nil _ v2).\n auto.\n intros v1 v2; rewrite (decomp _ _ v1);rewrite (decomp _ _ v2).\n apply X0; auto.\nDefined.\n\nRequire Import Bool.\n\nDefinition bitwise_or n v1 v2 : Vector.t bool n :=\n   vector_double_rect bool  (fun n v1 v2 => Vector.t bool n)\n                        Vector.nil\n                        (fun n v1 v2 a b r => Vector.cons (orb a b) r) n v1 v2.\n\n\nFixpoint vector_nth (A:Set)(n:nat)(p:nat)(v:Vector.t A p){struct v}\n                  : option A :=\n  match n,v  with\n    _   , Vector.nil => None\n  | 0   , Vector.cons b _ => Some b\n  | S n', Vector.cons _ v' => vector_nth A n' _ v'\n  end.\n\nArguments vector_nth [A] _ [p].\n\n\nLemma nth_bitwise : forall (n:nat) (v1 v2: Vector.t bool n) i  a b,\n      vector_nth i v1 = Some a ->\n      vector_nth i v2 = Some b ->\n      vector_nth i (bitwise_or _ v1 v2) = Some (orb a b).\nProof.\n intros  n v1 v2; pattern n,v1,v2.\n apply vector_double_rect.\n simpl.\n destruct i; discriminate 1.\n destruct i; simpl;auto. \n injection 1 as ->; injection 1 as ->; auto.\nQed.\n\n Set Implicit Arguments.\n\n CoInductive Stream (A:Set) : Set   :=\n |  Cons : A -> Stream A -> Stream A.\n\n CoInductive LList (A: Set) : Set :=\n |  LNil : LList A\n |  LCons : A -> LList A -> LList A.\n\n\n\n\n\n Definition head (A:Set)(s : Stream A) := match s with Cons a s' => a end.\n\n Definition tail (A : Set)(s : Stream A) :=\n      match s with Cons a s' => s' end.\n\n CoFixpoint repeat (A:Set)(a:A) : Stream A := Cons a (repeat a).\n\n CoFixpoint iterate (A: Set)(f: A -> A)(a : A) : Stream A:=\n    Cons a (iterate f (f a)).\n\n CoFixpoint map (A B:Set)(f: A -> B)(s : Stream A) : Stream B:=\n  match s with Cons a tl => Cons (f a) (map f tl) end.\n\nEval simpl in (fun (A:Set)(a:A) => repeat a).\n\nEval simpl in (fun (A:Set)(a:A) => head (repeat a)).\n\n\nCoInductive EqSt (A: Set) : Stream A -> Stream A -> Prop :=\n  eqst : forall s1 s2: Stream A,\n      head s1 = head s2 ->\n      EqSt (tail s1) (tail s2) ->\n      EqSt s1 s2.\n\n\nSection Parks_Principle.\nVariable A : Set.\nVariable    R      : Stream A -> Stream A -> Prop.\nHypothesis  bisim1 : forall s1 s2:Stream A, R s1 s2 ->\n                                          head s1 = head s2.\nHypothesis  bisim2 : forall s1 s2:Stream A, R s1 s2 ->\n                                          R (tail s1) (tail s2).\n\nCoFixpoint park_ppl     : forall s1 s2:Stream A, R s1 s2 ->\n                                               EqSt s1 s2 :=\n fun s1 s2 (p : R s1 s2) =>\n      eqst s1 s2 (bisim1  p)\n                 (park_ppl  (bisim2  p)).\nEnd Parks_Principle.\n\n\nTheorem map_iterate : forall (A:Set)(f:A->A)(x:A),\n                       EqSt (iterate f (f x)) (map f (iterate f x)).\nProof.\n intros A f x.\n apply park_ppl with\n   (R:=  fun s1 s2 => exists x: A,\n                      s1 = iterate f (f x) /\\ s2 = map f (iterate f x)).\n\n intros s1 s2 (x0,(eqs1,eqs2));rewrite eqs1;rewrite eqs2;reflexivity.\n intros s1 s2 (x0,(eqs1,eqs2)).\n exists (f x0);split;[rewrite eqs1|rewrite eqs2]; reflexivity.\n exists x;split; reflexivity.\nQed.\n\nLtac infiniteproof f :=\n  cofix f; constructor; [clear f| simpl; try (apply f; clear f)].\n\n\nTheorem map_iterate' : forall (A:Set)(f:A->A)(x:A),\n                       EqSt (iterate f (f x)) (map f (iterate f x)).\ninfiniteproof map_iterate'.\n reflexivity.\nQed.\n\n\nArguments LNil [A].\n\nLemma Lnil_not_Lcons : forall (A:Set)(a:A)(l:LList A),\n                               LNil <> (LCons a l).\n intros;discriminate.\nQed.\n\nLemma injection_demo : forall (A:Set)(a b : A)(l l': LList A),\n                       LCons a (LCons b l) = LCons b (LCons a l') ->\n                       a = b /\\ l = l'.\nProof.\n intros A a b l l' e; injection e; auto.\nQed.\n\n\nInductive Finite (A:Set) : LList A -> Prop :=\n|  Lnil_fin : Finite (LNil (A:=A))\n|  Lcons_fin : forall a l, Finite l -> Finite (LCons a l).\n\nCoInductive Infinite  (A:Set) : LList A -> Prop :=\n| LCons_inf : forall a l, Infinite l -> Infinite (LCons a l).\n\nLemma LNil_not_Infinite : forall (A:Set), ~ Infinite (LNil (A:=A)).\nProof.\n  intros A H;inversion H.\nQed.\n\nLemma Finite_not_Infinite : forall (A:Set)(l:LList A),\n                                Finite l -> ~ Infinite l.\nProof.\n intros A l H; elim H.\n apply LNil_not_Infinite.\n intros a l0 F0 I0' I1.\n case I0'; inversion_clear I1.\n trivial.\nQed.\n\nLemma Not_Finite_Infinite : forall (A:Set)(l:LList A),\n                            ~ Finite l -> Infinite l.\nProof.\n cofix H.\n destruct l.\n intro; absurd (Finite (LNil (A:=A)));[auto|constructor].\n constructor.\n apply H.\n red; intro H1;case H0.\n constructor.\n trivial.\nQed.\n\n\n\n\n", "meta": {"author": "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/RecTutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.894789461192692, "lm_q1q2_score": 0.8186437346390503}}
{"text": "From Coq Require Import List Lia ZArith.\n\nGlobal Open Scope list_scope.\n\n(* Check that a predicate holds elementwise across two lists, while\n   also making sure that the lists have equal length.\n*)\nFixpoint zip_pred {X Y} (pred : X -> Y -> bool) (xs : list X) (ys : list Y) : bool\n  := match xs, ys with\n     | nil, nil => true\n     | x::xs, y::ys => pred x y && zip_pred pred xs ys\n     | _, _ => false\n     end.\n\nLemma list_sum_map :\n  forall {X} (f : X -> nat) x xs,\n    In x xs ->\n    list_sum (map f xs) >= f x.\nProof.\n  induction xs; intros In; [contradiction|].\n  destruct In; subst.\n  - cbn. lia.\n  - cbn. specialize (IHxs H).\n    unfold list_sum in IHxs.\n    lia.\nQed.\n\nLemma map_In {A B : Type} (l : list A) (f : forall (x : A), In x l -> B) : list B.\nProof.\n  induction l.\n  - exact nil.\n  - refine (f a _ :: IHl _).\n    + simpl. auto.\n    + intros x H. apply (f x). simpl. auto.\nDefined.\n\nFixpoint zipwith {X Y Z} (f : X -> Y -> Z) (xs : list X) (ys : list Y) : list Z\n  := match xs, ys with\n     | (x :: xs), (y :: ys) => f x y :: (zipwith f xs ys)\n     | _, _ => nil\n     end.\n\nFixpoint addIndices' {A} (i : N) (l : list A) : list (N * A)\n  := match l with\n     | nil => nil\n     | (x::xs) => (i,x) :: addIndices' (N.succ i) xs\n     end.\n\nDefinition addIndices {A} := @addIndices' A 0.\n", "meta": {"author": "Chobbes", "repo": "cofq", "sha": "11f9467cf15255d6d82225a5c71938ee64a9c98c", "save_path": "github-repos/coq/Chobbes-cofq", "path": "github-repos/coq/Chobbes-cofq/cofq-11f9467cf15255d6d82225a5c71938ee64a9c98c/coq/Utils/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.894789457685656, "lm_q1q2_score": 0.8186437272780546}}
{"text": "Module play1.\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nFixpoint evenb (a: nat) : bool :=\n  match a with\n    | O => true\n    | S O => false\n    | S (S n) => evenb n\n  end.\n\nFixpoint plus (a b :nat) : nat :=\n  match a, b with\n    | O, n => n\n    | (S m) , n => (plus m (S n)) \n  end.\nFixpoint muti (a b :nat) : nat :=\n  match a, b with\n    | O, _ => O\n    | (S n) , m => (plus m (muti n m))\n  end.\nFixpoint factorial (n : nat) : nat :=\n  match n with\n    | O => S O\n    | S x => muti (S x) (factorial x)\n  end.\n\nExample test_factorial1: (factorial (S (S (S O)))) = S (S (S (S (S (S O))))).\nreflexivity. Qed.\n\nFixpoint add (n : nat) : nat :=\n  (S n).\n\nx", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-BeforeCh15", "sha": "fa69bb170f91e5e358747575815f03ad8846646f", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15/SoftwareFoundations-BeforeCh15-fa69bb170f91e5e358747575815f03ad8846646f/08182016-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811631528337, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.818612102753417}}
{"text": "Require Import Arith.\nDefinition f x := x + 100.\nDefinition g x := x - 100.\nCompute f 10.\n\nTheorem g_f : forall x, g (f x) = x.\nProof.\nintros.\nunfold f, g.\nSearchRewrite(_ + _ - _).\nrewrite Nat.add_sub.\nreflexivity.\nQed.\n\nRequire Import List.\nImport ListNotations.\n\nFixpoint reverse {A : Type} (xs : list A) :=\n  match xs with\n  | nil => nil\n  | x :: xs' =>\n    reverse xs' ++ [x]\n  end.\nCompute reverse [1;2;3].\n\nLemma reverse_append : forall (A:Type) (xs ys:list A),\n  reverse (xs ++ ys) = reverse ys ++ reverse xs.\nProof.\n  intros A xs ys.\n  induction xs.\n  - simpl.\n  SearchRewrite(_ ++ []).\n  rewrite app_nil_r.\n  reflexivity.\n  - simpl.\n  rewrite IHxs.\n  SearchRewrite((_ ++ _) ++ _).\n  rewrite app_assoc_reverse.\n  reflexivity.\nQed.\n\nTheorem reverse_reverse : forall (A : Type) (xs: list A),\n  reverse (reverse xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n  -\n  simpl.\n  reflexivity.\n  -\n  simpl.\n  rewrite reverse_append.\n  rewrite IHxs.\n  simpl.\n  reflexivity.\nQed.\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/reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.9032942086563877, "lm_q1q2_score": 0.8183753509754109}}
{"text": "Require Import ZArith.\nRequire Import ZArith.Zmax.\nRequire Import ssr.ssreflect.\n\nOpen Scope Z_scope.\n\nSection BinaryTree.\n\nInductive Tree : Set :=\n| leaf : Tree\n| node : Tree -> Tree -> Tree.           \n\nDefinition max := Z.max.\n\nFixpoint height (t : Tree) : Z := \nmatch t with \n| leaf => 0\n| node t1 t2 => 1 + (max (height t1) (height t2))\nend.\n\nFixpoint numleaves (t : Tree) : Z :=\nmatch t with \n| leaf => 1\n| node t1 t2 => numleaves t1 + numleaves t2\nend.\n\nInductive complete : Tree -> Prop :=\n| complete_leaf : complete leaf\n| complete_node : \n    forall t1 t2, \n      complete t1 -> \n      complete t2 -> \n      height t1 = height t2 ->\n      complete (node t1 t2).\n\nLemma height_nonnegative : forall t, height t >= 0.\nProof.\nelim => //=.\nmove => t1 Ht1 t2 Ht2.\nhave H0: height (node t1 t2) = 1 + max (height t1) (height t2) by auto.\nhave H1: height t1 <= max (height t1) (height t2) by apply Z.le_max_l.\nhave H2: 1 + max (height t1) (height t2) >= 0 by auto with zarith.\nby [].\nQed.\n\nTheorem complete_numleaves_height : forall t, complete t -> numleaves t = 2^(height t).\nProof.\nelim => //=.\nmove => t1 IHt1 t2 IHt2 Hc.\nhave H1: complete t1 by inversion Hc.\nhave H2: complete t2 by inversion Hc.\nhave H3: (height t1 = height t2) by inversion Hc; auto.\napply IHt1 in H1.\napply IHt2 in H2.\nhave H6: (1 >= 0) by intuition.\nhave H7: (height t1 >= 0) by apply height_nonnegative.\nhave H8: (height t1 = max (height t1) (height t1)) by erewrite Zmax_idempotent.\nsimpl numleaves.\nrewrite H1 H2.\nrewrite -H3.\nhave Hh: 2 ^ height t1 + 2 ^ height t1 = (2 * 2^(height t1)) by auto with zarith.\nrewrite Hh.\nhave Hh': (2 * 2^(height t1)) = (2^1 * 2^(height t1)) by auto with zarith.\nrewrite Hh'.\nhave Hh'': 2^(1 + height t1) = (2^1 * 2^(height t1)).\n  by apply (Zpower_exp 2 1 (height t1) H6 H7).\nby rewrite -Hh'' {1}H8.\nQed.\n\nEnd BinaryTree.\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/elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8181764497196652}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_numeric.\nRequire Import kernel_graph.\n\n(** \nLet us define some graphs. \n**)\n\n(* Empty graph on [n] vertices *)\nDefinition Empty (n : nat) : Graph.\nProof.\n  refine {| V := n ;\n            E := (fun x y => False)\n         |} ; auto.\nDefined.\n\n(* Complete graph on [n] vertices *)\nDefinition K (n : nat) : Graph.\nProof.\n  refine {| V := n ;\n            E := (fun x y => x <> y)\n         |}.\n  - intros.\n    destruct (Nat.eq_dec x y) ; tauto.\n  - intros x H L.\n    absurd (x = x) ; tauto.\n  - intros ; now apply not_eq_sym.\nDefined.\n\n(* Path on [n] vertices. *)\nDefinition Path (n : nat) : Graph.\nProof.\n  (* We will do this proof very slowly by hand to practice. *)\n  refine {| V := n ;\n            E := fun x y => S x = y \\/ x = S y\n         |}.\n  - intros.\n    destruct (eq_nat_dec (S x) y).\n    + tauto.\n    + destruct (eq_nat_dec x (S y)).\n      * tauto.\n      * { right.\n          intros [ ? | ? ].\n          - absurd (S x = y) ; assumption.\n          - absurd (x = S y) ; assumption.\n        }\n  - (* This case we do by using a powerful tactic \"firstorder\".\n       We tell it to use the statement [n_Sn] from the [Arith] library.\n       To see what [n_Sn] is, run command [Check n_Sn].\n       To find [n_Sn], we ran the command [Search (?m <> S ?m)]. *)\n    firstorder using n_Sn.\n  - intros ? ? ? ? [?|?].\n    + right ; now symmetry.\n    + left; now symmetry.\nDefined.\n\n\n(* [Cycle n] is the cycle on [n+3] vertices. We define it in a way\n    which avoids modular arithmetic. *)\nDefinition Cycle (n : nat) : Graph.\nProof.\n  refine {| V := 3 + n ; (* Do not forget: we have [3+n] vertices 0, 1, ..., n+2 *)\n            E := fun x y =>\n                 ((S x = y \\/ x = S y) \\/ (x = 0 /\\ y = 2 + n) \\/ (x = 2 + n /\\ y = 0))\n         |}.\n  - intros.\n    destruct (eq_nat_dec (S x) y); auto.\n    destruct (eq_nat_dec x (S y)); auto.\n    destruct (eq_nat_dec x 0); destruct (eq_nat_dec y (2 + n)); auto;\n    destruct (eq_nat_dec y 0); destruct (eq_nat_dec x (2 + n)); tauto.\n  - intros ? ? H.\n    destruct H as [[?|?]|[[? ?]|[? ?]]].\n    + firstorder using Nat.neq_succ_diag_l.\n    + firstorder using Nat.neq_succ_diag_r.\n    + apply (Nat.neq_succ_0 (S n)) ; transitivity x.\n      * now symmetry.\n      * assumption.\n    + apply (Nat.neq_succ_0 (S n)) ; transitivity x.\n      * now symmetry.\n      * assumption.\n  - intros ? ? ? ? [[?|?]|[[? ?]|[? ?]]].\n    + left; right; now symmetry.\n    + left; left; now symmetry.\n    + auto.\n    + auto.\nDefined.\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/graph_examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8991213738910259, "lm_q1q2_score": 0.8181168417752551}}
{"text": "(* \u6709\u9650\u306a\u7b49\u5dee\u7d1a\u6570\uff08\u7b49\u5dee\u6570\u5217\u306e\u548c\uff09\u306e\u300c\u516c\u5f0f\u300d\u3092\u8a3c\u660e\u3059\u308b\u3002 *)\n(*\n   \u4ee5\u4e0b\u306e\u5f0f\u3092\u8a3c\u660e\u3059\u308b\u3002\n   Sum(n) = \u03a3(i=0, n) = 0 + 1 + ... + n = n * (n + 1) / 2\n\n   \u305f\u3060\u3057\u3001(1/2)\u306f\u6271\u3044\u96e3\u3044\u306e\u3067\u30012\u500d\u3057\u3066\u3001\u4ee5\u4e0b\u3092\u8a3c\u660e\u3059\u308b\u3002\n   Sum2(n) = 2 * \u03a3(i=0, n) = 2 * (0 + 1 + ... + n) = n * (n + 1)\n   *)\n\n(*****************************************************************\n   0\u4ee5\u4e0a\u306e\u81ea\u7136\u6570\u3068\u3001\u305d\u306e\u8db3\u3057\u7b97\u3068\u639b\u3051\u7b97\u3092\u5b9a\u7fa9\u3059\u308b\u3002\n   ***************************************************************)\nInductive nat : Type :=\n  | O : nat                                 (* O\u306f0 *)\n  | S : nat -> nat.                         (* S\u306f\u5f8c\u8005\u95a2\u6570 *)\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\nNotation \"x + y\" := (plus x y)  (at level 50, left associativity) : nat_scope.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\nNotation \"x * y\" := (mult x y)  (at level 40, left associativity) : nat_scope.\n(* \u81ea\u7136\u6570\u306e\u5b9a\u7fa9\u3001\u304a\u308f\u308a *)\n\n(*****************************************************************\n   \u7b49\u5dee\u6570\u5217\u306e\u548c\u306e\u5e30\u7d0d\u7684\u5b9a\u7fa9\n   Sum(0) = 0\n   Sum(n + 1) = Sum(n) + (n + 1)\n\n   \u5b9f\u969b\u306f2\u500d\u306e\u307b\u3046\u3092\u4f7f\u3046\u3002\n   Sum2(0) = 0\n   Sum2(n + 1) = Sum2(n) + 2*(n + 1)\n   ***************************************************************)\n(* issum n s \u306f\u30010\u304b\u3089n\u307e\u3067\u306e\uff08\u7b49\u5dee\u6570\u5217\u306e\uff09\u7dcf\u548c\u304cs\u3067\u3042\u308b\u3053\u3068\u3092\u793a\u3059\u3002 *)\nInductive issum : nat -> nat -> Prop :=\n| Sum_0 : issum O O                         (* 0\u307e\u3067\u306e\u7dcf\u548c\u306f0 *)\n| Sum_N : \n  forall (n s : nat), issum n s ->          (* n\u307e\u3067\u306e\u7dcf\u548c\u304cs\u306a\u3089\u3001*)\n    issum (S n) (S n + s).                  (* n+1\u307e\u3067\u306e\u7dcf\u548c\u306f(n+1)+s *)\n\n(* issum2 n s \u306f\u30010\u304b\u3089n\u307e\u3067\u306e\uff08\u7b49\u5dee\u6570\u5217\u306e\uff09\u7dcf\u548c\u306e2\u500d\u304cs\u3067\u3042\u308b\u3053\u3068\u3092\u793a\u3059\u3002 *)\nInductive issum2 : nat -> nat -> Prop :=\n| Sum2_0 : issum2 O O\n| Sum2_N :\n  forall (n s : nat), issum2 n s -> issum2 (S n) (S n + S n + s).\n(* \u7b49\u5dee\u6570\u5217\u306e\u548c\u306e\u5b9a\u7fa9\u3001\u7d42\u308f\u308a *)\n\n(*****************************************************************\n   \u81ea\u7136\u6570\u306e\u8db3\u3057\u7b97\u3068\u639b\u3051\u7b97\u306e\u6cd5\u5247\u306e\u3046\u3061\u5fc5\u8981\u306a\u3082\u306e\u3092\u6ce5\u7e04\u5f0f\u306b\u8a3c\u660e\u3059\u308b\u3002\n   ***************************************************************)\nTheorem plus_n_Sm : forall n m,\n  S (m + n) = m + S n.\nProof.  \n  intros n m.\n  induction m as [| m'].\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHm'.\n  reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  induction n as [| n'].\n  simpl.\n  reflexivity.\n\n  simpl.\n  rewrite <- plus_n_Sm.\n  f_equal.\n  apply IHn'.\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  reflexivity.\n  simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem mult_n_Sm : forall n m,\n  n + n * m = n * S m.\nProof.\n  intros n m.\n  induction n as [| n'].\n  simpl.\n  reflexivity.\n  simpl.\n  f_equal.\n  rewrite <- IHn'.\n  apply plus_swap.\nQed.\n\nTheorem mult_develop : forall n m,\n  S n + m + n * m  = S n * S m.\nProof.\n  intros n m.\n  simpl.\n  f_equal.\n  rewrite <- mult_n_Sm.\n  rewrite <- plus_swap. \n  rewrite plus_assoc.\n  reflexivity.\nQed.\n(* \u81ea\u7136\u6570\u306e\u8db3\u3057\u7b97\u3068\u639b\u3051\u7b97\u306e\u6cd5\u5247\u3001\u7d42\u308f\u308a *)\n\n(*****************************************************************\n   \u7b49\u5dee\u6570\u5217\u306e\u548c\u306e\uff08\u5e30\u7d0d\u7684\u3001\u7e70\u308a\u8fd4\u3057\u7684\uff09\u5b9a\u7fa9\u3068\u3001\u3044\u308f\u3086\u308b\u300c\u516c\u5f0f\u300d\u304c\u4e00\u81f4\u3059\n   \u308b\u3053\u3068\u3092\u8a3c\u660e\u3059\u308b\u3002\n   Sum(n) = n * (n + 1) / 2\n   \n   \u5b9f\u969b\u306f\u30012\u500d\u3057\u3066\u8a3c\u660e\u3059\u308b\u3002\n   Sum2(n) = n * (n + 1)\n   ***************************************************************)\nTheorem sum_of_arith_progress : forall n,\n  issum2 n (n * S n).\nProof.\n  intros n.\n  \n  (* n\u306b\u3064\u3044\u3066\u306e\u5e30\u7d0d\u6cd5\u3092\u304a\u3053\u306a\u3046\u3002*)\n  induction n as [| n'].\n\n  (* n = 0 \u3092\u8a3c\u660e\u3059\u308b\u3002 *)\n  (* issum2 O (O * S O) *)\n  simpl.                              (* \u03b2\u7c21\u7d04\u3059\u308b\u3002 *)\n  apply Sum2_0.                       (* \u5e30\u7d0d\u7684\u5b9a\u7fa9\u306eSum2_0\u3068\u540c\u3058\u3002 *)\n\n  (* n = n' \u304c\u6210\u7acb\u3059\u308b\u3068\u3057\u3066\u3001n = S n' \u3092\u8a3c\u660e\u3059\u308b\u3002 *)\n  (* issum2 n' (n' * S n') \u306a\u3089\u3070\u3001issum2 (S n') (S n' * S (S n')) *)\n  rewrite <- mult_develop.  (* \u8db3\u3057\u7b97\u3068\u639b\u3051\u7b97\u306e\u5909\u5f62\u3092\u3059\u308b\u3002 *)\n  apply Sum2_N.             (* \u5e30\u7d0d\u7684\u5b9a\u7fa9\u306eSum2_N\u3092\u4f7f\u3063\u3066\u5909\u5f62\u3059\u308b\u3002 *)\n  apply IHn'.               (* \u5e30\u7d0d\u6cd5\u306e\u4eee\u5b9a\u3068\u304a\u306a\u3058\u3002 *)\nQed.\n\n(* [] *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_sum_of_arith_prog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8180093788209173}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Arith.Max.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\n\nLemma beq_nat_sym : \n  forall n1 n2, beq_nat n1 n2 = beq_nat n2 n1.\nProof.\n  induction n1; destruct n2; simpl; auto.\nQed.\n\nLemma max_0 : \n  forall n1 n2, max n1 n2 = 0 -> n1 = 0 /\\ n2 = 0.\nProof.\n  intros ; induction n1.\n  auto.\n  simpl in *|-*.\n  destruct n2.\n  inversion H.\n  inversion H.\nQed.\n\nLemma plus_minus:\n  forall (m n p:nat), n <= p -> m+p-n = m+(p-n).\nProof.\n  induction m ; intros.\n  omega.\n  omega.\nQed.\n\nLemma plus_minus_n:\n  forall (m n:nat), m+n-n = m.\nProof.\n  induction m ; intros.\n  omega.\n  omega.\nQed.\n\nModule List2.\n\n  Definition hd_cons {T:Type} (l:list T) (e:T) : T * list T :=\n    match l with\n    | nil => (e, nil)\n    | e :: l => (e, l)\n    end.\n\n  Fixpoint map_iter {T T':Type} (f:T -> nat -> T') (l:list T) (n:nat) :=\n    match l with\n    | nil => nil\n    | cons e l => (f e n) :: map_iter f l (S n)\n    end.\n\nEnd List2.\n\nModule List2Properties.\n\n  Import List2.\n\n  Lemma length_map_iter:\n    forall {T T':Type} (f:T -> nat -> T') (l:list T) (n:nat),\n    length (map_iter f l n) = length l.\n  Proof.\n    induction l ; simpl ; intros ; auto.\n  Qed. \n\n  Lemma map_iter_app:\n    forall {T T':Type} (f:T -> nat -> T') (l1 l2:list T) (n:nat),\n    map_iter f (l1++l2) n = (map_iter f l1 n)++(map_iter f l2 (n+(length l1))).\n  Proof.\n    induction l1 ; simpl ; intros ; auto.\n    rewrite IHl1.\n    rewrite plus_Snm_nSm.\n    reflexivity.\n  Qed. \n\n  Lemma map_iter_nth:\n    forall {T T':Type} (f:T -> nat -> T') (l:list T) (m n:nat) (e:T),\n    nth m (map_iter f l n) (f e (m+n)%nat) = f (nth m l e) (m+n)%nat.\n  Proof.\n    induction l ; simpl ; intros.\n    destruct n ; destruct m ; reflexivity.\n    destruct m.\n    reflexivity.\n    simpl.\n    specialize (IHl m (S n)).\n    rewrite <- plus_Snm_nSm in IHl.\n    rewrite IHl.\n    reflexivity.\n  Qed.\n\n  Lemma map_iter_nth_indep:\n    forall {T T':Type} (f:T -> nat -> T') (l:list T) (m n:nat) (e1:T) (e2:T'),\n    m < length l ->\n    nth m (map_iter f l n) e2 = f (nth m l e1) (m+n)%nat.\n  Proof.\n    intros.\n    rewrite nth_indep with (d':=f e1 (m+n)%nat).\n    apply map_iter_nth.\n    rewrite length_map_iter.\n    assumption.\n  Qed.\n\nEnd List2Properties.", "meta": {"author": "GitoriousLispBackup", "repo": "monadic-translation", "sha": "662661b323f61250ba91c364fdd0b76dd663e57c", "save_path": "github-repos/coq/GitoriousLispBackup-monadic-translation", "path": "github-repos/coq/GitoriousLispBackup-monadic-translation/monadic-translation-662661b323f61250ba91c364fdd0b76dd663e57c/Misc/Library.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.897695295528596, "lm_q1q2_score": 0.8179617347283494}}
{"text": "(* A sorting example : \n   (C) Yves Bertot, Pierre Cast\u00e9ran \n*)\n\nRequire Import List.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nFixpoint insert (z:Z) (l:list Z) {struct l} : list Z :=\n  match l with\n  | nil => z :: nil\n  | cons a l' => if Z.leb z a\n      then z :: a :: l'\n      else a :: insert z l'\n end.\n\n   \n\nCompute  insert 4 (2 :: 5 :: nil).\n\nCompute insert 4 (24 :: 50 ::nil).\n\nFixpoint insertion_sort (l:list Z) : list Z :=\nmatch l with\n| nil => nil\n| z::l' => insert z (insertion_sort l')\nend.\n\nCompute insertion_sort (4::9::7::9::12::3::nil).\n\n\n\n\nInductive sorted : list Z -> Prop :=\n  | sorted0 : sorted nil\n  | sorted1 : forall z:Z, sorted (z :: nil)\n  | sorted2 :\n      forall (z1 z2:Z) (l:list Z),\n        z1 <= z2 ->\n        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\nHint Resolve sorted0 sorted1 sorted2 : sort.\n\nLemma sort_2357 :\n sorted (2 :: 3 :: 5 :: 7 :: nil).\nProof.\n auto with sort zarith.\nQed.\n\n\nTheorem sorted_inv :\n forall (z:Z) (l:list Z), sorted (z :: l) -> sorted l.\nProof.\n intros z l H.\n inversion H; auto with sort.\nQed.\n\n(*  Number of occurrences of z in l *)\n\nCheck Z.eqb.\n\nFixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat\n  | (z' :: l') =>\n      if Z.eqb z z' \n      then S (nb_occ z l')\n      else nb_occ z l'\n   end.\n\nEval compute in (nb_occ 3 (3 :: 7 :: 3 :: nil)).\n\nEval compute in (nb_occ 36725 (3 :: 7 :: 3 :: nil)).\n\n\n(* list l' is a permutation of list l *)\n\nDefinition equiv (l l':list Z) := \n    forall z:Z, nb_occ z l = nb_occ z l'.\n\n(* equiv is an equivalence ! *)\n\nLemma equiv_refl : forall l:list Z, equiv l l.\nProof.\n unfold equiv; trivial.\nQed.\n\nLemma equiv_sym : forall l l':list Z, equiv l l' -> equiv l' l.\nProof.\n  unfold equiv; auto.\nQed.\n\nLemma equiv_trans :\n forall l l' l'':list Z, equiv l l' -> \n                         equiv l' l'' -> \n                         equiv l l''.\nProof.\n intros l l' l'' H H0 z.\n eapply trans_eq; eauto.\nQed.\n\nLemma equiv_cons :\n forall (z:Z) (l l':list Z), equiv l l' -> \n                             equiv (z :: l) (z :: l').\nProof.\n intros z l l' H z'.\n simpl; case_eq  (Z.eqb z' z); auto. \nQed.\n\n\nLemma equiv_perm :\n forall (a b:Z) (l l':list Z),\n   equiv l l' -> \n   equiv (a :: b :: l) (b :: a :: l').\nProof.\n intros a b l l' H z; simpl.\n case_eq (Z.eqb z a); case_eq (Z.eqb z b); \n  simpl; case (H z); auto.\nQed.\n\nHint Resolve equiv_cons equiv_refl equiv_perm : sort.\n\n\n(* insertion of z into l at the right place \n   (assuming l is sorted) \n*)\n\n\n(** Correlation between Z.leb and Z.le *)\n\nSearchAbout (Z.leb _ _ = true).\n(*\nZle_bool_imp_le: forall n m : Z, (n <=? m) = true -> n <= m\nZle_imp_le_bool: forall n m : Z, n <= m -> (n <=? m) = true\n...\nZ.leb_le: forall n m : Z, (n <=? m) = true <-> n <= m\n*)\nSearchAbout (Z.leb _ _ = false).\n \n\nLtac le_from_bool := repeat (rewrite Z.leb_le in * || rewrite Z.leb_gt in *).\n(** Z.leb_gt: forall x y : Z, (x <=? y) = false <-> y < x *)\n\n\n(* the insert function seems to be a good tool for sorting ... *)\n\nLemma insert_equiv : forall (l:list Z) (x:Z), \n                  equiv (x :: l) (insert x l).\nProof.\n induction l as [|a l0 H]; simpl ; auto with sort.\n intros x; case_eq (Z.leb x a);\n   simpl; auto with sort.\n  intro; apply equiv_trans with (a :: x :: l0); \n   auto with sort.\nQed.\n\n\nLemma insert_sorted :\n forall (l:list Z) (x:Z), sorted l -> sorted (insert x l).\nProof.\n  intros l x H; elim H; simpl; auto with sort.\n  -  intro z; case_eq (Z.leb x z); simpl; intros; \n     le_from_bool;  auto with sort zarith.\n  -  intros z1 z2; case_eq (Z.leb x z2); simpl; intros; \n     case_eq (Z.leb x z1);intros; le_from_bool;  auto with sort zarith.\nQed.\n\n\nLemma sort_equiv : forall l, equiv l (insertion_sort l).\nProof.\n induction l;simpl;auto with sort.\n SearchAbout equiv.\napply equiv_trans with (a:: insertion_sort l).\n apply equiv_cons;auto.\n apply insert_equiv.\nQed.\n\nLemma sort_sorted : forall l, sorted (insertion_sort l).\ninduction l;simpl;auto with sort.\nnow apply insert_sorted.\nQed.\n\nLemma sort_sorted : forall l, sorted (insertion_sort l).\ninduction l;simpl;auto with sort.\nnow apply insert_sorted.\nQed.\n\n\nExtraction \"insert-sort\" insert insertion_sort.\n\n(**\n\n Projet :\n\n Specifier de la facon la plus generique possible ce qu'est une fonction\n correcte de tri polymorphe sur des listes:\n\n Construire une version polymorphe du tri par insertion, et prouver qu'elle \n realise la specification ci-dessus\n\n Afin d'illustrer la genericite de votre construction, montrer qu'elle\n permet de trier des listes de divers types de  donn\u00e9es, et comment \n realiser les transformations suivantes :\n  + tri par ordre decroissant \n  + tri sur un produit lexicographique\n  + tri selon les valeurs d'une fonction \n\n*)", "meta": {"author": "jordane51", "repo": "MTOCPLCOQ", "sha": "586564bf0ff303582e6a429b6eb42dd167ae73f6", "save_path": "github-repos/coq/jordane51-MTOCPLCOQ", "path": "github-repos/coq/jordane51-MTOCPLCOQ/MTOCPLCOQ-586564bf0ff303582e6a429b6eb42dd167ae73f6/insertionv8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.8179396228867578}}
{"text": "Module MYIFF.\n\nDefinition iff (P Q:Prop) : Prop := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q) (at level 95, no associativity) (* : type_scope *).\n\nEnd MYIFF.\n\n\nTheorem iff_sym : forall (P Q:Prop),\n    (P <-> Q) -> (Q <-> P).\nProof. intros P Q [H1 H2]. split. exact H2. exact H1. Qed.\n\n\nLemma not_true_iff_false : forall (b:bool),\n    b <> true <-> b = false.\nProof.\n    intros b. destruct b. \n    - split.\n        + intros H. exfalso. apply H. reflexivity.\n        + intros H. inversion H.\n    - split.\n        + intros. reflexivity.\n        + intros H1 H2. inversion H2.\nQed.\n\n\nTheorem iff_refl : forall (P:Prop),\n    P <-> P.\nProof. \n    intros P. split.\n    - intros H. exact H.\n    - intros H. exact H.\nQed.\n\nTheorem iff_trans : forall (P Q R:Prop),\n    (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n    intros P Q R [Hpq Hqp] [Hqr Hrq]. split.\n    - intro Hp. apply Hqr. apply Hpq. exact Hp.\n    - intro Hr. apply Hqp. apply Hrq. exact Hr.\nQed.\n\n\nTheorem or_distributes_over_and : forall (P Q R:Prop),\n    P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n    intros P Q R. split. \n    - intros [Hp|[Hq Hr]].\n        + split. { left. exact Hp. } { left. exact Hp. }\n        + split. { right. exact Hq. } { right. exact Hr. }\n    - intros [[H1|Hq] [H2|Hr]].\n        + left. exact H1.\n        + left. exact H1.\n        + left. exact H2. \n        + right. split. { exact Hq. } { exact Hr. }\nQed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/iff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8840392786908831, "lm_q1q2_score": 0.8179396220682105}}
{"text": "Example test (b1 :bool) : true = true.\nAdmitted.\n\n(*https://people.inf.elte.hu/akaposi/fsz/*)\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\nNotation \"x && y\" := (andb x y)\n  (at level 50, left associativity).\n\nExample negneg (b : bool) : negb (negb b) = b.\nintros c.\ndestruct c.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n(* More basic tactics computer foundation *)\n\nInductive Nat : Type := \n  | O : Nat\n  | S : Nat -> Nat.\n\nDefinition isOne (n : Nat) : bool :=\n  match n with\n  | O => false\n  | S O => true\n  | _ => false\n  end.\n\nDefinition four : Nat := S (S (S (S O))).\nDefinition six : Nat := S(S four).\nEval compute in isOne four.\nEval compute in isOne O.\nEval compute in isOne (S O).\n\n(* Sn * 2 = (1 + n) * 2 = 2 + 2n *) \n(* Fixpoint For recursive definiton*)\nFixpoint twice (n : Nat) : Nat :=\n match n with\n | O => O\n | S n => S(S (twice n))\nend.\n\nEval compute in twice six.\n(* S n must be less then f n (or swapped :) ) *)\nFixpoint f (n :Nat) : Nat := match n with\n | O => O\n | S n => f n\n end.\n\n(* Fixpoint f (n : Nat) : Nat := f n.*)\n\n(* \n  S(S (S O)) + m \n  S(S(S O) + m) = <- S n' + m = S(n'+m)\n  S(S(S O + m)) =\n  S(S(S(O+m))) = <- O + m = m\n  S(S(S(M)))\n *)\nFixpoint plus (n m : Nat) {struct n}  : Nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nEval compute in plus (twice six) (twice four).\n\nNotation \"x + y\" := (plus x y)\n  (at level 50, left associativity).\n\nLemma leftid (n : Nat) : O + n = n.\nsimpl.\nreflexivity.\nQed.\n\nLemma rightid (n : Nat) : n + O = n.\nsimpl.\ninduction n as [|m H].\nreflexivity.\nsimpl.\n(* swap m + O to m // <- swap m to m + O*)\nrewrite -> H.\nreflexivity.\nQed.\n(* profe associativity for NAT*)\n", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/02/02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8872045937171067, "lm_q1q2_score": 0.8179332850282457}}
{"text": "Require Import nat.\nRequire Import bool.\nRequire Import induction.\n\n\nTheorem S_inj : forall (n m:nat) (b:bool),\n    eqb (S n) (S m) = b -> eqb n m = b.\nProof. intros n m b H. simpl in H. exact H. Qed.\n\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 H1 H2. symmetry in H2. apply H1 in H2. \n    symmetry in H2. exact H2.\nQed.\n\nTheorem plus_n_n_injective : forall (n m:nat),\n    n + n = m + m -> n = m.\nProof.\n    induction n as [|n H].\n    - intros m H. destruct m as [|m].\n        + reflexivity.\n        + simpl in H. inversion H.\n    - intros m H'. destruct m.\n        + simpl in H'. inversion H'.\n        + simpl in H'. inversion H' as [H1]. clear H'.\n            rewrite (plus_comm n (S n)) in H1.\n            rewrite (plus_comm m (S m)) in H1.\n            simpl in H1. inversion H1 as [H']. clear H1.\n            apply H in H'. rewrite H'. 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/tactic_hyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.8179160805185073}}
{"text": "Module fmcthanos.\n\nInductive Nat : Type :=\n  | O\n  | S (n : Nat).\n\nFixpoint plus (n m : Nat) : Nat :=\n  match m with\n  | O => n\n  | S m => S (plus n m)\n  end.\nNotation \"x + y\" := (plus x y).\n\n(** Exerc\u00edcio x4.3 *)\nCompute O + S(S(S(S O))).\n\n(** Exerc\u00edcio x4.4 *)\nCompute S(S(S O)) + S(S O).\nCompute (S(S(S O)) + S(S O)) + S O.\n\n(** Exerc\u00edcio x4.5 *)\nFixpoint double (n : Nat) : Nat :=\n  n + n.\n\n(** Exerc\u00edcio x4.6 *)\nFixpoint mult (n m : Nat) :=\n  match m with\n  | O => O\n  | S m => (mult n m) + n\n  end.\nNotation \"x * y\" := (mult x y).\n\n(** Exerc\u00edcio x4.7 *)\nCompute S(S O) * (O + S O).\n\n(** Exerc\u00edcio x4.8 *)\nCompute S(S O) * S(S(S O)).\nCompute S(S(S O)) * S(S O).\n\n(** Exerc\u00edcio x4.9 *)\nFixpoint power (n m : Nat) : Nat :=\n  match m with\n  | O => S O\n  | S m => (power n m) * n\n  end.\nNotation \"x ^ y\" := (power x y).\n\n(** Exerc\u00edcio x4.10 *)\nCompute S(S O) ^ S(S(S O)).\n\n(** Exerc\u00edcio x4.11 *)\nFixpoint fib (n : Nat) : Nat :=\n  match n with\n  | O => O\n  | S O => S O\n  | S(S n as n') => fib (n') + fib (n)\n  end.\n\nCompute fib (S O).\nCompute fib (S(S O)).\nCompute fib (S(S(S O))).\nCompute fib (S(S(S(S O)))).\n\nTheorem plus_assoc :\nforall (a m y : Nat), (a + m) + y = a + (m + y).\nProof.\n  intros a m y.\n  induction y as [ | z].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHz.\n    reflexivity.\nQed.\n\nLemma plus_Sa_b :\nforall (a b : Nat), S a + b = a + S b.\nProof.\n  intros a b.\n  induction b as [ | c].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHc.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem plus_comm :\nforall (n m : Nat), n + m = m + n.\nProof.\n  intros n m.\n  induction n as [ | t].\n  - induction m as [ | u].\n    + reflexivity.\n    + simpl.\n      rewrite -> IHu.\n      simpl.\n      reflexivity.\n  - rewrite -> plus_Sa_b.\n    simpl.\n    rewrite -> IHt.\n    reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.16 *)\nTheorem mult_distr :\nforall (x y z : Nat), x * (y + z) = (x * y) + (x * z).\nProof.\n  intros x y z.\n  induction z as [ | z'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHz'.\n    rewrite <- plus_assoc.\n    reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.14 *)\nTheorem mult_assoc :\nforall (n m k : Nat), (n * m) * k = n * (m * k).\nProof.\n  intros n m k.\n  induction k as [ | k'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHk'.\n    rewrite <- mult_distr.\n    reflexivity.\nQed.\n\n(** Extra *)\nLemma mult_SO_a :\nforall (a : Nat), S O * a = a.\nProof.\n  intro a.\n  induction a as [ | x].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHx.\n    reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.15 *)\nLemma Sn_m :\nforall (n t : Nat), S t * n = (t * n) + n.\nProof.\n  intros n m.\n  induction n as [ | x].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHx.\n    rewrite -> plus_assoc.\n    rewrite -> plus_assoc.\n    rewrite <- (plus_comm m x).\n    reflexivity.\nQed.\n\nTheorem mult_comm :\nforall (n m : Nat), n * m = m * n.\nProof.\n  intros n m.\n  induction m as [ | t].\n  - induction n as [ | u].\n    + reflexivity.\n    + simpl.\n      rewrite <- IHu.\n      simpl.\n      reflexivity.\n  - simpl.\n    rewrite -> Sn_m.\n    rewrite -> IHt.\n    reflexivity.\nQed.\n\nDefinition leq (n m : Nat) : Prop :=\nexists (k : Nat), n + k = m.\nNotation \"x <= y\" := (leq x y).\n\n(** Exerc\u00edcio x4.20 *)\nExample leq_or_equal_1 :\nforall (n m : Nat), (n <= S m) -> (n <= m \\/ n = S m).\nProof.\n  intros n m.\n  intro Hnlsm.\n  destruct Hnlsm as [k Hk].\n  destruct k as [ | k'].\n  - right.\n    assumption.\n  - left.\n    simpl in Hk.\n    exists k'.\n    inversion Hk.\n    reflexivity.\nQed.\n\nExample leq_or_equal_2 :\nforall (n m : Nat), (n <= m \\/ n = S m) -> (n <= S m).\nProof.\n  intros n m.\n  intro Hnmnsm.\n  destruct Hnmnsm as [Hnm | Hnsm].\n  - destruct Hnm as [k Hk].\n    exists (S k).\n    simpl.\n    inversion Hk.\n    reflexivity.\n  - exists O.\n    simpl.\n    assumption.\nQed.\n\n(** Exerc\u00edcio x4.21 *)\nTheorem leq_refl :\nforall (x : Nat), x <= x.\nProof.\n  intro x.\n  exists O.\n  simpl.\n  reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.22 *)\nTheorem leq_trans :\nforall (x y z: Nat), (x <= y) /\\ (y <= z) -> x <= z.\nProof.\n  intros x y z.\n  unfold leq.\n  intro Hxyyz.\n  destruct Hxyyz as [Hxy Hyz].\n  destruct Hxy as [k Hk].\n  destruct Hyz as [k' Hk'].\n  rewrite <- Hk in Hk'.\n  exists (k + k').\n  rewrite <- Hk'.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.23 *)\nLemma x_diff :\nforall (x y : Nat), x <> x + S y.\nProof.\n  intros x y.\n  unfold not.\n  induction x as [ | w].\n  - intro Hxxsy.\n    rewrite -> plus_comm in Hxxsy.\n    simpl in Hxxsy.\n    inversion Hxxsy.\n  - intro Hswswsy.\n    rewrite -> plus_comm in Hswswsy.\n    simpl in Hswswsy.\n    inversion Hswswsy as [Hwsyw].\n    rewrite -> plus_comm in Hwsyw.\n    apply (IHw Hwsyw).\nQed.\n\nLemma y_equality :\nforall (x y : Nat), x + y = x -> y = O.\nProof.\n  intros x y.\n  intro Hxyx.\n  destruct y as [ | y'].\n  - reflexivity.\n  - simpl in Hxyx.\n    destruct x as [ | x'].\n    + inversion Hxyx.\n    +\n  \n(*   \n   induction x as [ | x'].\n    + simpl in Hxyx.\n      discriminate.\n    + rewrite -> IHy' in IHx'. *)\n(*       * discriminate. *)\nAbort.\n\nLemma xaxbab :\nforall (x a b : Nat), a + x = b + x -> a = b.\nProof.\n  intros x a b.\n  intro Hxaxb.\n  induction x as [ | x'].\n  - assumption.\n  - rewrite <- IHx' in Hxaxb.\n    simpl in Hxaxb.\nAbort.\n\nLemma abo :\nforall (a b : Nat), a + b = O -> a = O /\\ b = O.\nProof.\n  intros a b Habo.\n  destruct b as [ | b'].\n  - split.\n    + simpl in Habo.\n      assumption.\n    + reflexivity.\n  - simpl in Habo.\n    discriminate.\nQed.\n\nTheorem leq_antisym :\nforall (x y: Nat), (x <= y) /\\ (y <= x) -> x = y.\nProof.\n  intros x y.\n  intro Hxyyx.\n  destruct Hxyyx as [Hxy Hyx].\n  destruct Hxy as [w Hw].\n  destruct Hyx as [v Hv].\n  rewrite <- Hw in Hv.\n  induction y as [ | y'].\n  - induction x as [ | x'].\n    + induction w as [ | w'].\n      * reflexivity.\n      * reflexivity.\n    + rewrite -> plus_comm in Hw.\n      simpl in Hw.\n      discriminate.\n  - induction x as [ | x''].\n    + induction w as [ | w''].\n      * simpl in Hw.\n        discriminate.\n      * rewrite -> plus_comm in Hv.\n        simpl in Hv.\n        discriminate.\n    + induction w as [ | w'''].\n      * rewrite -> plus_comm in Hw.\n        simpl in Hw.\n        rewrite -> plus_comm in Hw.\n        simpl in Hw.\n        assumption.\n      * induction v as [ | v'].\n        simpl in Hv.\n        -- rewrite Hv.\n           reflexivity.\n        --\n        rewrite -> plus_comm in H.\n  \n  \n  \n  \n  induction w as [ | u].\n  - reflexivity.\n  - pattern x at 1. rewrite <- Hv.\n    induction v as [ | t].\n    + rewrite -> Hw.\n      reflexivity.\n    + rewrite <- Hw in Hv.\n      rewrite -> plus_assoc in Hv.\n      simpl (S u + S t) in Hv.\n      induction x as [ | s].\n      * simpl in Hv.\n        discriminate.\n      * \n      \n    destruct x as [ | Su].\n    + rewrite -> plus_comm.\n      simpl.\n      discriminate.\n    \n    rewrite -> plus_assoc.\n    reflexivity.\n  - destruct Hxyyz as [Hxy Hyz].  \n    destruct Hxy as [k Ek].\n    destruct Hyz as [k' Ek'].\n    destruct Hxz as [k'' Ek''].\n    rewrite <- Ek'.\n    rewrite <- Ek.\n(*     rewrite <- Ek. *)\nAbort.\n\n(** Exerc\u00edcio x4.24 *)\nTheorem leq_total :\nforall (x y: Nat), (x <= y) \\/ (y <= x).\nProof.\n  intros x y.\n  destruct y as [ | y'].\n  - destruct x as [ | x'].\n    + left.\n      exists O.\n      reflexivity.\n    + right.\n      exists (S x').\n      rewrite -> plus_comm.\n      simpl.\n      reflexivity.\n  - induction x as [ | x'].\n    + left.\n      exists (S y').\n      rewrite -> plus_comm.\n      simpl.\n      reflexivity.\n    + destruct IHx' as [Hx'sy' | Hsy'x'].\n      destruct Hx'sy' as [w Hw].\n      destruct w as [ | w'].\n      * rewrite <- Hw.\n        right.\n        exists (S O).\n        simpl.\n        reflexivity.\n      * rewrite <- Hw.\n        left.\n        exists w'.\n        rewrite -> plus_comm.\n        simpl.\n        rewrite -> plus_comm.\n        reflexivity.\n      * destruct Hsy'x' as [v Hv].\n        right.\n        exists (S v).\n        simpl.\n        rewrite -> Hv.\n        reflexivity.\nQed.\n\n(** Exerc\u00edcio x4.25 *)\n(* Example n2_leq_2n :\nforall (n : Nat), S(S(S(S(S O)))) <= n -> n ^ (S(S O)) < S(S O) ^ n.\nAdmitted. *)\n\n(** Homework: 20/02/2021, 1 *)\nFixpoint sum (i n x : Nat) : Nat :=\n  match n with\n  | O => O\n  | S n' => x + (sum i n' x)\n  end.\n\nCompute (sum (S O) (S(S(S O))) (S O)).\nCompute (sum (S O) (S(S(S(S(S(S O)))))) (S O)).\n\nTheorem n_equals_sum_3_5 :\nforall (n : Nat), exists (t u : Nat), n = S(S(S O)) * t + S(S(S(S(S O)))) * u.\nProof.\n  intro n.\n  induction n as [ | m].\n  - exists O.\n    exists O.\n    simpl.\n    reflexivity.\n  - destruct IHm as [v Hv].\n    destruct Hv as [w Hw].\n    rewrite -> Hw.\n    destruct v as [ | x].\n    + destruct w as [ | y].\n      * simpl.\n        exists O.\n        exists O.\n        simpl.\n(*     exists (S(S O)).\n    exists (S O). *)\nAbort.\n\n\nFixpoint sum1 (n : Nat) (s : Nat -> Nat) : Nat :=\n  match n with\n  | O => O\n  | S n' => (s n) + (sum1 n' s)\n  end.\n\nCompute (sum1 (S(S(S O))) (fun i => (S O))).\n(* Compute (sum1 (S O) (S(S(S(S(S(S O)))))) (S O)). *)\n\n(* Fixpoint sum_natseq (i n : Nat) (x : Nat -> Nat) : Nat :=\n  match i with\n  | i' => (x i') + (sum_natseq (S i') n x)\n  | S n => O\n  end. *)\n  \n(**  Preciso estudar listas primeiro para definir isso.\n  *)\n  \n(** (* (* (* (* (* (* Problem Set 1.1 *) *) *) *) *) *) *)\n\nDefinition less_than (n m : Nat) : Prop :=\nexists (k : Nat), n + S k = m.\nNotation \"x < y\" := (less_than x y).\n\nExample problema_1_1 :\nforall (x y : Nat), x <= y -> x < y \\/ x = y.\nProof.\n  intros x y.\n  intro Hxleqy.\n  destruct Hxleqy as [k Hk].\n  destruct k as [ | k'].\n  - simpl in Hk.\n    right.\n    assumption.\n  - left.\n    unfold less_than.\n    exists k'.\n    assumption.\nQed.\n\nExample problema_1_2 :\nforall (x y : Nat), x < y \\/ x = y -> x <= y.\nProof.\n  intros x y.\n  intro Hxy.\n  destruct Hxy as [Hxlty | Hxeqy].\n  - destruct Hxlty as [n Hsn].\n    unfold leq.\n    exists (S n).\n    assumption.\n  - exists O.\n    simpl.\n    assumption.\nQed.\n\nExample problema_1_3 :\nforall (x y : Nat), x < y -> x <= y /\\ x <> y.\nProof.\n  intros x y.\n  intro Hxy.\n  destruct Hxy as [n Hn].\n  split.\n  - exists (S n).\n    assumption.\n  - simpl in Hn.\n    destruct y as [ | y'].\n    + inversion Hn.\n    + injection Hn.\nAbort.\n\nExample problema_1_4 :\nforall (x y : Nat), x <= y /\\ x <> y -> x < y.\nProof.\n  intros x y.\n  intro xleqy_and_xdiffy.\n  destruct xleqy_and_xdiffy as [xleqy xdiffy].\n  destruct xleqy as [n defleq].\n  destruct n as [ | n'].\n  - simpl in defleq.\n    contradiction.\n  - exists n'.\n    assumption.\nQed.\n\nExample problema_2_1 :\nforall (a x y : Nat), x <= y -> x ^ a < y ^ a.\nProof.\n  intros a x y.\n  intro xleqy.\n  destruct xleqy as [k existsk].\n  rewrite <- existsk.\n  induction x as [ | x'].\n  - rewrite -> plus_comm.\n    simpl.\n    destruct k as [ | k'].\n  simpl.\nAbort.\n\nExample problema_3 :\nforall n : Nat,\n(exists k : Nat, n = S(S O) * k) \\/\n(exists k' : Nat, n = S(S(S O) * k')).\nProof.\n  intro n.\n  induction n as [ | n'].\n  - left.\n    exists O.\n    simpl.\n    reflexivity.\n  - destruct IHn' as [IHn'1 | IHn'2].\n    + right.\n      destruct IHn'1 as [m Em].\n      exists m.\n      rewrite <- Em.\n      simpl.\n      reflexivity.\n    + left.\n      destruct IHn'2 as [m Em].\n      rewrite -> Em.\n      exists (S m).\n      simpl.\n      reflexivity.\nQed.\n  \nEnd fmcthanos.\n", "meta": {"author": "jopefd", "repo": "fmc1-coq", "sha": "f503e5d06bf894cf56d3566d03c4e39f144b2651", "save_path": "github-repos/coq/jopefd-fmc1-coq", "path": "github-repos/coq/jopefd-fmc1-coq/fmc1-coq-f503e5d06bf894cf56d3566d03c4e39f144b2651/NatRecInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.8175481265543985}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\n(* Chapter 4: Primality *)\nDefinition divides (a b : nat) := \n  exists q, b = a * q.\n\nNotation \"x `div y\" := (divides x y) (at level 70).\n\nDefinition prime (p : nat) :=\n  (p <> 1) /\\ (forall x, x `div p -> (x = 1) \\/ (x = p)).\n\nRemark one_not_prime: ~ prime 1.\nProof.\nintros [h1 h2]; now apply h1.\nQed.\n\nRemark two_is_prime: prime 2.\nProof.\nsplit; [now firstorder | ].\nintros x [q hq].\ndestruct x as [ | [ | [ | x ]]]; try now intuition.\ndestruct q as [ | q]; [ now rewrite mult_0_r in hq | ].\nsimpl in hq.\ninjection hq; clear hq; intro hq.\nrewrite Nat.add_succ_r in hq.\ninjection hq; clear hq; intro hq.\nnow rewrite !Nat.add_succ_r in hq.\nQed.\n\nLemma divides_refl: forall n, n `div n.\nProof.\nintro n; exists 1.\nnow rewrite mult_1_r.\nQed.\n\nLemma divides0: forall n, n `div 0.\nProof.\nnow intro n; eexists; eauto.\nQed.\n\nRemark eq1: forall a b, 1 = a * b -> a = 1 /\\ b = 1.\nProof.\nintros [ | [ | a]] [ | [ | b]] h; simpl in *;\n  try solve [discriminate | firstorder ].\nQed.\n\nLemma divides1: forall n, n `div 1 <-> n = 1.\nProof.\nintro n; split; intro h.\n- destruct h as [ q hq ].\n  now apply eq1 in hq as [h1 h2].\n- subst.\n  apply divides_refl.\nQed.\n\nLemma divides_trans:forall a b c, a `div b -> b `div c -> a `div c.\nProof.\nintros a b c [q hq] [p hp].\nrewrite hq in hp.\nexists (q * p).\nrewrite mult_assoc.\nexact hp.\nQed.\n\nLemma divides_add: forall d a b, d `div a -> d `div b -> d `div (a + b).\nProof.\nintros d a b [q hq] [p hp].\nexists (q + p).\nrewrite hq, hp.\nSearchAbout mult.\nSearchPattern (_ + _ = _ + _).\nrewrite Nat.mul_add_distr_l.\nreflexivity.\nQed.\n\nLemma divides_sub: forall d a b, d `div a -> d `div b -> d `div (a - b).\nProof.\nintros d a b [q hq] [p hp].\nexists (q - p).\nrewrite hq, hp, Nat.mul_sub_distr_l.\nreflexivity.\nQed.\n\nLemma divides_addl: forall d a b, d `div a -> d `div (a + b) -> d `div b.\nProof.\nintros d a b ha hab.\nreplace b with ((a + b) - a).\n- apply divides_sub; assumption.\n- auto with arith.\nQed.\n\nLemma divides_lmul: forall d a x, d `div a -> d `div (x * a).\nProof.\nintros d a x [q hq].\nexists (q * x).\nrewrite hq.\nnow rewrite mult_comm, mult_assoc.\nQed.\n\nLemma divides_rmul: forall d a x, d `div a -> d `div (a * x).\nProof.\nnow intros; rewrite mult_comm; apply divides_lmul.\nQed.\n\nLemma divides_le: forall m n, m `div n -> (m <= n \\/ n = 0).\nProof.\nintros m n [q hq]; subst.\ndestruct q as [ | q].\n- now right; auto with arith.\n- left.\n  rewrite mult_succ_r.\n  now auto with arith.\nQed.\n\nFixpoint factorial (n: nat) : nat :=\n  match n with\n  | 0 => 1\n  | S n => (S n) * (factorial n)\n  end.\n\nLemma factorial_non_zero: forall n, factorial n <> 0.\nProof.\ninduction n as [ | n hi]; simpl in *; intro h; [ discriminate | ].\napply plus_is_O in h as [h _].\nnow apply hi.\nQed.\n\nRemark le_lt_eq: forall a b, a <= S b -> a = S b \\/ a <= b.\nProof.\nintros a b h.\ninversion h; subst; clear h.\n- now left.\n- now right.\nQed.\n\nLemma divides_fact:forall m n, 0 < m -> m <= n -> \n  m `div (factorial n).\nProof.\nShow Proof.\nintros m; induction n as [ | n hi]; simpl in *; intros hlt hle.\nShow Proof.\n- apply le_n_0_eq in hle; subst.\n  Show Proof.\n  apply lt_irrefl in hlt.\n  elim hlt.\n- apply le_lt_eq in hle as [h | h].\n  + subst.\n    replace (factorial n + n * factorial n) with\n       (S n * factorial n) by (auto with arith).\n    apply divides_rmul.\n    apply divides_refl.\n  + apply divides_add.\n    * now apply hi.\n    * apply divides_lmul.\n      now apply hi.\nQed.\n\nPrint divides_fact.\n\n(* all prime factors of n! + 1 are > n *)\nLemma prime_div_factor: forall n p, p `div (factorial n + 1) -> prime p -> n < p.\nProof.\nintros n p hdiv0 hp.\ndestruct (lt_dec n p) as [ h | h]; [assumption | ].\nassert (hdiv1: p `div factorial n).\n- apply divides_fact.\n  + destruct p as [ | p].\n    * destruct hp as [_ hp].\n      now destruct (hp 2 (divides0 2)).\n    * now auto with arith.\n  + now apply not_lt in h.\n- assert (h1: p `div 1) by now apply divides_addl with (factorial n).\n  apply divides1 in h1.\n  elim one_not_prime. \n  now rewrite <- h1.\nQed.\n\n(* for any natural number, there exists a natural number greater than it *)\nLemma euclid_: (forall n, n <> 1 -> exists p, prime p /\\ p `div n)\n    -> forall n, exists p, n < p /\\ prime p.\nProof.\nintros hprime_factor n.\ndestruct (hprime_factor (factorial n + 1)) as [p [hp hd]].\n- rewrite plus_comm; intro hf; injection hf; clear hf; intro hf.\n  now apply factorial_non_zero in hf.\n- exists p; split; [ | assumption ]. \n  now apply prime_div_factor.\nQed.\n\n(* Let's prove the \"prime_factor\" part with the excluded middle, so\n   we can reason \"naturally\" by contradiction\n *)\nRequire Import Wf.\n\nSection WithEM.\n\nLemma prime_factor_with_EM: \n    (forall A: Prop, A \\/ ~ A) -> \n    forall n, n <> 1 -> exists p, prime p /\\ p `div n.\nProof.\nintro EM.\ninduction n as [ n hi ] using (well_founded_induction lt_wf).\ncase_eq (n =? 0); intros hn0;\n  [ intros _; apply Nat.eqb_eq in hn0; subst;\n    exists 2; split; [ apply two_is_prime | apply divides0 ] | ].\napply Nat.eqb_neq in hn0.\nintros hn1.\ndestruct (EM (prime n)) as [hp | hp].\n- exists n; split; [ assumption | ].\n  now apply divides_refl.\n- destruct (EM (exists m, 1 < m /\\ m < n /\\ m `div n)) as [hd | hd ].\n  + destruct hd as [d [h0 [h1 h2]]].\n    destruct (hi d h1) as [p [hp1 hp2]]; [now intuition | ].\n    exists p; intuition.\n    now apply divides_trans with d.\n  + elim hp; split; [ assumption | intros x hx].\n    case_eq (x =? n); intro hxn; [ now apply Nat.eqb_eq in hxn; right | ].\n    case_eq (x =? 0); intro hx0.\n    * apply Nat.eqb_eq in hx0; subst.\n      destruct hx as [ q hq].\n      now rewrite hq; right.\n    * case_eq (x =? 1); intro hx1.\n      -- apply Nat.eqb_eq in hx1; now left.\n      -- apply Nat.eqb_neq in hx0.\n         apply Nat.eqb_neq in hx1.\n         apply Nat.eqb_neq in hxn.\n         elim hd.\n         exists x; repeat split; [ now intuition | | assumption ].\n         now apply divides_le in hx as [hx | hx]; [ intuition | subst; now elim hn0].\nQed.\n\n(* for any natural number, there exists a natural number greater than it *)\nLemma euclid_with_EM: (forall A: Prop, A \\/ ~A) ->\n    forall n, exists p, n < p /\\ prime p.\nProof.\nintros hem n.\napply euclid_.\nnow apply prime_factor_with_EM.\nQed.\n\nEnd WithEM.\n\n(* Now let's be good intuitionistic lads and do the same without the excluded\n   middle. In `prime_factor_with_EM`, we used the EM to test if a natural\n   number was prime or not. Let's write some code just to do that.\n*)\n\nSection NoEM.\n(*\nNow let's avoid EM and build a function to test the primality of natural\nnumbers. We'll do that by writing a function to perform the division\n(there's probably a few in the lib, this is for showing how it's done).\n*)\n\n(* Write concrete implementation of division (stollen from ssreflect) *)\nFixpoint divn_rec d m q :=\n  match m - d with\n  | S x => divn_rec d x (S q)\n  | _ => (q, m)\n  end.\n\nLemma divn_rec_unroll : forall d m q, divn_rec d m q =\n  match m - d with\n  | S x => divn_rec d x (S q)\n  | _ => (q, m)\n  end.\nProof.\nnow intros d [] q.\nQed.\n\n\n(* And its specification *)\nLemma divn_rec_spec: forall d m x,\n let (q, r) := divn_rec d m x in m = (q - x) * (S d) + r /\\ x <= q /\\ r < S d.\nProof.\nintro d; induction m as [m hi] using (well_founded_induction lt_wf); intros x; simpl in *.\nrewrite divn_rec_unroll.\ncase_eq (m - d); [ now intros;  rewrite Nat.sub_diag; firstorder | ].\nintros md heq.\nassert (hlt: md < m) by omega.\nspecialize hi with md (S x).\ndestruct divn_rec as [ q r].\nreplace m with (d + S md) by now apply Nat.add_sub_eq_nz in heq.\ndestruct (hi hlt) as [ h [hle hr]].\nsplit; [ | split; [now auto with arith | assumption ]].\nrewrite h.\nreplace ((q - x) * S d) with ((q - S x) * S d + S d).\nomega.\nreplace (q - x) with (S (q - S x)) by omega.\nrewrite Nat.mul_succ_l.\nreflexivity.\nQed.\n\n(* Main function *)\nDefinition divn m d := \n match d with \n | 0 => (0, m)\n | S d => divn_rec d m 0\nend.\n\nInductive divn_spec m d : nat * nat -> Type :=\n  DivnSpec: forall q r, m = q * d + r -> ((d > 0) -> (r < d)) -> divn_spec m d (q, r).\n\n(* And specification *)\nLemma divn_spec_ok m d : divn_spec m d (divn m d).\nProof.\nunfold divn.\ndestruct d as [ | d]; [ now constructor | ].\npose (hrec := divn_rec_spec d m 0).\ncase_eq (divn_rec d m 0); intros q r heq.\nrewrite heq in hrec; destruct hrec as [h1 [h2 h3]].\nconstructor.\n- now rewrite Nat.sub_0_r in h1.\n- now intros.\nQed.\n\n(* We now show that divn is equivalent to divides *)\nLemma divn_div: forall m d,\n  d `div m <-> (let (q, r) := divn m d in r = 0).\nProof.\nintros m d; split; intro h.\n- destruct h as [q hq].\n  destruct (divn_spec_ok m d) as [k s heq hrem].\n  rewrite mult_comm in heq.\n  destruct d as [ | d].\n  + now simpl in *; subst.\n  + rewrite heq in hq.\n    apply Nat.add_sub_eq_l in hq.\n    rewrite <- Nat.mul_sub_distr_l in hq.\n    case_eq (q - k).\n    * intro h; rewrite h in hq. \n      now rewrite mult_comm in hq.\n    * intros x hx; rewrite hx in hq.\n      assert (hn : S d <= s).\n      -- replace (S d) with ((S d) * 1) by now rewrite mult_comm, mult_1_l.\n         rewrite <- hq.\n         apply mult_le_compat_l.\n         now auto with arith.\n      -- elim (lt_irrefl s).\n         apply lt_le_trans with (S d); [ now apply hrem; auto with arith | now apply hn ].\n- destruct (divn_spec_ok m d) as [q s heq hrem].\n  rewrite heq, h, plus_0_r.\n  now exists q; rewrite mult_comm.\nQed.\n\n(* Now let's write an algorithm that tests if a number is prime, by\n   testing all of the possible divisors. Remember we prove things so\n   we don't care at all if that inefficent\n*)\nFixpoint prime_rec p d :=\n  match d with\n  | 1 => true\n  | 0 => true\n  | S d => \n    let (q, r) := divn p (S d) in\n    if Nat.eqb r 0\n    then false\n    else prime_rec p d\n  end.\n\n(* Spec of the function *)\nLemma prime_rec_spec: forall p d,\n  2 <= d ->\n  (prime_rec p d = true <-> (forall x, x <= d -> 1 < x -> ~ x `div p)).\nProof.\nintro p; induction d as [ | d hi]; intros hd; split; simpl in *.\n- now auto with arith.\n- intros _; reflexivity.\n- apply le_S_n in hd.\n  destruct d as [ | d]; [ now auto with arith | ].\n  intros h x hle hlt hdiv.\n  apply le_lt_eq in hle as [ -> | hle ].\n  + apply divn_div in hdiv; unfold divn in hdiv.\n    now destruct divn_rec; subst.\n  + assert (hd' : 2 <= S d) by\n       now destruct d as [ | d];\n       [ elim (lt_irrefl 1); apply lt_le_trans with x | auto with arith ].\n    apply hi in hd'.\n    destruct hd' as [hl hr].\n    revert h.\n    generalize (divn_rec_spec (S d) p 0).\n    destruct divn_rec as [ q r ]; intros [heq [_ hrem]] h.\n    rewrite Nat.sub_0_r in heq.\n    case_eq (r =? 0); intro h0; rewrite h0 in h; [ discriminate | ].\n    now apply hl with x.\n- destruct d as [ | d]; [ intros _; reflexivity | ].\n  clear hd.\n  intro h.\n  generalize (divn_rec_spec (S d) p 0).\n  destruct divn_rec as [ q r ]; intros [heq [_ hrem]].\n  rewrite Nat.sub_0_r in heq.\n  case_eq (r =? 0); intro h0.\n  + apply Nat.eqb_eq in h0; rewrite h0 in *; clear h0.\n    rewrite plus_0_r in heq.\n    elim (h (S (S d))).\n    * now apply le_refl.\n    * now auto with arith.\n    * now exists q; rewrite mult_comm.\n  + apply Nat.eqb_neq in h0.\n    destruct d as [ | d].\n    * replace r with 1 in *; [ now idtac | ].\n      assert (0 < r) by now destruct r; [elim h0 | auto with arith]. \n      destruct r as [ | ]; [now elim h0 | ].\n      destruct r as [ | ]; [ reflexivity | ].\n      apply lt_S_n in hrem.\n      apply lt_S_n in hrem.\n      now apply lt_n_0 in hrem.\n   * apply hi; [now auto with arith | ].\n     intros x hle ht hdiv.\n     apply h with x; now auto with arith.\nQed.\n\n(* We also need the negative case -> if we are not prime, we get a non trivial\n   divisor from the function *)\nLemma prime_rec_spec_false: forall p d,\n    prime_rec p d = false -> exists x, x <= d /\\ 1 < x /\\ x `div p.\nProof.\nintro p; induction d as [ | d hi]; intros hp; simpl in *; [ discriminate | ].\ndestruct d as [ | d]; [ discriminate | ].\ngeneralize (divn_rec_spec (S d) p 0).\nrevert hp.\ndestruct divn_rec.\ndestruct n0 as [ | n0].\n- intros _.\n  rewrite Nat.sub_0_r, plus_0_r.\n  intros [-> _].\n  exists (S (S d)); intuition.\n  apply divides_lmul.\n  now apply divides_refl.\n- simpl Nat.eqb; intro h.\n  apply hi in h as [q [h0 [h1 h2]]].\n  rewrite Nat.sub_0_r; intros [hp [_ hlt]].\n  now exists q; intuition.\nQed.\n\n(* Main function *)\nDefinition primen p :=\n    match p with\n    | 0 => false\n    | 1 => false\n    | S q => prime_rec p q\n    end.\n\n(* and spec *)\nLemma primen_spec: forall p, primen p = true <-> prime p.\nProof.\nunfold primen, prime.\nintros [ | p]; split; intro h.\n- discriminate h.\n- destruct h as [_ h].\n  destruct (h 2); [ now apply divides0 | discriminate | discriminate ].\n- destruct p as [ | p]; [ discriminate | ].\n  split; [ now idtac | ].\n  intros x hdiv.\n  generalize (prime_rec_spec (S (S p)) (S p)); intro hp.\n  destruct p as [ | p].\n  + now apply two_is_prime in hdiv.\n  + assert (hh: 2 <= S ( S p)) by now auto with arith.\n    apply hp in hh as [hl hr].\n    case_eq (x =? (S (S (S p)))); intro hx; [ now right; apply Nat.eqb_eq |].\n    apply Nat.eqb_neq in hx.\n    destruct x as [ | x]; [ destruct hdiv as [q hq]; discriminate | ].\n    destruct x as [ | x]; [now left | ].\n    right.\n    apply hl with (S (S x)) in h.\n    * now apply h in hdiv.\n    * apply divides_le in hdiv.\n      destruct hdiv as [hdiv | ]; [ | discriminate ].\n      apply le_lt_eq in hdiv as [ h0 | h1]; [now subst | assumption ].\n    * now auto with arith.\n- destruct h as [hp hf].\n  destruct p as [ | p]; [ now elim hp | ].\n  clear hp.\n  destruct p as [ | p]; [ reflexivity | ].\n  apply prime_rec_spec; [now auto with arith | ].\n  intros x hle ht hdiv.\n  apply hf in hdiv as [ h | h].\n  + subst; now apply lt_irrefl in ht.\n  + subst.\n    repeat apply le_S_n in hle.\n    apply (lt_irrefl (S p)).\n    apply le_lt_trans with p; [ assumption | ].\n    now constructor.\nQed.\n\n(* every number as at least one prime factor *)\nLemma prime_factor: forall n, n <> 1 -> exists p, prime p /\\ p `div n.\nProof.\ninduction n as [ n hi ] using (well_founded_induction lt_wf).\nintros hn1.\ncase_eq (primen n); intro hp.\n- exists n; split.\n  + now apply primen_spec.\n  + now apply divides_refl.\n- unfold primen in hp.\n  destruct n as [ | n].\n  + now exists 2; split; [ apply two_is_prime | apply divides0 ].\n  + destruct n as [ | n]; [ now elim hn1 | ].\n    apply prime_rec_spec_false in hp as [q [h0 [h1 h2]]].\n    destruct (hi q) as [y [hy0 hy1]].\n    * now auto with arith.\n    * now intro; subst; apply lt_irrefl in h1.\n    * exists y; split;[ assumption | ].\n      now apply divides_trans with q.\nQed.\n\n(* for any natural number, there exists a natural number greater than it *)\nLemma euclid: forall n, exists p, n < p /\\ prime p.\nProof.\nintros n.\napply euclid_.\nnow apply prime_factor.\nQed.\n\nEnd NoEM.\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/1-prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.817512429986447}}
{"text": "Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n \nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(*Fixpoint length(l:natlist):nat:=\nmatch l with\n|[ ] = 0\n|h::t => 1+ length t\nend.*)\n\nFixpoint append(m n :natlist) : natlist :=\nmatch m with\n|[] => n\n|a :: b => a::(append b n)\nend.\n\nNotation \"x ++ y\" := (append x y)(at level 60, right associativity).\n\nTheorem associative_L3 : forall n o p : natlist, n++(o++p) = (n++o)++p.\nProof.\nintros n o p.\ninduction n.\nsimpl. reflexivity.\nsimpl. rewrite -> IHn.\nreflexivity.\nQed.\n\nTheorem associative_L4 : forall m n o p : natlist, m++(n++(o++p)) = ((m++n)++o)++p.\nProof.\nintros m n o p.\nsimpl.\ninduction m as [| x xs]. \nsimpl. \nrewrite associative_L3. \nreflexivity.\nsimpl.\nrewrite -> IHxs. reflexivity.\nQed. \n\n\n\n\n \n(*\nFixpoint snoc(m:natlist)(n:nat) :natlist:=\nmatch m with\n|[] => [n]\n|a::b => a:: (snoc b n)\nend.\n\nFixpoint reverse(n:natlist) : natlist :=\nmatch n with\n|[] => []\n|a::b => snoc(reverse b) a\nend.\n\nTheorem appendEmptyList : forall list : natlist, list ++ [] = list.   \nProof.\n  intros.\n    \n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. \n    rewrite -> IHxs.\n    reflexivity.\nQed.\n\n*)", "meta": {"author": "psjyothiprasad", "repo": "Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "sha": "bda5df849ce973def8aa145660aa806e7743af35", "save_path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography/Software-Modelling---Theorem-Provers---Program-Verification---Cryptography-bda5df849ce973def8aa145660aa806e7743af35/Exercise1_Backup/associativeL4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8174725298495428}}
{"text": "Fixpoint factorial (n: nat) : nat :=\n    match n with \n    |0 => 1\n    |S n' => (n'+1) * factorial (n')\n    end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\nCheck ((0 + 1) + 1) : nat.\n", "meta": {"author": "ayushpandey8439", "repo": "CoqProofs", "sha": "a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b", "save_path": "github-repos/coq/ayushpandey8439-CoqProofs", "path": "github-repos/coq/ayushpandey8439-CoqProofs/CoqProofs-a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b/factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.8172760166135689}}
{"text": "Require Import Arith.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\n  intros.\n  rewrite mult_plus_distr_r.\n\n  assert (2 * n * m = n * m + n * m).\n  simpl.\n  rewrite plus_assoc.\n  rewrite NPeano.Nat.add_0_r.\n  rewrite mult_plus_distr_r.\n  reflexivity.  \n\n  rewrite H.\n  rewrite plus_assoc.\n\n  assert ( n * n + m * m + n * m = n * n + n * m + m * m ).\n  apply NPeano.Nat.add_shuffle0.\n  rewrite H0.\n\n  rewrite <-mult_plus_distr_l.\n\n  assert ( m * (n + m) = m * m + n * m ).\n  rewrite plus_comm.\n  rewrite mult_comm.\n  rewrite mult_plus_distr_r.\n  reflexivity.\n  rewrite H1.\n\n  rewrite plus_assoc.\n  reflexivity.\n\nQed.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  apply plus_permute_2_in_4.\nQed.", "meta": {"author": "odanado", "repo": "coq", "sha": "6524eb11b64fc6703af806e94b5405279d099ef2", "save_path": "github-repos/coq/odanado-coq", "path": "github-repos/coq/odanado-coq/coq-6524eb11b64fc6703af806e94b5405279d099ef2/coqex2014/2/kadai2_9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.8170954344409211}}
{"text": "Require Import QArith.\n\nPrint Q.\n\nPrint Qnum.\nPrint Qden.\n\nCheck Qnum.\n\nDefinition inj (z :Z):= Qmake z 1.\n\n Eval compute in (inj 3).\n\nEval compute in ( (3 # 5) * (4# 6)).\n\nEval compute in ((2#3)+(4#8)).\n\nCheck transitivity.\n\nCheck Qlt.\nCheck Qlt_le_trans.\nCheck Qlt_le_weak.\n\nDefinition interval (p q :Q):={x : Q| p < x /\\ x< q}.\nDefinition interval_empty(p : Q):={x :Q | p < x /\\ x< p}.\n\nLemma ref:forall p q r :Q,p < q /\\ q < r -> p < r.\nProof.\nintros.\ndestruct H.\napply (Qlt_le_trans p q r).\napply H.\napply Qlt_le_weak.\napply H0.\nDefined.\n\n", "meta": {"author": "mmaleki", "repo": "LogicalDifferentiation", "sha": "2a46afc6ae55680fb4416dadbe295c0b617bc4f4", "save_path": "github-repos/coq/mmaleki-LogicalDifferentiation", "path": "github-repos/coq/mmaleki-LogicalDifferentiation/LogicalDifferentiation-2a46afc6ae55680fb4416dadbe295c0b617bc4f4/PracticeRational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.8170877042039608}}
{"text": "(** * Indu\u00e7\u00e3o em Coq *)\n\nRequire Export aula04_inducao.\nModule NatList.\n\n(* ############################################### *)\n(** * Pares de n\u00fameros *)\n\n(** A seguinte declara\u00e7\u00e3o pode ser lida como\n    \"s\u00f3 existe uma maneira de construir um\n    par de n\u00fameros, que \u00e9 aplicando o construtor\n    [pair] a dois argumentos do tipo [nat]\" *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\n(** Definindo fun\u00e7\u00f5es para pares.\n    Observe o casamento de padr\u00e3o. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(* Definindo uma nota\u00e7\u00e3o mais conveniente. *)\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\n\n(* Observe que \u00e9 poss\u00edvel, inclusive,\n   usar esta sintaxe no casamento de padr\u00f5es. *)\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Algumas provas associadas a pares. *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  simpl. reflexivity.\nQed.\n\n(** Observe que o pr\u00f3ximo teorema representa\n    o mesmo fato, mas [reflexivity] n\u00e3o\n    \u00e9 suficiente para concluir esta prova. *)\n\nTheorem surjective_pairing_stuck :\n  forall (p : natprod),\n    p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** \u00c9 preciso expor a estrutura de [p], tal\n    que [simpl] possa realizar casamento de\n    padr\u00e3o. [destruct] permite fazer isto. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\n(** **** Exercise: (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros. destruct p as [x y]. simpl. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Lista de n\u00fameros *)\n\n(** Defini\u00e7\u00e3o de uma lista de n\u00fameros. *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** Exemplo de uma lista com 3 elementos. *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** Definindo uma nota\u00e7\u00e3o mais conveniente. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** As defini\u00e7\u00f5es a seguir s\u00e3o equivalentes. *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** Definindo fun\u00e7\u00f5es para listas. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:\n[1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2:\nnil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3:\n[1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\n(** Na defini\u00e7\u00e3o a seguir, observe o\n    valor [default]. *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:\nhd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2:\nhd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl:\ntl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(** **** Exercise: (list_funs)  *)\n(** Complete as defini\u00e7\u00f5es de [nonzeros],\n    [oddmembers] e [countoddmembers]. Os testes\n    mostram o comportamento esperado. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | n :: t => n :: nonzeros t\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint filter (p: nat -> bool)(l: natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => if p h then h :: filter p t else filter p t\n  end.\n\nFixpoint oddmembers (l:natlist) : natlist := filter oddb l.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l: natlist): nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(* ############################################### *)\n(** * Representando multiconjuntos como listas *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: (bag_functions)  *)\n(** Complete as defini\u00e7\u00f5es de: [count], [sum],\n    [add], e [member] para multiconjuntos (bags).\n    Os testes mostram o comportamento esperado. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match beq_nat v h with\n              | true => 1 + count v t\n              | false => count v t\n              end\n  end.\n\nExample test_count1:\n  count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\nExample test_count2:\n  count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** A opera\u00e7\u00e3o [sum] em multiconjuntos \u00e9 similar\n    ao conceito de [union] de conjuntos: [sum a b]\n    cont\u00e9m todos os elementos de [a] e [b].\n\n    Observe que a pr\u00f3xima defini\u00e7\u00e3o n\u00e3o possui\n    nome para os par\u00e2metros, mas somente seus tipos.\n    Al\u00e9m disto, a defini\u00e7\u00e3o n\u00e3o \u00e9 recursiva. Portanto,\n    [sum] precisa ser definida em fun\u00e7\u00e3o de defini\u00e7\u00f5es\n    passadas. *)\n\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nExample test_sum1:\n  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:\n  count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2:\n  count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\n(** Observe que a pr\u00f3xima defini\u00e7\u00e3o\n    tamb\u00e9m n\u00e3o \u00e9 recursiva. *)\n\nDefinition member (v:nat) (s:bag) : bool :=\n  negb (beq_nat 0 (count v s)).\n\nExample test_member1:\n  member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2:\n  member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: (bag_theorem)  *)\n(** Prove o seguinte teorema. Talvez voc\u00ea\n    precise provar um teorema auxiliar. *)\n\nLemma beq_n: forall n: nat,\n  beq_nat n n = true.\nProof.\n  induction n as [| n' IH].\n    - reflexivity.\n    - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem bag_theorem :\n  forall (v : nat) (b : bag),\n    (count v (add v b)) = (1 + (count v b)).\nProof.\n  intros.\n  simpl. try reflexivity.\n  rewrite beq_n.\n  reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Raciocinando sobre listas *)\n\n(** Algumas propriedades podem ser provadas\n    somente com [reflexivity]. *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n  Print app. simpl. reflexivity.\nQed.\n\n(** \u00c0s vezes, ser\u00e1 preciso fazer an\u00e1lise de casos. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  (* Observe a quantidade de elementos\n     da segunda lista do destruct. *)\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    simpl. reflexivity.\n  - (* l = cons n l' *)\n    Print length. simpl. reflexivity.\nQed.\n\n(** \u00c0s vezes, ser\u00e1 preciso fazer indu\u00e7\u00e3o. *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  Print app.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl. reflexivity.\n  - (* l1 = cons n l1' *)\n    Print app. simpl.\n    rewrite -> IHl1'. reflexivity.\nQed.\n\n(** Considere a seguinte defini\u00e7\u00e3o de [rev]. *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:\n  rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:\n  rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** Vamos tentar provar a seguinte afirma\u00e7\u00e3o.\n    Observe que ficamos \"travados\" no segundo caso. *) \n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. rewrite <- IHl'.\n    (* Como continuar a partir daqui? *)\nAbort.\n\n(** Vamos definir um teorema auxiliar a partir\n    do ponto em que ficamos \"travados\" no\n    teorema anterior. Contudo, vamos tornar\n    o teorema auxiliar o mais geral poss\u00edvel:\n    [l1] e [l2] no lugar de [rev l'] e [n]. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n(** Agora concluimos a prova de [rev_length]. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    (* Observe o rewrite  com duas t\u00e1ticas *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(** **** Exercise: (list_exercises)  *)\n(** Prove os seguintes teoremas. *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [| n' l' IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  induction l1 as [|n1 l1' IH].\n  - intros l2. simpl. Search (_ ++ []). rewrite app_nil_r.\n    reflexivity.\n  - intros l2. simpl. rewrite IH, app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| n l' IH].\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. simpl. rewrite IH. 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' IH].\n  - simpl. reflexivity.\n  - simpl. destruct n1.\n    + rewrite IH. reflexivity.\n    + rewrite IH. reflexivity.\nQed.\n\n(** **** Exercise: (beq_natlist)  *)\n(** Complete a defini\u00e7\u00e3o de [beq_natlist], que\n    compara listas de n\u00fameros. Veja os exemplos.\n    Em seguida, prove o teorema [beq_natlist_refl]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | [] =>\n    match l2 with\n    | [] => true\n    | (n2 :: l2') => false\n    end\n  | (n1 :: l1') => \n    match l2 with\n    | [] => false\n    | (n2 :: l2') => beq_nat n1 n2 && beq_natlist l1' l2'\n    end\n  end.\n  \n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof.\n  reflexivity.\nQed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof.\n  reflexivity.\nQed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [| n l' IH].\n  - reflexivity.\n  - simpl. rewrite IH. Search beq_nat.\n    rewrite beq_n. simpl. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Options *)\n\n(** Considere a seguinte implementa\u00e7\u00e3o de uma\n    fun\u00e7\u00e3o que retorna o i-\u00e9simo elemento\n    de uma lista. *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* um valor arbitr\u00e1rio! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** Outra alternativa seria considerar um\n    elemento padr\u00e3o -- ver defini\u00e7\u00e3o de [hd].\n\n    Uma melhor solu\u00e7\u00e3o \u00e9 definir um \"option\".\n    Similar ao conceito de \"maybe\" em Haskell. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** Veja agora a fun\u00e7\u00e3o [nth_error]. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 :\n  nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 :\n  nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 :\n  nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** A seguir, uma outra possibilidade de\n    implementa\u00e7\u00e3o de [nth_error] usando \"if\". *)\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** No entanto, cuidado com o \"if\". *)\n\nInductive tipo : Type :=\n  | cons1 : tipo\n  | cons2 : tipo.\n\nDefinition beq_tipo (n m : nat) : tipo :=\n  if beq_nat n m then cons2 else cons1.\n\nDefinition teste_if (n m : nat) : bool :=\n  if beq_tipo n m then true\n  else false.\n\nCompute (teste_if 2 2).\n\n(** O \"if\" s\u00f3 pode ser aplicado a tipos\n    indutivos com dois construtores. *)\n\n(** A fun\u00e7\u00e3o a seguir retira o [nat] encapsulado\n    no [natoption]. Observe aqui o uso do default. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: (hd_error)  *)\n(** Use a ideia do \"option\" e atualize\n    a defini\u00e7\u00e3o da fun\u00e7\u00e3o [hd]. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | [] => None\n  | h :: t => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof.\n  reflexivity.\nQed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof.\n  reflexivity.\nQed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof.\n  reflexivity.\nQed.\n\n(** **** Exercise: (option_elim_hd)  *)\n(** Prove o seguinte teorema relacionando\n    [hd_error] com [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default.\n  destruct l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\n\n(* ############################################### *)\n(** * Mapeamentos parciais *)\n\n(** Veja a seguinte defini\u00e7\u00e3o de mapeamentos parciais,\n    similar aos tipos map ou dictionary das\n    principais linguagens de programa\u00e7\u00e3o.\n\n    Inicialmente, definimos a \"chave\": o [id]. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: (beq_id_refl)  *)\nTheorem beq_id_refl :\n  forall x, true = beq_id x x.\nProof.\n  intros x. destruct x. simpl.\n  Search beq_nat. rewrite NatList.beq_n.\n  reflexivity.\nQed.\n\n(** Agora, o tipo de mapeamentos parciais *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** Logo, existem duas maneiras de construir\n    [partial_map]: usando o construtor [empty],\n    representando o mapeamento vazio; usando\n    o construtor [record], passando uma chave,\n    um n\u00famero e um mapeamento existente.\n\n    A fun\u00e7\u00e3o [update] atualiza um mapeamento.\n    Observe que, conceitualmente, o valor antigo,\n    caso exista, \u00e9 mantido no mapeamento. O\n    primeiro valor ser\u00e1 o mais recente. *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nExample test_partial_map1 :\n  (update empty (Id 0) 3)\n  = (record (Id 0) 3 empty).\nProof.\n    simpl. reflexivity.\nQed.\n\nExample test_partial_map2 :\n  (update (record (Id 0) 2 empty) (Id 0) 3)\n  = (record (Id 0) 3 (record (Id 0) 2 empty)).\nProof.\n    simpl. reflexivity.\nQed.\n\n(** A fun\u00e7\u00e3o [find] procura por um valor em\n    um mapeamento. Se houver m\u00faltiplos mapeamentos,\n    retorna o primeiro. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n\n(** **** Exercise: (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros d x v. simpl. destruct x.\n  - simpl. rewrite NatList.beq_n. reflexivity.\nQed.\n\n(** **** Exercise: (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false ->\n    find x (update d y o) = find x d.\nProof.\n  intros d x y o.\n  intros. simpl. rewrite H. reflexivity.\nQed.\n\nEnd PartialMap.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Lists\n  https://softwarefoundations.cis.upenn.edu/lf-current/Lists.html\n*)\n(* Site legal: https://pjreddie.com/coq-tactics/*)", "meta": {"author": "gabritto", "repo": "TAES", "sha": "68512767bd3658beae20196f34ba785d001cca9a", "save_path": "github-repos/coq/gabritto-TAES", "path": "github-repos/coq/gabritto-TAES/TAES-68512767bd3658beae20196f34ba785d001cca9a/aula05_listas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.9161096193153989, "lm_q1q2_score": 0.8169966773374097}}
{"text": "Inductive Z : Type :=\n| Pos : nat -> Z\n| Zero : Z\n| Neg : nat -> Z.\n\nDefinition neg (n: Z) : Z :=\nmatch n with\n| Pos k => Neg k\n| Zero => Zero\n| Neg k => Pos k\nend.\n\nDefinition abs (n: Z) : Z :=\nmatch n with\n| Pos k => Pos k\n| Zero => Zero\n| Neg k => Pos k\nend.\n\nDefinition succ (n: Z) : Z :=\nmatch n with\n| Pos k => Pos (S k)\n| Zero => Pos O\n| Neg O => Zero\n| Neg (S n) => Neg n\nend.\n\nDefinition pred (n: Z) : Z :=\nmatch n with\n| Pos (S n) => Pos n\n| Pos O => Zero\n| Zero => Neg O\n| Neg n => Neg (S n)\nend.\n\nTheorem one_is_zero_succ : Pos O = succ Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem succ_S : forall n: nat, Pos (S n) = succ (Pos n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem minus_one_is_zero_pred : Neg O = pred Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem pred_S : forall n: nat, Neg (S n) = pred (Neg n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem Z_ind' (P : Z -> Prop) (base: P Zero) (suc: forall z: Z, P z -> P (succ z)) \n  (pre: forall z: Z, P z -> P (pred z)) : forall z: Z, P z.\nProof.\n  intro z. destruct z.\n  - induction n.\n    + rewrite one_is_zero_succ. apply suc. assumption.\n    + rewrite succ_S. apply suc. assumption.\n  - assumption.\n  - induction n.\n    + rewrite minus_one_is_zero_pred. apply pre. assumption.\n    + rewrite pred_S. apply pre. assumption.\nQed.\n\nTheorem Z_ind'' (P : Z -> Prop) (base: P Zero) (base_pos: P (Pos O)) (base_neg: P (Neg O))\n  (suc: forall n: nat, P (Pos n) -> P (Pos (S n))) \n  (pre: forall n: nat, P (Neg n) -> P (Neg (S n))) : forall z: Z, P z.\nProof.\n  intro z. destruct z.\n  - induction n.\n    + assumption.\n    + apply suc. assumption.\n  - assumption.\n  - induction n.\n    + assumption.\n    + apply pre. assumption.\nQed.\n\nTheorem neg_neg: forall n : Z, neg (neg n) = n.\nProof.\n  intro n. destruct n; cbn; reflexivity.\nQed.\n\nTheorem abs_impotent: forall n : Z, abs n = abs (abs n).\nProof.\n  intro n. destruct n; cbn; reflexivity.\nQed.\n\nTheorem succ_pred : forall n: Z, succ (pred n) = n.\nProof.\n  intro n. induction n.\n  - destruct n; cbn; trivial.\n  - cbn. trivial.\n  - destruct n; cbn; trivial.\nQed.\n\nTheorem pred_succ : forall n: Z, pred (succ n) = n.\nProof.\n  intro n. induction n.\n  - destruct n; cbn; trivial.\n  - cbn. trivial.\n  - destruct n; cbn; trivial.\nQed.\n\n\n\n\n\n\n\n(* add *)\n\nFixpoint map_n {A: Type} (n: nat) (f: A -> A) (x: A) : A :=\nmatch n with\n| O => x\n| S n' => f (map_n n' f x)\nend.\n\nDefinition add (a b : Z) : Z :=\nmatch a with \n| Pos n => map_n (S n) succ b\n| Zero => b\n| Neg n => map_n (S n) pred b\nend.\n\nTheorem add_r_zero : forall x: Z, add x Zero = x.\nProof.\n  induction x using Z_ind''; trivial.\n  - cbn; rewrite succ_S; f_equal; apply IHx.\n  - cbn; rewrite pred_S; f_equal; apply IHx.\nQed.\n\nTheorem add_r_succ : forall x y: Z, add x (succ y) = succ (add x y).\nProof.\n  intros x y. revert x. induction x using Z_ind''; trivial.\n  - cbn. rewrite pred_succ. rewrite succ_pred. trivial.\n  - cbn in *. f_equal. apply IHx.\n  - cbn in *. rewrite succ_pred. rewrite succ_pred in IHx. rewrite IHx. trivial.\nQed.\n\nTheorem add_r_pred : forall x y: Z, add x (pred y) = pred (add x y).\nProof.\n  intros x y. revert x. induction x using Z_ind''; trivial.\n  - cbn. rewrite pred_succ. rewrite succ_pred. trivial.\n  - cbn in *. rewrite pred_succ in *. rewrite IHx. trivial.\n  - cbn in *. f_equal. apply IHx.\nQed.\n\nTheorem add_sym: forall x y: Z, add x y = add y x.\nProof.\n  intro x. induction x using Z_ind''; intro y.\n  - rewrite add_r_zero. cbn. trivial.\n  - cbn. rewrite one_is_zero_succ. rewrite add_r_succ. rewrite add_r_zero. trivial.\n  - cbn. rewrite minus_one_is_zero_pred. rewrite add_r_pred.\n    rewrite add_r_zero. trivial.\n  - cbn. rewrite succ_S. rewrite add_r_succ. f_equal. apply IHx.\n  - cbn. rewrite pred_S. rewrite add_r_pred. f_equal. apply IHx.\nQed.\n\nTheorem neg_succ : forall x: Z, neg (succ x) = pred (neg x).\nProof.\n  destruct x.\n  - cbn. trivial.\n  - cbn. trivial.\n  - destruct n; cbn; trivial.\nQed.\n\nTheorem neg_pred : forall x: Z, neg (pred x) = succ (neg x).\nProof.\n  destruct x.\n  - destruct n; cbn; trivial.\n  - cbn. trivial.\n  - cbn. trivial.\nQed.\n\nTheorem add_pred_succ : forall x y: Z, add (pred x) (succ y) = add x y.\nProof.\n  intros x y. rewrite add_r_succ. rewrite (add_sym (pred x) y). rewrite add_r_pred.\n  rewrite succ_pred. rewrite add_sym. trivial.\nQed.\n\nTheorem neg_is_add_inv : forall x: Z, add x (neg x) = Zero.\nProof.\n  induction x using Z_ind''; trivial.\n  - rewrite succ_S. rewrite neg_succ. rewrite add_sym. rewrite add_pred_succ.\n    rewrite add_sym. assumption.\n  - rewrite pred_S. rewrite neg_pred. rewrite add_pred_succ. assumption.\nQed.\n\n\nTheorem add_l_succ : forall x y: Z, add (succ x) y = succ (add x y).\nProof.\n  intros x y. rewrite (add_sym (succ x) y). rewrite add_r_succ. f_equal.\n  apply add_sym.\nQed.\n\nTheorem add_succ_swap : forall x y: Z,  add x (succ y) = add (succ x) y.\nProof.\n  intros x y. rewrite add_r_succ. rewrite add_l_succ. trivial.\nQed.\n\nTheorem add_l_pred : forall x y: Z, add (pred x) y = pred (add x y).\nProof.\n  intros x y. rewrite (add_sym (pred x) y). rewrite add_r_pred. f_equal.\n  apply add_sym.\nQed.\n\nTheorem add_pred_swap : forall x y: Z, add x (pred y) = add (pred x) y.\nProof.\n  intros x y. rewrite add_r_pred. rewrite add_l_pred. trivial.\nQed.\n\nTheorem add_assoc : forall x y z: Z, add (add x y) z = add x (add y z).\nProof.\n  intros x y z. revert y. induction x using Z_ind''; intro y.\n  - cbn. trivial.\n  - cbn. apply add_l_succ.\n  - cbn. apply add_l_pred.\n  - rewrite succ_S. rewrite add_l_succ. rewrite add_l_succ. rewrite add_l_succ. f_equal.\n    apply IHx.\n  - rewrite pred_S. rewrite add_l_pred. rewrite add_l_pred. rewrite add_l_pred. f_equal.\n    apply IHx.\nQed.\n\nTheorem add_one : forall x: Z, add x (Pos O) = succ x.\nProof.\n  intro x. rewrite one_is_zero_succ. rewrite add_r_succ. rewrite add_r_zero. trivial.\nQed.\n\nTheorem add_minus_one : forall x: Z, add x (Neg O) = pred x.\nProof.\n  intro x. rewrite minus_one_is_zero_pred. rewrite add_r_pred.\n  rewrite add_r_zero. trivial.\nQed.\n\nTheorem add_neg : forall x y: Z, add (neg x) (neg y) =  neg (add x y).\nProof.\n  intro x. induction x using Z_ind''; intro y; trivial.\n  - cbn. symmetry. apply neg_succ.\n  - cbn. symmetry. apply neg_pred.\n  - rewrite succ_S. rewrite add_l_succ. rewrite neg_succ. rewrite neg_succ. rewrite <- IHx.\n    rewrite add_l_pred. f_equal.\n  - rewrite pred_S. rewrite add_l_pred, neg_pred, neg_pred. rewrite <- IHx, add_l_succ.\n    f_equal.\nQed.\n\nTheorem add_r_neg : forall x y: Z, add x (neg y) =  neg (add (neg x) y).\nProof.\n  intro x. induction x using Z_ind''; intro y; trivial.\n  - cbn. rewrite neg_pred. trivial.\n  - cbn. rewrite neg_succ. trivial.\n  - rewrite succ_S. rewrite add_l_succ. rewrite IHx. rewrite neg_succ, add_l_pred, neg_pred.\n    f_equal. \n  - rewrite pred_S, add_l_pred, neg_pred, add_l_succ, neg_succ. \n    f_equal. apply IHx.\nQed.\n\nTheorem add_l_neg : forall x y: Z, add (neg x) y =  neg (add x (neg y)).\nProof.\n  intros x y. rewrite add_sym. rewrite add_r_neg. rewrite add_sym. trivial.\nQed.\n\n\n\n\n\n\n\n(* mul *)\n  \nDefinition mul (a b: Z) : Z :=\nmatch a with \n| Pos n => map_n (S n) (add b) Zero\n| Zero => Zero\n| Neg n => neg (map_n (S n) (add b) Zero)\nend.\n\nDefinition id {A: Type} (x: A) := x.\n\nTheorem mul_r_zero : forall x: Z, mul x Zero = Zero.\nProof.\n  intros x. destruct x.\n  - cbn. induction n; cbn; auto.\n  - cbn. auto.\n  - cbn. induction n; cbn; auto.\nQed.\n\nTheorem mul_r_one : forall x: Z, mul x (Pos O) = x.\nProof.\n  induction x using Z_ind''; trivial.\n  - cbn. rewrite succ_S. f_equal. assumption.\n  - cbn. rewrite pred_S. rewrite neg_succ. f_equal. assumption. \nQed.\n\nTheorem mul_r_minus_one : forall x: Z, mul x (Neg O) = neg x.\nProof.\n  induction x using Z_ind''; trivial.\n  - cbn. rewrite pred_S. f_equal. assumption.\n  - cbn. rewrite succ_S. rewrite neg_pred. f_equal. assumption. \nQed.\n\nTheorem mul_r_succ : forall x y: Z, mul x (succ y) = add (mul x y) x.\nProof.\n  intros x y. revert x. induction x using Z_ind''; trivial.\n  - cbn. rewrite add_r_zero. rewrite add_r_zero. rewrite add_one. trivial.\n  - cbn. rewrite add_r_zero. rewrite add_r_zero. rewrite add_minus_one. apply neg_succ.\n  - cbn in *. rewrite IHx. rewrite add_l_succ. rewrite succ_S.\n    rewrite add_r_succ. f_equal. rewrite add_assoc. rewrite add_assoc.\n    rewrite add_assoc. trivial.\n  - cbn in *. rewrite pred_S. rewrite <- add_neg, IHx, <- add_neg,  <- add_neg.\n    rewrite <- add_neg. rewrite add_r_pred, neg_succ, add_l_pred. f_equal.\n    rewrite add_assoc, add_assoc, add_assoc. trivial.\nQed.\n\nTheorem mul_r_pred : forall x y: Z, mul x (pred y) = add (mul x y) (neg x).\nProof.\n  intros x y. revert x. induction x using Z_ind''; trivial.\n  - cbn. rewrite add_r_zero. rewrite add_r_zero. rewrite add_minus_one. trivial.\n  - cbn. rewrite add_r_zero, add_r_zero. rewrite add_one. apply neg_pred.\n  - cbn in *. rewrite IHx. rewrite add_l_pred. rewrite pred_S.\n    rewrite add_r_pred. f_equal. rewrite add_assoc. rewrite add_assoc.\n    rewrite add_assoc. trivial.\n  - cbn in *. rewrite succ_S. rewrite <- add_neg, IHx, <- add_neg,  <- add_neg.\n    rewrite <- add_neg. rewrite add_r_succ, neg_pred, add_l_succ. f_equal.\n    rewrite add_assoc, add_assoc, add_assoc. trivial.\nQed.\n\nTheorem mul_sym : forall x y: Z, mul x y = mul y x.\nProof.\n  intros x. induction x using Z_ind''; intro y.\n  - rewrite mul_r_zero. cbn. trivial.\n  - rewrite mul_r_one. cbn. rewrite add_r_zero. trivial.\n  - rewrite mul_r_minus_one. cbn. rewrite add_r_zero. trivial.\n  - rewrite succ_S. rewrite mul_r_succ. rewrite <- IHx. cbn. rewrite add_assoc.\n    f_equal. apply add_sym.\n  - rewrite pred_S. rewrite mul_r_pred. rewrite <- IHx. cbn.\n    rewrite <- add_neg, <- add_neg. rewrite add_sym. trivial.\nQed.\n\nTheorem mul_l_succ : forall x y: Z, mul (succ x) y = add (mul x y) y.\nProof.\n  intros x y. rewrite mul_sym. rewrite mul_r_succ. rewrite (mul_sym x y). trivial.\nQed.\n\nTheorem mul_l_pred : forall x y: Z, mul (pred x) y = add (mul x y) (neg y).\nProof.\n  intros x y. rewrite mul_sym. rewrite mul_r_pred. rewrite (mul_sym x y). trivial.\nQed.\n\nTheorem mul_r_neg : forall x y: Z, mul x (neg y) = neg (mul x y).\nProof.\n  intros x. induction x using Z_ind'; intro y; trivial.\n  - rewrite mul_l_succ, mul_l_succ.\n    rewrite IHx. rewrite add_neg. trivial.\n  - rewrite mul_l_pred, mul_l_pred, IHx.\n    rewrite add_r_neg, neg_neg. trivial.\nQed.\n\nTheorem mul_l_neg : forall x y: Z, mul (neg x) y = neg (mul x y).\nProof.\n  intros x y. rewrite mul_sym, mul_r_neg, mul_sym. trivial.\nQed.\n\nTheorem mul_neg : forall x y: Z, mul (neg x) (neg y) = mul x y.\nProof.\n  intros x y. rewrite mul_r_neg, mul_l_neg, neg_neg. trivial.\nQed.\n\nTheorem mul_neg_swap : forall x y: Z, mul (neg x) y = mul x (neg y).\nProof.\n  intros x y. rewrite mul_r_neg, mul_l_neg. trivial.\nQed.\n\nTheorem mul_dist_add : forall x y z: Z, mul x (add y z) = add (mul x y) (mul x z).\nProof.\n  intros x y z. revert x. induction x using Z_ind'; trivial.\n  - rewrite mul_l_succ, mul_l_succ, mul_l_succ. rewrite IHx.\n    rewrite add_assoc, add_assoc. rewrite (add_sym (mul x z) (add y z)). \n    rewrite (add_sym (mul x z) z). rewrite add_assoc. trivial.\n  - rewrite mul_l_pred, mul_l_pred, mul_l_pred. rewrite IHx.\n    rewrite add_assoc, add_assoc. rewrite (add_sym (neg y) (add (mul x z) (neg z))). \n    rewrite (add_sym y z). rewrite add_assoc. rewrite add_neg. trivial.\nQed. \n\nTheorem mul_assoc : forall x y z: Z, mul (mul x y) z = mul x (mul y z).\nProof.\n  intros x y z. revert y. induction x using Z_ind'; intro y; trivial.\n  - rewrite mul_l_succ. rewrite mul_l_succ.\n    rewrite mul_sym, mul_dist_add. rewrite <- IHx. f_equal; apply mul_sym.\n  - rewrite mul_l_pred, mul_l_pred. rewrite add_r_neg. rewrite mul_l_neg.\n    rewrite add_r_neg. f_equal. rewrite mul_sym, mul_dist_add. f_equal.\n    + rewrite <- IHx. rewrite mul_r_neg. f_equal. rewrite mul_sym. trivial.\n    + apply mul_sym.\nQed.\n\n\n\n(* uniqeu representation *)\n\nRecord Izomorphism (A B: Type) := Izo {\n  izo_fun : A -> B;\n  izo_inv : B -> A;\n  izo_id  : forall x: A, izo_inv (izo_fun x) = x;\n  izo_id' : forall x: B, izo_fun (izo_inv x) = x;\n}.\n\nRecord Integer := Int {\n  v : nat * nat;\n  one_zero : let (x, y) := v in (x = O) \\/ (y = O); \n}.\n\nFixpoint norm (x y : nat) : (nat * nat) :=\nmatch x, y with\n| S x, S y => norm x y\n| _, _ => (x, y)\nend.\n\nDefinition norm' (p: nat * nat) : (nat * nat) := \n  let (x, y) := p in norm x y.\n\nTheorem norm_is_normal (p: nat * nat) : let (x, y) := (norm' p) in (x = O) \\/ (y = O).\nProof.\n  destruct p. revert n0. induction n.\n  - cbn. left. reflexivity.\n  - destruct n0.\n    + cbn. right. reflexivity.\n    + cbn. apply IHn.\nQed.\n\nTheorem norm_is_impotent : forall p: nat * nat, norm' p = norm' (norm' p).\nProof.\n  intro p. destruct p. revert n0. induction n; intro n'.\n  - cbn. reflexivity.\n  - destruct n'; cbn.\n    + reflexivity.\n    + apply IHn.\nQed.\n\nDefinition get_integer (p: nat * nat) : Integer := {|\n  v := norm' p;\n  one_zero := norm_is_normal p;\n|}.\n\nDefinition Z_to_Integer' (z : Z) : nat*nat := \nmatch z with \n| Pos n => (S n, O)\n| Zero => (O, O) \n| Neg n => (O, S n)\nend.\n\nTheorem Z_to_Integer_proof : forall z: Z, let (x, y) := (Z_to_Integer' z) in (x = O) \\/ (y = O).\nProof.\n  intro z. destruct z; cbn; auto.\nDefined.\n\nDefinition Z_to_Integer (z : Z) : Integer := {|\n  v := Z_to_Integer' z;\n  one_zero := Z_to_Integer_proof z;\n|}.\n\nDefinition Integer_to_Z (i : Integer) : Z :=\nmatch v i with\n| (O, O) => Zero\n| (S n, O) => Pos n\n| (O, S n) => Neg n\n| (S n, S n') => Zero\nend.\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/better_integer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.8168192365518445}}
{"text": "Require Export Arith.EqNat. \n\nInductive natlist : Type :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition new_bob (a:bool)(b:bool):bool := if a then b else false.\n\nFixpoint beq_natlist (l : natlist) (m : natlist) : bool :=\nmatch l,m with\n|[] , [] => true\n| _ , [] => false\n|[] , _ => false\n|h :: t , h'::t' =>  new_bob (beq_nat h h') (beq_natlist t t')\nend.\n\nCheck new_bob.\n\nEval compute in (beq_natlist [1;2;3] [4;5;6]).\nEval compute in (beq_natlist [1;1;1] [1;1;1]).\n\nSearchAbout beq_nat.\n\nTheorem beq_nat_refl : forall n: nat, true = beq_nat n n.\nProof.\nintros.\ninduction n. \nsimpl. reflexivity.\nsimpl. rewrite IHn.\nsimpl. reflexivity.\nQed.\n\n\nTheorem beq_natlist_refl : forall l:natlist, true = beq_natlist l l.\nProof.\nsimpl. \ninduction l.\nsimpl. reflexivity.\nsimpl. rewrite <- IHl.\nsimpl. rewrite <- beq_nat_refl.\nsimpl. reflexivity.\nQed.\n\n", "meta": {"author": "psjyothiprasad", "repo": "Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "sha": "bda5df849ce973def8aa145660aa806e7743af35", "save_path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography/Software-Modelling---Theorem-Provers---Program-Verification---Cryptography-bda5df849ce973def8aa145660aa806e7743af35/Exercise1/beq_natlist_refl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.8168188906868267}}
{"text": "Section Sets.\n  (* Extensional: Explicitly spell out all the members of a set.\n     I.e. The set of states in the US is \"Alabama, Alaska, ....\" *)\n  (* Seen this style of definition before... *)\n  Definition Set' (A : Type) := list A.\n\n  (* Intensional: Characteristic 'Function' approach: every input to a\n     boolean valued function which returns true is a member of the\n     set, and is not an element otherwise. *)\n\n  Definition Bool_Set (A : Type) := A -> bool.\n\n  Fixpoint evenb (n:nat) : bool :=\n    match n with\n    | O => true\n    | S O => false\n    | S (S n') => evenb n'\n    end.\n\n  Definition evens : Bool_Set nat := evenb.\n  Definition In_b {A} (a : A) (e : Bool_Set A) : Prop :=\n    e a = true.\n\n  Example even_4 : In_b 4 evens. Proof. unfold In_b. simpl. reflexivity. Qed.\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  (* This encoding of sets means membership is always decideable! *)\nEnd Sets.\n\nSection Fixpoints.\n\n  (* Propositional analogues to Characteristic Function from above.  A\n     set is a property (propositional-valued function), and an object\n     is an element if there is some proof that it satisfies that property. *)\n  Definition PSet (A : Type) := A -> Prop.\n  Definition In {A} (a : A) (e : PSet A) : Prop := e a.\n  Notation \"x '\u2208' e\" := (In x e) (at level 60).\n\n  Definition even x := exists n : nat, x = 2 * n.\n\n  Example even_6 : 6 \u2208 even. Proof. unfold In. exists 3. reflexivity. Qed.\n\n  Definition Subset {A} (e1 e2 : PSet A) : Prop :=\n    forall x, x \u2208 e1 -> x \u2208 e2.\n\n  Notation \"s1 \u2286 s2\" := (Subset s1 s2) (at level 60).\n\n  Lemma Subset_trans {A} : forall (s1 s2 s3 : PSet A),\n      s1 \u2286 s2 -> s2 \u2286 s3 -> s1 \u2286 s3.\n  Proof.\n    unfold Subset; intros.\n    apply H0.\n    apply H.\n    assumption.\n  Qed.\n\n  Lemma Subset_refl {A} : forall (s1 : PSet A), s1 \u2286 s1.\n  Proof.\n    unfold Subset; intros.\n    assumption.\n  Qed.\n\n  Definition Same_set {A} (s1 s2 : PSet A) := s1 \u2286 s2 /\\ s2 \u2286 s1.\n\n  Lemma Same_set_refl {A} : forall (s1 : PSet A), Same_set s1 s1.\n  Proof.\n    unfold Same_set; split.\n    - apply Subset_refl.\n    - apply Subset_refl.\n  Qed.\n\n  Lemma Same_set_sym {A} : forall (s1 s2 : PSet A), Same_set s1 s2 -> Same_set s2 s1.\n  Proof.\n    unfold Same_set; intros s1 s2 [? ?]; split; assumption.\n  Qed.\n\n  Lemma Same_set_trans {A} : forall (s1 s2 s3 : PSet A),\n      Same_set s1 s2 ->\n      Same_set s2 s3 ->\n      Same_set s1 s3.\n  Proof.\n    unfold Same_set; intros s1 s2 s3 [? ?] [? ?]; split.\n    - eapply Subset_trans; eassumption.\n    - eapply Subset_trans; eassumption.\n  Qed.\n\n  Context {U : Type}. (* The type of elements of our set. *)\n  Variable F : PSet U -> PSet U. (* Our generating function-- 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 : PSet U -> PSet U) : Prop :=\n    forall (S S' : PSet U),\n      S \u2286 S' -> F S \u2286 F S'.\n\n  Variable Monotone_F : Monotone F.\n\n  Definition FClosed (S : PSet U) : Prop := F S \u2286 S.\n\n  Definition FConsistent (S : PSet U) : Prop := S \u2286 F S.\n\n  Definition FixedPoint (S : PSet U) : Prop :=\n    FClosed S /\\ FConsistent S.\n\n  Lemma FixedPoint_unfold FP : FixedPoint FP -> Same_set FP (F FP).\n  Proof.\n    unfold Same_set; intros [? ?]; split.\n    - apply H0.\n    - apply H.\n  Qed.\n\n  (* LFP is defined as the intersection of all F-closed sets. An\n     element is in LFP iff it is a member of every F-Closed set. *)\n  Definition LFP : PSet U :=\n    fun a => forall S, FClosed S -> a \u2208 S.\n\n  Theorem LFP_is_FClosed\n    : FClosed LFP.\n  Proof.\n    unfold FClosed.\n    (* By the definition of LFP, it is a subset of every F-Closed set. *)\n    assert (forall (X : PSet U), FClosed X -> LFP \u2286 X).\n    { unfold Subset; intros. apply H0.  assumption. }\n    (* Since F is monotone, the previous fact entails that [F LFP \u2286 F X]\n       for every F-Closed set X.*)\n    assert (forall (X : PSet U), FClosed X -> F LFP \u2286 F X).\n    { intros. apply Monotone_F. apply H. assumption. }\n    (* By transitivity of the subset relation, it follows that [F LFP \u2286 X]\n       for every F-Closed set X.  *)\n    assert (forall (X : PSet U), FClosed X -> F LFP \u2286 X).\n    { intros. apply Subset_trans with (s2 := F X).\n      - apply H0. assumption.\n      - apply H1. }\n    (* Now we just need to show that every element of [F LFP] is an\n       element of [LFP], By definition, this is equivalent to showing\n       that every element of [F LFP] is also a member of every\n       F-Closed set. This follows from the fact that [F LFP] is a\n       the previously proof that [F LFP] is a subset of every F-Closed set! *)\n    unfold Subset; intros ? ? S FClosed_S.\n    apply H1.\n    assumption.\n    assumption.\n  Qed.\n\n  Theorem LFP_is_FConsistent\n    : FConsistent LFP.\n  Proof.\n    unfold FConsistent; intros.\n    (*By the previous lemma, we know that F LFP \u2286 LFP. By monotonicity of\n       F, F (F LFP) \u2286 F LFP. *)\n    assert (F (F LFP) \u2286 F LFP).\n    { apply Monotone_F. apply LFP_is_FClosed. }\n    (* By definition, this means [F LFP] is F-Closed. *)\n    assert (FClosed (F LFP)) by apply H.\n    (* Since [F LFP] is F-Closed, it is a superset of LFP. *)\n    intros x In_x.\n    apply In_x.\n    assumption.\n  Qed.\n\n  Theorem LFP_is_FixedPoint\n    : FixedPoint LFP.\n  Proof.\n    unfold FixedPoint.\n    split.\n    - apply LFP_is_FClosed; eauto.\n    - apply LFP_is_FConsistent; eauto.\n  Qed.\n\n  Theorem LFP_is_LeastFixedPoint :\n    forall FP, FixedPoint FP -> LFP \u2286 FP.\n  Proof.\n    unfold FixedPoint; intros FP [? ?].\n    intros x In_x.\n    apply In_x.\n    apply H.\n  Qed.\n\n  Corollary LFP_unfold : Same_set LFP (F LFP).\n  Proof. apply FixedPoint_unfold. apply LFP_is_FixedPoint. Qed.\n\n  Corollary LFP_fold : Same_set (F LFP) LFP.\n  Proof. apply Same_set_sym. apply LFP_unfold. Qed.\n\n  (* This admits the principle of Induction-- if we can show a set is\n     F-Closed, it follows that every element of LFP is in that set. *)\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  (* GFP is defined as the union of all F-consistent sets.  An\n     element is in GFP iff it is a member of /some/ F-Consistent set.*)\n  Definition GFP : PSet U :=\n    fun a => exists S, FConsistent S /\\ a \u2208 S.\n\n  Lemma GFP_is_FConsistent\n    : FConsistent GFP.\n  Proof.\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 \u2286 F GFP: *)\n    revert x H0; fold (Subset (F X) (F GFP)).\n    (* Since F is monotone, it suffices to show that X \u2286 GFP *)\n    eapply Monotone_F.\n    (* To show X \u2286 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    : FClosed GFP.\n  Proof.\n    intros ? ?.\n    (* By our previous lemma, we know that GFP \u2286 F GFP. By monotonicity of\n       F, F GFP \u2286 F (F GFP). *)\n    assert (F GFP \u2286 F (F GFP)).\n    { apply Monotone_F.\n      apply GFP_is_FConsistent. }\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    split; assumption.\n  Qed.\n\n  Theorem GFP_is_FixedPoint\n    : FixedPoint GFP.\n  Proof.\n    unfold FixedPoint.\n    split.\n    - apply GFP_is_FClosed; eauto.\n    - apply GFP_is_FConsistent; eauto.\n  Qed.\n\n  Theorem GFP_is_Greatest_FixedPoint\n    : forall FP, FixedPoint FP -> FP \u2286 GFP.\n  Proof.\n    intros ? [? ?].\n    intros x In_x.\n    exists FP; split; assumption.\n  Qed.\n\n  (* This admits the principle of Co-Induction-- if we can show a set is\n     F-Consistent, every element of that set is also in GFP. *)\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\n(*A quick example of the principle of Induction *)\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\nNotation \"x '\u2208' e\" := (In x e) (at level 60).\nNotation \"s1 \u2286 s2\" := (Subset s1 s2) (at level 60).\n\nLemma In_pair_inv {A B} :\n  forall ab (s : PSet (Datatypes.prod A B)),\n    ab \u2208 s -> exists a b, ab = Datatypes.pair a b /\\ s (Datatypes.pair a b).\nProof.\n  destruct ab; eauto.\nQed.\n\nLtac In_inversion :=\n  repeat match goal with\n           H : @In (Datatypes.prod ?A ?B) ?ab _ |- _ =>\n           apply In_pair_inv in H;\n           destruct H as [? [? [? H] ] ]; subst ab\n         | H : @In _ _ _ |- _ => unfold In in H\n         | H : _ /\\ _ |- _ => destruct H\n         | H : _ \\/ _ |- _ => destruct H\n         | H : exists _, _ |- _ => destruct H\n         | H : _ = _ |- _ => solve [discriminate]\n         end.\n\nLtac In_intro :=\n  repeat match goal with\n         | |- In _ _ => unfold In\n         | |- _ = _ => solve [intuition]\n         end.\n", "meta": {"author": "bendy", "repo": "SFExtras", "sha": "a9676cc28a5d3d27d09da3e620ca6e7ceb43de65", "save_path": "github-repos/coq/bendy-SFExtras", "path": "github-repos/coq/bendy-SFExtras/SFExtras-a9676cc28a5d3d27d09da3e620ca6e7ceb43de65/DenotationalSemantics/Fixpoints.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.8168188745913926}}
{"text": "(* Exercise: 1 star (nandb) *)\nDefinition nandb (b1 : bool) (b2 : bool) : bool :=\n  match b1 with\n    | false => true\n    | true => negb b2\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. reflexivity. Qed.\n\n(* Exercise: 1 star (andb3) *)\nDefinition andb3 (b1 : bool) (b2 : bool) (b3 : bool) : bool :=\n  match b1 with\n    | true => match b2 with\n                | true => b3\n                | false => false\n              end\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(* Exercise: 1 star (factorial) *)\nFixpoint factorial (n : nat) : nat :=\n  match n with\n    | 0 => 1\n    | S n' => (S n') * (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\n(* Exercise: 2 star (blt_nat) *)\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n    | 0 =>  true\n    | S n' =>  match m with\n                | 0 => false\n                | S m' => ble_nat n' m'\n              end\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool := ble_nat (n + 1) 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(* Exercise: 1 star (plus_id_exercise) *)\nTheorem plus_id_exercise:\n  forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H1.\n  intros H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  reflexivity.\nQed.\n\n(* Exercise: 2 stars (mult_S_1) *)\nTheorem mult_S_1:\n  forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(* Exercise: 1 star (zero_nbeq_plus_1) *)\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | 0 => match m with\n         | 0 => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | 0 => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem zero_nbeq_plus_1 :\n  forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n. destruct n as [| n'].\n  (* CASE n = 0 *)\n    simpl. reflexivity.\n  (* CASE n = S n' *)\n    simpl. reflexivity.\nQed.\n\n(* Exercise: 2 stars (boolean functions) *)\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* Exercise: 2 stars (andb_eq_orb) *)\nLemma andb_t_f : andb true false = false.\nProof. reflexivity. Qed.\n\nLemma andb_f_t : andb false true = false.\nProof. reflexivity. Qed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) -> b = c.\nProof.\n  intros b c H. destruct b.\n  (* CASE b = true *)\n    destruct c.\n    (* CASE c = true *)\n      reflexivity.\n    (* CASE c = false *)\n      rewrite <- andb_t_f.\n      rewrite H.\n      reflexivity.\n  (* CASE b = false *)\n    destruct c.\n    (* CASE c = true *)\n      rewrite <- andb_f_t.\n      rewrite H.\n      reflexivity.\n    (* CASE C = false *)\n      reflexivity.\nQed.\n\n(* Exercise: 3 stars (binary) *)\nInductive bin : Type := \n  | O : bin\n  | twice : bin -> bin\n  | one_more_twice : bin -> bin.\n\nFixpoint add1_bin (b : bin) : bin :=\n  match b with\n    | O => one_more_twice O\n    | twice b' => one_more_twice b'\n    | one_more_twice b' => twice (add1_bin b')\n  end.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | O => 0\n    | twice b' => 2 * (bin_to_nat b')\n    | one_more_twice b' => S (2 * (bin_to_nat b'))\n  end.\n\nExample test_add1_bin0 : bin_to_nat (add1_bin O) = S (bin_to_nat O).\nProof. reflexivity. Qed.\nExample test_add1_bin1 : bin_to_nat (add1_bin (one_more_twice O)) = S (bin_to_nat (one_more_twice O)).\nProof. reflexivity. Qed.\nExample test_add1_bin5 : bin_to_nat (add1_bin (one_more_twice (twice (one_more_twice O)))) =\n  S (bin_to_nat (one_more_twice (twice (one_more_twice O)))).\nProof. reflexivity. Qed.\n\n(* Exercise: 2 stars, optional (decreasing) *)\n(*\nFixpoint terminating_but_unacceptable (x : nat) : nat :=\n  match x with\n    | 0 => 0\n    | S x' => terminating_but_unacceptable ((x' * 2) - (x' * 3))\n  end.\n*)", "meta": {"author": "mkolosick", "repo": "Software-Foundations-Exercises", "sha": "5f0f4d2653ff6118aef58c6953b6ba0f102e3516", "save_path": "github-repos/coq/mkolosick-Software-Foundations-Exercises", "path": "github-repos/coq/mkolosick-Software-Foundations-Exercises/Software-Foundations-Exercises-5f0f4d2653ff6118aef58c6953b6ba0f102e3516/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.8166304891968118}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import PeanoNat.\nRequire Import Lia.\nRequire Import Bool.\n \n(* ----- Definition of insertion sort ----- *)\n \n(* Inserts integer i into the list l, as part of insertion sort.\nisSorted l should hold. *)\nFixpoint insert (n : nat) (l : list nat) : list nat :=\n  match l with\n    nil => [n]\n  | head :: tail => if n <=? head then n :: l else head :: insert n tail\n  end.\n \n(* Insertion sort of list l *)\nFixpoint sort (l : list nat) : list nat :=\n  match l with\n    nil => nil\n  | head :: tail => insert head (sort tail)\n  end.\n \n(* Example test *)\nCompute sort [10;8;3;5;6;7;1;2;4;9].\n \n(* ----- Definition of sorted lists ----- *)\n \nFixpoint isSorted (l : list nat) : Prop :=\n  match l with\n    | nil => True\n    | [x] => True\n    | x :: ((y :: _) as tail) => x <= y /\\ isSorted tail\n  end.\n \n(* ----- Definition of permutations ----- *)\n \nFixpoint count (x : nat) (l : list nat) : nat :=\n  match l with\n    nil => 0 |\n    head :: tail => if x =? head then S (count x tail) else count x tail\n  end.\n \nDefinition isPermutation (l1 l2 : list nat) :=\nforall x : nat, count x l1 = count x l2.\n \n(* ----- Proof of sortedness ----- *)\n \n(* Insertion of an element keeps a sorted list still sorted *)\nLemma insert_keepsListSorted: forall x : nat, forall l : list nat,\nisSorted l -> isSorted (insert x l).\nProof.\nintros x l H. induction l; simpl.\n  - trivial.\n  - case_eq (x <=? a); intros; simpl.\n    + apply Nat.leb_le in H0. split.\n      * trivial.\n      * assumption.\n    + apply Nat.leb_gt in H0. destruct l; simpl.\n      * lia.\n      * firstorder. case_eq (x <=? n).\n        ** intro. firstorder.\n           *** lia.\n           *** apply Nat.leb_le. assumption.\n        ** firstorder. replace (n :: insert x l) with (insert x (n :: l)).\n           *** assumption.\n           *** simpl. case_eq (x <=? n); intro; simpl.\n             **** absurd ((x <=? n) = true); auto. rewrite <- not_false_iff_true in H4. auto.\n             **** trivial.\nQed.\n \nTheorem sort_createsSortedness : forall l : list nat, isSorted (sort l).\nProof.\nintros l. induction l.\n  - compute. trivial.\n  - simpl. apply insert_keepsListSorted. trivial.\nQed.\n \n(* ----- Proof of permutation ----- *)\n \nLemma insert_sameXIncreasesCount:\nforall x : nat, forall l : list nat, count x (insert x l) = S (count x l).\nProof.\nintros x l.\ninduction l.\n  - simpl. rewrite Nat.eqb_refl. trivial.\n  - simpl. case_eq (x <=? a); intro; simpl.\n    + replace (x =? x) with true. trivial. rewrite Nat.eqb_refl. trivial.\n    + case_eq (x =? a); intro; simpl; rewrite IHl; trivial.\nQed.\n \nLemma insert_differentXDoesNotChangeCount:\nforall x y : nat, forall l : list nat, (x =? y) = false -> count x (insert y l) = count x l.\nProof.\nintros x y l H0. induction l; simpl.\n  - rewrite H0. trivial.\n  - case_eq (x =? a); intro; simpl.\n    + case (y <=? a); simpl.\n      * rewrite H0. rewrite H. trivial.\n      * rewrite H. rewrite IHl. trivial.\n    + case_eq (y <=? a); intro; simpl.\n      * rewrite H0. rewrite H. trivial.\n      * rewrite H. rewrite IHl. trivial.\nQed.\n \nTheorem sort_createsPermutation: forall l : list nat, isPermutation l (sort l).\nProof.\nintros l.\ninduction l; simpl; intro.\n  - reflexivity.\n  - simpl. case_eq (x =? a); intro; simpl.\n    + replace a with x.\n      * rewrite insert_sameXIncreasesCount. rewrite IHl. trivial.\n      * apply Nat.eqb_eq. assumption.\n    + rewrite insert_differentXDoesNotChangeCount.\n      * rewrite IHl. trivial.\n      * assumption.\nQed.\n \n(* ----- Full definition of total correctness ----- *)\n \n(* Beware that sort is defined structurally inductive on lists and it is primitive recursive.\nIn Coq's calculus of inductive constructions, sort is terminating.*)\nTheorem sort_correctness: forall l : list nat,\nisPermutation l (sort l) /\\ isSorted (sort l).\nProof.\nintros l. split.\n  - apply sort_createsPermutation.\n  - apply sort_createsSortedness.\nQed.", "meta": {"author": "daipenger", "repo": "VerifiedInsertionSort", "sha": "3ac23cfe6e1d15354f2b69fef14c04b47d1b446d", "save_path": "github-repos/coq/daipenger-VerifiedInsertionSort", "path": "github-repos/coq/daipenger-VerifiedInsertionSort/VerifiedInsertionSort-3ac23cfe6e1d15354f2b69fef14c04b47d1b446d/insertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.8166304769722824}}
{"text": "Module Playground1.\n\n  Inductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n  Definition pred (n : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => n'\n    end.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\n\nCheck (S (S (S (S O)))).\nEval compute in (minustwo 4).\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n : nat) : bool := negb (evenb n).\n\nExample test_oddb1 : (oddb (S O)) = true.\nProof. reflexivity. Qed.\n\nExample test_oddb2 : (oddb (S (S (S (S O))))) = false.\nProof. 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 compute in (plus (S (S (S O))) (S (S O))).\n\n  Fixpoint mult (n : nat) (m : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n    end.\n\n  Example test_mult1 : (mult 3 3) = 9.\n  Proof. reflexivity. Qed.\n\n  Fixpoint minus (n m:nat) : nat :=\n    match n, m with\n    | O, _ => O\n    | S _, O => n\n    | S n', S m' => minus n' m'\n    end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S p => mult base (exp base p)\n  end.\n\nFixpoint factorial (n : nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mult (S n') (factorial n')\n  end.\n\nExample test_factorial1 : (factorial 3) = 6.\nProof.\n  reflexivity.\nQed.\n\nExample test_factorial2 : (factorial 5) = (mult 10 12).\nProof.\n  reflexivity.\nQed.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem plus_n_O : forall n : nat, n = 0 + n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem plus_id_example : forall n m : nat,\n    n = m ->\n    n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\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 H0.\n  rewrite -> H.\n  rewrite -> H0.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n    (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_1 : forall n m : nat,\n    m = S n ->\n    m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem plus_1_neq_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\nInductive even : nat -> Prop :=\n| zero_is_even : even 0\n| S_of_odd_is_even : (forall n : nat, odd n -> even (S n))\nwith odd : nat -> Prop :=\n| S_of_even_is_odd : (forall n : nat, even n -> odd (S n)).\n\n", "meta": {"author": "cbresendiz1", "repo": "coq-presentation", "sha": "12232a3084b8a51b8e452eeffad3920a2b7d77f7", "save_path": "github-repos/coq/cbresendiz1-coq-presentation", "path": "github-repos/coq/cbresendiz1-coq-presentation/coq-presentation-12232a3084b8a51b8e452eeffad3920a2b7d77f7/playground1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8166304725701341}}
{"text": "Require Export Basics.\n\nTheorem plus_n_0 : forall n : nat,\n  n = n + 0.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity. (* n = 0 *)\n  - simpl. rewrite <- IHn'. reflexivity. (* n = S n' *)\nQed.\n\nTheorem minus_diag : forall n : nat,\n  minus n n = 0.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(* Exercise *)\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m: nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - rewrite <- plus_n_0. simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat, \n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nFixpoint double (n : nat) := \n  match n with\n  | O => O\n  | S n' => S(S(double n'))\nend.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros n.\n  unfold double.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. simpl. rewrite -> plus_n_Sm. 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  \nTheorem nnb : forall b : bool, negb (negb b) = b.\nProof.\n  intros b.\n  induction b.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat, evenb (S n) = negb (evenb n).\nProof.\n  intros n.\n  unfold evenb.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. rewrite -> nnb. reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n). { reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H : n + m = m + n). {\n    rewrite -> plus_comm.\n    reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (H : p + n = n + p). { rewrite -> plus_comm. reflexivity. }\n  rewrite <- plus_comm.\n  rewrite <- H.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nTheorem mult_n_Sm : forall m n : nat,\n  n * S m = n + n * m.\nProof.\n  intros m n.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m as [| m'].\n  - simpl. rewrite -> mult_0_r. reflexivity.\n  - simpl. rewrite -> IHm'. rewrite mult_n_Sm. reflexivity.\nQed.\n\n(* first think about whether \n     (a) it can be proved using only simplification and rewriting, \n     (b) it also requires case analysis (destruct), or \n     (c) it also requires induction.\n*)\n\nTheorem leb_refl : forall n : nat,\n  true = leb n n.\nProof.\n  intros n.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n : nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n.\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  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n  intros n m p.\n  intros H.\n  induction p as [| p'].\n  - simpl. rewrite H. reflexivity.\n  - simpl. rewrite IHp'. reflexivity.\nQed.\n\nTheorem Sn_beq_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  induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n  orb (andb b c)\n      (orb (negb b) (negb c))\n      = true.\nProof.\n  intros b c.\n  destruct b.\n  - simpl.\n    destruct c.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> mult_plus_distr_r. reflexivity.\nQed.\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros n.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  replace (n + p) with (p + n).\n  - rewrite plus_assoc. reflexivity.\n  - rewrite plus_comm. reflexivity.\nQed.\n\n(* TODO: bin_to_nat_pres_incr *)\n\n(* TODO: binary_inverse *)\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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.8164486898645752}}
{"text": "Require Import ZArith.\n\nDefinition pow2_p p := Zpos (iter_pos positive xO xH p).\n\nDefinition mersenne p := (pow2_p p - 1)%Z.\n\nDefinition next_s mp s := (((s*s) - 2) mod mp)%Z.\n\nDefinition lucas_residue p :=\n  let mp := mersenne p in\n  let pm2 := (p-2)%positive in\n  iter_pos Z (next_s mp) 4%Z pm2.\n\nDefinition lucas_test p :=\n  Zeq_bool (lucas_residue p) 0.\n\nDefinition p89 := 89%positive.\nDefinition p521 := 521%positive.\n\nDefinition res := lucas_test p521.\n\nTime Eval native_compute in res. (* p521 *)\n", "meta": {"author": "maximedenes", "repo": "native-compute-bench", "sha": "ac7891508239f9cc1f7ba0190b1814fb152d2126", "save_path": "github-repos/coq/maximedenes-native-compute-bench", "path": "github-repos/coq/maximedenes-native-compute-bench/native-compute-bench-ac7891508239f9cc1f7ba0190b1814fb152d2126/src/Lucas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.8163963316094599}}
{"text": "(* Software Foundations Chapter 6 : Propositions and Evidence *)\nAdd LoadPath \"./sf\".\n(* Add LoadPath \"./bin\". *)\nRequire Export MoreCoq.\nRequire Export Lists.\nRequire Import lesson3_Lists.\n\n\n\n(**************************************************\n  Exercise: 2 stars (b_timesm)\n**************************************************)\n\nInductive beautiful : nat -> Prop :=\n  b_0 : beautiful 0\n| b_3 : beautiful 3\n| b_5 : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\nTheorem b_timesm: forall n m, \n                    beautiful n ->  beautiful (m*n).\nProof.\n  intros n m.\n  induction m as [|mm].\n  Case \"m is zero\".\n  simpl.\n  intros H.\n  apply b_0.\n  Case \"m is some S mm\".\n  rewrite -> mult_comm.\n  rewrite <- mult_n_Sm.\n  intro H.\n  apply b_sum.\n  rewrite -> mult_comm.\n  apply IHmm.\n  apply H.\n  apply H.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star (gorgeous_tree)\n  Write out the definition of gorgeous numbers using inference rule notation.\n**************************************************)\n\n(**\n                    ------------ (g_0)\n                     gorgeous n\n\n\n  \n      gorgeous n                 gorgeous n\n  ------------------ (g_3)    ----------------- (g_5)\n   gorgeous (3 + n)            gorgeous (5 + n)\n\n\n**)\n\n\n\n\n\n(**************************************************\n  Exercise: 1 star (gorgeous_plus13)\n **************************************************)\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\nTheorem gorgeous_plus13: forall n, \n                           gorgeous n -> gorgeous (13+n).\nProof.\n  intros n E.\n  induction E as [|nn|nn].\n  Case \"n is zero\".\n  simpl.\n  apply g_plus3.\n  apply g_plus5.\n  apply g_plus5.\n  apply g_0.\n  rewrite plus_comm with (n:=3) (m:=nn).\n  rewrite plus_assoc.\n  rewrite plus_comm.\n  apply g_plus3.\n  apply IHE.\n  rewrite plus_comm with (n:=5) (m:=nn).\n  rewrite plus_assoc.\n  rewrite plus_comm.\n  apply g_plus5.\n  apply IHE.\nQed.\n\n\n\n(**************************************************\n  Exercise: 2 stars (gorgeous_sum)\n **************************************************)\n\nTheorem gorgeous_sum : forall n m,\n                         gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m E1 E2.\n  induction E1 as [|nn|nn].\n  Case \"gorgeous n base case : n is zero\".\n  simpl.\n  apply E2.\n  Case \"gorgeous n IStep1 -> n is 3 + nn\".\n  rewrite <- plus_assoc.\n  apply g_plus3.\n  apply IHE1.\n  Case \"gorgeous n IStep2 -> n is 5 + nn\".\n  rewrite <- plus_assoc.\n  apply g_plus5.\n  apply IHE1.\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, advanced (beautiful__gorgeous)\n **************************************************)\nTheorem beautiful__gorgeous : forall n, \n                                beautiful n -> gorgeous n.\nProof.\n  intros n E.\n  induction E as [ | | |nn].\n  Case \"n is zero\".\n  apply g_0.\n  Case \"n is three\".\n  rewrite <- plus_0_r.\n  apply g_plus3.\n  apply g_0.\n  Case \"n is five\".\n  rewrite <- plus_0_r.\n  apply g_plus5.\n  apply g_0.\n  Case \"beautiful (nn + m)\".\n  apply gorgeous_sum.\n  apply IHE1.\n  apply IHE2.\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, optional (g_times2)\n  Prove the g_times2 theorem below without using gorgeous__beautiful. You might find the following helper lemma useful.\n**************************************************)\n\nLemma helper_g_times2 : forall x y z, \n                          x + (z + y)= z + x + y.\nProof.\n  intros x y z.\n  rewrite plus_assoc.\n  rewrite plus_comm with (n:=x) (m:=z).\n  reflexivity.\nQed.\n\nTheorem g_times2: forall n, \n                    gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   induction H.\n   Case \"gorgeous 0\".\n   simpl.\n   apply g_0.\n   Case \"gorgeous (3+n)\".\n   rewrite plus_0_r in IHgorgeous.\n   rewrite plus_0_r.\n   rewrite <- plus_assoc.\n   apply g_plus3.\n   rewrite helper_g_times2.\n   rewrite <- plus_assoc.\n   apply g_plus3.\n   apply IHgorgeous.\n   Case \"gorgeous (5+n)\".\n   rewrite plus_0_r in IHgorgeous.\n   rewrite plus_0_r.\n   rewrite <- plus_assoc.\n   apply g_plus5.\n   rewrite helper_g_times2.\n   rewrite <- plus_assoc.\n   apply g_plus5.\n   apply IHgorgeous.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star (double_even)\n **************************************************)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev O\n| ev_SS : forall n:nat, \n            ev n -> ev (S (S n)).\n\nTheorem double_even : forall n,\n                        ev (double n).\nProof.\n  intros n.\n  induction n as [|nn].\n  simpl.\n  apply ev_0.\n  simpl.\n  apply ev_SS.\n  apply IHnn.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star (ev__even)\n  Here is a proof that the inductive definition of evenness implies the computational one.\n **************************************************)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\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(**\n  Could this proof also be carried out by induction on n instead of E? If not, why not?\n**)\n\n(**\n  No - if we use induction on n, we end up having to consider ev (S n). We cannot determine whether S n is even or odd from the form given and have no further evidence for it. Furthermore, we have no mechanism for pulling out the S from ev (S n), and so we cannot apply the inductive hypothesis in any way.\n**)\n\n\n\n(**************************************************\n  Exercise: 1 star (l_fails)\n  The following proof attempt will not succeed.\n     Theorem l : \u2200n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n  Intuitively, we expect the proof to fail because not every number is even. However, what exactly causes the proof to fail?\n **************************************************)\n\n(**\n  This fails for the same reason as the previous problem.\n**)\n\n\n(**************************************************\nExercise: 2 stars (ev_sum)\nHere'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 E1 E2.\n  induction E1 as [| nn E].\n  Case \"ev n is ev_0\".\n  destruct E2 as [|mm E'].\n  SCase \"ev m is ev_0\".\n  simpl.\n  apply ev_0.\n  SCase \"ev m is some ev mm, called E'\".\n  simpl.\n  apply ev_SS.\n  apply E'.\n  Case \"ev_n is some ev nn, called E\".\n  destruct E2 as [|mm E'].\n  rewrite plus_0_r.\n  rewrite plus_0_r in IHE.\n  apply ev_SS.\n  apply IHE.\n  rewrite plus_comm.\n  rewrite <- plus_n_Sm.\n  rewrite <- plus_n_Sm.\n  apply ev_SS.\n  rewrite plus_comm.\n  apply IHE.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star, optional (ev_minus2_n)\n  What happens if we try to use destruct on n instead of inversion on E?\n **************************************************)\nTheorem ev_minus2: forall n,\n                     ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'. Qed.\n\n(** \n  inversion on E gives us some S (S n) to work with. If we destruct, we only get some S n. We can strip the first S with pred, but we will be left with an extra pred and have no way of reducing it to something over which we can apply evidence.\n**)\n\n\n\n(**************************************************\n  Exercise: 1 star (inversion_practice)\n **************************************************)\nTheorem SSSSev__even : forall n,\n                         ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E.\n  inversion E as [|nn E1].\n  inversion E1 as [|nn' E2].\n  apply E2.\nQed.\n\n(**\n  The inversion tactic can also be used to derive goals by showing the absurdity of a hypothesis.\n**)\n\nTheorem even5_nonsense : ev 5 -> 2 + 2 = 9.\nProof.\n  intro E.\n  inversion E as [|n0 E1].\n  inversion E1 as [|n1 E2].\n  inversion E2 as [|n2 E3].\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, advanced (ev_ev__ev)\n  Finding the appropriate thing to do induction on is a bit tricky here:\n **************************************************)\nTheorem ev_ev__ev : forall n m,\n                      ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m Enm En.\n  induction En.\n  Case \"ev n is ev 0\".\n  simpl in Enm.\n  apply Enm.\n  Case \"ev n is ev (S (S n))\".\n  apply IHEn.\n  rewrite plus_comm in Enm.\n  rewrite <- plus_n_Sm in Enm.\n  rewrite <- plus_n_Sm in Enm.\n  apply ev_minus2 in Enm.\n  simpl in Enm.\n  rewrite <- plus_comm in Enm.\n  apply Enm.\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, optional (ev_plus_plus)\n  Here's an exercise that just requires applying existing lemmas. No induction or even case analysis is needed, but some of the rewriting may be tedious.\n**************************************************)\n\nTheorem ev_plus_plus : forall n m p,\n                         ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p Enm Enp.\n  generalize Enm.\n  apply ev_ev__ev.\n  rewrite plus_comm.\n  rewrite <- plus_assoc.\n  rewrite plus_comm.\n  rewrite plus_assoc.\n  rewrite <- plus_assoc with (n:=p+n) (m:=m) (p:=m).\n  rewrite plus_comm with (n:=p) (m:=n).\n  rewrite plus_comm with (n:=n+p) (m:=m+m).\n  generalize Enp.\n  apply ev_sum with (m:=n+p) (n:=m+m).\n  rewrite <- double_plus.\n  apply double_even.\nQed.  \n\n\n\n(**************************************************\n  Exercise: 4 stars (palindromes)\n  A palindrome is a sequence that reads the same backwards as forwards.\n  \n  Define an inductive proposition pal on list X that captures what it means to be a palindrome. (Hint: You'll need three cases. Your definition should be based on the structure of the list; just having a single constructor\n\n  c : \u2200l, l = rev l \u2192 pal l\n\n  may seem obvious, but will not work very well.)\n\nProve that\n   \n  \u2200l, pal (l ++ rev l).\n\nProve that\n \n  \u2200l, pal l \u2192 l = rev l.\n**************************************************)\n\nInductive pal_1 {X : Type} : list X -> Prop :=\n| even_seed : pal_1 []\n| odd_seed : forall x, pal_1 [x]\n| tack_one : forall x l, pal_1 l -> pal_1 (rev l) -> pal_1 (x::(snoc l x)).\n\nInductive pal_2 {X:Type} : list X -> Prop :=\n| empty : pal_2 []\n| one : forall x, pal_2 [x]\n| more : forall x l, pal_2 (l ++ (rev l)) -> pal_2 (x::(snoc (l ++ (rev l)) x)).\n\nTheorem app_nil_end : forall X (l : list X),\n                        l ++ [] = l.\nProof. \n  intros X l. induction l as [|h t].\n  simpl. reflexivity.\n  simpl. rewrite IHt. reflexivity.\nQed.\n\nTheorem distr_rev : forall X (l1 l2 : list X),\n                      rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof. \n  intros X l1 l2.\n  induction l1 as [| h1 t1].\n  simpl. rewrite app_nil_end. reflexivity.\n  simpl. rewrite IHt1. rewrite snoc_with_append. reflexivity.\nQed.\n\nTheorem pal_app_rev_1 : forall X (l:list X) ,\n                        pal_1 (l++(rev l)).\nProof.\n  intros X l. induction l as [|h t].\n  simpl. apply even_seed.\n  simpl. rewrite <- snoc_with_append.\n  apply tack_one.\n  apply IHt.\n  rewrite distr_rev. rewrite rev_involutive. apply IHt.\nQed. \n\nTheorem pal_app_rev_2 : forall X (l : list X),\n                          pal_2 (l++(rev l)).\nProof. \n  intros X l. induction l as [|h t].\n  simpl. apply empty.\n  simpl. rewrite <- snoc_with_append. generalize IHt. \n  apply more with (x:=h).\nQed.\n\nTheorem pal_to_rev_1 : forall X (l : list X),\n                       pal_1 l -> l = rev l.\nProof. \n  intros X l H.\n  induction H as [|x|x ll].\n  Case \"l is empty\".\n  simpl. reflexivity.\n  Case \"l has a single element\".\n  simpl. reflexivity.\n  Case \"l is some arbitrary length palindrome\".\n  simpl. rewrite rev_snoc. \n  simpl. rewrite <- IHpal_1_1. \n  reflexivity.\nQed.\n\nTheorem rev_pal : forall X (l : list X),\n                    l ++ (rev l) = rev (l ++ (rev l)).\nProof.\n  intros X l. induction l as [|h t].\n  simpl. reflexivity.\n  simpl. rewrite <- snoc_with_append. rewrite rev_snoc. rewrite <- IHt.  \n  simpl. reflexivity.\nQed.\n\nTheorem pal_to_rev_2 : forall X (l : list X),\n                         pal_2 l -> l = rev l.\nProof. \n  intros X l H.\n  inversion H as [|x|x ll].\n  simpl. reflexivity.\n  simpl. reflexivity.\n  simpl. rewrite rev_snoc.\n  rewrite <- rev_pal.\n  simpl. reflexivity.\nQed.\n\n(**************************************************\n  Exercise: 5 stars, optional (palindrome_converse)\n  Using your definition of pal from the previous exercise, prove that\n     \u2200l, l = rev l \u2192 pal l.\n**************************************************)\n\nTheorem cons_app : forall X (x : X) (l : list X),\n                     x::l = [x] ++ l.\nProof. \n  intros X x l. destruct l as [|h t].\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\nTheorem snoc_app : forall X (x : X) (l : list X),\n                     snoc l x = l ++ [x].\nProof.\n  intros X x l. induction l as [|h t].\n  simpl. reflexivity.\n  simpl. rewrite IHt. reflexivity.\nQed.\n\nTheorem app_ass_3 : forall X (l1 l2 l3 : list X),\n                    (l1 ++ l2) ++ l3 = l1 ++ l2 ++ l3.\nProof. \n  intros X l1 l2 l3.\n  induction l1 as [|h t].\n  simpl. reflexivity.\n  simpl. rewrite IHt. reflexivity.\nQed.\n\nDefinition tail {X : Type} (l : list X) :=\n  match l with\n    | [] => []\n    | _::t => t\n  end.\n\nDefinition head {X : Type} (l : list X) :=\n  match l with \n    | [] => None\n    | h::_ => Some h\n  end.\n\nTheorem rev_first_last_head : forall X (l : list X),\n                           l = rev l -> head l = head (rev l).\nProof.\n  intros X l H. induction l as [|h t].\n  simpl. reflexivity.\n  simpl. simpl in H. rewrite <- H. simpl. reflexivity.\nQed.\n\nTheorem rev_first_last_tail : forall X (l : list X),\n                                l = rev l -> tail (rev (tail l)) = tail (rev (tail (rev l))).\nProof. \n  intros X l H. rewrite <- H. reflexivity.\nQed.\n\nTheorem rev_first_last_equal : forall X (x: X) (l : list X),\n                                 x::l = rev(x::l) -> Some x = head (rev (x::l)).\nProof. \n  intros X x l H. rewrite <- H. simpl. reflexivity.\nQed.\n\nTheorem palindrome_converse_1 : forall X (l : list X),\n                                l = rev l -> pal_1 l.\nProof. \n  intros X l. induction l as [|h t].\n  Case \"l is empty\".\n  intros H. apply even_seed.\n  Case \"l is not empty\".\n  intros H. rewrite H. simpl.\n  induction t as [|hh tt].\n  simpl. apply odd_seed.\n  \n  \n\nTheorem palindrome_converse : forall l,\n                                l = rev l -> pal_1 l.\nProof.\n  intros l H.  \n  \n\n  rewrite tail_inv with (x:=h).\n  rewrite rev_snoc. \n  assert (tail_rev : forall X (h : X) t,  tail (h :: rev t) = rev (tail (h::t))).\n   intros X h0 t0. simpl. reflexivity.\n  rewrite tail_rev.\n  rewrite <- rev_involutive.\n  rewrite rev_snoc. \n\n  inversion H.\n  induction l as [|h t].\n  Case \"l is empty\".\n  apply even_seed.\n  Case \"l is not empty\".\n  simpl in H. rewrite H.\n  \n  apply pal_to_rev in IHt.\n  \n  apply tack_one in IHt.\n\nTheorem snoc_rev : forall X (h : X) t,\n                    snoc t h = rev (h::rev t).\nProof.\n  intros X h t.\n  simpl.\n  rewrite rev_involutive.\n  reflexivity.\nQed.\n\nTheorem pal_add_one : forall l x,\n                       pal l -> pal (x :: (snoc l x)).\nProof.\n  intros l x H.\n  inversion H as [E| xx ll odd| ll even].\n  Case \"l is the empty palindrome\".\n  simpl.\n  assert (Lem1 : forall X (h : X) t,\n                   h::t = [h] ++ t).\n   intros X h t.\n   simpl.\n   reflexivity.\n  rewrite Lem1.\n  apply even_list.\n  Case \"l is the odd palindrome\".\n  rewrite snoc_with_append.  \n  simpl.\n  rewrite snoc_rev.\n  rewrite rev_involutive.\n  apply odd_list with (x:=xx) (l:=x::ll).\n  Case \"l is the even palindrome\".\n  rewrite snoc_with_append.\n  rewrite snoc_rev.\n  rewrite rev_involutive.\n  apply even_list with (l:=x::ll).\nQed.\n\nTheorem pal_remove_one : forall (X : Type) (l : list X),\n                           l = rev l -> l = match l with\n                                              | [] => []\n                                              | h::t => match (rev t) with\n                                                          | [] => [h]\n                                                          | _::m => h::(snoc (rev m) h)\n                                                        end\n                                            end.\nProof.\n  intros X l H.\n  destruct l as [|h t].\n  Case \"l is empty\".\n  reflexivity.\n  Case \"l is some h::t\".\n  destruct (rev t) as [|h' t'] eqn:revt.\n  SCase \"t is empty\".\n  simpl in H.\n  rewrite revt in H.\n  simpl in H.\n  apply H.\n  SCase \"t is some h'::t'\".\n  inversion H.\n  rewrite revt in H1.\n  simpl in H1.\nAdmitted.\n\n\n\nTheorem palindrome_converse : forall l,\n                                l = rev l -> pal l.\nProof.\n  intros l H.\n  destruct l as [|h t].\n  Case \"l is the empty list\".\n  apply empty.\n  Case \"l is some h::t\".\nAdmitted.\n  \n\n(**************************************************\nExercise: 4 stars, advanced (subsequence)\nA list is a subsequence of another list if all of the elements in the first list occur in the same order in the second list, possibly with some extra elements in between. For example,\n    [1,2,3]\nis 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]\nbut it is not a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\nDefine an inductive proposition subseq on list nat that captures what it means to be a subsequence. (Hint: You'll need three cases.)\nProve that subsequence is reflexive, that is, any list is a subsequence of itself.\nProve that for any lists l1, l2, and l3, if l1 is a subsequence of l2, then l1 is also a subsequence of l2 ++ l3.\n(Optional, harder) Prove that subsequence is transitive \u2014 that is, if l1 is a subsequence of l2 and l2 is a subsequence of l3, then l1 is a subsequence of l3. Hint: choose your induction carefully!\n**************************************************)\n\n\n(**************************************************\nExercise: 2 stars, optional (R_provability)\nSuppose we give Coq the following definition:\n**************************************************)\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(**\n  Which of the following propositions are provable?\n  R 2 [1,0]\n   c2 : R 2 [1,0] -> R (S 2) 2::[1,0]\n        c2 : R 3 [2,1,0]\n   c3 : R (S 1) [1,0] -> R 1 [1,0]\n  R 1 [1,2,1,0]\n  R 6 [3,2,1,0]\n**)\n", "meta": {"author": "madsravn", "repo": "software_foundations", "sha": "2a7cf402b0a05430961018bd113fb4b2ec03b113", "save_path": "github-repos/coq/madsravn-software_foundations", "path": "github-repos/coq/madsravn-software_foundations/software_foundations-2a7cf402b0a05430961018bd113fb4b2ec03b113/lesson6_Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.888758793492457, "lm_q1q2_score": 0.8163073915433654}}
{"text": "Require Export NArith.\nOpen Scope N_scope.\n\nDefinition pos_log2 (p:positive) : N :=\nN.log2 (Npos p).\n\n(** Write a function that given any positive number p, returns a pair\n   of type (n, q) : N * positive such that p = 2^n * q\n\n*)\n\nFixpoint decompose2 (p:positive) : N * positive :=\nmatch p with xH => (0,xH)\n           | xI q => (0, p)\n           | xO q => let d := decompose2 q in (fst d + 1, snd d)\nend.\n\nCompute decompose2 (88%positive).\nCompute decompose2 (1024%positive).\n\n(** binary exponentiation *)\n\nDefinition sqr_pos (p:positive) := (p * p)%positive.\n\nFixpoint binary_pow_aux (x:N)(a:N)(p:positive) : N :=\n match p with xH => a * x\n            | xO q  => binary_pow_aux (x * x) a q\n            | xI q  => binary_pow_aux (x * x)  (a * x ) q\n\nend.\n\nDefinition pow  (x:N) (n : N) :=\n  match n with 0 => 1\n             | Npos 1 => x\n             | Npos p => binary_pow_aux x x (Pos.pred p)\n end.\n\nCompute pow 2 5.\nCompute pow 2 10.\n\n\n\n(** Comparison with N.pow *)\n\nTime Compute 1 ^ 55556666.\n\nTime Compute pow 1 55556666.\n\nDefinition pow_test (x n:N) :=\n  N.eqb (pow x n) (N.pow x n).\n\nCompute pow_test 2  555.\n\n\nFixpoint exp2_pos  (p:positive) : positive :=\n(match p with 1 => 2\n           | p~0 => sqr_pos (exp2_pos p)\n           | p~1 => (sqr_pos (exp2_pos p))~0\n end)%positive.\n\n\nDefinition exp2 (n:N) : positive :=\nmatch n with N0 => xH\n           | Npos p =>  (exp2_pos p)\nend.\n\n\nCompute exp2 10.\n\nCompute exp2 7.\n\n\n\nCompute pos_log2 63%positive.\nCompute pos_log2 1023%positive.\n\n\nDefinition test_exp2 (p:positive) := N.eqb (Npos p)  (pos_log2 (exp2 (Npos p))).\nCompute test_exp2 45%positive.\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch2_types_expressions/SRC/bin_nums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8159470753788265}}
{"text": "Definition nandb (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n  | true => match b2 with\n    | true => false\n    | false => true\n    end\n  | false => true\n  end.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3: bool): bool :=\nmatch b1 with\n  | true => match b2 with\n    | true => match b3 with\n      | true => true\n      | false => false\n      end\n    | false => false\n    end\n  | false => false\n  end.\n\nFixpoint factorial (n: nat) : nat :=\n  match n with\n    | 0 => 1\n    | S n => S n * factorial n\n  end.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\nintros n m o.\nintros H.\nrewrite -> H.\nintros I.\nrewrite -> I.\nreflexivity.\nQed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m' end\n  end.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\nintros n.\ndestruct n as [ | n'].\n- reflexivity.\n- reflexivity.\nQed.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\nintros p.\ndestruct p as [n m].\nsimpl.\nreflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\nintros p.\ndestruct p as [n m].\nsimpl.\nreflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition bag := natlist.\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n    | nil => 0\n    | h :: t => match beq_nat h v with\n      | true => S (count v t)\n      | false => count v t\n     end\n  end.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nsimpl.\nreflexivity.\nQed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nsimpl.\nreflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\nintros s.\nsimpl.\nreflexivity.\nQed.\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\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 (default: nat) (l: natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\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 nil = None.\nreflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nreflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nreflexivity. Qed.\n\nTheorem option_elim_hd : forall (l: natlist) (default: nat),\n  hd default l = option_elim default (hd_error l).\nProof.\nintros l default.\ndestruct l.\nreflexivity.\nreflexivity.\nQed.\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\nintros x.\ndestruct x.\nsimpl.\ninduction n.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n    | empty => None\n    | record y v d' => if beq_id x y\n      then Some v\n      else find x d'\n  end.\n\nDefinition update (d: partial_map) (x: id) (value: nat): partial_map :=\n  record x value d.\n\nTheorem update_eq: forall (d: partial_map) (x: id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\nintros d x v.\nunfold update.\nsimpl.\nrewrite <- beq_id_refl.\nreflexivity.\nQed.\n\nTheorem update_neq: forall (d: partial_map) (x y: id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\nintros d x y o.\nsimpl.\nintros H.\nrewrite H.\nreflexivity.\nQed.\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\nArguments Some {X} _.\nArguments None {X}.\n\nInductive list (X: Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n    | nil _ => None\n    | cons _ h t => Some h\n  end.\n\nCheck @hd_error.\nCheck @nil.\n\nArguments nil {X}.\nArguments cons {X} _ _.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nExample test_hd_error1 : hd_error [1; 2] = Some 1.\nsimpl.\nreflexivity.\nQed.\n\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nsimpl.\nreflexivity.\nQed.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\n\nExample inversion_ex3 : forall (X : Type) (x y z w : X) (l j : list X),\n  x :: y :: l = w :: z :: j ->\n  x :: l = z :: j ->\n  x = y.\nProof.\nintros X x y z w l j.\nintros H.\nintros G.\ninversion G.\ninversion H.\nreflexivity.\nQed.\n\nExample inversion_ex6 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = nil ->\n  y :: l = z :: j ->\n  x = z.\nProof.\nintros X x y z l j.\nintros H.\ninversion H.\nQed.\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\nintros P Q.\nintros H.\napply H.\nQed.\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 not_both_true_and_false : forall P : Prop,\n  ~(P /\\ ~P).\nProof.\nintros P contra.\napply contradiction_implies_anything with (P := P).\napply contra.\nQed.\n\nTheorem dist_not_exists : forall (X: Type) (P: X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\nintros X P x H.\nunfold not.\ndestruct H as [y E].\napply E.\napply x.\nQed.\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nFixpoint double (n: nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\nintros.\ninduction n.\napply ev_0.\napply ev_SS.\napply IHn.\nQed.\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\nintros.\ninversion H  as [|n' H'].\ninversion H'  as [|n'' H''].\napply H''.\nQed.\n\nTheorem even5_nonsense:\n  ev 5 -> 2 + 2 = 9.\nProof.\nintros.\ninversion H.\ninversion H1.\ninversion H3.\nQed.\n", "meta": {"author": "imel96", "repo": "logical-coq", "sha": "233e1424e277e7f8eb082b766a9d44d7b9c9b501", "save_path": "github-repos/coq/imel96-logical-coq", "path": "github-repos/coq/imel96-logical-coq/logical-coq-233e1424e277e7f8eb082b766a9d44d7b9c9b501/indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.903294196941332, "lm_q1q2_score": 0.8159404197495113}}
{"text": "Check True.\nCheck False.\n\nCheck 3.\n\nCheck (3+4).\n\nCheck (3=4).\n\nCheck (forall x:nat, x < 3 \\/ (exists y:nat, x = y + 3)).\n\nLocate \"_ <= _\".\n\nCheck fun a b c d e => (a + b + c + d + e).\n\nCompute let f := fun a b c d e => a + b + c + d + e in f 1 2 3 4 5.\n\nDefinition example1 := fun x : nat => x * x+2 * x+1.\n\nCheck example1.\n\nCompute example1 1.\n\nRequire Import Bool.\n\nCompute if true then 3 else 5.\n\nSearchPattern bool.\n\nRequire Import Arith.\n\nFixpoint sum_n n :=\n  match n with\n    0 => 0\n  | S p => p + sum_n p\n  end.\n\nFixpoint evenb n :=\n  match n with\n    0 => true\n  | 1 => false\n  | S (S p) => evenb p\n  end.\n\nRequire Import List.\n\n(* Exercise on lists *)\nFixpoint numlist n :=\n  match n with\n    0 => nil\n  | S p => p :: numlist p\n  end.\n\nCompute numlist 1.\nCompute numlist 3.\n\nDefinition sorted_aux := fun list =>\n  match list with\n    nil => true\n  | x1::nil => true\n  | x1::x2::xs => x1 <=? x2\n  end.\n\nCheck sorted_aux.\n\nFixpoint sorted list :=\n  match list with\n    x::xs => sorted_aux list && sorted xs\n  | _ => sorted_aux list\n  end.\n\nCheck sorted.\n\nCompute sorted (1::3::nil).\nCompute sorted (3::1::nil).\nCompute sorted (1::3::2::nil).\n\nFixpoint countn n list :=\n  match list with\n    nil => 0\n  | x::xs => let\n      next := countn n xs\n    in if Nat.eqb n x then next + 1 else next\n  end.\n\nCheck countn.\n\nCompute countn 3 (nil).\nCompute countn 3 (3::nil).\nCompute countn 3 (3::1::3::nil).\n\nSearch True.\nSearchPattern (_ <= _).\nSearch (_ <= _) (_ + _).\nSearchPattern (_ + _ <= _ + _).\nSearchRewrite (_ + (_ - _)).\n\nLemma example2 : forall a b:Prop, a /\\ b -> b /\\ a.\nProof.\n  intros a b H.\n  split.\n  destruct H as [H1 H2].\n  exact H2.\n  intuition.\nQed.\n\nLemma example3 : forall A B, A \\/ B -> B \\/ A.\nProof.\n  intros A B H.\n  destruct H as [H1 | H2].\n  right; assumption.\n  left; assumption.\nQed.\n\n\nCheck le_n.\nCheck le_S.\n\nLemma example4 : 3 <= 5.\nProof.\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\nCheck le_trans.\n\nLemma example5 : forall x y, x <= 10 -> 10 <= y -> x <= y.\nProof.\n  intros x y x10 y10.\n  apply le_trans with (m := 10).\n  assumption.\n  assumption.\nQed.\n\nLemma example6 : forall x y, (x + y) * (x + y) = x*x + 2*x*y + y*y.\nProof.\n  intros x y.\n  SearchRewrite (_ * (_ + _)).\n  rewrite Nat.mul_add_distr_l.\n  SearchRewrite ((_ + _) * _).\n  rewrite Nat.mul_add_distr_r.\n  rewrite Nat.mul_add_distr_r.\n  SearchRewrite (_ + (_ + _)).\n  rewrite Nat.add_assoc.\n  rewrite <- Nat.add_assoc with (n := x * x).\n  SearchPattern (?x * ?y = ?y * ?x).\n  rewrite Nat.mul_comm with (n := y) (m := x).\n  SearchRewrite (S _ * _).\n  rewrite <- (Nat.mul_1_l (x * y)) at 1.\n  rewrite <- Nat.mul_succ_l.\n  SearchRewrite (_ * (_ * _)).\n  rewrite Nat.mul_assoc.\n  reflexivity.\n  Qed.\n\nLemma exercise1 : forall A B C : Prop, A/\\(B/\\C)->(A/\\B)/\\C.\nProof.\n  intros A B C H.\n  destruct H as [H1 H2].\n  destruct H2 as [H21 H22].\n  split.\n  split.\n  exact H1.\n  exact H21.\n  exact H22.\nQed.\n\nLemma exercise2 : forall A B C D : Prop, (A->B)/\\(C->D)/\\A/\\C -> B/\\D.\nProof.\n  intros A B C D H.\n  destruct H as [H1 H2].\n  destruct H2 as [H21 H22].\n  destruct H22 as [H221 H222].\n  split.\n  apply H1.\n  exact H221.\n  apply H21.\n  exact H222.\nQed.\n\nLemma exercise3 : forall A : Prop, ~(A /\\ ~A).\nProof.\n  intros A H.\n  destruct H as [H1 H2].\n  elim H2.\n  exact H1.\nQed.\n\nLemma exercise4 : forall A B C : Prop, A\\/(B\\/C)->(A\\/B)\\/C.\nProof.\n  intros A B C H.\n  destruct H as [H1 | H2].\n  left.\n  left.\n  exact H1.\n  destruct H2 as [H21 | H22].\n  left.\n  right.\n  exact H21.\n  right.\n  exact H22.\nQed.\n\n(*\nLemma exercise5 : forall A B : Prop, (A\\/B)/\\ ~A->B.\nProof.\n  intros A B H.\n  destruct H as [H1 H2].\n  apply H2.\n*)\n\nLemma universal_quant : forall A : Type, forall P Q : A->Prop,\n    (forall x, P x) \\/ (forall y, Q y) -> forall x, P x \\/ Q x.\nProof.\n  intros P Q A x y.\n  destruct x as [x1 | x2].\n  left.\n  apply x1.\n  right.\n  apply x2.\nQed.\n\nLemma sum_n_p : forall n, 2 * sum_n n + n = n * n.\nProof.\n  induction n.\n  reflexivity.\n  assert (SnSn : S n * S n = n * n + 2 * n + 1).\n  ring.\n  rewrite SnSn.\n  rewrite <- IHn.\n  simpl.\n  ring.\nQed.\n\nLemma evenb_p : forall n, evenb n = true -> exists x, n = 2 * x.\nProof.\n  assert (Main : forall n, (evenb n = true -> exists x, n = 2 * x) /\\\n           (evenb (S n) = true -> exists x, S n = 2 * x)).\n  induction n.\n  split.\n    exists 0; ring.\n  simpl; intros H; discriminate H.\n  split.\n    destruct IHn as [_ IHn']; exact IHn'.\n  simpl evenb; intros H; destruct IHn as [IHn' _].\n  assert (H' : exists x, n = 2 * x).\n    apply IHn'; exact H.\n  destruct H' as [x q]; exists (x + 1); rewrite q; ring.\n  intros n ev.\n  destruct (Main n) as [H _]; apply H; exact ev.\nQed.\n\nFixpoint add n m :=\n  match n with\n    0 => m\n  | S p => add p (S m)\n  end.\n\nLemma exercise6 : forall n m, add n (S m) = S (add n m).\nProof.\n  induction n; intros m; simpl.\n    reflexivity.\n  rewrite IHn; reflexivity.\nQed.\n\nLemma exercise7 : forall n m, add (S n) m = S (add n m).\nProof.\n  intros n; induction m; simpl.\n  apply exercise6;\n  reflexivity.\n  rewrite <- exercise6.\n  reflexivity.\nQed.\n\nLemma exercise8 : forall n m, add n m = n + m.\nProof.\n  induction n; intros m; simpl.\n  reflexivity.\n  rewrite <- IHn.\n  apply exercise6.\nQed.\n", "meta": {"author": "johnchildren", "repo": "coq-in-a-hurry-exercises", "sha": "434120f178fae08f04b3fc67e42797a7a094b671", "save_path": "github-repos/coq/johnchildren-coq-in-a-hurry-exercises", "path": "github-repos/coq/johnchildren-coq-in-a-hurry-exercises/coq-in-a-hurry-exercises-434120f178fae08f04b3fc67e42797a7a094b671/Exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.8918110511888303, "lm_q1q2_score": 0.8159187844752458}}
{"text": "Add LoadPath \"C:/Coq/buffer\".\nRequire Export Logic.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof. intros n H. apply (ev_SS (2 + n) (ev_SS n H)). \nQed.\n\nTheorem ev_double : forall n, ev (double n).\nProof. intros n. induction n as [| n' In'].\n  - apply ev_0.\n  - simpl. apply ((ev_SS (double n')) In'). \nQed.\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof. intros n E.\n  inversion E as [| n' E'].\n  -simpl. apply ev_0.\n  -simpl. apply E'.\nQed. \n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n intros n E. inversion E as [| n' E'].\n  apply ev_minus2 in E'. simpl in E'. apply E'.\nQed.\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, le n m -> le n (S m).\n\nNotation \"m <= n\" := (le m n).\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 : forall n : nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof. intros n m o H H'. induction H' as [| m' o' IH].\n  - apply H.\n  - apply le_S. apply IH.\nQed. \n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n. induction n as [| n' Hn'].\n  - apply le_n.\n  - apply le_S. apply Hn'.\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 as [| n' m' H'].\n  - apply le_n.\n  - apply le_S in H'. apply H'.\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. inversion H.\n  - apply le_n.\n  - apply le_trans with (n:=S n).\n    + apply le_S. apply le_n.\n    + apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b. induction a as [| a' Ha'].\n  -apply O_le_n.\n  -simpl. apply n_le_m__Sn_le_Sm. apply Ha'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt. intros n1 n2 m H. split.\n + apply le_trans with (m:=S n1) (n:= S (n1 + n2)) (o:=m).\n  - apply n_le_m__Sn_le_Sm. apply le_plus_l.\n  - apply H.\n + apply le_trans with (m:=S n2) (n:= S (n1 + n2)) (o:=m).\n  - apply n_le_m__Sn_le_Sm. rewrite -> plus_comm. apply le_plus_l.\n  - apply H.\nQed.\n\nLemma le_Sn__n : forall n m, le (S n) m -> le n m.\nProof. intros. apply le_trans with (m:=n) (n:=S n) (o:=m).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros n m H. apply le_Sn__n in H.\n  apply n_le_m__Sn_le_Sm. apply H.\nQed. \nSearch leb.\n\nLemma leb_Sn_r : forall (n m : nat),\n   leb n m = true -> leb n (S m) = true.\nProof. intros n. induction n as [| n' Hn'].\n  - intros m H. reflexivity.\n  - intros m H. simpl. destruct m as [| m'].\n    + inversion H.\n    + simpl in H. apply Hn' in H. apply H.\nQed.\n\nLemma leb_Sn_l : forall (n m : nat),\n   leb (S n) m = true -> leb n m = true.\nProof. intros n. induction n as [| n' Hn'].\n  - intros m H. reflexivity.\n  - intros m H. simpl. destruct m as [| m'].\n    + inversion H.\n    + simpl in H. apply Hn' in H. apply H.\nQed.\n\nLemma leb_extended_refl : forall n m, leb n (n + m) = true.\nProof. intros n m. induction n as [| n' Hn'].\n  - reflexivity.\n  - simpl. apply Hn'.\nQed.\n\nLemma leb_plus : forall n m, \n  leb n m = true <-> (exists k, n + k = m).\nProof. intros n. induction n as [| n' Hn'].\n  - intros m. split. \n    + intros H. exists m. reflexivity.\n    + intros H. reflexivity.\n  - intros [| m']; split.\n    + intros H. inversion H.\n    + intros H. inversion H as [x H0]. inversion H0.\n    + simpl. intros H. apply Hn' in H. destruct H. exists x. rewrite H. reflexivity.\n    + simpl. intros H. inversion H as [x H0]. inversion H0. apply leb_extended_refl.\nQed. \n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  intros n m H. apply leb_plus in H. destruct H. rewrite <- H. apply le_plus_l.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m -> leb n m = true.\nProof. intros n. induction n as [| n' Hn'].\n  - intros [| m']. reflexivity. reflexivity.\n  - intros [| m'] H. \n    + inversion H.\n    + simpl. apply Sn_le_Sm__n_le_m in H. apply Hn' in H.\n      apply H.\nQed.\n\n(* there must be an easier way to do this, still \n   I like how this proof feels like a written proof *)\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof. intros n m o H H'. apply leb_plus in H.\n       apply leb_plus in H'. destruct H. destruct H'.\n       rewrite <- H0. rewrite <- H. rewrite <- plus_assoc.\n       apply leb_extended_refl.\nQed.\n\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof. split. apply leb_complete. apply leb_correct.\nQed.\n\nModule R.\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\nTheorem R_112 : R 1 1 2.\nProof. apply c3. apply c2. apply c1.\nQed.\n\nDefinition fR : nat -> nat -> nat := plus.\nSearch plus.\n\nTheorem R_equiv_fR : forall n m o, R n m o <-> fR m n = o.\nProof. intros n m o. split.\n  - intros H. induction H; unfold fR.\n    + reflexivity.\n    + unfold fR in IHR. rewrite <- plus_n_Sm.\n      rewrite IHR. reflexivity.\n    + unfold fR in IHR. simpl. rewrite IHR. reflexivity.\n    + unfold fR in IHR. simpl in IHR. rewrite <- plus_n_Sm in IHR.\n      inversion IHR. reflexivity.\n    + rewrite -> plus_comm. apply IHR.\n  - intros H. induction H. \n    + unfold fR. generalize dependent n. induction m as [| m' IHm'].\n    ++ induction n as [| n' IHn']. apply c1. apply c2. apply IHn'.\n    ++ intros n. simpl. apply c3. apply IHm'.\nQed.\n\nEnd R.\n\nInductive reg_exp (T : Type) : Type :=\n| EmptySet : reg_exp T\n| EmptyStr : reg_exp T\n| Char : T -> reg_exp T\n| App : reg_exp T -> reg_exp T -> reg_exp T\n| Union : reg_exp T -> reg_exp T -> reg_exp T\n| Star : reg_exp T -> reg_exp T.\n\nArguments EmptySet {T}.\nArguments EmptyStr {T}.\nArguments Char {T} _.\nArguments App {T} _ _.\nArguments Union {T} _ _.\nArguments Star {T} _.\n\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n| MEmpty : exp_match [] EmptyStr\n| MChar : forall x, exp_match [x] (Char x)\n| MApp : forall s1 re1 s2 re2,\n           exp_match s1 re1 ->\n           exp_match s2 re2 ->\n           exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL : forall s1 re1 re2,\n              exp_match s1 re1 ->\n              exp_match s1 (Union re1 re2)\n| MUnionR : forall re1 s2 re2,\n              exp_match s2 re2 ->\n              exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n               exp_match s1 re ->\n               exp_match s2 (Star re) ->\n               exp_match (s1 ++ s2) (Star re).\n\nNotation \"s =~ r\" := (exp_match s r) (at level 80).\n\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\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\nLemma MStar1 :\n  forall T s (re : reg_exp T) ,\n    s =~ re ->\n    s =~ Star re.\nProof.\n  intros T s re H.\n  rewrite <- (app_nil_r _ s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  unfold not. intros T s H. inversion H.\nQed.\n  \nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s re1 re2 H. destruct H.\n  - apply (MUnionL _ _). apply H.\n  - apply (MUnionR _ _). apply H.\nQed.\n\nLemma fold_app_distr : forall T (x x0 : list (list T)),\n    fold app (x ++ x0) [] = fold app x [] ++ fold app x0 [].\nProof. induction x.\n           -reflexivity.\n           -simpl. intros. rewrite IHx. apply app_assoc.\nQed.\n\nLemma In_or : forall T (s : list T) (x x0 : list (list T)),\n    In s (x ++ x0) -> In s x \\/ In s x0.\nProof. intros. induction x. simpl in H. right. apply H. simpl in H.\n       destruct H. left. rewrite H. left. reflexivity. destruct IHx.\n       apply H. left. right. apply H0. right. apply H0.\nQed.\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros T ss re H. apply All_In in H. induction ss as [| h t Ht ].\n  - simpl. apply MStar0.\n  - simpl. simpl in H. destruct H. apply Ht in H0. apply (MStarApp h (fold app t []) re).\n    + apply H.\n    + apply H0.\nQed.\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp T),\n  s =~ Star re ->\n  exists ss : list (list T),\n    s = fold app ss []\n    /\\ forall s', In s' ss -> s' =~ re.\nProof. intros. remember (Star re) as re'. induction H.\n       -inversion Heqre'.\n       -inversion Heqre'.\n       -inversion Heqre'.\n       -inversion Heqre'.\n       -inversion Heqre'.\n       -exists []. intros. split. reflexivity. intros. inversion H.\n       -apply IHexp_match2 in Heqre' as HH. destruct HH. destruct H1.\n        exists (s1::x). split.\n        +simpl. rewrite <- H1. reflexivity.\n        +intros. simpl in H3. destruct H3. rewrite <- H3. inversion Heqre'.\n         rewrite <- H5. apply H. apply H2. apply H3.\nQed.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. split.\n  - intros. generalize dependent s1. induction s2.  \n    + intros. simpl in H. inversion H. reflexivity.\n    + intros. simpl in H. inversion H. apply IHs2 in H4. inversion H3. rewrite H4. reflexivity.\n  - intros. rewrite H. generalize dependent s1. induction s2. \n    + intros. simpl. apply MEmpty. \n    + intros. simpl. replace (x :: s2) with ([x] ++ s2). apply MApp. apply MChar. \n      apply IHs2 with (s1 := s2). reflexivity. reflexivity.\nQed.\n\nFixpoint re_chars {T} (re : reg_exp T) : list T :=\n  match re with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App re1 re2 => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re => re_chars re\n  end.\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp T) (x : T),\n  s =~ re ->\n  In x s ->\n  In x (re_chars re).\nProof.\n  intros T s re x Hmatch Hin.\n  induction Hmatch\n    as [\n        |x'\n        |s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n        |re|s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. rewrite In_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      left. apply (IH1 Hin).\n    + (* In x s2 *)\n      right. apply (IH2 Hin).\n  - (* MUnionL *)\n    simpl. rewrite In_app_iff.\n    left. apply (IH Hin).\n  - (* MUnionR *)\n    simpl. rewrite In_app_iff.\n    right. apply (IH Hin).\n  - (* MStar0 *)\n    destruct Hin.\n    - (* 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 _ => true\n  | App r1 r2 => andb (re_not_empty r1) (re_not_empty r2)\n  | Union r1 r2 => orb (re_not_empty r1) (re_not_empty r2)\n  | Star r => true\n  end.\n\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  split.\n  - intros. destruct H. induction  H.\n    + reflexivity.\n    + reflexivity.\n    + simpl. rewrite IHexp_match1. rewrite IHexp_match2. reflexivity.\n    + simpl. rewrite IHexp_match. reflexivity.\n    + simpl. rewrite orb_true_iff. right. rewrite IHexp_match. reflexivity.\n    + reflexivity.\n    + reflexivity.\n  - intros. induction re.\n    + inversion H.\n    + exists []. apply MEmpty.\n    + exists [t]. apply MChar.\n    + simpl in H. apply andb_true_iff in H. destruct H. apply IHre1 in H. destruct H.\n      apply IHre2 in H0. destruct H0. exists (x ++ x0). apply MApp. apply H. apply H0. \n    + simpl in H. apply orb_true_iff in H. destruct H.\n      ++ apply IHre1 in H. destruct H. exists x. apply MUnionL. apply H.\n      ++ apply IHre2 in H. destruct H. exists x. apply MUnionR. apply H.\n    + exists []. apply MStar0.\nQed.\n\n\nInductive nostutter {X : Type} : list X -> Prop :=\n  | NoStutO : nostutter []\n  | NoStutChar : forall c : X, nostutter [c]\n  | NoStutApp : forall (c h : X) (l : list X),\n      c <> h -> nostutter (h::l) -> nostutter (c::h::l).\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\nQed.\n\nExample test_nostutter_2: nostutter (@nil nat).\n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\nQed.\n\nExample test_nostutter_3: nostutter [5].\n  Proof. repeat constructor; apply beq_nat_false; auto. \nQed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H1; auto. \nQed.\n\nLemma star_app : forall T ( s1 s2 : list T) (re : reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof. intros T s1 s2 re H1. remember (Star re) as re'. \n  generalize dependent s2. induction H1.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - inversion Heqre'.\n  - intros.  apply H.\n  - intros. apply IHexp_match2 in H. rewrite <- app_assoc. apply MStarApp. apply H1_. apply H.\n    apply Heqre'.\nQed.\n\nModule Pumping.\n\n  Fixpoint pumping_constant {T} (re : reg_exp T) : nat :=\n    match re with\n    | EmptySet => 0\n    | EmptyStr => 1\n    | Char _ => 2\n    | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n    | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n    | Star _ => 1\n    end.\n\n  Fixpoint napp {T} (n : nat) (l : list T) : list T :=\n    match n with\n    | 0 => []\n    | S n' => l ++ napp n' l\n    end.\n\n  Lemma napp_plus : forall T (n m : nat) (l : list T),\n      napp (n + m) l = napp n l ++ napp m l.\n  Proof.\n    intros T n m l.\n    induction n as [| n IHn].\n    -reflexivity.\n    -simpl. rewrite IHn, app_assoc. reflexivity.\n   Qed.\n\n  Lemma pumping : forall T (re : reg_exp T) s,\n      s =~ re ->\n      pumping_constant re <= length s ->\n      exists s1 s2 s3,\n        s = s1 ++ s2 ++ s3 /\\\n        s2 <> [] /\\\n        forall m, s1 ++ napp m s2 ++ s3 =~ re.\n            Require Import Coq.omega.Omega.\n            Proof.\n              Admitted. \nEnd Pumping.\n\nTheorem filter_not_empty_In : forall n l,\n    filter (beq_nat n) l <> [] ->\n    In n l.\nProof.\n  intros n l. induction l as [| m l' IHl'].\n  -simpl. intros H. apply H. reflexivity.\n  -simpl. destruct (beq_nat n m) eqn:H.\n   + intros _. rewrite beq_nat_true_iff in H. rewrite H.\n     left. reflexivity.\n   + intros H'.  right. apply IHl'. apply H'.\nQed.\n\nModule FirstTry.\n\n  Inductive reflect : Prop -> bool -> Prop :=\n  | ReflectT : forall (P : Prop), P -> reflect P true\n  | ReflectF : forall (P : Prop), ~P -> reflect P false.\n\nEnd FirstTry.\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~P -> reflect P false.\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof. intros P b H. destruct b.\n       -apply ReflectT. rewrite H. reflexivity.\n       -apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof. intros P b H. destruct b; split.\n       -intros. reflexivity.\n       -intros. inversion H. apply H1.\n       -intros. inversion H. apply H1 in H0. inversion H0.\n       -intros. inversion H0.\nQed.\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m.\n  apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\n(*this generates n = m (P) and n <> m (~P) as hypothesis directly\n  making the proof more streamlined than before *)\nTheorem filter_not_empty_In' : forall n l,\n    filter (beq_nat n) l <> [] ->\n    In n l.\nProof.\n  intros n l. induction l as [| m l' IHl'].\n  -simpl. intros H. apply H. reflexivity.\n  -simpl. destruct (beq_natP n m) as [H | H].\n   +intros _. rewrite H. left. reflexivity.\n   +intros H'. right. apply IHl'. apply H'.\nQed.\n\nFixpoint count n l :=\n  match l with\n  | [] => 0\n  | m :: l' => (if beq_nat n m then 1 else 0) + count n l'\n  end.\n\nTheorem beq_natP_practice : forall n l,\n    count n l = 0 -> ~(In n l).\nProof.\n  intros n l H. induction l as [| m l' IH].\n  -unfold not. intros. inversion H0.\n  -simpl in H. destruct (beq_natP n m) in H.\n   +inversion H.\n   +apply IH in H. unfold not. intros. simpl in H1. destruct H1.\n    ++symmetry in H1. apply H0 in H1. inversion H1.\n    ++apply H in H1. inversion H1.\nQed.\n\n\n\n                                           \n\n\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8872045922259089, "lm_q1q2_score": 0.8159110768671964}}
{"text": "(* Software Foundations *)\n(* Exercice 1 star, double_even *)\n\nFixpoint double (n: nat): nat :=\nmatch n with\n|O => O\n|S n' => S(S (double n'))\nend.\n\nInductive ev: nat -> Prop :=\n|ev_0: ev 0\n|ev_ss: forall n: nat, ev n -> ev (S (S n)).\n\nTheorem double_even: forall n: nat, ev (double n).\nProof.\n    induction n as [|n'].\n    simpl. apply ev_0.\n    simpl. apply ev_ss. apply IHn'.\nQed.\n\n\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/double_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8158856117167919}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\n(* Inductive predicate *)\nInductive even : nat -> Prop :=\n| even_0 : even 0\n| even_SS : forall n, even n -> even (S (S n)).\n\nInductive odd : nat -> Prop :=\n| odd_1 : odd 1\n| odd_SS : forall n, odd n -> odd (S (S n)).\n\nTheorem even_double : forall n, even (n + n).\nProof.\ninduction n.\n(* Proof *)\nQed.\n\nTheorem even_plus : forall m n, even m -> even n -> even (m + n).\nProof.\nintros m n Hm Hn.\ninduction Hm.\n(* Proof *)\nQed.\n\nTheorem not_even_1 : ~even 1.\nProof.\nintro. inversion H.\nQed.\n\nTheorem even_SS_inv : forall n, even (S (S n)) -> even n.\nProof.\nintros n H.\n(* Proof *)\nQed.\n\nTheorem even_odd : forall n, even n -> odd (S n).\nProof.\nintros n H.\ninduction H.\n(* Proof *)\nQed.\n\nTheorem odd_even : forall n, odd n -> even (S n).\nProof.\n(* Proof *)\nQed.\n\nTheorem even_not_odd : forall n, even n -> ~odd n.\nProof.\n(* Proof *)\nQed.\n\nTheorem even_or_odd : forall n, even n \\/ odd n.\nProof.\nintro n.\ninduction n.\n left. apply even_0.\ninduction n. \n(* Proof. even_odd and odd_even are useful. *)\nQed.\n\nTheorem odd_odd_even : forall m n, odd m -> odd n -> even (m + n).\nProof.\nintros m n Hm Hn.\ninduction Hm.\n induction Hn.\n(* Proof. *)\nQed.\n\nSection List_inversion.\n\nRequire Import List.\n\nVariable A:Type.\n\nTheorem app_inv_l : forall l l1 l2:list A,\n  l ++ l1 = l ++ l2 -> l1 = l2.\nProof.\n(* Proof. *)\nQed.\n\nCheck app_nil_r.\nCheck app_cons_not_nil.\n\nLemma app_cons_assoc : forall (a:A)(l1 l2:list A),\n  l1 ++ a::l2 = (l1 ++ a::nil) ++ l2.\nProof.\n(* Proof. *)\nQed.\n\nLemma app_snoc_inv : forall (a:A)(l1 l2:list A),\n  l1 ++ a::nil = l2 ++ a::nil -> l1 = l2.\nProof.\n(* Proof. *)\nQed.\n\nTheorem app_inv_r : forall l l1 l2:list A,\n  l1 ++ l = l2 ++ l -> l1 = l2.\nProof.\n(* Proof. *)\nQed.\n\nCheck app_inv_l.\nEnd List_inversion.\nCheck app_inv_l.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120209/tutorial5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.8158499188378658}}
{"text": "From Coq Require Import Arith ZArith Psatz Bool String List Program.Equality.\nFrom CDF Require Import Sequences Simulation.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope list_scope.\n\n(** * 1.  The IMP language *)\n\n(** ** 1.1 Arithmetic expressions *)\n\nDefinition ident := string.\n\n(** The abstract syntax: an arithmetic expression is either... *)\n\nInductive aexp : Type :=\n  | CONST (n: Z)                       (**r a constant, or *)\n  | VAR (x: ident)                     (**r a variable, or *)\n  | PLUS (a1: aexp) (a2: aexp)         (**r a sum of two expressions, or *)\n  | MINUS (a1: aexp) (a2: aexp).       (**r a difference of two expressions *)\n\n(** The denotational semantics: an evaluation function that computes\n  the integer value denoted by an expression.  This function is\n  parameterized by a store [s] that associates values to variables. *)\n\nDefinition store : Type := ident -> Z.\n\nFixpoint aeval (a: aexp) (s: store) : Z :=\n  match a with\n  | CONST n => n\n  | VAR x => s x\n  | PLUS a1 a2 => aeval a1 s + aeval a2 s\n  | MINUS a1 a2 => aeval a1 s - aeval a2 s\n  end.\n\n(** Such evaluation functions / denotational semantics have many uses.\n    First, we can use [aeval] to evaluate a given expression in a given store. *)\n\nEval compute in (aeval (PLUS (VAR \"x\") (MINUS (VAR \"x\") (CONST 1)))  (fun x => 2)).\n\n(** Result: [ = 3 : Z ]. *)\n\n(** We can also do partial evaluation with respect to an unknown store *)\n\nEval cbn in (aeval (PLUS (VAR \"x\") (MINUS (CONST 10) (CONST 1)))).\n\n(** Result: [ = fun s : store => s \"x\" + 9 ]. *)\n\n(** We can prove mathematical properties of a given expression. *)\n\nLemma aeval_xplus1:\n  forall s x, aeval (PLUS (VAR x) (CONST 1)) s > aeval (VAR x) s.\nProof.\n  intros. cbn. lia.\nQed.\n\n(** Finally, we can prove \"meta-properties\" that hold for all expressions.\n  For example: the value of an expression depends only on the values of its\n  free variables.\n\n  Free variables are defined by this recursive predicate:\n*)\n\nFixpoint free_in_aexp (x: ident) (a: aexp) : Prop :=\n  match a with\n  | CONST n => False\n  | VAR y => y = x\n  | PLUS a1 a2 | MINUS a1 a2 => free_in_aexp x a1 \\/ free_in_aexp x a2\n  end.\n\nTheorem aeval_free:\n  forall s1 s2 a,\n  (forall x, free_in_aexp x a -> s1 x = s2 x) ->\n  aeval a s1 = aeval a s2.\nProof.\n  induction a; cbn; intros SAMEFREE.\n- (* Case a = CONST n *)\n  auto.\n- (* Case a = VAR x *)\n  apply SAMEFREE. auto.\n- (* Case a = PLUS a1 a2 *)\n  rewrite IHa1, IHa2; auto.\n- (* Case a = MINUS a1 a2 *)\n  rewrite IHa1, IHa2; auto.\nQed.\n\n(** ** 1.2.  Growing the language of arithmetic expressions *)\n\n(** We can enrich the language with new operators in several ways.\n    The simplest way is to define derived forms in terms of existing operators.\n    For example, the \"opposite\" operator is: *)\n\nDefinition OPP (a: aexp) : aexp := MINUS (CONST 0) a.\n\n(** Its semantics is the one we expect. *)\n\nLemma aeval_OPP: forall s a, aeval (OPP a) s = - (aeval a s).\nProof.\n  intros; cbn. lia.\nQed.\n\n(** In other cases, we must add constructors to the [aexp] type\n    and cases to the [aeval] function.  For example, let's add multiplication.\n*)\n\nModule AExp_mul.\n\nInductive aexp : Type :=\n  | CONST (n: Z)\n  | VAR (x: ident)\n  | PLUS (a1: aexp) (a2: aexp)\n  | MINUS (a1: aexp) (a2: aexp)\n  | TIMES (a1: aexp) (a2: aexp).      (**r NEW! *)\n\nFixpoint aeval (a: aexp) (s: store) : Z :=\n  match a with\n  | CONST n => n\n  | VAR x => s x\n  | PLUS a1 a2 => aeval a1 s + aeval a2 s\n  | MINUS a1 a2 => aeval a1 s - aeval a2 s\n  | TIMES a1 a2 => aeval a1 s * aeval a2 s\n  end.\n\nEnd AExp_mul.\n\n(** Why not add division as well? *)\n\nModule AExp_div.\n\nInductive aexp : Type :=\n  | CONST (n: Z)\n  | VAR (x: ident)\n  | PLUS (a1: aexp) (a2: aexp)\n  | MINUS (a1: aexp) (a2: aexp)\n  | TIMES (a1: aexp) (a2: aexp)\n  | QUOT (a1: aexp) (a2: aexp).    (**r NEW! *)\n\n(** We have a problem!  The evaluation of an expression can now fail,\n  in case of a division by zero.  We must change the type of [aeval]\n  to reflect this error case: [aeval] now returns an option type [option Z].\n  The result [Some n] means \"no errors, and the value is [n]\".\n  The result [None] means \"error during evaluation\".\n\n  Now that we know how to handle errors, we can make our semantics more\n  realistic in other places:\n  - variables can be uninitialized; using such a variable in an expression\n    is a run-time error;\n  - arithmetic operations can overflow the range of integers representable\n    by a machine (e.g. 64-bit integers); this is a run-time error as well.\n*)\n\nDefinition min_int := - (2 ^ 63).  (**r the smallest representable integer *)\nDefinition max_int := 2 ^ 63 - 1.  (**r the greatest representable integer *)\n\nDefinition check_for_overflow (n: Z): option Z :=\n  if (min_int <=? n) && (n <=? max_int) then Some n else None.\n\nFixpoint aeval (s: ident -> option Z) (a: aexp) : option Z :=\n  match a with\n  | CONST n => check_for_overflow n\n  | VAR x => s x\n  | PLUS a1 a2 =>\n      match aeval s a1, aeval s a2 with\n      | Some n1, Some n2 => check_for_overflow (n1 + n2)\n      | _, _ => None\n      end\n  | MINUS a1 a2 =>\n      match aeval s a1, aeval s a2 with\n      | Some n1, Some n2 => check_for_overflow (n1 - n2)\n      | _, _ => None\n      end\n  | TIMES a1 a2 =>\n      match aeval s a1, aeval s a2 with\n      | Some n1, Some n2 => check_for_overflow (n1 * n2)\n      | _, _ => None\n      end\n  | QUOT a1 a2 =>\n      match aeval s a1, aeval s a2 with\n      | Some n1, Some n2 => if n2 =? 0 then None else check_for_overflow (n1 / n2)\n      | _, _ => None\n      end\n  end.\n\nEnd AExp_div.\n\n(** ** 1.3 Boolean expressions *)\n\n(** The IMP language has conditional statements (if/then/else) and\n  loops.  They are controlled by expressions that evaluate to Boolean\n  values.  Here is the abstract syntax of Boolean expressions. *)\n\nInductive bexp : Type :=\n  | TRUE                              (**r always true *)\n  | FALSE                             (**r always false *)\n  | EQUAL (a1: aexp) (a2: aexp)       (**r whether [a1 = a2] *)\n  | LESSEQUAL (a1: aexp) (a2: aexp)   (**r whether [a1 <= a2] *)\n  | NOT (b1: bexp)                    (**r Boolean negation *)\n  | AND (b1: bexp) (b2: bexp).        (**r Boolean conjunction *)\n\n(** Just like arithmetic expressions evaluate to integers,\n  Boolean expressions evaluate to Boolean values [true] or [false]. *)\n\nFixpoint beval (b: bexp) (s: store) : bool :=\n  match b with\n  | TRUE => true\n  | FALSE => false\n  | EQUAL a1 a2 => aeval a1 s =? aeval a2 s\n  | LESSEQUAL a1 a2 => aeval a1 s <=? aeval a2 s\n  | NOT b1 => negb (beval b1 s)\n  | AND b1 b2 => beval b1 s && beval b2 s\n  end.\n\n(** There are many useful derived forms. *)\n\nDefinition NOTEQUAL (a1 a2: aexp) : bexp := NOT (EQUAL a1 a2).\n\nDefinition GREATEREQUAL (a1 a2: aexp) : bexp := LESSEQUAL a2 a1.\n\nDefinition GREATER (a1 a2: aexp) : bexp := NOT (LESSEQUAL a1 a2).\n\nDefinition LESS (a1 a2: aexp) : bexp := GREATER a2 a1.\n\nDefinition OR (b1 b2: bexp) : bexp := NOT (AND (NOT b1) (NOT b2)).\n\n(** *** Exercise (1 star) *)\n(** Prove that the [OR] derived form has the expected semantics. *)\n\nLemma beval_OR:\n  forall s b1 b2, beval (OR b1 b2) s = beval b1 s || beval b2 s.\nProof.\n  intros; cbn.\n  (* Hint: use \"SearchAbout negb\" to see the available lemmas\n     that deal with Boolean negation. *)\n  (* Hint: or just do a case analysis on [beval b1 s] and [beval b2 s],\n     there are only 4 cases to consider. *)\n  (* FILL IN HERE *)\nAbort.\n\n(** ** 1.4 Commands *)\n\n(** To complete the definition of the IMP language, here is the\n  abstract syntax of commands, also known as statements. *)\n\nInductive com: Type :=\n  | SKIP                                     (**r do nothing *)\n  | ASSIGN (x: ident) (a: aexp)              (**r assignment: [v := a] *)\n  | SEQ (c1: com) (c2: com)                  (**r sequence: [c1; c2] *)\n  | IFTHENELSE (b: bexp) (c1: com) (c2: com) (**r conditional: [if b then c1 else c2] *)\n  | WHILE (b: bexp) (c1: com).               (**r loop: [while b do c1 done] *)\n\n(** We can write [c1 ;; c2] instead of [SEQ c1 c2], it is easier on the eyes. *)\n\nInfix \";;\" := SEQ (at level 80, right associativity).\n\n(** Here is an IMP program that performs Euclidean division by\n  repeated subtraction.  At the end of the program, \"q\" contains\n  the quotient of \"a\" by \"b\", and \"r\" contains the remainder.\n  In pseudocode:\n<<\n       r := a; q := 0;\n       while b <= r do r := r - b; q := q + 1 done\n>>\n  In abstract syntax:\n*)\n\nDefinition Euclidean_division :=\n  ASSIGN \"r\" (VAR \"a\") ;;\n  ASSIGN \"q\" (CONST 0) ;;\n  WHILE (LESSEQUAL (VAR \"b\") (VAR \"r\"))\n    (ASSIGN \"r\" (MINUS (VAR \"r\") (VAR \"b\")) ;;\n     ASSIGN \"q\" (PLUS (VAR \"q\") (CONST 1))).\n\n(** A useful operation over stores:\n    [update x v s] is the store that maps [x] to [v] and is equal to [s] for\n    all variables other than [x]. *)\n\nDefinition update (x: ident) (v: Z) (s: store) : store :=\n  fun y => if string_dec x y then v else s y.\n\nLemma update_same: forall x v s, (update x v s) x = v.\nProof.\n  unfold update; intros. destruct (string_dec x x); congruence.\nQed.\n\nLemma update_other: forall x v s y, x <> y -> (update x v s) y = s y.\nProof.\n  unfold update; intros. destruct (string_dec x y); congruence.\nQed.\n\n(** Naively, we would like to define the semantics of a command with\n    an execution function [cexec s c] that runs the command [c]\n    in initial store [s] and returns the final store when [c] terminates. *)\n\nFail Fixpoint cexec (c: com) (s: store) : store :=\n  match c with\n  | SKIP => s\n  | ASSIGN x a => update x (aeval a s) s\n  | SEQ c1 c2 => let s' := cexec c1 s in cexec c2 s'\n  | IFTHENELSE b c1 c2 => if beval b s then cexec c1 s else cexec c2 s\n  | WHILE b c1 =>\n      if beval b s\n      then (let s' := cexec c1 s in cexec (WHILE b c1) s')\n      else s\n  end.\n\n(** The definition above is rejected by Coq, and rightly so, because\n  all Coq functions must terminate, yet the [WHILE] case may not\n  terminate.  Consider for example the infinite loop\n  [WHILE TRUE SKIP].\n\n  Let's attempt a different style of semantics, based on sequences\n  of reductions.\n*)\n\n(** ** 1.5.  Reduction semantics *)\n\n(** The relation [ red (c, s) (c', s') ] defines a basic reduction,\n    that is, the first computation step when executing command [c]\n    in initial memory state [s].\n    [s'] is the memory state \"after\" this computation step.\n    [c'] is a command that represent all the computations that remain\n    to be performed later.\n\n    The reduction relation is presented as a Coq inductive predicate,\n    with one case (one \"constructor\") for each reduction rule.\n*)\n\nInductive red: com * store -> com * store -> Prop :=\n  | red_assign: forall x a s,\n      red (ASSIGN x a, s) (SKIP, update x (aeval a s) s)\n  | red_seq_done: forall c s,\n      red (SEQ SKIP c, s) (c, s)\n  | red_seq_step: forall c1 c s1 c2 s2,\n      red (c1, s1) (c2, s2) ->\n      red (SEQ c1 c, s1) (SEQ c2 c, s2)\n  | red_ifthenelse: forall b c1 c2 s,\n      red (IFTHENELSE b c1 c2, s) ((if beval b s then c1 else c2), s)\n  | red_while_done: forall b c s,\n      beval b s = false ->\n      red (WHILE b c, s) (SKIP, s)\n  | red_while_loop: forall b c s,\n      beval b s = true ->\n      red (WHILE b c, s) (SEQ c (WHILE b c), s).\n\n(** An interesting property of this reduction relation is that it is\n    functional: a configuration [(c,s)] reduces to at most one configuration.\n    This corresponds to the fact that IMP is a deterministic language. *)\n\nLemma red_determ:\n  forall cs cs1, red cs cs1 -> forall cs2, red cs cs2 -> cs1 = cs2.\nProof.\n  induction 1; intros cs2 R2; inversion R2; subst; eauto.\n- inversion H3.\n- inversion H.\n- assert (EQ: (c2, s2) = (c4, s3)) by auto. congruence.\n- congruence.\n- congruence.\nQed.\n\n(** We define the semantics of a command by chaining successive reductions.\n    The command [c] in initial state [s] terminates with final state [s']\n    if we can go from [(c, s)] to [(skip, s')] in a finite number of reductions.\n*)\n\nDefinition terminates (s: store) (c: com) (s': store) : Prop :=\n  star red (c, s) (SKIP, s').\n\n(** The [star] operator is defined in library [Sequences].\n    [star R] is the reflexive transitive closure of relation [R].\n    On paper it is often written [R*].\n    The [star red] relation therefore represents zero, one or several\n    reduction steps. *)\n\n(** Likewise, command [c] diverges (fails to terminate) in initial state [s]\n    if there exists an infinite sequence of reductions starting with [(c, s)].\n    The [infseq] relation operator is defined in library [Sequences].\n*)\n\nDefinition diverges (s: store) (c: com) : Prop :=\n  infseq red (c, s).\n\n(** Generally speaking, a third kind of executions is possible:\n    \"going wrong\" after a finite number of reductions.\n   A configuration [(c', s')] \"goes wrong\" if it cannot reduce and is\n   not a final configuration, that is, [c' <> SKIP]. *)\n\nDefinition goes_wrong (s: store) (c: com) : Prop :=\n  exists c', exists s',\n  star red (c, s) (c', s') /\\ irred red (c', s') /\\ c' <> SKIP.\n\n(** *** Exercise (2 stars) *)\n(** Prove that IMP command never go wrong.\n    Hint: first show the following \"progress\" property, showing that\n    a command other than [SKIP] can always reduce. *)\n\nLemma red_progress:\n  forall c s, c = SKIP \\/ exists c', exists s', red (c, s) (c', s').\nProof.\n  induction c; intros.\n  (* FILL IN HERE *)\nAbort.\n\nLemma not_goes_wrong:\n  forall c s, ~(goes_wrong s c).\nProof.\n  intros c s (c' & s' & STAR & IRRED & NOTSKIP).\n  (* FILL IN HERE *)\nAbort.\n\n(** A technical lemma: a sequence of reductions can take place to the left\n    of a [SEQ] constructor.  This generalizes rule [red_seq_step]. *)\n\nLemma red_seq_steps:\n  forall c2 s c s' c',\n  star red (c, s) (c', s') -> star red ((c;;c2), s) ((c';;c2), s').\nProof.\n  intros. dependent induction H.\n- apply star_refl.\n- destruct b as [c1 st1].\n  apply star_step with (c1;;c2, st1). apply red_seq_step. auto. auto.  \nQed.\n\n(** ** 1.6.  Natural semantics *)\n\nInductive cexec: store -> com -> store -> Prop :=\n  | cexec_skip: forall s,\n      cexec s SKIP s\n  | cexec_assign: forall s x a,\n      cexec s (ASSIGN x a) (update x (aeval a s) s)\n  | cexec_seq: forall c1 c2 s s' s'',\n      cexec s c1 s' -> cexec s' c2 s'' ->\n      cexec s (SEQ c1 c2) s''\n  | cexec_ifthenelse: forall b c1 c2 s s',\n      cexec s (if beval b s then c1 else c2) s' ->\n      cexec s (IFTHENELSE b c1 c2) s'\n  | cexec_while_done: forall b c s,\n      beval b s = false ->\n      cexec s (WHILE b c) s\n  | cexec_while_loop: forall b c s s' s'',\n      beval b s = true -> cexec s c s' -> cexec s' (WHILE b c) s'' ->\n      cexec s (WHILE b c) s''.\n\n(** The predicate [cexec s c s'] holds iff there exists a finite derivation\n    for this conclusion, using the axioms and inference rules above.\n\n    The structure of this derivation represents the computations performed\n    by [c] as a tree --- not as a sequence of reductions.\n\n    The finiteness of the derivation guarantees that only terminating executions\n    satisfy [cexec].  As an example, [WHILE TRUE SKIP] does not satisfy [cexec].\n*)\n\nLemma cexec_infinite_loop:\n  forall s, ~ exists s', cexec s (WHILE TRUE SKIP) s'.\nProof.\n  assert (A: forall s c s', cexec s c s' -> c = WHILE TRUE SKIP -> False).\n  { induction 1; intros EQ; inversion EQ.\n  - subst b c. cbn in H. discriminate.\n  - subst b c. apply IHcexec2. auto.\n  }\n  intros s (s' & EXEC). apply A with (s := s) (c := WHILE TRUE SKIP) (s' := s'); auto.\nQed.\n\n(** We now show an equivalence between evaluations that terminate according\n    to the natural semantics\n        (existence of a derivation of [cexec s c s'])\n    and to the reduction semantics\n        (existence of a reduction sequence from [(c,s)] to [(SKIP, s')].\n\n    We start with the natural semantics => reduction sequence direction,\n    which is proved by an elegant induction on the derivation of [cexec]. *)\n\nTheorem cexec_to_reds:\n  forall s c s', cexec s c s' -> star red (c, s) (SKIP, s').\nProof.\n  induction 1.\n- (* SKIP *)\n  apply star_refl.\n- (* ASSIGN *)\n  apply star_one. apply red_assign. \n- (* SEQ *)\n  eapply star_trans. apply red_seq_steps. apply IHcexec1.\n  eapply star_step.  apply red_seq_done.  apply IHcexec2.\n- (* IFTHENELSE *)\n  eapply star_step. apply red_ifthenelse. auto.\n- (* WHILE stop *)\n  apply star_one. apply red_while_done. auto.\n- (* WHILE loop *)\n  eapply star_step. apply red_while_loop. auto.\n  eapply star_trans. apply red_seq_steps. apply IHcexec1.\n  eapply star_step. apply red_seq_done. apply IHcexec2.\nQed.\n\n(** The other direction, from a reduction sequence to a [cexec]\n    derivation, is more subtle.  Here is the key lemma, showing how a\n    reduction step followed by a [cexec] execution can combine into a\n    [cexec] execution. *)\n\nLemma red_append_cexec:\n  forall c1 s1 c2 s2, red (c1, s1) (c2, s2) ->\n  forall s', cexec s2 c2 s' -> cexec s1 c1 s'.\nProof.\n  intros until s2; intros STEP. dependent induction STEP; intros.\n- (* red_assign *)\n  inversion H; subst. apply cexec_assign. \n- (* red_seq_done *)\n  apply cexec_seq with s2. apply cexec_skip. auto.\n- (* red seq step *)\n  inversion H; subst. apply cexec_seq with s'0.\n  eapply IHSTEP; eauto.\n  auto.\n- (* red_ifthenelse *)\n  apply cexec_ifthenelse. auto.\n- (* red_while_done *)\n  inversion H0; subst. apply cexec_while_done. auto.\n- (* red while loop *)\n  inversion H0; subst. apply cexec_while_loop with s'0; auto.\nQed.\n\n(** By induction on the reduction sequence, it follows that a command\n    that reduces to [SKIP] executes according to the natural semantics,\n    with the same final state. *)\n\nTheorem reds_to_cexec:\n  forall s c s',\n  star red (c, s) (SKIP, s') -> cexec s c s'.\nProof.\n  intros. dependent induction H.\n- apply cexec_skip.\n- destruct b as [c1 s1]. apply red_append_cexec with c1 s1; auto.\nQed.\n\n(** ** 1.7.  Bounded interpreter *)\n\n(** We found it impossible to define the semantics of commands as\n    a Coq execution function.  However, we can define an approximation\n    of such a function by bounding a priori the recursion depth,\n    using an extra parameter [fuel] of type [nat].\n\n    The \"fuel\" is decremented by 1 at each recursive call.  If it drops\n    to 0, execution returns [None], meaning that the final state at\n    the end of the command execution could not be determined:\n    either the command diverges, or more fuel is needed to execute it. *)\n\nFixpoint cexec_f (fuel: nat) (s: store) (c: com) : option store :=\n  match fuel with\n  | O => None\n  | S fuel' =>\n      match c with\n      | SKIP => Some s\n      | ASSIGN x a => Some (update x (aeval a s) s)\n      | SEQ c1 c2 =>\n          match cexec_f fuel' s c1 with\n          | None  => None\n          | Some s' => cexec_f fuel' s' c2\n          end\n      | IFTHENELSE b c1 c2 =>\n          cexec_f fuel' s (if beval b s then c1 else c2)\n      | WHILE b c1 =>\n          if beval b s then\n            match cexec_f fuel' s c1 with\n            | None  => None\n            | Some s' => cexec_f fuel' s' (WHILE b c1)\n            end\n          else Some s\n      end\n  end.\n\n(** This bounded execution function is very useful to compute the semantics\n    of test programs.  For example, let's compute the quotient and the remainder\n    of 14 divided by 3 using the IMP program for Euclidean division shown\n    above. *)\n\nEval compute in\n  (let s := update \"a\" 14 (update \"b\" 3 (fun _ => 0)) in\n   match cexec_f 100 s Euclidean_division with\n   | None => None\n   | Some s' => Some (s' \"q\", s' \"r\")\n   end).\n\n(** *** Exercise (3 stars) *)\n\n(** Show that function [cexec_f] is sound with respect to the natural semantics\n    [cexec], by proving the two following lemmas. *)\n\nLemma cexec_f_sound:\n  forall fuel s c s', cexec_f fuel s c = Some s' -> cexec s c s'.\nProof.\n  induction fuel as [ | fuel ]; cbn; intros.\n- discriminate.\n- destruct c.\n  (* FILL IN HERE *)\nAbort.\n\nLemma cexec_f_complete:\n  forall s c s', cexec s c s' ->\n  exists fuel1, forall fuel, (fuel >= fuel1)%nat -> cexec_f fuel s c = Some s'.\nProof.\n  induction 1.\n  (* FILL IN HERE *)\nAbort.\n\n(** ** 1.8.  Transition semantics with continuations *)\n\n(** To help with the verification of a compiler (module [Compil]),\n    we now introduce another form of \"small-step\" semantics\n    as an alternative to the reduction semantics.  In the new semantics,\n    the command to be executed is explicitly decomposed into\n    - a sub-command under focus, where computation takes place;\n    - a context that describes the position of the sub-command in the\n      whole command; or, equivalently, a continuation that describes\n      the parts of the whole command that remain to execute once\n      the sub-command terminates.\n\n    Consequently, the semantics is presented as a transition relation\n    between triples (sub-command under focus, continuation, state).\n\n    Here is the syntax of continuations:\n*)\n\nInductive cont : Type :=\n  | Kstop\n  | Kseq (c: com) (k: cont)\n  | Kwhile (b: bexp) (c: com) (k: cont).\n\n(** Intuitive meaning of these three constructors:\n  - [Kstop] means that nothing remains to be done once the sub-command\n    terminates.  In other words, the sub-command under focus is the whole\n    command.\n  - [Kseq c k] means that when the sub-command terminates, we will then\n    execute the command [c], then continue as described by [k].\n  - [Kwhile b c k] means that when the sub-command terminates, we will then\n    execute the loop [WHILE b DO c END].  When this loop terminates,\n    we will continue as described by [k].\n*)\n\n(** Another way to form intuitions about continuations is to ponder\n    the [apply_cont k c] function below.  It takes the sub-command [c]\n    and the continuation [k], and rebuilds the whole command.  This is\n    achieved quite simpl by inserting [c] to the left of the nested\n    [SEQ] constructors described by [k]. *)\n\nFixpoint apply_cont (k: cont) (c: com) : com :=\n  match k with\n  | Kstop => c\n  | Kseq c1 k1 => apply_cont k1 (SEQ c c1)\n  | Kwhile b1 c1 k1 => apply_cont k1 (SEQ c (WHILE b1 c1))\n  end.\n\n(** The transitions between triples (sub-command, continuation, state)\n    can be classified in three groups:\n    - Computation steps: evaluate an arithmetic or Boolean expression,\n      and modify the triple accordingly.\n    - Focusing: replace the sub-command by a sub-sub-command that must\n      be executed first, enriching the continuation accordingly.\n    - Resumption: when the sub-command under focus is [SKIP], and therefore\n      has terminated, examine the head of the continuation to find\n      the next sub-command to focus on.\n\n    Here are the transition rules, annotated by the groups to which they\n    belong.\n*)\n\nInductive step: com * cont * store -> com * cont * store -> Prop :=\n\n  | step_assign: forall x a k s,              (**r computation *)\n      step (ASSIGN x a, k, s) (SKIP, k, update x (aeval a s) s)\n\n  | step_seq: forall c1 c2 s k,               (**r focusing *)\n      step (SEQ c1 c2, k, s) (c1, Kseq c2 k, s)\n\n  | step_ifthenelse: forall b c1 c2 k s,      (**r computation *)\n      step (IFTHENELSE b c1 c2, k, s) ((if beval b s then c1 else c2), k, s)\n\n  | step_while_done: forall b c k s,          (**r computation *)\n      beval b s = false ->\n      step (WHILE b c, k, s) (SKIP, k, s)\n\n  | step_while_loop: forall b c k s,          (**r computation + focusing *)\n      beval b s = true ->\n      step (WHILE b c, k, s) (c, Kwhile b c k, s)\n\n  | step_skip_seq: forall c k s,              (**r resumption *)\n      step (SKIP, Kseq c k, s) (c, k, s)\n\n  | step_skip_while: forall b c k s,          (**r resumption *)\n      step (SKIP, Kwhile b c k, s) (WHILE b c, k, s).\n\n(** As with every small-step semantics, we define termination and\n    divergence in terms of transition sequences.\n    Initial states are of the shape [(c, Kstop, s_initial)]\n    and final states [(SKIP, Kstop, s_final)].\n*)\n\nDefinition kterminates (s: store) (c: com) (s': store) : Prop :=\n  star step (c, Kstop, s) (SKIP, Kstop, s').\n\nDefinition kdiverges (s: store) (c: com) : Prop :=\n  infseq step (c, Kstop, s).\n\n(** *** Correspondence between continuation semantics and reduction semantics *)\n\n(** To build confidence, we can prove that the two small-step semantics\n    for IMP are equivalent: they agree on which commands terminate\n    and which commands diverge.\n\n    To prove this claim, we follow the approach based on simulation\n    diagrams that we also use to prove the correctness of the IMP compiler\n    (module [Compil]).  This proof is fairly technical and can be skipped\n    on first reading.\n    \n    Here is the relation between a configuration of the continuation semantics\n    and a configuration of the reduction semantics.\n*)\n\nInductive match_conf : com * cont * store -> com * store -> Prop :=\n  | match_conf_intro: forall c k s c',\n      c' = apply_cont k c ->\n      match_conf (c, k, s) (c', s).\n\n(** We show that every transition of the continuation semantics\n    is simulated by zero, one or several reduction steps.\n    The anti-stuttering measure counts the nesting of [SEQ] constructs\n    in the command. *)\n\nFixpoint num_seq (c: com) : nat :=\n  match c with\n  | SEQ c1 c2 => S (num_seq c1)\n  | _ => O\n  end.\n\nDefinition kmeasure (C: com * cont * store) : nat :=\n  let '(c, k, s) := C in num_seq c.\n\nRemark red_apply_cont:\n  forall k c1 s1 c2 s2,\n  red (c1, s1) (c2, s2) ->\n  red (apply_cont k c1, s1) (apply_cont k c2, s2).\nProof.\n  induction k; intros; simpl; eauto using red_seq_step.\nQed.\n\nLemma simulation_cont_red:\n  forall C1 C1', step C1 C1' ->\n  forall C2, match_conf C1 C2 ->\n  exists C2',\n     (plus red C2 C2' \\/ (star red C2 C2' /\\ kmeasure C1' < kmeasure C1))%nat\n  /\\ match_conf C1' C2'.\nProof.\n  destruct 1; intros C2 MC; inversion MC; subst; cbn.\n  2: econstructor; split; [right; split; [apply star_refl | lia] | constructor; auto ].\n  1-6: econstructor; split; [left; apply plus_one; apply red_apply_cont; auto using red | constructor; auto].\nQed.\n\n(** It follows that termination according to the continuation semantics\n    implies termination according to the reduction semantics,\n    and likewise for divergence. *)\n\nTheorem kterminates_terminates:\n  forall s c s', kterminates s c s' -> terminates s c s'.\nProof.\n  intros. \n  destruct (simulation_star _ _ _ _ _ _ simulation_cont_red _ _ H (c, s)) as ((c' & s'') & STAR & INV).\n  constructor; auto.\n  inversion INV; subst. apply STAR.\nQed.\n\nTheorem kdiverges_diverges:\n  forall s c, kdiverges s c ->  diverges s c.\nProof.\n  intros. \n  apply (simulation_infseq _ _ _ _ _ _ simulation_cont_red _ _ H).\n  constructor; auto.\nQed.\n\n(** The reverse implications follow from the symmetrical simulation diagram.\n    First, we need a technical lemma on reductions of commands of the\n    shape [apply_cont k c]. *)\n\nInductive red_apply_cont_cases: cont -> com -> store -> com -> store -> Prop :=\n  | racc_base: forall c1 s1 c2 s2 k,\n      red (c1, s1) (c2, s2) ->\n      red_apply_cont_cases k c1 s1 (apply_cont k c2) s2\n  | racc_skip_seq: forall c k s,\n      red_apply_cont_cases (Kseq c k) SKIP s (apply_cont k c) s\n  | racc_skip_while: forall b c k s,\n      red_apply_cont_cases (Kwhile b c k) SKIP s (apply_cont k (WHILE b c)) s.\n\nLemma invert_red_apply_cont:\n  forall k c s c' s',\n  red (apply_cont k c, s) (c', s') ->\n  red_apply_cont_cases k c s c' s'.\nProof.\n  induction k; simpl; intros. \n- (* Kstop *)\n  change c' with (apply_cont Kstop c'). apply racc_base; auto.\n- (* Kseq *)\n  specialize (IHk _ _ _ _ H). inversion IHk; subst.\n  + (* base *)\n    inversion H0; clear H0; subst.\n    * (* seq finish *)\n      apply racc_skip_seq.\n    * (* seq step *)\n      change (apply_cont k (c4;;c)) with (apply_cont (Kseq c k) c4). \n      apply racc_base; auto.\n- (* Kwhile *)\n  specialize (IHk _ _ _ _ H). inversion IHk; subst.\n  inversion H0; clear H0; subst.\n    * (* seq finish *)\n      apply racc_skip_while.\n    * (* seq step *)\n      change (apply_cont k (c4;;WHILE b c)) with (apply_cont (Kwhile b c k) c4). \n      apply racc_base; auto.\nQed.\n\nDefinition rmeasure (C: com * store) : nat := O.   (**r there is no stuttering *)\n\nLemma simulation_red_cont:\n  forall C1 C1', red C1 C1' ->\n  forall C2, match_conf C2 C1 ->\n  exists C2',\n     (plus step C2 C2' \\/ (star step C2 C2' /\\ rmeasure C1' < rmeasure C1))%nat\n  /\\ match_conf C2' C1'.\nProof.\n  intros C1 C1' R C2 MC. inversion MC; subst. destruct C1' as (c' & s').\n  assert (A: red_apply_cont_cases k c s c' s') by (apply invert_red_apply_cont; auto).\n  clear MC R. inversion A; subst; clear A.\n- cut (exists C2', plus step (c, k, s) C2' /\\ match_conf C2' (apply_cont k c2, s')).\n  intros (C2' & A & B). exists C2'; auto.\n  revert k. dependent induction H; intros.\n  + econstructor; split. apply plus_one; constructor. constructor; auto.\n  + econstructor; split.\n    eapply plus_left. constructor. eapply star_one. constructor.\n    constructor; auto.\n  + edestruct IHred as (((cx & kx) & sx) & A & B); eauto.\n    econstructor; split.\n    eapply plus_left. constructor. apply plus_star. eexact A. \n    exact B.\n  + econstructor; split. apply plus_one; constructor. constructor; auto.\n  + econstructor; split. apply plus_one; apply step_while_done; auto. constructor; auto.\n  + econstructor; split. apply plus_one; apply step_while_loop; auto. constructor; auto.\n- econstructor; split. \n  left; apply plus_one; constructor.\n  constructor; auto.\n- econstructor; split. \n  left; apply plus_one; constructor.\n  constructor; auto.\nQed.\n\nLemma apply_cont_is_skip:\n  forall k c, apply_cont k c = SKIP -> k = Kstop /\\ c = SKIP.\nProof.\n  induction k; cbn; intros.\n- auto.\n- apply IHk in H. intuition discriminate.\n- apply IHk in H. intuition discriminate.\nQed.\n\nTheorem terminates_kterminates:\n  forall s c s', terminates s c s' -> kterminates s c s'.\nProof.\n  intros. \n  destruct (simulation_star _ _ _ _ _ _ simulation_red_cont _ _ H (c, Kstop, s)) as ((c' & s'') & STAR & INV).\n  constructor; auto.\n  inversion INV; subst.\n  edestruct apply_cont_is_skip; eauto. subst k c0. apply STAR.\nQed.\n\nTheorem diverges_kdiverges:\n  forall s c, diverges s c ->  kdiverges s c.\nProof.\n  intros. \n  apply (simulation_infseq _ _ _ _ _ _ simulation_red_cont _ _ H).\n  constructor; auto.\nQed.\n", "meta": {"author": "xavierleroy", "repo": "cdf-mech-sem", "sha": "f8dc6f7e2cb42f0861406b2fa113e2a7e825c5f3", "save_path": "github-repos/coq/xavierleroy-cdf-mech-sem", "path": "github-repos/coq/xavierleroy-cdf-mech-sem/cdf-mech-sem-f8dc6f7e2cb42f0861406b2fa113e2a7e825c5f3/IMP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.907312226373181, "lm_q1q2_score": 0.8157838161379266}}
{"text": "Require Import ZArith_base.\nRequire Import Ring_theory.\n\nOpen Local Scope Z_scope.\n\n(** [Zpower_pos z n] is the n-th power of [z] when [n] is an binary\n      integer (type [positive]) and [z] a signed integer (type [Z]) *)\nDefinition Zpower_pos (z:Z) (n:positive) := iter_pos n Z (fun x:Z => z * x) 1.\n\nDefinition Zpower (x y:Z) :=\n    match y with\n      | Zpos p => Zpower_pos x p\n      | Z0 => 1\n      | Zneg p => 0\n    end.\n\nLemma Zpower_theory : power_theory 1 Zmult (eq (A:=Z)) Z_of_N Zpower.\nProof.\n constructor. intros.\n destruct n;simpl;trivial.\n unfold Zpower_pos.\n assert (forall k, iter_pos p Z (fun x : Z => r * x) k = pow_pos Zmult r p*k).\n induction p;simpl;intros;repeat rewrite IHp;trivial;\n   repeat rewrite Zmult_assoc;trivial.\n rewrite H;rewrite Zmult_1_r;trivial.\nQed.\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/ZArith/Zpow_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8157591855475645}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection IntLogic.\n\nVariables A B C : Prop.\n\nLemma notTrue_iff_False : (~ True) <-> False.\nProof.\n(* step-wise solutiton *)\nsplit.\n- by apply.\nmove=> f _. apply: f.\n\nRestart.\n\n(* idiomatic solution *)\nby [].\nQed.\n\n\nLemma dne_False : ~ ~ False -> False.\nProof.\nmove=> nnF; apply: nnF; apply.\n\nRestart.\n\n(* let's golf it a bit, just for fun *)\nexact: (@^~ id).\n\nRestart.\n(* and then a bit more *)\nexact.\n\nQed.\n\nLemma dne_True : ~ ~ True -> True.\nProof.\nmove=> _. exact: I.\n\nRestart.\n\nby [].\nQed.\n\nLemma weak_peirce : ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\nmove=> H.\napply: (H).\napply.\nmove=> p.\napply: H.\nmove=> _.\nexact: p.\n\nRestart.\n\nmove=> abaab; apply: (abaab); apply=> a.\nby apply: abaab.\nQed.\n\nLemma imp_trans : (A -> B) -> (B -> C) -> (A -> C).\nProof.\nmove=> pq qr p.\napply: qr.\napply: pq.\nexact: p.\n\nRestart.\n\nby move=> pq qr /pq/qr.\nQed.\n\n\nEnd IntLogic.\n\n\n(** Let's familiarize ourselves with some lemmas from [ssrbool] module.\n    The proofs are very easy, so the lemma statements are more important here.\n *)\nSection BooleanLogic.\n\nVariables (A B : Type) (x : A) (f : A -> B) (a b : bool) (vT vF : A).\n\nLemma negbNE : ~~ ~~ b -> b.\nProof. by case: b. Qed.\n\n(** Figure out what [involutive] and [injective] mean\n    using Coq's interactive queries. Prove the lemmas.\n    Hint: to unfold a definition in the goal use [rewrite /definition] command.\n*)\nLemma negbK : involutive negb.\nProof.\n(* A step-by-step solution *)\nrewrite /involutive.\nrewrite /cancel.\ncase.\n- done.\ndone.\n\nRestart.\n\n(* An idiomatic solution *)\nby case.\nQed.\n\nLemma negb_inj : injective negb.\nProof.\n(* A step-by-step solution *)\nrewrite /injective.\ncase.\n- case.\n  + done.\n  done.\ncase.\n- done.\ndone.\n\nRestart.\n\n(* An idiomatic solution is based on the fact that each involutive function is\n   injective *)\napply: inv_inj.\napply: negbK.\n\nRestart.\n\n(* or in one go: *)\n\nexact: inv_inj negbK.\nQed.\n\nLemma ifT : b -> (if b then vT else vF) = vT.\nProof.\n(* step-by-step *)\nSet Printing Coercions.\nrewrite /is_true.\nUnset Printing Coercions.\nmove=> ->.\ndone.\n\nRestart.\n\n(* SSReflect can see under coercions (definitions) and use [b] with\n   implicit coercion [is_true] as equation directly *)\nby move=> ->.\n\nRestart.\n\n(* another option would be to use case analysis on [b] like so: *)\nby case: b.\nQed.\n\nLemma ifF : b = false -> (if b then vT else vF) = vF.\nProof. by move=> ->. Qed.\n\nLemma if_same : (if b then vT else vT) = vT.\nProof.\ncase: b.\n- by [].\nby [].\n\nRestart.\n\nby case: b.\n(* It's important to understand why just [by [].] wouldn't work here.\n   We have to do case analysis on [b] if we want the to reduce the [if]-expression *)\nQed.\n\nLemma if_neg : (if ~~ b then vT else vF) = if b then vF else vT.\nProof. by case: b. Qed.\n\nLemma fun_if : f (if b then vT else vF) = if b then f vT else f vF.\nProof. by case: b. Qed.\n\nLemma if_arg (fT fF : A -> B) :\n  (if b then fT else fF) x = if b then fT x else fF x.\nProof. by case: b. Qed.\n\nLemma andbK : a && b || a = a.\nProof.\n(* (almost) step-wise solutiton *)\ncase: a.\n- by case: b.\nby [].\n\nRestart.\n\n(* idiomatic solution *)\nby case: a; case: b. (* case analyze on [a] and then for each of the two new\n                        subgoals do case analysis on [b] *)\nQed.\n\n(** Find out what [left_id], [right_id] mean\n    using Coq's interactive queries. Prove the lemmas.\n *)\nLemma addFb : left_id false addb.    (* [addb] means XOR (eXclusive OR operation) *)\nProof.\nrewrite /left_id.\nby case.\n\nRestart.\n\n(* idiomatic solution: don't have to unfold definitions, [case] will do it for us *)\nby case.\nQed.\n\nLemma addbF : right_id false addb.\nProof. by case. Qed.\n\nLemma addbC : commutative addb.\nProof.\ncase.\n- by case.\nby case.\n\nRestart.\n\n(* idiomatic solution: *)\nby do 2 case.  (* case-analyze on the head of the \"goal stack\" two times in a row *)\nQed.\n\nLemma addbA : associative addb.\nProof.\ncase.\n- case.\n  + by case.\n  by case.\ncase.\n- by case.\nby case.\n\nRestart.\n\nby do 3 case.\nQed.\n\n\n(** Formulate analogous laws (left/right identity, commutativity, associativity)\n    for boolean AND and OR and prove those.\n    Find the names of corresponding lemmas in the standard library using\n    [Search] command. For instance: [Search _ andb left_id.]\n    Have you noticed the naming patterns?\n *)\n\nLemma andFb : left_id true andb.\nProof. by case. Qed.\n\nLemma andbF : right_id true andb.\nProof. by case. Qed.\n\nLemma andbC : commutative andb.\nProof. by do 2 case. Qed.\n\nLemma andbA : associative andb.\nProof. by do 3 case. Qed.\n\nLemma orFb : left_id false orb.\nProof. by case. Qed.\n\nLemma orbF : right_id false orb.\nProof. by case. Qed.\n\nLemma orbC : commutative orb.\nProof. by do 2 case. Qed.\n\nLemma orbA : associative orb.\nProof. by do 3 case. Qed.\n\nEnd BooleanLogic.\n\n\n\nSection NaturalNumbers.\n(** Figure out what [cancel], [succn], [predn] mean\n    using Coq's interactive queries. Prove the lemmas.\n *)\nLemma succnK : cancel succn predn.\nProof.\nrewrite /cancel.\nmove=> n.\nby [].\n\nRestart.\nby [].\nQed.\n\nLemma add0n : left_id 0 addn.\nProof.\nrewrite /left_id.\nmove=> n.\nby [].\n\nRestart.\nby [].\nQed.\n\nLemma addSn m n : m.+1 + n = (m + n).+1.\nProof. by []. Qed.\n\nLemma add1n n : 1 + n = n.+1.\nProof. by []. Qed.\n\nLemma add2n m : 2 + m = m.+2.\nProof. by []. Qed.\n\nLemma subn0 : right_id 0 subn.\nProof.\nrewrite /right_id.\nmove=> n.\nFail by [].\ncase: n.\n- by [].\nmove=> n.\nby [].\n\nRestart.\nby case.\nQed.\n\nEnd NaturalNumbers.\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/homework/hw02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8962513710552469, "lm_q1q2_score": 0.8155054060736076}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat ssrfun.\n\nModule Lesson5.\n(* SSReflect tactics *)\n\nLemma modus_ponens (A B: Prop): A -> (A -> B) -> B.\nProof.\n  move=> a.\n  apply. (* Goal is a stack                           *)\n         (* apply takes top of the stack and apply it *)\n  exact: a.\nQed.\n\nLemma modus_ponens' (A B: Prop): A -> (A -> B) -> B.\nProof.\n  move=> a ab.\n  apply: ab.\n  exact: a.\nQed.\n\nDefinition and1 (A B: Prop):\n  A /\\ B -> A.\nProof.\n  case. (* stack operation again. take top of stack, destruct it, and put back to stack *)\n  move=> pa _.\n  exact: pa.\nQed.\n\nDefinition andC (A B: Prop):\n  A /\\ B -> B /\\ A.\nProof.\n  case=> pa pb.\n  split.\n  - exact: pb.\n  - exact: pa.\nQed.\n\nDefinition orC (A B: Prop):\n  A \\/ B -> B \\/ A.\nProof.\n  case.\n  - right.\n    exact: a.\n  left.\n  exact: b.\nQed.\n\nDefinition andD (A B C: Prop):\n  (A \\/ B) /\\ C -> (A /\\ C) \\/ (B /\\ C).\nProof.\n  case.\n  case => [a|b] c.\n    by left.\n  by right.\nQed.\n\nDefinition andD1 (A B C: Prop):\n  (A \\/ B) /\\ C -> (A /\\ C) \\/ (B /\\ C).\nProof.\n  by case => [[a|b] c]; [left | right].\nQed.\n\n\nLemma HilbertSaxion A B C: (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> abc ab a.\nmove: abc. (* move back    \"move: (abc).\" will move to stack and safe it in context *)\napply.     (* apply top of the stack to goal *)\n  exact: a.\napply: ab. (* apply from context *)\nexact: a.\nQed.\n\n(* => - move from stack to ctx\n   :  - move from ctx to stack and apply tactic from left *)\n\n(* by [].  -  done. *)\n\n\nLemma HilbertSaxion1 A B C: (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> abc ab a.\nby apply: abc; [done | apply: ab].\nQed.\n\nLemma HilbertSaxion2 A B C: (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> abc ab a.\napply: abc=> //.\nby apply: ab.\nQed.\n\n\nSection RewriteTactic.\nVariable (A: Type).\nImplicit Types x y z : A.\nLemma esym x y :\n  x = y -> y = x.\nProof.\nmove=> eq_xy.\nrewrite eq_xy.\ndone.\nQed.\n\nLemma esym_short x y :\n  x = y -> y = x.\nProof.\nmove=> ->.\ndone.\nQed.\n\nLemma trans x y z:\n  x = y -> y = z -> x = z.\nProof.\nmove=> ->.\ndone.\nQed.\n\nEnd RewriteTactic.\n\n\nLemma addnA : associative addn.\nProof.\nrewrite /associative.\nmove => x y z.\nRestart.\nmove => x y z.\nelim: x => [|x' IHx] //.\nShow Proof.\nSearch (_.+1 + _).\nby rewrite addSn IHx.\nQed.\n\nLemma addnA2 : associative addn.\nProof.\nelim => [|x' IHx] y z //. (* elim top stack *)\nby rewrite addSn IHx.\nQed.\n\nEnd Lesson5.\n", "meta": {"author": "cattingcat", "repo": "coq_lessons", "sha": "49ea5727398acddd5b347b234d6b4efcab305422", "save_path": "github-repos/coq/cattingcat-coq_lessons", "path": "github-repos/coq/cattingcat-coq_lessons/coq_lessons-49ea5727398acddd5b347b234d6b4efcab305422/comp_sci_club-formal_verif_2021/Lesson5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.894789457685656, "lm_q1q2_score": 0.8153140007338286}}
{"text": "\nSet Warnings \"-notation-overriden,-parsing\".\nFrom LF Require Export Volume1_Ch5_Tactics.\n\n(* Logic in Coq *) \n\nCheck 3 = 3 : Prop.\n\nCheck forall n m : nat, n + m = m + n : Prop.\n\n\nCheck 2 = 2 : Prop.\n\nCheck 3 = 2 : Prop.\n\nCheck forall n : nat, n = 2 : Prop.\n\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity. Qed.\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : Prop.\n\nTheorem plus_claim_is_true :\n  plus_claim.\nProof. reflexivity. Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three : nat -> Prop.\n\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1.\n  apply H1.\nQed.\n\nCheck @eq : forall A : Type, A -> A -> Prop.\n\n\n(* Logical Connectives *) \n\n(* Conjunction *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 * 2 = 4 *) reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n\n(* Exercise *)\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\nAdmitted.\n\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn.\n  rewrite Hm.\n  reflexivity.\nQed.\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.\n  rewrite Hm.\n  reflexivity.\nQed.\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\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  apply and_exercise in H.\n  destruct H as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n\nLemma proj1 : forall P Q : Prop,\n    P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  apply HP. Qed.\n\n\n(* Exercise *)\n\nLemma proj2 : forall P Q : Prop,\n    P /\\ Q -> Q.\nProof.\nAdmitted.\n\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 *)\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]].\nAdmitted.\n\nCheck and : Prop -> Prop -> Prop.\n\n(* Disjunction *)\n\nLemma eq_mult_0 :\n  forall n m : nat, n = 0 \\/ m = 0 -> n *  m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - (* n = 0 *)\n    rewrite Hn. reflexivity.\n  - (* m = 0 *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma 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\n(* Falsehood and Negation *)\nModule MyNot.\n  Definition not (P:Prop) := P -> False.\n\n  Notation \"~ x\" := (not x) : type_scope.\n\n  Check not : Prop -> Prop.\n\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n    False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\n(* Exercise *)\nFact not_implies_our_not : forall (P:Prop),\n    ~P -> (forall (Q:Prop), P -> Q).\nProof.\nAdmitted.\n\nNotation \"x <> y\" := (~(x = y)).\n\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate contra.\nQed.\n\nTheorem not_False :\n  ~False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n    (P /\\ ~P) -> Q.\nProof.\n  intros P Q [HP HNA].\n  unfold not in HNA.\n  apply HNA in HP.\n  destruct HP.\nQed.\n\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\n\n(* Exercise *)\n\n  \nTheorem contrapositive : forall (P Q : Prop),\n    (P -> Q) -> (~Q -> ~P).\nProof.\nAdmitted.\n\nTheorem not_both_true_and_false : forall P : Prop,\n    ~(P /\\ ~P).\nProof.\nAdmitted.\n\nTheorem not_true_is_false : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn:HE.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H.\n    reflexivity.\n  - (* b = fasle *)\n    reflexivity.\nQed.\n\n\nTheorem not_tru_is_false' : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    exfalso.\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\n\n(* Truth *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n       \n(* Logical Equivalence *)\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\n\nTheorem iff_sym : forall P Q : Prop,\n    (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB. Qed.\n\n\nLemma not_true_iff_false : forall b,\n    b <> true <-> b = false.\nProof.\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *) intros H.\n    rewrite H. intros H'. discriminate H'.\nQed.\n\n\n(* Exercise *)\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n    P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nAdmitted.\n\n(* Setoids and Logical Equivalence *)\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. inversion contra.\nQed.\n\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply eq_mult_0.\nQed.\n\n\nTheorem or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\nLemma mult_0_3:\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\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(* Existential Quantification *)\n\nDefinition even x := exists n : nat, x = double n.\n\nLemma four_is_even : even 4.\nProof.\n  unfold even. exists 2. reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n    (exists m, n = 4 + m) ->\n    (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm. Qed.\n\nTheorem dist_not_exists : forall (X:Type) (P: X -> Prop),\n    (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\nAdmitted.\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.\nAdmitted.\n\n\n\n(* Programming with Propositions *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1;2;3;4;5].\nProof. simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n            exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n\n(* Exercise *)\n\nTheorem In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\nAdmitted.\n\n\nTheorem In_app_iff : forall A l l' (a:A),\n    In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l. induction l as [|a' l' IH].\nAdmitted.\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop\n. Admitted.\n\nTheorem All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\nAdmitted.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop\n. Admitted.\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.\nAdmitted.\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.\nAdmitted.\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.\nAdmitted.\n\n(* Applying Theorems to Arguments *)\n\nCheck plus_comm : forall n m : nat, n + m = m + n.\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite plus_comm.\nAbort.\n\nLemma plus_comm3_take2 : \n      forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nTheorem in_not_nil:\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl.\n  rewrite Hl in H.\n  simpl in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  Fail applhy in_not_nil.\nAbort.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take5:\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns ) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n    as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(* Coq vs Set Theory *) \n\n(* functional Extensionality *)\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\nAbort.\n\nAxiom functional_extensionality : forall {X Y : Type}\n                                         {f g : X -> Y},\n    (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2' : \n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2'.\n\n\n(* Exercise *)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x::l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n    \nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\nAdmitted.\n\n(* Propositions vs. Booleans *)\n\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\n\nExample even_42_prop : even 42.\nProof. unfold even. exists 21. reflexivity. Qed.\n\n\nLemma evenb_double: forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\nLemma evenb_double_conv : forall n, exists k,\n      n = if evenb n then double k else S (double k).\nProof.\nAdmitted.\n\nTheorem even_bool_prop : forall n,\n    evenb n = true <-> even n.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n    n1 =? n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply eqb_true.\n  - intros H. rewrite H. rewrite <- eqb_refl. reflexivity.\nQed.\n\nFail\n  Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\nExample even_1000 : even 1000.\nProof. unfold even. exists 500. reflexivity. Qed.\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\nExample even_1000'' : even 1000.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  reflexivity.\nQed.\n\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 plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  intros n m p H.\n  rewrite eqb_eq in H.\n  rewrite H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\n(* Exercise *)\n\nTheorem andb_true_iff : forall b1 b2 : bool,\n    b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\nAdmitted.\n\nTheorem orb_true_iff : forall b1 b2,\n    b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\nAdmitted.\n\n\nTheorem eqb_neq : forall x y : nat,\n    x =? y = false <-> x <> y.\nProof.\nAdmitted.\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n         (l1 l2 : list A) : bool\n. Admitted.\n\n\nTheorem eqb_list_true_iff :\n  forall A (eqb : A -> A -> bool),\n    (forall a1 a2, eqb a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, eqb_list eqb l1 l2 = true <-> l1 = l2.\nProof.\nAdmitted.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n\nTheorem forallb_true_iff : forall X test (l : list X),\n    forallb test l = true <-> All (fun x => test x = true) l.\nProof.\nAdmitted.\n\n\n(* Classical vs Contructive Logic *)\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\n(* Exercise *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n    ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H.\nAdmitted.\n\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\nAdmitted.\n\nDefinition peirce := forall P Q: Prop,\n    ((P->Q)->P)->P.\n\nDefinition double_negation_elemination := 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           \n\n\n\n", "meta": {"author": "leechanwoo", "repo": "coq", "sha": "0ac863e4686c608d29ffb9c361d98180e45a727d", "save_path": "github-repos/coq/leechanwoo-coq", "path": "github-repos/coq/leechanwoo-coq/coq-0ac863e4686c608d29ffb9c361d98180e45a727d/Volume1_Ch6_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.888758803068433, "lm_q1q2_score": 0.8152608117756255}}
{"text": "Require Export Induction.\nModule NatList.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition myList := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | 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\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | n :: m => match beq_nat n 0 with\n              | true => (nonzeros m)\n              | false => n :: (nonzeros m)\n              end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | n :: m => match oddb n with\n              | true => n :: (oddmembers m)\n              | false => (oddmembers m)\n              end\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | n :: m => match l2 with\n              | nil => l1\n              | a :: b => n :: a :: (alternate m b)\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  | n :: m => match beq_nat v n with\n              | true => 1 + (count v m)\n              | false => (count v m)\n              end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match (count v s) with\n  | 0 => false\n  | S 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  | n :: m => match beq_nat v n with\n              | true => m\n              | false => n :: (remove_one v m)\n              end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | n :: m => match beq_nat v n with\n              | true => (remove_all v m)\n              | false => n :: (remove_all v m)\n              end\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | n :: m => match (member n s2) with\n              | true => (subset m (remove_one n 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\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\n\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1'.\n    rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive: forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l IHl'].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n    rewrite -> IHl'. 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. rewrite -> app_assoc.\n  reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. destruct beq_nat.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | nil => match l2 with\n           | nil => true\n           | o :: p => false\n           end\n  | n :: m => match (member n l2) with\n              | false => false\n              | true => (beq_natlist m (remove_one n l2))\n              end\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof.\n  reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof.\n  reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof.\n  reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [|n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. destruct member.\n    + destruct beq_nat.\n      * rewrite <- IHl'. reflexivity.\n      * rewrite -> IHl'. \n  Admitted.\n\nTheorem count_member_nonzero : forall(s:bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. simpl. reflexivity. Qed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'.\n    reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s:bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. induction s as [|n s' IHs'].\n  - simpl. reflexivity.\n  - destruct n as [|n'].\n    + simpl. rewrite -> ble_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs'. reflexivity.\nQed.\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match beq_nat n 0 with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n 0 with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof.\n  reflexivity. Qed.\n\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof.\n  reflexivity. Qed.\n\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof.\n  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 0 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.\n  reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof.\n  reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof.\n  reflexivity. Qed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l d. induction l as [|n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intros x. destruct x.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d : partial_map)\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.\n  Proof.\n    intros d x v.\n    simpl. rewrite <- beq_id_refl.\n    reflexivity.\n  Qed.\n\nTheorem update_neq :\n  forall(d : partial_map) (x : id) (v : nat),\n    find x (update d x v) = Some v.\n  Proof.\n    intros d x v.\n    simpl. rewrite <- beq_id_refl.\n    reflexivity.\n  Qed.\n\nEnd PartialMap.\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n\n\n\n", "meta": {"author": "binaks", "repo": "funtp", "sha": "b196c7da3aecea3ff6afcc5902560dbc0afb5bad", "save_path": "github-repos/coq/binaks-funtp", "path": "github-repos/coq/binaks-funtp/funtp-b196c7da3aecea3ff6afcc5902560dbc0afb5bad/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.91243616285804, "lm_q1q2_score": 0.8150878118885759}}
{"text": "Inductive Nat : Type :=\n  z : Nat\n| s : Nat -> Nat\n.\nEval simpl in nat_ind.\nEval simpl in Nat_ind.\n\nEval simpl in z.\nEval simpl in s(s z).\n\n\nFixpoint add(l:Nat)(r:Nat) : Nat :=\n  match l with\n  | z => r\n  | s l' => s (add l' r)\nend.\n\nEval simpl in add (s z) (s (s z)).\n\nLemma add_succ : forall l r : Nat, s (add l r) = add l (s r).\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\n  reflexivity.\nQed.\n\nTheorem add_comm : forall l r : Nat, add l r = add r l.\nProof.\n  intros.\n  induction l.\n  simpl.\n  induction r.\n  reflexivity.\n  simpl.\n  rewrite <- IHr.\n  reflexivity.\n  simpl.\n  rewrite IHl.\n  assert (forall x y, s(add x y) = add x (s y)).\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  rewrite <- IHx.\n  reflexivity.\n  apply H.\nQed.\n  \nFixpoint add_tr(l:Nat)(r:Nat) : Nat :=\n  match l with\n  | z => r\n  | s l' => add_tr l' (s r)\nend.\n\nEval simpl in add_tr (s z) (s (s z)).\n\nLemma add_tailrec_succ : forall l r : Nat, add_tr (s l) r = add_tr l (s r).\nProof.\n  intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem add_tailrec_comm : forall l r : Nat, add_tr l r = add_tr r l.\nProof.\n  intros.\n  induction l.\n  simpl.\n  assert (forall x, add_tr z x = add_tr x z).\n  induction x.\n  reflexivity.\n  simpl.\n  assert (forall x, add_tr x (s z) = s (add_tr x z)).\n  induction x0.\n  simpl.\n  reflexivity.\n  \n", "meta": {"author": "tsukimizake", "repo": "coq_add_tailrec", "sha": "37306352e4be0692cb94d7fa318f95366148a642", "save_path": "github-repos/coq/tsukimizake-coq_add_tailrec", "path": "github-repos/coq/tsukimizake-coq_add_tailrec/coq_add_tailrec-37306352e4be0692cb94d7fa318f95366148a642/hoge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8933093996634686, "lm_q1q2_score": 0.8150878051280699}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars (optimize_0plus_b)  *)\n(** Since the [optimize_0plus] tranformation doesn't change the value\n    of [aexp]s, we should be able to apply it to all the [aexp]s that\n    appear in a [bexp] without changing the [bexp]'s value.  Write a\n    function which performs that transformation on [bexp]s, and prove\n    it is sound.  Use the tacticals we've just seen to make the proof\n    as elegant as possible. *)\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)\nend.\n\nExample optimize_0plus_b_example1:\n  optimize_0plus_b (BEq \n     (AMult (APlus (ANum 0) (APlus (ANum 0) (ANum 3)))\n            (AMinus (ANum 5) (APlus (ANum 0) (ANum 1))))\n     (APlus (ANum 2)\n            (APlus (ANum 0)\n                   (APlus (ANum 0) (ANum 1)))))\n  = (BEq (AMult (ANum 3) (AMinus (ANum 5) (ANum 1)))\n         (APlus (ANum 2) (ANum 1))).\nProof. simpl. reflexivity. Qed.  \n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\"\n  | Case_aux c \"BEq\"   | Case_aux c \"BLe\"\n  | Case_aux c \"BNot\"  | Case_aux c \"BAnd\" ].\n\nTheorem optimize_0plus_sound : forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof. intros. induction a; try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  Case \"ANum\". reflexivity.\n  Case \"APlus\". destruct a1; try(simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    SCase \"a1 = ANum n\". destruct n. simpl. assumption. simpl. rewrite IHa2. reflexivity.\nQed.\n\nTheorem optimize_0plus_b_sound : forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros. bexp_cases (induction b) Case; try(reflexivity;reflexivity).\n  simpl; repeat (rewrite optimize_0plus_sound); reflexivity.\n  simpl; repeat (rewrite optimize_0plus_sound); reflexivity.\n  simpl. rewrite IHb. reflexivity.\n  simpl. rewrite IHb1. rewrite IHb2. reflexivity.\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/07/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.9219218396818158, "lm_q1q2_score": 0.8150151266115134}}
{"text": "(* I have not worked with any partners. *)\n(** * Lists: Working with Structured Data *)\n\nRequire Export LF.Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    [Basics] chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p as [m n]. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n   the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n   you read them in a .v file.  The inner brackets, around 3, indicate\n   a list, but the outer brackets, which are invisible in the HTML\n   rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | O::t => (nonzeros t)\n    | h::t => h::(nonzeros t)\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity.  Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h::t => 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\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity.  Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    | nil, _ => l2\n    | _, nil => l1\n    | (h1::t1), (h2::t2) => h1::h2::(alternate t1 t2)\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n    | nil => O\n    | h::t => match (beq_nat h v) with\n      | true => S (count v t)\n      | false => count v t\n    end\n  end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  v::s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  negb (blt_nat (count v s) (S O)).\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\nExample test_member3:             member 2 [1;2;1] = true.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more bag functions for you to practice with. *)\n\n(** When remove_one is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    | nil => nil\n    | h::t => match (beq_nat v h) with\n      | true => t\n      | false => h::(remove_one v t)\n    end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n    | nil => nil\n    | h::t => match (beq_nat v h) with\n      | true => remove_all v t\n      | false => h::(remove_all v t)\n    end\n  end.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n    | nil => true\n    | h::t => match (member h s2) with\n      | true => (subset t (remove_one h s2))\n      | false => false\n    end\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\nExample test_subset3:              subset [1;2;2] [2;2;1] = true.\nProof. reflexivity. Qed.\nExample test_subset4:              subset [1;2;2] [2;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\nTheorem add_count_plus : forall (n : nat) (s : bag) ,\n  count n (add n s) = S (count n s).\nProof.\n  intro n. destruct s.\n  - simpl. rewrite<-beq_nat_refl. reflexivity.\n  - simpl. rewrite<-beq_nat_refl. reflexivity.\nQed.\n\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Notice that, as when doing induction on natural numbers, the\n    [as...] clause provided to the [induction] tactic gives a name to\n    the induction hypothesis corresponding to the smaller list [l1']\n    in the [cons] case. Once again, this Coq proof is not especially\n    illuminating as a static written document -- it is easy to see\n    what's going on if you are reading the proof in an interactive Coq\n    session and you can see the current goal and context at each\n    point, but this state is not visible in the written-down parts of\n    the Coq proof.  So a natural-language proof -- one written for\n    human readers -- will need to include more explicit signposts; in\n    particular, it will help the reader stay oriented if we remind\n    them exactly what the induction hypothesis is in the second\n    case. *)\n\n(** For comparison, here is an informal proof of the same theorem. *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (the induction hypothesis). We must show\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     By the definition of [++], this follows from\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     which is immediate from the induction hypothesis.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reversing a List *)\n\n(** For a slightly more involved example of inductive proof over\n    lists, suppose we use [app] to define a list-reversing function\n    [rev]: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Properties of [rev] *)\n\n(** Now let's prove some theorems about our newly defined [rev].\n    For something a bit more challenging than what we've seen, let's\n    prove that reversing a list does not change its length.  Our first\n    attempt gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving [++], but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\n(** So let's take the equation relating [++] and [length] that\n    would have enabled us to make progress and prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\nSearch rev.\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite->IHl. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - simpl. rewrite->app_nil_r. reflexivity.\n  - simpl. rewrite<-app_assoc. rewrite<-IHl1'. reflexivity.\nQed.\n  \n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite->rev_app_distr. simpl. rewrite->IHl'. reflexivity.\nQed.\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros.\n  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. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. destruct n as [|n'].\n    + rewrite->IHl1'. reflexivity.\n    + simpl. rewrite<-IHl1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n    | nil => match l2 with\n      | nil => true\n      | _ => false\n      end\n    | h1::t1 => match l2 with\n      | nil => false\n      | h2::t2 => match (beq_nat h1 h2) with\n        | true => beq_natlist t1 t2\n        | false => false\n        end\n      end\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite<-beq_nat_refl. rewrite<-IHl'. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs)  *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags above. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  destruct s.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(** The following lemma about [leb] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nCheck leb.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  induction s.\n  - reflexivity.\n  - destruct n as [|n'].\n    + simpl. rewrite->ble_n_Sn. reflexivity.\n    + simpl. rewrite->IHs. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it.  (You may\n    find that the difficulty of the proof depends on how you defined\n    [count]!) *)\n\nTheorem bag_count_sum: forall (s1 s2 : bag) (n : nat),\n  count n (sum s1 s2) = count n s1 + count n s2.\nProof.\n  intros. induction s1 as [|h s1' IHs1'].\n  - reflexivity.\n  - simpl. destruct (beq_nat h n).\n    + simpl. rewrite IHs1'. reflexivity.\n    + rewrite IHs1'. reflexivity.\nQed.\n  \n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(There is a hard way and an easy way to do this.) *)\n\nLemma rev_func: \n  forall (l1 l2 : natlist), l1 = l2 -> rev l1 = rev l2.\nProof.\n  intros. rewrite->H. reflexivity.\nQed.\n\nTheorem rev_injective:\n  forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros. replace l1 with (rev (rev l1)). replace l2 with (rev (rev l2)).\n  apply rev_func. rewrite H. reflexivity. \n  rewrite->rev_involutive. reflexivity.\n  rewrite->rev_involutive. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n    | nil => None\n    | h::t => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros. destruct l.\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish.\n\n    We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  destruct x.\n  simpl. rewrite<-beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros. simpl. rewrite<-beq_id_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros. simpl. rewrite->H. reflexivity. Qed.\n  \n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?  (Answer in English\n    or the natural language of your choice.)\n\nZero. Because both [Baz1] and [Baz2] require a [baz] in order to construct a new [baz].\nHowever we do not have a basic [baz] type that can be constructed immediately.\n*)\n(** [] *)\n\n(** $Date: 2017-08-24 10:54:05 -0400 (Thu, 24 Aug 2017) $ *)\n\n", "meta": {"author": "qq456cvb", "repo": "lf", "sha": "1a0b565880df5f4d891aa88c9674afeff8991cc8", "save_path": "github-repos/coq/qq456cvb-lf", "path": "github-repos/coq/qq456cvb-lf/lf-1a0b565880df5f4d891aa88c9674afeff8991cc8/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8146997255042434}}
{"text": "Require Export A007logic.\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n\n\nInductive ev : nat -> Prop :=\n  | ev0  : ev 0\n  | evSS : forall n : nat, ev n -> ev (S (S n)).\n\n\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intro.\n  induction n.\n  simpl. apply ev0.\n  simpl. apply evSS. exact IHn.\nQed.\n\n\nTheorem ev__even : forall n,\n                    ev n -> even n.\nProof.\n  intros.\n  induction H.\n  simpl.\n  reflexivity.\n  unfold even in IHev. unfold even. simpl. assumption.\nQed.\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros.\n  induction H.\n  simpl. assumption.\n  simpl. apply evSS. 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 : forall m n : nat,\n            beautiful m -> beautiful n ->\n            beautiful (m + n).\n\nTheorem beautiful_8 : beautiful 8.\nProof.\n  replace (8) with (3 + 5).\n  apply b_sum.\n  apply b_3.\n  apply b_5.\n  reflexivity.\nQed.\n\nTheorem beautiful_8' : beautiful 8.\nProof.\n  replace (8) with ((5 + 3) + 0).\n  apply b_sum.\n  apply b_sum.\n  apply b_5.\n  apply b_3.\n  apply b_0.\n  reflexivity.\nQed.\n\nTheorem beautiful_plus_eight:\n  forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros.\n  apply b_sum.\n  apply beautiful_8.\n  assumption.\nQed.\n\nTheorem b_times2:\n  forall n, beautiful n -> beautiful (2 * n).\nProof.\n  simpl.\n  intros.\n  rewrite plus_assoc.\n  apply b_sum.\n  apply b_sum.\n  assumption. assumption.\n  apply b_0.\nQed.\n\nTheorem b_timesm:\n  forall n m, beautiful n -> beautiful (m * n).\nProof.\n  intros.\n  induction m.\n  simpl. apply b_0.\n  simpl. apply b_sum.\n  assumption.\n  assumption.\nQed.\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\nTheorem gorgeous_plus13: forall n,\n                           gorgeous n -> gorgeous (13+n).\nProof.\n  intros.\n  replace 13 with (3 + 5 + 5).\n  replace (3 + 5 + 5 + n) with (3 + (5 + (5 + n))).\n  apply g_plus3. apply g_plus5. apply g_plus5.\n  assumption.\n  reflexivity.\n  reflexivity.\nQed.\n\n\nTheorem gorgeous__beautiful : forall n,\n                                gorgeous n -> beautiful n.\nProof.\n  intros.\n  induction H.\n  Case \"0\".\n  apply b_0.\n  Case \"3 + n\".\n  apply b_sum. apply b_3. assumption.\n  Case \"5 + n\".\n  apply b_sum. apply b_5. assumption.\nQed.\n\n\nTheorem gorgeous_sum : forall n m,\n                         gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros.\n  induction H.\n  Case \"0\". simpl. assumption.\n  Case \"3+n\". rewrite <- plus_assoc. apply g_plus3. assumption.\n  Case \"5+n\". rewrite <- plus_assoc. apply g_plus5. assumption.\nQed.\n\nTheorem beautiful__gorgeous :\n  forall n, beautiful n -> gorgeous n.\nProof.\n  intros.\n  induction H.\n  SCase \"0\". apply g_0.\n  SCase \"3\". apply g_plus3 with (n:=0). apply g_0.\n  SCase \"5\". apply g_plus5. apply g_0.\n  SCase \"m + n\". apply gorgeous_sum; assumption.\nQed.\n\nLemma helper_g_times2 :\n  forall x y z, x + (z + y)= z + x + y.\nProof.\n  intros.\n  rewrite plus_assoc.\n  replace (x + z) with (z + x). reflexivity.\n  rewrite plus_comm. reflexivity.\nQed.\n\nTheorem g_times2:\n  forall n, gorgeous n -> gorgeous (2 * n).\nProof.\n   intros n H. simpl.\n   induction H.\n\n   Case \"0\".\n   simpl. apply g_0.\n\n   Case \"3 + n\".\n   rewrite <- helper_g_times2.\n   apply gorgeous_sum. assumption.\n   apply g_plus3. rewrite <- plus_assoc. apply g_plus3.\n   rewrite plus_comm. simpl. assumption.\n\n   Case \"5 + n\".\n   rewrite <- helper_g_times2.\n   apply gorgeous_sum. assumption.\n   apply g_plus5. rewrite <- plus_assoc. apply g_plus5.\n   rewrite plus_comm. simpl. assumption.\nQed.\n\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros.\n(*(* the induction way *)\n  induction H.\n  simpl. apply ev0.\n  simpl. apply H.\n*)\n  (* the inversion way *)\n  inversion H.\n  simpl. apply ev0.\n  simpl. assumption.\n\n  (* ex: Why not `destruct`?\n     because destruct does not introduce the inductive rule for\n      ev n -> ev (S (S n))\n     therefore the second goal will be `ev (S (S n))` while without an\n     assumption of `ev n`, which is not provable.\n  *)\n Qed.\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros.\n  inversion H.\n  assumption.\nQed.\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  assumption.\nQed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H. inversion H1. inversion H3.\nQed.\n\n\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros.\n  induction H0.\n\n  simpl in H. assumption.\n\n  simpl in H. inversion H.\n  apply IHev in H2. 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  apply ev_sum with (n := n + p) in H.\n  replace (n + p + (n + m)) with (double n + m + p) in H.\n  rewrite <- plus_assoc in H.\n  apply ev_ev__ev with (m := m + p) in H. assumption.\n\n  (* disgusting.... *)\n  assert (forall n' m', double n' + m' + m' = double (n' + m')).\n  clear. intros. rewrite double_plus.\n  replace (n' + n' + m' + m') with ((n' + m') + (n' + m')).\n  rewrite <- double_plus. reflexivity.\n  rewrite <- plus_assoc. replace (m' + (n' + m')) with (n' + m' + m').\n  rewrite plus_assoc. rewrite plus_assoc. reflexivity.\n  rewrite plus_comm. reflexivity.\n  rewrite H1. apply double_even.\n\n  rewrite double_plus.\n  rewrite plus_assoc. rewrite <- plus_assoc with (m := p).\n  rewrite <- plus_comm with (m := p) (n := n).\n  rewrite plus_assoc. rewrite <- plus_assoc with (m := p).\n  rewrite plus_comm with (m := m) (n := p).\n  rewrite plus_assoc. reflexivity.\n\n  assumption.\nQed.\n\n\nInductive pal {X : Type} : list X -> Prop :=\n  | pal_null : pal []\n  | pal_one : forall x, pal [x]\n  | pal_induction : forall (xs : list X) (x : X),\n                      pal xs -> pal ([x] ++ xs ++ [x]).\n\nLemma snoc_app :\n  forall {X : Type} (xs : list X) (x : X), snoc xs x = xs ++ [x].\nProof.\n  intros.\n  induction xs.\n  simpl. reflexivity.\n  simpl.\n  rewrite IHxs. reflexivity.\nQed.\n\nLemma cons_app :\n  forall {X : Type} (xs : list X) (x : X), cons x xs = [x] ++ xs.\nProof.\n  intros.\n  induction xs.\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\nLemma app_assoc' : forall {X : Type} (l m n: list X),\n                     l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite IHl.\n  reflexivity.\nQed.\n\n\nGoal forall {X : Type} (l : list X), pal (l ++ rev l).\nProof.\n  intros.\n  induction l.\n  Case \"l = []\".\n    simpl. apply pal_null.\n  Case \"l = x :: l\".\n    simpl. rewrite cons_app.\n    rewrite snoc_app.\n    replace ([x] ++ l ++ rev l ++ [x]) with ([x] ++ (l ++ rev l) ++ [x]).\n    apply pal_induction. assumption.\n\n    replace ((l ++ rev l) ++ [x]) with (l ++ rev l ++ [x]).\n    reflexivity. apply app_assoc'.\nQed.\n\nLemma rev_appl : forall {X:Type} (l : list X) (x : X),\n                   rev (l ++ [x]) = [x] ++ rev l.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite snoc_app.\n  rewrite snoc_app.\n  rewrite IHl.\n  rewrite cons_app with (xs := (rev l ++ [x0])).\n  symmetry.\n  apply app_assoc'.\nQed.\n\nGoal forall {X:Type} (l : list X), pal l -> l = rev l.\nProof.\n  intros.\n  induction H.\n  reflexivity.\n  reflexivity.\n\n  simpl.\n  rewrite snoc_app.\n  rewrite rev_appl.\n  rewrite cons_app.\n  rewrite <- IHpal.\n  apply app_assoc'.\nQed.\n\nLemma rev_appr : forall {X:Type} (l : list X) (x : X),\n                   rev ([x] ++ l) = rev l ++ [x].\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  rewrite snoc_app.\n  rewrite snoc_app.\n  reflexivity.\nQed.\n\nGoal forall {X:Type} (l:list X), l = rev l -> pal l.\nProof.\n  induction l.\n  intros.\n  apply pal_null.\n\n  simpl.\n  rewrite cons_app.\n  rewrite snoc_app.\n  intros.\n\n  induction (rev l) eqn:revl.\n  inversion H. constructor.\n\n  inversion H. clear IHl0.\n\n  (* TODO: too difficult. 5 star question *)\nAbort.\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | ss_nul : forall ns, subseq [] ns\n  | ss_mat : forall ns ms, subseq ns ms -> (forall n, subseq (n::ns) (n::ms))\n  | ss_notmat : forall ns ms, subseq ns ms -> (forall m, subseq ns (m :: ms)).\n\nTheorem subseq_refl : forall l, subseq l l.\nProof.\n  intros.\n  induction l.\n\n  constructor.\n  constructor. assumption.\nQed.\n\nLemma app_comm_cons' :\n  forall {A:Type} (x y:list A) (a:A), a :: (x ++ y) = (a :: x) ++ y.\nProof.\n  intros.\n  induction x.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem subseq_app : forall l1 l2 l3, subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H.\n\n  constructor.\n\n  rewrite <- app_comm_cons'.\n  constructor. assumption.\n\n  rewrite <- app_comm_cons'.\n  constructor. assumption.\nQed.\n\nLemma subseq_notnull : forall x, forall l1,\n                         ~(subseq (x :: l1) []).\nProof.\n  intros. intro.\n  inversion H.\nQed.\n\n\nTheorem subseq_trans : forall l1 l2 l3,\n                         subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H1 H2.\n  generalize dependent l2.\n  generalize dependent l3.\n\n  induction l1.\n  constructor.\n\n  intros.\n  induction H1.\n  constructor.\n\n(* To save your life, keep away from such tough questions *)\nAbort.\n\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\nGoal R 2 [1;0].\nProof.\n  apply c2. apply c2. apply c1.\nQed.\n\nGoal R 1 [1;2;1;0].\nProof.\n  apply c3. apply c2. apply c3. apply c3. apply c2. apply c2. apply c2.\n  apply c1.\nQed.\n\nGoal R 6 [3;2;1;0].\nProof.\n  (* impossible to prove this *)\nAbort.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nDefinition lt n m := le (S n) m.\n\nNotation \"m <= n\" := (le m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\nInductive total_relation : nat -> nat -> Prop :=\n  | tr_0 : forall m, total_relation 0 m\n  | tr_n : forall n m,\n             total_relation n m -> total_relation (S n) m.\n\nTheorem total_relation_all : forall n m, total_relation n m.\nProof.\n  intros.\n  induction n.\n  constructor.\n  constructor. assumption.\nQed.\n\n\nInductive empty_relation : nat -> nat -> Prop :=.\n\nExample er_1: ~(empty_relation 6 5). Proof. intro. induction H. Qed.\n\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros.\n  induction H0.\n  assumption.\n  constructor.\n  apply IHle.\n  assumption.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n.\n  constructor.\n  constructor. assumption.\nQed.\n\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros.\n  induction H.\n  constructor.\n  constructor.\n  assumption.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  induction m.\n  intros.\n  inversion H.\n  constructor.\n\n  inversion H2.\n\n  intros.\n  inversion H.\n  constructor.\n\n  apply IHm in H2.\n  constructor.\n  assumption.\nQed.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  induction b.\n  rewrite plus_0_r.\n  constructor.\n\n  rewrite plus_comm.\n  simpl.\n  rewrite plus_comm.\n  constructor.\n  assumption.\nQed.\n\nLemma plus_le_l : forall n1 n2 m,\n                    le (n1 + n2) m -> le n1 m.\nProof.\n  intros.\n  generalize dependent n2.\n  induction n2.\n\n  intros.\n  replace (n1 + 0) with n1 in H. assumption.\n  rewrite plus_0_r. reflexivity.\n\n  intros. apply IHn2.\n  replace (n1 + S n2) with (S (n1 + n2)) in H.\n  apply le_S in H.\n  apply Sn_le_Sm__n_le_m in H. assumption.\n  rewrite plus_comm with (m := S n2) (n := n1).\n  simpl.\n  rewrite plus_comm with (m := n2) (n := n1). reflexivity.\nQed.\n\nLemma plus_le_self : forall n m, le n (n + m).\nProof.\n  intros.\n  induction n.\n  simpl. apply O_le_n.\n  simpl.\n  apply n_le_m__Sn_le_Sm. assumption.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  lt (n1 + n2) m ->\n  lt n1 m /\\ lt n2 m.\nProof.\n  unfold lt.\n  intros. inversion H.\n  split.\n\n  apply n_le_m__Sn_le_Sm.\n  apply plus_le_self.\n\n  apply n_le_m__Sn_le_Sm. rewrite plus_comm.\n  apply plus_le_self.\n\n  split. subst.\n\n  apply n_le_m__Sn_le_Sm.\n  apply Sn_le_Sm__n_le_m in H.\n  assert (n1 <= n1 + n2). apply plus_le_self.\n  apply le_trans with (n1+n2); assumption.\n\n  apply n_le_m__Sn_le_Sm. subst.\n  apply Sn_le_Sm__n_le_m in H.\n  assert (n2 <= n1 + n2). rewrite plus_comm. apply plus_le_self.\n  apply le_trans with (n1+n2); assumption.\nQed.\n\n\nTheorem lt_S : forall n m,\n  lt n m ->\n  lt n (S m).\nProof.\n  unfold lt.\n  intros.\n  apply le_S. assumption.\nQed.\n\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intro.\n  induction n.\n  intros. apply O_le_n.\n\n  intros.\n  induction m.\n  simpl in H. inversion H.\n  simpl in H. apply n_le_m__Sn_le_Sm. apply IHn.\n  assumption.\nQed.\n\nLemma ble_refl : forall m, ble_nat m m = true.\nProof.\n  intros. induction m. reflexivity. simpl. assumption.\nQed.\n\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros.\n  generalize dependent n.\n  induction m.\n  intro. intro.\n  inversion H. reflexivity.\n\n  destruct n.\n  simpl. reflexivity.\n\n  intro. simpl. apply IHm. apply Sn_le_Sm__n_le_m in H.\n  assumption.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  intros.\n  apply le_ble_nat.\n  apply ble_nat_true in H.\n  apply ble_nat_true in H0.\n\n  apply le_trans with m; assumption.\nQed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros.\n  generalize dependent n.\n\n  induction m. intros. intro. inversion H0. subst. inversion H.\n\n  intros. intro. destruct n. inversion H.\n\n  simpl in H. apply IHm in H. apply Sn_le_Sm__n_le_m in H0.\n  apply H. assumption.\nQed.\n\nModule R.\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\nExample r_test_1 : R 1 1 2.\nProof. apply c3. apply c2. apply c1. Qed.\n\nExample r_test_2 : R 2 2 6.\nProof.\n  apply c3. apply c2. apply c3. apply c2.\nAbort.\n\n(* If we dropped constructor c5 from the definition of R, would the set of provable propositions change? Briefly (1 sentence) explain your answer.  *)\n\n(* Answer: No, because c2 and c3 is symmetric over m and n. *)\n\n\n(* If we dropped constructor c4 from the definition of R, would the set of provable propositions change? Briefly (1 sentence) explain your answer. *)\n\n(* Answer: No, because c4 is equivalent to c2 + c3. *)\n\nGoal forall m n o, m + n = o -> R m n o.\nProof.\n  intros.\n  generalize dependent o.\n  induction m.\n    induction n.\n      destruct o.\n        constructor.\n        intro. inversion H.\n      destruct o.\n        intro. inversion H.\n        intro. constructor. apply IHn. inversion H. reflexivity.\n    induction n.\n      intros. destruct o.\n        inversion H.\n        constructor. apply IHm. inversion H. reflexivity.\n      intros.\n        destruct o.\n          inversion H.\n          destruct o.\n            inversion H. destruct m; inversion H1.\n            constructor. apply IHm. inversion H. reflexivity.\nQed.\n\nGoal forall m n o, R m n o -> m + n = o.\nProof.\n  intros.\n  induction H.\n    reflexivity.\n    rewrite plus_Sn_m. apply f_equal. assumption.\n    rewrite <- plus_n_Sm. apply f_equal. assumption.\n    inversion IHR. rewrite <- plus_n_Sm in H1. inversion H1. reflexivity.\n    rewrite plus_comm. assumption.\nQed.\n\nEnd R.\n\n\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n\nDefinition teen : nat->Prop := between 13 19.\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\nDefinition preserved_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 ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\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.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  apply H. reflexivity.\n  apply H0. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros.\n  unfold combine_odd_even in H.\n  rewrite H0 in H. assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros.\n  unfold combine_odd_even in H.\n  rewrite H0 in H. assumption.\nQed.\n\nFixpoint true_upto_n__true_everywhere n (P : nat -> Prop) : Prop :=\n  match n with\n    | 0 => (forall m, P m)\n    | S n => P (S n) -> true_upto_n__true_everywhere n P\n  end.\n\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity. Qed.\n", "meta": {"author": "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/A009prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.8902942224835226, "lm_q1q2_score": 0.8145310405722236}}
{"text": "From LF Require Export Basics. \n\nExample add_0_1 : forall n : nat,\n  0 + n = n.\nProof. reflexivity. Qed.\n\nExample add_0_r_firsttry : forall n : nat,\n  n + 0 = n.\nProof.\n  intros n.\n  simpl.\nAbort.\n\n\nExample add_0_r_secondtry : forall n : nat,\n  n + 0 = n.\nProof.\n  intros n. destruct n as [|n'] eqn:E.\n  - reflexivity.\n  - simpl.\nAbort.\n\nTheorem add_0_r : forall n : nat,\n  n + 0 = n.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_n_n: forall n,\n  n - n = 0.\nProof.\n  intros n. induction n as [| k].\n   - reflexivity.\n   - simpl. rewrite -> IHk. reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m : nat,\n  S (n + m) = n + S m.\nProof.\n  intros n m. induction n as [| n'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem add_comm : forall a b : nat,\n  a + b = b + a.\nProof.\n  intros a b. induction a as [| a'].\n  - simpl. rewrite add_0_r. reflexivity.\n  - simpl. rewrite IHa'. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (n + 0 + 0) * m = n * m.\nProof.\n  intros n m.\n  assert (H: n + 0 + 0 = n).\n  { \n    (*Set Printing Parentheses.*)\n    rewrite add_comm.\n    simpl.\n    rewrite add_comm.\n    simpl.\n    reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* Set Printing Parentheses. *)\n  rewrite add_comm.\nAbort.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite add_comm. reflexivity. }\n  rewrite H.\n  reflexivity. \nQed.\n\nTheorem mul_0_r : forall n : nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem add_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [|n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n. induction n as [|n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n  (n =? n) = true.\nProof.\n  intros n. induction n as [|n'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem even_S : forall n : nat,\n  even (S n) = negb (even n).\nProof.\n  intros n. induction n as [|n'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. rewrite negb_involutive. simpl. reflexivity.\nQed.\n\nTheorem add_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [|n' IHn']. reflexivity.\n  simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem add_assoc'' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [|n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite IHn'. reflexivity.\n(** - _Theorem_: For any [n], [m] and [p],\n      n + (m + p) = (n + m) + p.\n    _Proof_: By induction on [n].\n    - First, suppose [n = 0]. We must show that\n        0 + (m + p) = (0 + m) + p.\n      This follows directly from the definition of [+].\n    - Next, suppose [n = S n'], where\n      n' + (m + p) = (n' + m) + p.\n    We must now show that  \n      (S n') + (m + p) = ((S n') + m) + p.\n    By the definition of [+], this follows from\n      S (n' + (m + p)) = S((n' + m) + p),\n    which is immediate from the induction hypothesis. _Qed_.\n*)\nQed.\n\nTheorem add_comm' : forall a b : nat,\n  a + b = b + a.\nProof.\n  intros a b. induction a as [| a'].\n  - simpl. rewrite add_0_r. reflexivity.\n  - simpl. rewrite IHa'. rewrite plus_n_Sm. reflexivity.\n(** - _Theorem_: For any [a] and [b],\n      a + b = b + a.\n    _Proof_: By induction on [a].\n    - First, suppose [a = 0]. We must show that\n        0 + b = b + 0.\n      This follows directly from the definition of [+].\n    - Next, suppose [a = S a'], where\n      a' + b = b + 'a.\n    We must now show that  \n      (S a') + b = b + (S a').\n    By the definition of [+], this follows from\n      S (a' + b) = S (b + a').\n    which is immediate from the induction hypothesis. _Qed_.\n*)\nQed.\n\nTheorem add_shuffle3 : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite add_assoc.\n  assert (H1: m + (n + p) = m + n + p).\n  { rewrite add_assoc. reflexivity. }\n  assert (H2: n + m = m + n).\n  { rewrite add_comm. reflexivity. }\n  rewrite H1.\n  rewrite <- H2.\n  reflexivity.\nQed.\nTheorem  mul_n_0: forall n : nat,\n  n * 0 = 0.\nProof.\n  induction n.\n  - reflexivity.\n  Admitted.\n\nLemma n_k_1 : forall n k : nat,\n  n * (1 + k) = n + n * k.\nProof.\n  intros n k.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite add_assoc.\n    assert (n' + k = k + n').\n    { rewrite add_comm. reflexivity. }\n    rewrite H.\n    rewrite <- add_assoc.\n    rewrite <- IHn'.\n    Set Printing Parentheses.\n    assert (1 + k = S k).\n    { rewrite plus_1_n. reflexivity. }\n    rewrite H0.\n    reflexivity.\n  Qed.\n    \nTheorem mul_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros n m.\n  induction n as [|k IHk'].\n  - simpl.\n    assert (m * 0 = 0).\n    induction m.\n    -- rewrite mul_0_r. reflexivity.\n    -- simpl. rewrite IHm. reflexivity.\n    -- rewrite H. reflexivity.\n  - assert (m * (S k) = m * (1 + k)).\n    { rewrite <- plus_1_n. reflexivity. }\n    rewrite H.\n    rewrite n_k_1.\n    rewrite <- IHk'.\n    rewrite <- plus_1_n.\n    simpl.\n    reflexivity.\nQed.\n\nCheck leb.\n\nLemma leb_a : forall a,\n  leb a a = true.\nProof.\n  intros [].\n  - reflexivity.\n  - induction n.\n    -- simpl. reflexivity.\n    -- simpl. rewrite <- IHn. simpl. reflexivity.\nQed.\n\nLemma leb_a_S_a : forall a,\n  leb a (S a) = true.\nProof.\n  intros a.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHa. reflexivity.\nQed.\n\nLemma leb_a_b : forall a b,\n  leb a (a + b) = true.\nProof.\n  intros a b.\n  induction b.\n  - rewrite add_comm. simpl. rewrite leb_a. reflexivity.\n  - rewrite <- plus_n_Sm.\n    destruct b.\n    -- rewrite add_comm. simpl. rewrite leb_a_S_a. reflexivity.\n    -- rewrite <- IHb.\nAbort.\n\nTheorem plus_leb_compat_l : forall n m p : nat,\n  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n  intros n m p.\n  intros H.\n  induction p as [|p' IHp'].\n  - simpl. rewrite H. reflexivity.\n  - simpl. rewrite IHp'. reflexivity.\nQed.\n\n\n(* guess: destruction *)\n(* reality: induction *)\nTheorem leb_refl : forall n:nat,\n  (n <=? n) = true.\nProof.\n  intros [].\n  - reflexivity.\n  - induction n.\n    -- reflexivity.\n    -- rewrite <- IHn.\n       simpl. reflexivity.\nQed. \n\n(* guess: destruction *)\n(* reality: induction *)\nTheorem zero_neqb_S : forall n:nat,\n  0 =? (S n) = false.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - rewrite <- IHn'. simpl. reflexivity.\nQed.\n(* guess: destruction *)\n(* reality: destruction *)\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* guess: destruction *)\n(* reality: destruction *)\nTheorem S_neqb_0 : forall n:nat,\n(S n) =? 0 = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\n  Qed.\n  \n(* guess: induction *)\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- add_comm. simpl. reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool,\n  orb\n    (andb b c)\n    (orb (negb b)\n         (negb c))\n  = true.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  induction p as [|p' IHp'].\n  - rewrite mul_0_r. rewrite mul_0_r. rewrite mul_0_r. reflexivity.\n  - assert (Hs1: n * S p' = n * p' + n).\n    { rewrite mul_comm. simpl. rewrite mul_comm. rewrite add_comm. reflexivity. }\n    assert (Hs2: m * S p' = m * p' + m).\n    { rewrite mul_comm. simpl. rewrite mul_comm. rewrite add_comm. reflexivity. }\n    assert (Hs3: (n + m) * S p' = (n + m) * p' + (n + m)).\n    { rewrite mul_comm. simpl. rewrite mul_comm. rewrite add_comm. reflexivity. }\n    rewrite Hs1. rewrite Hs2. rewrite Hs3.\n    rewrite IHp'. rewrite add_assoc. rewrite add_assoc.\n    assert (Ha: (m * p') + (n * p') = (n * p') + (m * p')).\n    { rewrite add_comm. reflexivity. }\n    assert (Hf: ((n * p') + n) + (m * p') = (n * p') + (m * p') + n).\n    { rewrite add_comm. rewrite add_assoc. rewrite Ha. reflexivity. }\n    rewrite Hf.\n    reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'.\n    rewrite mult_plus_distr_r.\n    reflexivity.\nQed.\n\nTheorem add_shuffle3' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite add_assoc.\n  replace (n + m) with (m + n).\n  - rewrite add_assoc. reflexivity.\n  - rewrite add_comm. reflexivity.\nQed.\n\nTheorem bin_to_nat_pres_incr : forall b : bin,\n  bin_to_nat (incr b) = 1 + bin_to_nat b.\nProof.\n  intros b.\n  induction b as [|b' |b'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IHb'. rewrite plus_1_n. rewrite plus_n_Sm. reflexivity.\nQed.\n\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with\n    | O => Z\n    | S n' => incr (nat_to_bin n')\n  end.\n\n  \nTheorem nat_bin_nat : forall n,\n  bin_to_nat (nat_to_bin n) = n.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite bin_to_nat_pres_incr. rewrite IHn'. reflexivity.\nQed.\n\nTheorem bin_nat_bin_fails : forall b, nat_to_bin (bin_to_nat b) = b.\nAbort.\n\nLemma double_incr : forall n : nat,\n  double (S n) = S (S (double n)).\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nDefinition double_bin (b:bin) : bin :=\n  match b with\n  | Z => Z\n  | n => B_0 n\n  end.\n\nExample double_bin_zero : double_bin Z = Z.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma double_incr_bin : forall b,\n  double_bin (incr b) = incr (incr (double_bin b)).\nProof.\n  intros b.\n  induction b as [|b' |b' IHb'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem bin_nat_bin_fails : forall b, nat_to_bin (bin_to_nat b) = b.\nAbort.\n\nFixpoint normalize (b:bin) : bin :=\n  match b with\n  | Z => Z\n  | B_0 b' => double_bin (normalize b')\n  | B_1 b' => incr (double_bin (normalize b'))\nend.\n\nExample test_normalize0_1 : normalize Z = Z.\nProof. reflexivity. Qed.\n\nExample test_normalize0_2 : normalize (B_0 Z) = Z.\nProof. reflexivity. Qed.\n\nExample test_normalize0_3 : normalize (B_0 (B_0 Z)) = Z.\nProof. reflexivity. Qed.\n\nExample test_normalize0_4 : normalize (B_0 (B_0 (B_0 Z))) = Z.\nProof. reflexivity. Qed.\n\nExample test_normalize1 : bin_to_nat (normalize (B_1 Z)) = 1.\nProof. reflexivity. Qed.\n\nExample test_normalize2 : bin_to_nat (normalize (B_0 (B_1 Z))) = 2.\nProof. reflexivity. Qed.\n\nExample test_normalize3 : bin_to_nat (normalize (B_1 (B_1 Z))) = 3.\nProof. reflexivity. Qed.\n\nExample test_normalize4 : bin_to_nat (normalize (B_0 (B_0 (B_1 Z)))) = 4.\nProof. reflexivity. Qed.\n\nTheorem bin_nat_bin : forall b, nat_to_bin (bin_to_nat b) = normalize b.\nProof.\nAbort.\n\nLemma nat_to_bin_double : forall n : nat,\n  nat_to_bin(double n) = double_bin(nat_to_bin n).\nProof.\n  intros n.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite -> double_incr_bin. rewrite <- IHn. reflexivity.\nQed.\n\nCompute bin_to_nat (normalize (B_0 (B_1 Z))).\nCompute bin_to_nat (normalize (B_1 (B_1 Z))).\n\nTheorem bin_nat_bin : forall b,\n  nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  intros b.\n  induction b as [|b' |b'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHb'.\n    destruct (bin_to_nat b').\n    -- reflexivity.\n    -- rewrite <- double_plus. rewrite -> nat_to_bin_double. reflexivity.\n  - simpl. rewrite <- IHb'. rewrite <- double_plus. rewrite <- nat_to_bin_double. reflexivity.\nQed.\n   ", "meta": {"author": "lchudinov", "repo": "sf", "sha": "e513f57aac1e045ebf03633d735b18928aa71b8a", "save_path": "github-repos/coq/lchudinov-sf", "path": "github-repos/coq/lchudinov-sf/sf-e513f57aac1e045ebf03633d735b18928aa71b8a/lf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8902942246666266, "lm_q1q2_score": 0.8145310363722311}}
{"text": "\n(** %\\chapter{%#<H0>#Regular expressions and languages%}%#</H0># *)\nSection Reg_expression.\nRequire Import List.\nLoad Automata.\n\n(** * Regular expressions *)\n\n(** The _regular expressions_ are defined as simple expressions that denote the languages\n    accepted by finite automata. \n\n    We would like to define the three operations on languages that the operators of\n    regular expressions represent. \n\n    - The _union_ of two languages L and M , denoted %L\\cup M%, is the set of strings that\n      are either in L or in M, or in both. As a simple example, if L= { 1,01,013} and \n      M = {10,2} , then %L\\cup M% = {1,01,013,10,2}. In Coq notation, it is defined as:\n      \n      << \n     Definition lang_union (a:Alphabet)(l1:Language a)(l2:Language a):Language a :=\n         fun w:Word a =>  l1 w \\/ l2 w.\n      >>\n\n    - The _concatenation_ of languages L and M is the set of words that can be formed by taking \n      any string in L and concatenating it with any string in M. For example, if \n      [L= {101, 23, 9)] and [M={3,4}] , then [L * M = {1013, 1014, 233, 234, 93, 94}]. In Coq, we represent it as :\n      \n      <<\n      Definition 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      >>\n\n    \n\n    - The _Kleene operator_  (closure) represents the set of words that  can be produced by taking any number\n      of words from L, and concatenating all of them. \n\n     L* = L( L^2) (L^3) (.... L^n ...\n     \n     In the _Languages_ section, we have proved some useful properties concerning concatenation as\n     well as union and Kleene operator \n\n\n\n*)\n\n(** Defining the regular expression as an inductive term .\n   \n    Below, we make use of 7 constructors according to specific rules . The explanation are\n    as follows:\n\n\n\n    - the _[empty]_ expression represents a regular expression and denotes the empty set\n   \n    - [epsilon] is a regular expression and denotes the set [{epsilon}]\n   \n    - For each [a : Alphabet ] , _a_ is a regular expression and denotes the set [{a}]\n\n    - If [r] and [s] are regular expressions, then [r+s] is a regular expression denoting\n     the _union_ of L(r) and L(s), i.e L(r+s) = %L(r)\\cup L(s)% . \n\n    - If [r] and [s] are regular expressions, then [rs] is a regular expression , denoting the\n     _concatenation_ of [L(r)] and [L(s)] i.e L(rs) = $L(r) \\cap L(s)$\n\n    - If [r] is a regular expression, then [r*] is a regular expression, denoting the closure of\n      [L(r)] . That is, [L(r* )= L(r)]\n    \n    - If [r] is a regular expression, then [(r)] is also a regular expression, denoting the exactly\n      the same language like [r]. I.e, [L((r)) = L(r)]\n\n*)\n\nInductive RegExp (a:Alphabet) :Set :=\n| Empty : RegExp a \n\n| Epsilon : RegExp a\n\n| Var : Fin a -> RegExp a\n\n| Plus : RegExp a -> RegExp a -> RegExp a\n\n| Conc : RegExp a -> RegExp a -> RegExp a\n\n| Starex : RegExp a-> RegExp a\n\n| Paren : RegExp a-> RegExp a.  \n\nPrint nfa_void.\n\nPrint nfa_eps.\nPrint nfa_var.\nCheck Type.\nCheck ex.\nPrint ex.\n(*\nDefinition exas (a:Alphabet)(n:nat) :nfa n a.\ninduction n.\nsimpl in *.\nintuition.\ndestruct H.\nsimpl in *. *)\n\nFixpoint re_nr (a:Alphabet) (r:RegExp a) : nat :=\n\nmatch r with \n\n| Empty => 1\n\n| Epsilon => 1\n| Var xs => 2\n|  Plus xs ys => re_nr xs + re_nr ys\n\n| Conc xs ys => re_nr xs + re_nr ys\n| Starex xs => re_nr xs + 1\n\n| Paren xs  => re_nr xs\nend.\n\n\nFixpoint re_to_nfa(a:Alphabet)(r:RegExp a ) : nfa (re_nr r) a :=\n\n match r with\n| Empty => nfa_void a\n| Epsilon => nfa_eps a\n\n| Var xs => nfa_var xs\n\n|  Plus xs ys => nfa_disj (re_to_nfa xs) (re_to_nfa ys)\n\n| Conc xs ys => nfa_conc (re_to_nfa xs) (re_to_nfa ys)\n\n| Starex xs => nfa_star (re_to_nfa xs)\n\n| Paren xs => re_to_nfa xs\n\n\nend.\nInductive Star (a:Alphabet) (l:Language a) : Language a:= \n  | nil0: (Star l) nil\n  | cons0 : forall (x: Word a)(y:Word a),Star l x /\\ l y -> Star l (app x y).\n\n\n(*Definition single_lang1 (a:Alphabet)(x:Fin a):Language a:=\n\n fun w => w = nil.*)\n\nPrint single_lang.\nFixpoint reg2lang (a:Alphabet)(r : RegExp a) : Language a :=\n match r with \n | Empty => fun w:Word a =>False\n | Epsilon => fun w => w = nil (* fun w:Word a => match w with  |nil => True\n                                            | _  => False\n                              end *)\n | Var e => single_lang1 e\n | Plus e1 e2 => lang_union (reg2lang e1) (reg2lang e2)\n | Conc e1 e2 => lang_conc (reg2lang e1) (reg2lang e2)\n | Starex e => Star (reg2lang e)\n | Paren e => reg2lang e\n  end.\n\nPrint nfa_eps.\nLemma klth : forall (a:Alphabet)(w:Word a) (r:RegExp a) , nfa_lang (re_to_nfa r) w -> reg2lang r w.\nProof.\nintros.\nsimpl in *.\ninduction r.\nsimpl in *.\nunfold nfa_void in H.\nsimpl in H.\ntrivial.\nsimpl in *.\napply nfa_eps_lang in H.\nunfold eps_lang in H.\nexact H.\n\nsimpl in *.\napply nfa_var_lang.\n\nexact 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). *)\n\n\nsimpl in *.\napply nfa_disj_lang in H.\nadmit.\ndestruct H1.\nsimpl in *.\nunfold single_lang1.\nunfold nfa_var in *.\nsimpl in *.\nassert(reg2lang(Paren r) w).\nsimpl in *.\nassert(nfa_lang(nfa_eps a) (a0::w) -> False).\nintro.\nunfold nfa_eps in H1.\n\nadmit.\nsimpl in *.\nunfold single_lang1.\nunfold nfa_var in H.\nsimpl in *.\nLemma klth1 :forall (a:Alphabet)(w:Word a)(r:RegExp a), reg2lang r w -> nfa_lang (re_to_nfa r) w.\nintros.\ninduction r.\nsimpl in *.\ndestruct H.\nsimpl in *.\nunfold nfa_eps.\nsimpl.\n\n\n\n\n\n(** The meaning of regular expressions *)\n\n(** Definition Kleene star, encountered in the Introduction to Languages lecture *)\n\n\n\nDefinition reg2nfa_simpl (a:Alphabet) (r:simplRegExp a) := \n  \n    match r with\n | Empty => nfa_void a\n\n | Epsilon =>nfa_eps a\n\n \n  end.\n\n\nDefinition reg2nfa_bi (a:Alphabet)(r:biRegExp a) :=\n\n  match r with\n  | Var xs => nfa_var xs\n\n end.\n\nFixpoint reg2nfa_multi (a:Alphabet) (r:multiRegExp a) :=\n\n  match r with \n| Plus s1 s2 => match s1,s2 with \n\n                | Var x, Var y => nfa_disj a (reg2nfa_bi s1)(reg2nfa_bi s2)\n                | Var x, Plus l1 l2 => nfa_disj a (reg2nfa_bi s1) (nfa_disj (reg2nfa_multi l1)(reg2nfa_multi l2))\n\n  \n\n     end\n\nend.\n\nPrint reg2nfa.\n\n\n(** Defining a function that takes a regular expression as an input and produces its\n    corresponding language as an output \n*)\n(*\nFixpoint reg2lang (a:Alphabet)(r : RegExp a) : Language a :=\n match r with \n | Empty => fun w:Word a =>False\n | Epsilon => fun w:Word a => match w with  |nil => True\n                                            | _  => False\n                              end\n | Var e => single_lang1 e\n | Plus e1 e2 => lang_union (reg2lang e1) (reg2lang e2)\n | Conc e1 e2 => lang_conc (reg2lang e1) (reg2lang e2)\n | Starex e => Star (reg2lang e)\n | Paren e => reg2lang e\n  end. *)\n\n\n(** Translating regular expressions to NFA *)\n\n(*Fixpoint re_to_dfa (a:Alphabet) (r:RegExp a) :=\n\n   match r with \n\n   | Empty => dfa_void\n   \n    | Epsilon  => dfa_epsilon\n\n   | Var x => nfa2dfa (nfa_var a x)\n\n end. *)\n\n  Print nfa.\n\n\n\n    \n\n\n\n(** * Closure properties of regular languages : *)\n\n(** We shall prove some well known results that deal with languages that are regular. \n\n   - _Closure under union_ :if 2 languages are regular, then their union  is also regular.\n*)\n\nLemma union1 : forall (a:Alphabet)( l m :Language a) , l w\n\n\n\nEnd Reg_expression.", "meta": {"author": "radu07", "repo": "automat", "sha": "5d8c4ec7414025cb83ec094e45e09a7cd1d607da", "save_path": "github-repos/coq/radu07-automat", "path": "github-repos/coq/radu07-automat/automat-5d8c4ec7414025cb83ec094e45e09a7cd1d607da/auto/auto/Regular.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.8145154714075117}}
{"text": "Require Import Arith.\nRequire Import Recdef.\n\nInductive formula : Set :=\n    | True  : formula\n    | False : formula\n    | Var   : nat -> formula\n    | Not   : formula -> formula\n    | And   : formula -> formula -> formula\n    | Or    : formula -> formula -> formula\n    | Imply : formula -> formula -> formula.\n\nInductive equiv : formula -> formula -> Prop :=\n    | equiv_and_comm     : forall f1 f2 : formula, equiv (And f1 f2) (And f2 f1)\n    | equiv_or_comm      : forall f1 f2 : formula, equiv (Or f1 f2) (Or f2 f1)\n    | equiv_and_assoc    : forall f1 f2 f3 : formula,\n                           equiv (And (And f1 f2) f3) (And f1 (And f2 f3))\n    | equiv_or_assoc     : forall f1 f2 f3 : formula,\n                           equiv (Or (Or f1 f2) f3) (Or f1 (Or f2 f3))\n    | equiv_and_absorp   : forall f1 f2 : formula, equiv (And f1 (Or f1 f2)) f1\n    | equiv_or_absorp    : forall f1 f2 : formula, equiv (Or f1 (And f1 f2)) f1\n    | equiv_and_iden     : forall f : formula, equiv (And f True) f\n    | equiv_or_iden      : forall f : formula, equiv (Or f False) f\n    | equiv_and_distr    : forall f1 f2 f3 : formula,\n                           equiv (And f1 (Or f2 f3)) (Or (And f1 f2) (And f1 f3))\n    | equiv_or_distr     : forall f1 f2 f3 : formula,\n                           equiv (Or f1 (And f2 f3)) (And (Or f1 f2) (Or f1 f3))\n    | equiv_and_compl    : forall f : formula, equiv (And f (Not f)) False\n    | equiv_or_compl     : forall f : formula, equiv (Or f (Not f)) True\n    | equiv_not_cong     : forall f1 f2 : formula,\n                           equiv f1 f2 -> equiv (Not f1) (Not f2)\n    | equiv_and_cong_l   : forall f1 f2 f3 : formula,\n                           equiv f1 f2 -> equiv (And f1 f3) (And f2 f3)\n    | equiv_and_cong_r   : forall f1 f2 f3 : formula,\n                           equiv f2 f3 -> equiv (And f1 f2) (And f1 f3)\n    | equiv_or_cong_l    : forall f1 f2 f3 : formula,\n                           equiv f1 f2 -> equiv (Or f1 f3) (Or f2 f3)\n    | equiv_or_cong_r    : forall f1 f2 f3 : formula,\n                           equiv f2 f3 -> equiv (Or f1 f2) (Or f1 f3)\n    | equiv_imply_cong_l : forall f1 f2 f3 : formula,\n                           equiv f1 f2 -> equiv (Imply f1 f3) (Imply f2 f3)\n    | equiv_imply_cong_r : forall f1 f2 f3 : formula,\n                           equiv f2 f3 -> equiv (Imply f1 f2) (Imply f1 f3)\n    | equiv_refl         : forall f : formula, equiv f f\n    | equiv_sym          : forall f1 f2 : formula, equiv f1 f2 -> equiv f2 f1\n    | equiv_trans        : forall f1 f2 f3 : formula,\n                           equiv f1 f2 -> equiv f2 f3 -> equiv f1 f3\n    | equiv_imply_or     : forall f1 f2 : formula,\n                           equiv (Imply f1 f2) (Or (Not f1) f2).\n\nLemma equiv_not_true :\n    equiv (Not True) False.\nProof.\n    apply equiv_trans with (And (Not True) True).\n    apply equiv_sym.\n    apply equiv_and_iden.\n    apply equiv_trans with (And True (Not True)).\n    apply equiv_and_comm.\n    apply equiv_and_compl.\nQed.\n\nLemma equiv_not_false :\n    equiv (Not False) True.\nProof.\n    apply equiv_trans with (Or (Not False) False).\n    apply equiv_sym.\n    apply equiv_or_iden.\n    apply equiv_trans with (Or False (Not False)).\n    apply equiv_or_comm.\n    apply equiv_or_compl.\nQed.\n\nFixpoint elim_imply (f : formula) : formula :=\n    match f with\n    | True        => True\n    | False       => False\n    | Var n       => Var n\n    | Not   f1    => Not (elim_imply f1)\n    | And   f1 f2 => And (elim_imply f1) (elim_imply f2)\n    | Or    f1 f2 => Or (elim_imply f1) (elim_imply f2)\n    | Imply f1 f2 => Or (Not (elim_imply f1)) (elim_imply f2)\n    end.\n\nLemma elim_imply_equiv :\n    forall f : formula, equiv (elim_imply f) f.\nProof.\n    induction f as [| | n | f1 H | f1 H1 f2 H2 | f1 H1 f2 H2 | f1 H1 f2 H2];\n    simpl.\n\n        (* Case : f = True *)\n        apply equiv_refl.\n\n        (* Case : f = False *)\n        apply equiv_refl.\n\n        (* Case : f = Var n *)\n        apply equiv_refl.\n\n        (* Case : f = Not f1 *)\n        apply (equiv_not_cong _ _ H).\n\n        (* Case : f = And f1 f2 *)\n        apply equiv_trans with (And f1 (elim_imply f2)).\n        apply (equiv_and_cong_l _ _ _ H1).\n        apply (equiv_and_cong_r _ _ _ H2).\n\n        (* Case : f = Or f1 f2 *)\n        apply equiv_trans with (Or f1 (elim_imply f2)).\n        apply (equiv_or_cong_l _ _ _ H1).\n        apply (equiv_or_cong_r _ _ _ H2).\n\n        (* Case : f = Imply f1 f2 *)\n        apply equiv_sym.\n        apply equiv_trans with (Imply (elim_imply f1) (elim_imply f2)).\n        apply equiv_trans with (Imply f1 (elim_imply f2)).\n        apply (equiv_imply_cong_r _ _ _ (equiv_sym _ _ H2)).\n        apply (equiv_imply_cong_l _ _ _ (equiv_sym _ _ H1)).\n        apply equiv_imply_or.\nQed.\n\nFixpoint height (f : formula) : nat :=\n    match f with\n    | True        => 0\n    | False       => 0\n    | Var n       => 0\n    | Not   f1    => S (height f1)\n    | And   f1 f2 => S (Peano.max (height f1) (height f2))\n    | Or    f1 f2 => S (Peano.max (height f1) (height f2))\n    | Imply f1 f2 => S (Peano.max (height f1) (height f2))\n    end.\n\nFixpoint not_height (f : formula) : nat :=\n    match f with\n    | True        => 0\n    | False       => 0\n    | Var n       => 0\n    | Not   f1    => S (height f1)\n    | And   f1 f2 => Peano.max (not_height f1) (not_height f2)\n    | Or    f1 f2 => Peano.max (not_height f1) (not_height f2)\n    | Imply f1 f2 => Peano.max (not_height f1) (not_height f2)\n    end.\n\nLemma not_height_le_height :\n    forall f : formula, not_height f <= height f.\nProof.\n    induction f as [| | n | f1 H1 | f1 H1 f2 H2 | f1 H1 f2 H2 | f1 H1 f2 H2];\n    simpl;\n    try trivial.\n\n        (* Case : f = And f1 f2 *)\n        apply le_S.\n        apply (NPeano.Nat.max_le_compat _ _ _ _ H1 H2).\n\n        (* Case : f = And f1 f2 *)\n        apply le_S.\n        apply (NPeano.Nat.max_le_compat _ _ _ _ H1 H2).\n\n        (* Case : f = And f1 f2 *)\n        apply le_S.\n        apply (NPeano.Nat.max_le_compat _ _ _ _ H1 H2).\nQed.\n\nFunction move_not_aux (f : formula) {measure not_height} : formula :=\n    match f with\n    | True   => True\n    | False  => False\n    | Var n  => Var n\n    | Not f1 => match f1 with\n        | True          => Not True\n        | False         => Not False\n        | Var n         => Not (Var n)\n        | Not   f1'     => move_not_aux f1'\n        | And   f1' f2' => Or  (move_not_aux (Not f1')) (move_not_aux (Not f2'))\n        | Or    f1' f2' => And (move_not_aux (Not f1')) (move_not_aux (Not f2'))\n        | Imply f1' f2' => Not (Imply f1' f2')\n        end\n    | And   f1 f2 => And   f1 f2\n    | Or    f1 f2 => Or    f1 f2\n    | Imply f1 f2 => Imply f1 f2\n    end.\nProof.\n    (* Case : f = Not (Not f1' *)\n    intros _ _ f1' _ _.\n    simpl.\n    apply lt_S.\n    apply (le_lt_trans _ (height f1') _ (not_height_le_height _) (lt_n_Sn _)).\n\n    (* Case : f = Not (And f1' f2') : move_not_aux (Not f2') *)\n    intros _ _ f1' f2' _ _.\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Not (And f1' f2') : move_not_aux (Not f1')  *)\n    intros _ _ f1' f2' _ _.\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Not (Or f1' f2') : move_not_aux (Not f2')  *)\n    intros _ _ f1' f2' _ _.\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Not (Or f1' f2') : move_not_aux (Not f1')  *)\n    intros _ _ f1' f2' _ _.\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\nDefined.\n\nFixpoint move_not (f : formula) : formula :=\n    match f with\n    | True   => True\n    | False  => False\n    | Var n  => Var n\n    | Not f1 => match f1 with\n        | True          => Not True\n        | False         => Not False\n        | Var n         => Not (Var n)\n        | Not   f1'     => move_not_aux (Not (Not f1'))\n        | And   f1' f2' => move_not_aux (Not (And f1' f2'))\n        | Or    f1' f2' => move_not_aux (Not (Or  f1' f2'))\n        | Imply f1' f2' => Not (Imply (move_not f1') (move_not f2'))\n        end\n    | And   f1 f2 => And   (move_not f1) (move_not f2)\n    | Or    f1 f2 => Or    (move_not f1) (move_not f2)\n    | Imply f1 f2 => Imply (move_not f1) (move_not f2)\n    end.\n\nLemma move_not_equiv :\n    forall f : formula, equiv (move_not f) f.\nProof.\n    induction f as [| | n | f1 H1 | f1 H1 f2 H2 | f1 H1 f2 H2 | f1 H1 f2 H2];\n    simpl.\n\n        (* Case : f = True *)\n        apply equiv_refl.\n\n        (* Case : f = False *)\n        apply equiv_refl.\n\n        (* Case : f = Var n *)\n        apply equiv_refl.\n\n        (* Case : f = Not f1 *)\n        destruct f1 as [| | m | f1' | f1' f2' | f1' f2' | f1' f2'];\n        simpl.\n\n            (* Case : f1 = True *)\n            apply (equiv_not_cong _ _ (equiv_refl _)).\n\n            (* Case : f1 = False *)\n            apply (equiv_not_cong _ _ (equiv_refl _)).\n\n            (* Case : f1 = Var n *)\n            apply (equiv_not_cong _ _ (equiv_refl _)).\n\n            (* Case : f1 = Not f1' *)\n            admit.\n\n            (* Case : f1 = And f1' f2' *)\n            admit.\n\n            (* Case : f1 = Or f1' f2' *)\n            admit.\n\n            (* Case : f1 = Imply f1' f2' *)\n            simpl in H1.\n            apply (equiv_not_cong _ _ H1).\n\n        (* Case : f = And f1 f2 *)\n        apply equiv_trans with (And f1 (move_not f2)).\n        apply (equiv_and_cong_l _ _ _ H1).\n        apply (equiv_and_cong_r _ _ _ H2).\n\n        (* Case : f = Or f1 f2 *)\n        apply equiv_trans with (Or f1 (move_not f2)).\n        apply (equiv_or_cong_l _ _ _ H1).\n        apply (equiv_or_cong_r _ _ _ H2).\n\n        (* Case : f = Imply f1 f2 *)\n        apply equiv_trans with (Imply f1 (move_not f2)).\n        apply (equiv_imply_cong_l _ _ _ H1).\n        apply (equiv_imply_cong_r _ _ _ H2).\nQed.\n\nFixpoint eval_const (f : formula) : formula :=\n    match f with\n    | True  => True\n    | False => False\n    | Var n => Var n\n    | Not True  => False\n    | Not False => True\n    | Not f1 => match eval_const f1 with\n        | True  => False\n        | False => True\n        | f1'   => Not (eval_const f1)\n        end\n    | And f1 f2 => match eval_const f1, eval_const f2 with\n        | True,  f2'   => f2'\n        | False, f2'   => False\n        | f1',   True  => f1'\n        | f1',   False => False\n        | f1',   f2'   => And f1' f2'\n        end\n    | Or f1 f2 => match eval_const f1, eval_const f2 with\n        | True,  f2'   => True\n        | False, f2'   => f2'\n        | f1',   True  => True\n        | f1',   False => f1'\n        | f1',   f2'   => Or f1' f2'\n        end\n    | Imply f1 f2 => match eval_const f1, eval_const f2 with\n        | True,  False => False\n        | False, f2'   => True\n        | f1',   True  => True\n        | f1',   f2'   => Imply f1' f2'\n        end\n    end.\n\nFunctional Scheme eval_const_ind := Induction for eval_const Sort Prop.\n\nLemma eval_const_equiv :\n    forall f : formula, equiv (eval_const f) f.\nProof.\nAdmitted.\n\nFixpoint or_size (f : formula) : nat :=\n    match f with\n    | True        => 0\n    | False       => 0\n    | Var n       => 0\n    | Not   f1    => or_size f1\n    | And   f1 f2 => or_size f1 + or_size f2\n    | Or    f1 f2 => S (height f1 + height f2)\n    | Imply f1 f2 => or_size f1 + or_size f2\n    end.\n\nFunction distr_or_aux (f : formula) {measure or_size} : formula :=\n    match f with\n    | True   => True\n    | False  => False\n    | Var n  => Var n\n    | Not f1 => Not f1\n    | And f1 f2 => And f1 f2\n    | Or  f1 f2 => match f1, f2 with\n        | f1, And f1' f2' =>\n            And (distr_or_aux (Or f1 f1')) (distr_or_aux (Or f1 f2'))\n        | And f1' f2', f2 =>\n            And (distr_or_aux (Or f1' f2)) (distr_or_aux (Or f2' f2))\n        | f1, f2 => Or f1 f2\n        end\n    | Imply f1 f2 => Imply f1 f2\n    end.\nProof.\n    (* Case : f = Or True (And f1' f2') : distr_or_aux (Or True f2') *)\n    intros _ _ _ _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or True (And f1' f2') : distr_or_aux (Or True f1') *)\n    intros _ _ _ _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or False (And f1' f2') : distr_or_aux (Or False f2') *)\n    intros _ _ _ _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or True (And f1' f2') : distr_or_aux (Or False f1') *)\n    intros _ _ _ _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (Var n) (And f1' f2') : distr_or_aux (Or (Var n) f2') *)\n    intros _ _ _ n _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (Var n) (And f1' f2') : distr_or_aux (Or (Var n) f1') *)\n    intros _ _ _ n _ f1' f2' _ _ .\n    simpl.\n    apply lt_n_S.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (Not f0) (And f1' f2') : distr_or_aux (Or (Not f0) f2' *)\n    intros _ _ _ f0 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (Not f0) (And f1' f2') : distr_or_aux (Or (Not f0) f1' *)\n    intros _ _ _ f0 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') True : distr_or_aux (Or f2' True) *)\n    intros _ _ _ f1' f2' _ _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') True : distr_or_aux (Or f1' True) *)\n    intros _ _ _ f1' f2' _ _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') False : distr_or_aux (Or f2' False) *)\n    intros _ _ _ f1' f2' _ _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') False : distr_or_aux (Or f1' False) *)\n    intros _ _ _ f1' f2' _ _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') (Var n) : distr_or_aux (Or f2' (Var n)) *)\n    intros _ _ _ f1' f2' _ n _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_r _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1 f2') (Var n) : distr_or_aux (Or f1' (Var n)) *)\n    intros _ _ _ f1' f2' _ n _ _.\n    simpl.\n    repeat apply lt_n_S.\n    repeat rewrite plus_0_r.\n    apply (le_lt_trans _ (Peano.max (height f1') (height f2')) _\n           (Max.le_max_l _ _) (lt_n_Sn _)).\n\n    (* Case : f = Or (And f1' f2') (Not f0) : distr_or_aux (Or f2' (Not f0)) *)\n    intros _ _ _ f1' f2' _ f0 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply (plus_le_compat_r _ _ _ (Max.le_max_r _ _)).\n\n    (* Case : f = Or (And f1' f2') (Not f0) : distr_or_aux (Or f1' (Not f0)) *)\n    intros _ _ _ f1' f2' _ f0 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply (plus_le_compat_r _ _ _ (Max.le_max_l _ _)).\n\n    (* Case : f = Or (And f1' f2') (And f1'0 f2'0) : distr_or_aux (Or (And f1' f2') f2'0) *)\n    intros _ _ _ f1' f2' _  f1'0 f2'0 _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_r _ _)).\n\n    (* Case : f = Or (And f1' f2') (And f1'0 f2'0) : distr_or_aux (Or (And f1' f2') f1'0) *)\n    intros _ _ _ f1' f2' _  f1'0 f2'0 _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_l _ _)).\n\n    (* Case : f = Or (And f1' f2') (Or f0 f3) : distr_or_aux (Or f2' (Or f0 f3)) *)\n    intros _ _ _ f1' f2' _ f0 f3 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply plus_le_compat_r.\n    apply Max.le_max_r.\n\n    (* Case : f = Or (And f1' f2') (Or f0 f3) : distr_or_aux (Or f1' (Or f0 f3)) *)\n    intros _ _ _ f1' f2' _ f0 f3 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply plus_le_compat_r.\n    apply Max.le_max_l.\n\n    (* Case : f = Or (And f1' f2') (Imply f0 f3) : distr_or_aux (Or f2' (Imply f0 f3)) *)\n    intros _ _ _ f1' f2' _ f0 f3 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply plus_le_compat_r.\n    apply Max.le_max_r.\n\n    (* Case : f = Or (And f1' f2') (Imply f0 f3) : distr_or_aux (Or f1' (Imply f0 f3)) *)\n    intros _ _ _ f1' f2' _ f0 f3 _ _.\n    simpl.\n    apply lt_n_S.\n    apply le_lt_n_Sm.\n    apply plus_le_compat_r.\n    apply Max.le_max_l.\n\n    (* Case : f = Or (Or f0 f3) (And f1' f2') : distr_or_aux (Or (Or f0 f3) f2') *)\n    intros _ _ _ f0 f3 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_r _ _)).\n\n    (* Case : f = Or (Or f0 f3) (And f1' f2') : distr_or_aux (Or (Or f0 f3) f1') *)\n    intros _ _ _ f0 f3 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_l _ _)).\n\n    (* Case : f = Or (Imply f0 f3) (And f1' f2') : distr_or_aux (Or (Imply f0 f3) f2' *)\n    intros _ _ _ f0 f3 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_r _ _)).\n\n    (* Case : f = Or (Imply f0 f3) (And f1' f2') : distr_or_aux (Or (Imply f0 f3) f1') *)\n    intros _ _ _ f0 f3 _ f1' f2' _ _.\n    simpl.\n    repeat apply lt_n_S.\n    apply plus_lt_compat_l.\n    apply (le_lt_n_Sm _ _ (Max.le_max_l _ _)).\nDefined.\n\nFixpoint distr_or (f : formula) : formula :=\n    match f with\n    | True   => True\n    | False  => False\n    | Var n  => Var n\n    | Not f1 => Not (distr_or f1)\n    | And f1 f2 => And (distr_or f1) (distr_or f2)\n    | Or  f1 f2 => match f1, f2 with\n        | f1, And f1' f2' =>\n            And (distr_or_aux (Or f1 f1')) (distr_or_aux (Or f1 f2'))\n        | And f1' f2', f2 =>\n            And (distr_or_aux (Or f1' f2)) (distr_or_aux (Or f2' f2))\n        | f1, f2 => Or (distr_or f1) (distr_or f2)\n        end\n    | Imply f1 f2 => Imply (distr_or f1) (distr_or f2)\n    end.\n", "meta": {"author": "y-taka-23", "repo": "tppmark2015", "sha": "9cf5fd7dd207ab954a4b5ca9245c14741f2831fb", "save_path": "github-repos/coq/y-taka-23-tppmark2015", "path": "github-repos/coq/y-taka-23-tppmark2015/tppmark2015-9cf5fd7dd207ab954a4b5ca9245c14741f2831fb/Formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.8144783757386401}}
{"text": "Require Import Logic.FunctionalExtensionality.\nRequire Import Logic.ProofIrrelevance.\n\nRecord Group := {\n      G : Type;\n      mult : G -> G -> G;\n      id : G;\n      inverse : G -> G;\n\n      associative : forall (x y z : G),\n      mult x (mult y z) = mult (mult x y) z;\n      id_exists : forall (x : G), \n      mult id x = x /\\ mult x id = x;\n      inverses_exist : forall (x : G),\n      mult x (inverse x) = id /\\ mult (inverse x) x = id;\n}.\n\nFact inverse_is_unique (G: Group) : forall x y z,\nmult G x y = id G /\\ mult G x z = id G -> y = z.\nProof. intros. destruct H. rewrite <- H in H0.\nassert (mult G (inverse G x) (mult G x z) = \nmult G (inverse G x) (mult G x y) ).\n{  rewrite H0. reflexivity. }\nrewrite associative in H1. rewrite associative in H1.\nassert (mult G (inverse G x) x = id G).\n{ apply inverses_exist. }\nrewrite H2 in H1. \nassert (mult G (id G) z = z /\\ mult G (id G) y = y).\n{ split. \n+ apply id_exists.\n+ apply id_exists. }\ndestruct H3. rewrite H3 in H1. rewrite H4 in H1. auto.\nQed.\n\nFact mult_inverse (G: Group) : forall g g',\nmult G (inverse G g') (inverse G g) = inverse G (mult G g g').\nProof. intros. \nassert (mult G (mult G g g') (mult G (inverse G g') (inverse G g)) = id G /\\\nmult G (mult G g g') (inverse G (mult G g g')) = id G).\n{ assert (mult G (mult G g g') (inverse G (mult G g g')) = id G).\n{ apply inverses_exist. }\nassert (mult G (mult G g g') (mult G (inverse G g') (inverse G g)) = id G).\n{ rewrite associative. \nassert (mult G (mult G g g') (inverse G g') = g).\n{ rewrite <- associative.\nassert (mult G g' (inverse G g') = id G).\n{ apply inverses_exist. }\nrewrite H0. apply id_exists.\n  }\nrewrite H0. apply inverses_exist.\n }\nrewrite H. rewrite H0. auto.\n} apply inverse_is_unique with (G0:=G) (x:=mult G g g')\n(y:=mult G (inverse G g') (inverse G g)) (z:=inverse G (mult G g g')).\nauto.\nQed.\n\nFact inverse_id_is_id (G: Group) : inverse G (id G) = id G.\nProof. apply inverse_is_unique with (G0:=G) (x:=id G) \n(y:= inverse G (id G)) (z:=id G). \nsplit.\n+ apply inverses_exist.\n+ apply id_exists.\nQed.\n\nDefinition trivial_group : Group.\nrefine({|\n          G := unit;\n          mult a b := tt;\n          id := tt\n      |}).\nProof.\n- auto.\n- auto.\n- intros. destruct x. auto.\n- auto.\nDefined.\n\nDefinition product_group (X Y : Group) : Group.\nrefine ({|\n        G := (G X) * (G Y);\n        mult m n := (mult _ (fst m) (fst n), mult _ (snd m) (snd n));\n        id := (id _, id _);\n        inverse m := (inverse _ (fst m), inverse _ (snd m))\n       |}).\nProof.\n- intros. destruct x. destruct y. destruct z. simpl.\nrewrite associative. rewrite associative. reflexivity.\n- intros. destruct x. simpl.\nassert (mult _ (id _) g = g /\\ mult _ g (id _) = g).\n{ apply id_exists. }\nassert (mult _ (id _) g0 = g0 /\\ mult _ g0 (id _) = g0).\n{ apply id_exists. }\ndestruct H0. destruct H. rewrite H. rewrite H1. rewrite H0. rewrite H2. auto.\n- intros. destruct x. simpl. \nassert (mult _ g (inverse _ g) = id _ /\\ mult _ (inverse _ g) g = id _).\n{ apply inverses_exist. }\nassert (mult _ g0 (inverse _ g0) = id _ /\\ mult _ (inverse _ g0) g0 = id _).\n{ apply inverses_exist. }\ndestruct H. destruct H0. rewrite H. rewrite H1. rewrite H0. rewrite H2. auto.\nDefined.\n\nDefinition opposite_group (X : Group) : Group.\nrefine ({|\n        G := (G X) ;\n        mult m n := mult X n m;\n        id := id X;\n        inverse m := inverse X m\n       |}).\nProof.\n- intros. rewrite associative. auto.\n- intros. split.\n+ apply id_exists.\n+ apply id_exists. \n- intros. split.\n+ apply inverses_exist.\n+ apply inverses_exist.\nDefined.\n\nFact opposite_involutive (X : Group) : \nopposite_group (opposite_group X) = X.\nProof. unfold opposite_group. simpl. destruct X. simpl.\nf_equal; apply proof_irrelevance.\nQed.\n\nDefinition indexed_product_group (X : Group) (I : Type) : Group.\nrefine ({|\n        G := I -> (G X);\n        mult f g := (fun i => mult X (f i) (g i));\n        id := (fun i => id X);\n        inverse f := (fun i => inverse X (f i));\n       |}).\nProof.\n- intros. apply functional_extensionality. intros. apply associative.\n- intros.\nassert ((fun i : I => mult X (id X) (x i)) = (fun i : I => x i)).\n{apply functional_extensionality. intros. apply id_exists. }\nassert ((fun i : I => mult X (x i) (id X)) = (fun i : I => x i)).\n{apply functional_extensionality. intros. apply id_exists. }\nrewrite H. rewrite H0. auto.\n- intros.\nassert ((fun i : I => mult X (x i) (inverse X (x i))) = (fun i : I => id X)).\n{apply functional_extensionality. intros. apply inverses_exist. }\nassert ((fun i : I => mult X (inverse X (x i)) (x i)) = (fun i : I => id X)).\n{apply functional_extensionality. intros. apply inverses_exist. }\nrewrite H. rewrite H0. auto.\nDefined.\n\nDefinition bijective A (f : (A -> A) * (A -> A)) :=\n(forall a, (fst f) ((snd f) a) = a /\\ (snd f) ((fst f) a) = a).\n\nFact bijections_compose : forall A (f g : (A -> A) * (A -> A)),\nbijective A f -> bijective A g->\nbijective A ((fun x => (fst g) ((fst f) x)), (fun x => (snd f) ((snd g) x))).\nProof. intros. unfold bijective in *. destruct f. destruct g. simpl in *.\nsimpl. unfold bijective. split.\n+ intros. assert (a (a0 (a2 a3)) = a2 a3). {apply H. }\nrewrite H1. apply H0.\n+ intros. assert (a2 (a1 (a a3)) = a a3). {apply H0. }\nrewrite H1. apply H.\nQed.\n\nFact identity_is_bijective : forall A,\nbijective A ((fun x => x), (fun x => x)).\nProof. intros. unfold bijective. auto.\nQed.\n\nFact inverse_is_bijective : forall A (f : ((A -> A) * (A -> A))),\nbijective A f -> bijective A (snd f, fst f).\nProof. intros. destruct f. unfold bijective. unfold bijective in H.\nsimpl. simpl in *. split; apply H.\nQed.\n\nDefinition permutation_group (A : Type) : Group.\nrefine ({|\n        G := {f : ((A -> A) * (A -> A)) | bijective A f};\n        mult m n := let (f, p) := m in\n                    let (g, p') := n in\n                    exist (bijective A) \n                    ((fun x => (fst g) ((fst f) x)), \n                    (fun x => (snd f) ((snd g) x)))\n                    (bijections_compose A f g p p');\n        id := exist (bijective A) ((fun x => x), (fun x => x))\n             (identity_is_bijective A);\n        inverse m := let (f, p) := m in \n                     exist (bijective A) (snd f, fst f) \n                     (inverse_is_bijective A f p);\n       |}).\nProof.\n- intros. destruct x. destruct y. destruct z. destruct x.\ndestruct x0. destruct x1. simpl in *. simpl.\napply subset_eq_compat. auto.\n- intros. destruct x. destruct x. simpl. split.\n+ apply subset_eq_compat. auto.\n+ apply subset_eq_compat. auto.\n- intros. destruct x. destruct x. simpl. split.\n+ apply subset_eq_compat. unfold bijective in b. simpl in *.\nassert ((fun x : A => a0 (a x) ) = (fun x : A => x) ).\n{apply functional_extensionality. intros. apply b. }\nrewrite H. auto.\n+ apply subset_eq_compat. unfold bijective in b. simpl in *.\nassert ((fun x : A => a (a0 x) ) = (fun x : A => x) ).\n{apply functional_extensionality. intros. apply b. }\nrewrite H. auto.\nDefined.\n\nDefinition left_action (H : Group) (X : Type) (act : (G H) -> X -> X) :=\n(forall x, act (id H) x = x) /\\\n(forall g h x, act g (act h x) = act (mult H g h) x).\n\nDefinition right_action (H : Group) (X : Type) (act : X -> (G H) -> X) :=\n(forall x, act x (id H) = x) /\\\n(forall g h x, act (act x g) h = act x (mult H g h)).\n\nFact permutation_group_acts_on_index : forall A H,\nleft_action (permutation_group A)\n(G (indexed_product_group H A))\n(fun p f => match p with\n| exist _ (pi, _) b => (fun x => f (pi x))\nend).\nProof. intros. unfold left_action. split.\n- intros. simpl. auto.\n- intros. destruct g. destruct h. destruct x0. destruct x1.\napply functional_extensionality. intros. simpl.  auto.\nQed.\n\nDefinition wreath_product (X : Group) : Group.\nrefine ({|\n        G := (G (indexed_product_group X nat)) * (G (permutation_group nat));\n        mult m n := let (gs, bij) := m in\n                    let (f, p) := bij in \n                    let (pi, _) := f in\n                    let (gs', bij') := n in\n                    let (f', p') := bij' in \n                    let (pi', _) := f' in\n                    let new_gs := (fun i => mult _  (gs i) (gs' (pi i)) ) in\n                    let new_bij := exist _\n                    ((fun x => (fst f') ((fst f) x)), \n                    (fun x => (snd f) ((snd f') x)))\n                    (bijections_compose _ f f' p p') in (new_gs, new_bij);\n        id := ((fun _ => id X), exist _ ((fun n => n), (fun n => n)) (identity_is_bijective _));\n        inverse m := let (gs, bij) := m in\n                    let (f, p) := bij in \n                    let (pi, pi_inv) := f in\n                    let new_bij := inverse _ bij in \n                    let new_f := (fun n => inverse _ (gs (pi_inv n))) in\n                    (new_f, new_bij)\n       |}).\nProof.\n- intros. destruct x. destruct y. destruct z. destruct g0. destruct x.\ndestruct g2. destruct x. destruct g4. destruct x. simpl. f_equal.\n+ apply functional_extensionality. intros. rewrite associative. auto.\n+ apply subset_eq_compat. auto.\n- intros. destruct x. destruct g0. destruct x. simpl. split.\n+ f_equal.\n++ apply functional_extensionality. intros. apply id_exists.\n++ apply subset_eq_compat. auto.\n+ f_equal.\n++ apply functional_extensionality. intros. apply id_exists.\n++ apply subset_eq_compat. auto.\n- intros. destruct x. destruct g0. destruct x. simpl. split.\n+ f_equal.\n++ apply functional_extensionality. intros. unfold bijective in b.\nsimpl in b. assert (n0 (n x) = x). {apply b. } rewrite H.\napply inverses_exist.\n++ apply subset_eq_compat. unfold bijective in b. simpl in b. f_equal.\n+++ apply functional_extensionality. intros. apply b.\n+++ apply functional_extensionality. intros. apply b.\n+ f_equal.\n++ apply functional_extensionality. intros. unfold bijective in b.\nsimpl in b. apply inverses_exist.\n++ apply subset_eq_compat. unfold bijective in b. simpl in b. f_equal.\n+++ apply functional_extensionality. intros. apply b.\n+++ apply functional_extensionality. intros. apply b.\nDefined.", "meta": {"author": "SolomonAduolMaina", "repo": "AsynchronousGames", "sha": "7ef67d7a678129f61d3bf2efe7902f7c3bc2f88d", "save_path": "github-repos/coq/SolomonAduolMaina-AsynchronousGames", "path": "github-repos/coq/SolomonAduolMaina-AsynchronousGames/AsynchronousGames-7ef67d7a678129f61d3bf2efe7902f7c3bc2f88d/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.8143101180546843}}
{"text": "Add LoadPath \"$COQ_PROOFS\" as Path.\nLoad unit_5_tactics.\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. inversion H. reflexivity.\nQed.\n\nExample and_example : (3 + 4 = 7) /\\ (2 * 2 = 4).\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 plus_is_O :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  assert (forall (n m: nat), n + m = m + n).\n  {\n    intros.\n    induction n.\n    - simpl. induction m. reflexivity. simpl. rewrite <- IHm. reflexivity.\n    - simpl. rewrite IHn. rewrite plus_n_Sm.  reflexivity.\n  }\n  split.\n  - induction n. \n    * reflexivity.\n    * inversion H0.\n  - induction m.\n    * reflexivity.\n    * rewrite H in H0. inversion H0.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply plus_is_O. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP. Qed.\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ. Qed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP. Qed.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split.\n  - split. apply HP. apply HQ.\n  - apply HR.\nQed.\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     n = 0 \u2228 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 \"\u00ac x\" := (not x) (at level 60, right associativity): type_scope .\nCheck not.\n(* ===> Prop -> Prop *)\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra. Qed.\n\nFact not_implies_our_not : forall (P:Prop),\n  not P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros.\n  destruct H. apply H0.\nQed.\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\nCheck (0 <> 1).\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\nTheorem not_False :\n  ~False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* 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\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q PQ NQ HP.\n  apply NQ.\n  apply PQ.\n  apply HP.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P A.\n  unfold not in A.\n  destruct A. apply H0. apply 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 = false *)\n    unfold not in H.\n    exfalso. (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof. reflexivity. Qed.\n\nModule MyIff.\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB. Qed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - intros [HP|[HQ HR]]. split.\n    + left. apply HP.\n    + left. apply HP.\n    + split. \n      * right. apply HQ.\n      * right. apply HR.  \n  - intros [[HP | HQ] [HP' | HR]].\n    + left. apply HP.\n    + left. apply HP.\n    + left. apply HP'.\n    + right. split.\n      * apply HQ.\n      * apply HR.\nQed.\n\nRequire Import Coq.Setoids.Setoid.\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  destruct n as [|n'].\n  - left. reflexivity.\n  - right. simpl in H.\n    destruct m as [|m'].\n    + reflexivity.\n    + inversion H.\nQed.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  intros.\n  split.\n  - intros. apply mult_eq_0. apply H.\n  - intros [HN | HM]. \n    + inversion HN. reflexivity. \n    + inversion HM. rewrite n_times_m_comm. reflexivity.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R.\n  split.\n  - intros [HP|[HQ|HR]].\n    + left. left. apply HP.\n    + left. right. apply HQ.\n    + right. apply HR.\n  - intros [[HP|HQ]|HR].\n    + left. apply HP.\n    + right. left. apply HQ.\n    + right. right. apply HR.\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  (* WORKED IN CLASS *)\n  intros n [m Hm]. (* note implicit destruct here *)\n  exists (2 + m).\n  apply Hm. Qed.\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  unfold not.\n  intros X P A J.\n  destruct J.\n  apply H. apply A.\nQed.\n\n\n\n  ", "meta": {"author": "kino6052", "repo": "coq-course", "sha": "57de05e6eca44d8617794be1d8b41803af0a7cda", "save_path": "github-repos/coq/kino6052-coq-course", "path": "github-repos/coq/kino6052-coq-course/coq-course-57de05e6eca44d8617794be1d8b41803af0a7cda/unit_6_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8142004877355784}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.\n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n(** *** *)\n(**\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(**\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n   (* FILL IN HERE *) Admitted.\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\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\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\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *)\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(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we\n   can _look_ at that evidence for more information. For example, consider\n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead\n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice)  *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However,\n   we can define inductive predicates about any type of data. For example,\n   suppose we would like to characterize lists of _even_ length. We can\n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof.\n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H.\n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil.\n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l.\n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n\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 [pal_app_rev] that\n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that\n       forall l, pal l -> l = rev l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is,\n      any list is a subsequence of itself.\n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is\n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n      is a subsequence of [l3], then [l1] is a subsequence of [l3].\n      Hint: choose your induction carefully!\n*)\n\n(* FILL IN HERE *)\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(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.\n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.\n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(*\nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "ftiasch", "repo": "sf", "sha": "63ed39b75232f93f18f302099dc6c7637dea02ad", "save_path": "github-repos/coq/ftiasch-sf", "path": "github-repos/coq/ftiasch-sf/sf-63ed39b75232f93f18f302099dc6c7637dea02ad/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.888758801595206, "lm_q1q2_score": 0.8142004863747915}}
{"text": "Inductive B:Type :=\n|Bt\n|Bf\n|Bcom : B -> B -> B.\n\nInductive Br:B->B->Prop:=\n|Brf (B1 :B): Br (Bcom Bf B1) B1\n|Brt (B1 :B): Br (Bcom Bt B1) Bt.\n\nModule NatPlayground.\n\n  Inductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\nEnd NatPlayground.\n\nDefinition minustwo ( n : nat ) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S ( S n') => n'\n  end.\n\nCompute minustwo 3.\n\nFixpoint evenb ( n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb ( n : nat) : bool := negb ( evenb n).\n\nModule NatPlayground2.\n\n  Fixpoint plus ( n : nat)( m : nat ) : nat :=\n    match n with\n    | O => m\n    | S n' => S (plus n' m)\n    end.\n\n  Fixpoint mult ( n m : nat) : nat :=\n    match n with\n    |  O => O\n    | S n' => plus m (mult n' m)\n    end.\n\n  Fixpoint minus ( n m : nat) : nat :=\n    match n,m with\n    | O , _  => O\n    | S _ , O => n\n    | S n' , S m' => minus n' m'\n    end.\n\n  End NatPlayground2.\n\n  Fixpoint exp ( base power : nat) : nat :=\n    match power with\n    | O  => S O\n    | S p => mult base (exp base p)\n    end.\n\n  Fixpoint factorial (n:nat) : nat :=\n    match n with\n    | O => 1\n    | S n' => mult n (factorial n')\n    end.\n\n  Notation \"x + y\" := (plus x y)\n                        (at level 50, left associativity)\n                      : nat_scope.\n  Notation \"x - y\" := (minus x y)\n                        (at level 50, left associativity)\n                      :nat_scope.\n  Notation \" x * y\" :=(mult x y)\n                        (at level 40, left associativity)\n                      :nat_scope.\n\n  Fixpoint beq_nat (n m : nat) :bool :=\n    match n with\n    | O => match m with\n           | O => true\n           | S m' => false\n           end\n    | S n' => match m with\n              | O => false\n              | S m' => beq_nat n' m'\n              end\n    end.\n\n  Fixpoint leb (n m: nat) : bool :=\n    match  n with\n    | O => true\n    | S n' => match m with\n              | O => false\n              | S m' => leb n' m'\n              end\n    end.\n\n  Example test_leb1: (leb 2 2)  = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_leb2: (leb 1 4) = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_leb3: (leb 5 2) = false.\n  Proof. simpl. reflexivity. Qed.\n\n  Definition blt_nat (n m: nat) : bool :=\n    match (leb n m) with\n    | true =>(negb (beq_nat n m))\n    | false => false\n    end.\n\n  Example test_blt_nat1: (blt_nat 2 2) =false.\n  Proof. simpl. reflexivity. Qed.  \n\n  Theorem plus_O_n : forall n : nat, O + n = n.\n  Proof.\n    intros n. simpl. reflexivity. Qed.\n\n  Theorem puls_1_1 : forall n: nat, 1 + n = S n.\n  Proof.\n    intros n. reflexivity. Qed.\n\n  Theorem mult_0_1 : forall n: nat, 0 * n = 0.\n  Proof.\n    intros n. reflexivity. Qed.\n\n  Theorem plus_id_example : forall n m : nat,\n      n = m -> n + n = m + m.\n  Proof.\n    intros n m.\n    intros H.\n    rewrite -> H.\n    reflexivity. Qed.\n\n  Theorem plus_id_exercise: forall n m o: nat,\n      n = m -> m = o -> n + m = m + o.\n  Proof.\n    intros n m o.\n    intros H.\n    rewrite -> H.\n    intros H0.\n    rewrite -> H0.           \n    reflexivity. Qed.\n\n  Theorem mult_O_plus : forall n m: nat,\n      (O + n) * m = n * m.\n  Proof.\n    intros n m.\n    rewrite -> plus_O_n.\n    reflexivity. Qed.\n\n  Theorem mult_S_1 : forall n m: nat,\n      m = S n -> m * (1 + n) = m * m.\n  Proof.\n    intros n m.\n    intros H.\n    rewrite -> H.\n    reflexivity. Qed.\n\n  Theorem plus_1_neq_O : forall n : nat,\n      beq_nat ( n + 1) 0 =false.\n  Proof.\n    intros n. destruct n as [| n'].\n    - reflexivity.\n    - reflexivity. Qed.\n\n  Theorem andb_commutative : forall b c, andb b c = andb c b.\n  Proof.\n    intros b c. destruct b.\n    - destruct c.\n      + reflexivity.\n      + reflexivity.\n    - destruct c.\n      + reflexivity.\n      + reflexivity.\n  Qed.\n\n  Theorem andb_true_elim2 : forall b c:bool,\n      andb b c = true -> c = true.\n  Proof.\n    intros [] [] H.\n    - reflexivity.\n      Admitted.\n\n  \n      \n  \n    \n\n  Theorem zero__nbeq_plus_1 : forall n: nat,\n      beq_nat 0 (n + 1)=false.\n  Proof.\n    intros [| n].\n    - reflexivity.\n    - reflexivity.\n  Qed.\n  \n  (* Fixpoint tmp_rec ( n m : nat) : nat :=\n    match n with\n    | O => O\n    | _ =>\n      match m with\n      | O => (tmp_rec (n + 1) (m + 1))\n      | _ => (tmp_rec (minustwo n) O)\n      end \n    end. *)\n  Theorem identity_fn_applied_twice :\n    forall ( f : bool -> bool),\n      (forall (x : bool), f x = x) ->\n      forall (b : bool), f ( f b) = b.\n  Proof.\n    intros f x b.\n    rewrite -> x.\n    rewrite -> x.\n    reflexivity.\n    Qed.\n          \n  Theorem negation_fn_applied_twice :\n    forall (f :bool -> bool),\n      (forall (x : bool), f x = negb x) ->\n      forall (b : bool), f ( f b) = b.\n  Proof.\n    intros f x b.\n    rewrite -> x.\n    rewrite -> x.\n    destruct b.\n    - reflexivity.\n    - reflexivity.\n  Qed.\n\n  Theorem andb_eq_orb :\n    forall ( b c :bool), (andb b c = orb b c) -> b =c.\n  Proof.\n\n    \n", "meta": {"author": "Hatsunespica", "repo": "Coq", "sha": "969145e20cb6525d324bd6b5b03cfcb6f7fefa8d", "save_path": "github-repos/coq/Hatsunespica-Coq", "path": "github-repos/coq/Hatsunespica-Coq/Coq-969145e20cb6525d324bd6b5b03cfcb6f7fefa8d/SF/tmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8947894675053568, "lm_q1q2_score": 0.814175203226134}}
{"text": "Require Import Arith.\n\nTheorem AdditiveAssociativity : forall n m k : nat, n + (m + k) = (n + m) + k.\nProof.\n  intros n m k.\n  induction n.\n  simpl. reflexivity.\n  simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem AdditiveCommutativity : forall n m : nat, n + m = m + n.\nProof.\n  induction n. induction m. reflexivity.\n  simpl. rewrite <- IHm. simpl. reflexivity.\n  simpl. induction m. rewrite -> IHn. simpl. reflexivity.\n  simpl. rewrite -> IHn. simpl. rewrite <- IHm. rewrite IHn. reflexivity.\nQed.\n\nTheorem IdAdd : forall n : nat, n + 0 = n.\nProof.\n  intros n. rewrite AdditiveCommutativity. simpl. reflexivity.\nQed.\n\n\nLemma l0 : forall n m : nat, n + m = n -> m = 0.\nProof.\n  induction n. simpl. trivial. simpl. auto.\n  Qed.\n\n\n\nLemma l2 : forall n m k : nat, n + m + k = n + (m + k).\nProof.\n  intros n m k.\n  rewrite AdditiveAssociativity. reflexivity.\nQed.\n\nLemma l3 : forall n m k j : nat, n + m + k + j = n + (m + k) + j.\nProof.\n  intros n m j k.\n  rewrite AdditiveAssociativity. reflexivity.\nQed.\n\n\n\n\nTheorem Distributive : forall n m k : nat, n * (m + k) = n * m + n * k.\nProof.\n  intros n m k.\n  induction n. simpl. reflexivity.\n  simpl. rewrite -> IHn. simpl. rewrite AdditiveAssociativity. rewrite AdditiveAssociativity.\n  rewrite l3. rewrite l3. rewrite (AdditiveCommutativity k (n*m)).\n  rewrite AdditiveAssociativity. reflexivity.\nQed.\n\nTheorem MultiplicativeCommutativity : forall n m : nat, n * m = m * n.\nProof.\n  induction n.\n  induction m. reflexivity. simpl. rewrite <- IHm. simpl. reflexivity.\n  induction m. simpl. rewrite IHn. simpl. reflexivity.\n  simpl. rewrite <- IHm. simpl. rewrite IHn. simpl. rewrite AdditiveAssociativity.\n  rewrite AdditiveAssociativity. rewrite IHn. rewrite (AdditiveCommutativity m n).\n  reflexivity.\nQed.\n\n\n\nTheorem LeftCancelAddFwd : forall n m k : nat, n + m = n + k -> m = k.\nProof.\n  intros n m k.\n  induction n. simpl. trivial. auto.\nQed.\n\nTheorem LeftCancelAddBack : forall n m k : nat, m = k -> n + m = n + k.\nProof.\n  intros n m k.\n  induction n. simpl. trivial. simpl. auto.\nQed.\n\nTheorem LeftCancelAdd : forall n m k : nat, m = k <-> n + m = n + k.\nProof.\n  split.\n  induction n. simpl. trivial. simpl. auto.\n  induction n. simpl. trivial. auto.\nQed.\n\n\n\nTheorem MultiplicativeAssociativity : forall n m k : nat, n * (m * k) = (n *m ) * k.\nProof.\n  intros n m k.\n  induction n. simpl. reflexivity.\n  simpl. rewrite -> IHn. rewrite (MultiplicativeCommutativity (m + n*m) k).\n  rewrite Distributive. rewrite <- IHn.\n  rewrite (MultiplicativeCommutativity m k). rewrite <- LeftCancelAdd.\n  rewrite (MultiplicativeCommutativity k m). rewrite IHn. rewrite MultiplicativeCommutativity.\n  reflexivity.\nQed.\n", "meta": {"author": "Michael-Loula", "repo": "coq-stuff", "sha": "840e9708e9d46ec0f590f9404f42a65e600a21ff", "save_path": "github-repos/coq/Michael-Loula-coq-stuff", "path": "github-repos/coq/Michael-Loula-coq-stuff/coq-stuff-840e9708e9d46ec0f590f9404f42a65e600a21ff/proofs-testing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.814168113128645}}
{"text": "Require Import Arith.\n\nInductive even : nat -> Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\n\nHint Resolve O_even plus_2_even.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S (S (mult2 p))\n  end.\n\nLemma mult2_even : forall n:nat, even (mult2 n).\nProof. \n induction n; simpl; auto.\nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n + p).\nProof.\n intros n p Heven_n; elim Heven_n; simpl; auto.\nQed.\n\nHint Resolve sum_even.\n\nLemma square_even : forall n:nat, even n -> even (n * n).\nProof.\n intros n Hn; elim Hn; simpl; auto.\n Check mult_comm.\n intros n0 H0 H1; rewrite (mult_comm n0 (S (S n0))).\n simpl.\n auto.\n right.\n apply sum_even; auto.\nQed.\n\n\nLemma even_mult2 : forall n:nat, even n -> (exists p, n = mult2 p).\nProof.\n induction 1.\n exists 0;simpl;auto.\n case IHeven; intros p Hp.\n exists (S p); simpl; auto.\nQed.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/inductive-prop-chap/SRC/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8140361546054689}}
{"text": "Require Import Coq.Relations.Relations.\nFrom Coq.Classes Require Import RelationClasses Morphisms.\nFrom algebra Require Import Semigroups Monoids.\n\nSection Groups.\nContext {Carrier: Type}.\nContext (equiv: relation Carrier).\nContext {R_equiv: Equivalence equiv}.\nContext (op: Carrier -> Carrier -> Carrier).\nContext {op_proper: Proper (equiv ==> equiv ==> equiv) op}.\nContext (ident: Carrier).\nContext (inv: Carrier -> Carrier).\nContext {inv_proper: Proper (equiv ==> equiv) inv}.\n\nInfix \"==\" := equiv (at level 60, no associativity).\nInfix \"<o>\" := op (at level 40, left associativity).\n\nClass Group := {\n  group_monoid :> Monoid equiv op ident;\n  group_inv_l:\n    forall (a: Carrier), inv a <o> a == ident;\n  group_inv_r:\n    forall (a: Carrier), a <o> inv a == ident;\n}.\n\nContext {group: Group}.\n\nDefinition group_assoc :=\n  semigroup_assoc equiv op.\nDefinition group_op_l :=\n  semigroup_op_l equiv op.\nDefinition group_op_l_solo :=\n  monoid_op_l_solo equiv op ident.\nDefinition group_op_r :=\n  semigroup_op_r equiv op.\nDefinition group_op_r_solo :=\n  monoid_op_r_solo equiv op ident.\nDefinition group_ident_l :=\n  monoid_ident_l equiv op ident.\nDefinition group_ident_r :=\n  monoid_ident_r equiv op ident.\n\nLemma group_cancel_l (a b c: Carrier):\n  c <o> a == c <o> b -> a == b.\nProof.\n  intros H.\n  apply group_op_l with (c := inv c) in H.\n  setoid_rewrite <- (monoid_ident_l equiv op ident).\n  setoid_rewrite <- (group_inv_l c).\n  setoid_rewrite (semigroup_assoc equiv op).\n  assumption.\nQed.\n\nLemma group_cancel_r (a b c: Carrier):\n  a <o> c == b <o> c -> a == b.\nProof.\n  intros H.\n  apply group_op_r with (c := inv c) in H.\n  setoid_rewrite <- (monoid_ident_r equiv op ident).\n  setoid_rewrite <- (group_inv_r c).\n  setoid_rewrite <- (semigroup_assoc equiv op).\n  assumption.\nQed.\n\nLemma group_move_l (a b c: Carrier):\n  a <o> b == c -> b == inv a <o> c.\nProof.\n  intros H.\n  apply group_cancel_l with (a).\n  setoid_rewrite <- (semigroup_assoc equiv op).\n  setoid_rewrite group_inv_r.\n  setoid_rewrite (monoid_ident_l equiv op ident).\n  assumption.\nQed.\n\nLemma group_move_r (a b c: Carrier):\n  a <o> b == c -> a == c <o> inv b.\nProof.\n  intros H.\n  apply group_cancel_r with (b).\n  setoid_rewrite (semigroup_assoc equiv op).\n  setoid_rewrite group_inv_l.\n  setoid_rewrite (monoid_ident_r equiv op ident).\n  assumption.\nQed.\n\nTheorem group_idemp_ident (a: Carrier):\n  a <o> a == a ->\n  a == ident.\nProof.\n  intros H.\n  apply group_cancel_r with (a).\n  setoid_rewrite (monoid_ident_l equiv op ident).\n  assumption.\nQed.\n\nTheorem group_inv_l_unique (a aInv: Carrier):\n  aInv <o> a == ident ->\n  aInv == inv a.\nProof.\n  intros H.\n  apply group_cancel_r with (a).\n  setoid_rewrite group_inv_l.\n  assumption.\nQed.\n\nTheorem group_inv_r_unique (a aInv: Carrier):\n  a <o> aInv == ident ->\n  aInv == inv a.\nProof.\n  intros H.\n  apply group_cancel_l with (a).\n  setoid_rewrite group_inv_r.\n  assumption.\nQed.\n\nTheorem group_inv_involute (a: Carrier):\n  inv (inv a) == a.\nProof.\n  symmetry.\n  apply group_inv_r_unique.\n  apply group_inv_l.\nQed.\n\nTheorem group_inv_op (a b: Carrier):\n  inv (a <o> b) == inv b <o> inv a.\nProof.\n  symmetry.\n  apply group_inv_r_unique.\n  setoid_rewrite <- (semigroup_assoc equiv op).\n  symmetry.\n  apply group_move_r.\n  setoid_rewrite (monoid_ident_l equiv op ident).\n  apply group_move_r.\n  reflexivity.\nQed.\n\nTheorem group_solution_r (a b: Carrier):\n  (exists (x: Carrier), x <o> a == b) /\\\n  (forall (x: Carrier),\n    x <o> a == b -> x == b <o> inv a).\nProof.\n  split.\n  { exists (b <o> inv a).\n    setoid_rewrite (semigroup_assoc equiv op).\n    apply (monoid_op_l_solo equiv op ident).\n    apply group_inv_l. }\n  { intros x.\n    apply group_move_r. }\nQed.\n\nTheorem group_solution_l (a b: Carrier):\n  (exists (x: Carrier), a <o> x == b) /\\\n  (forall (x: Carrier),\n    a <o> x == b -> x == inv a <o> b).\nProof.\n  split.\n  { exists (inv a <o> b).\n    setoid_rewrite <- (semigroup_assoc equiv op).\n    apply (monoid_op_r_solo equiv op ident).\n    apply group_inv_r. }\n  { intros x.\n    apply group_move_l. }\nQed.\n\nTheorem group_inv_ident:\n  inv ident == ident.\nProof.\n  symmetry.\n  apply group_inv_r_unique.\n  apply group_ident_r.\nQed.\n\nSection Subgroups.\nContext (P: Carrier -> Prop).\nContext (P_proper: Proper (equiv ==> iff) P).\n\nLemma subset_op_inv_closed_ident:\n  (exists (x: Carrier), P x) ->\n  (forall (a b: Carrier),\n    P a -> P b -> P (a <o> inv b)) ->\n  P ident.\nProof.\n  intros [x HPx] Hop_inv.\n  specialize (Hop_inv x x HPx HPx).\n  assert (x <o> inv x == ident) by apply group_inv_r.\n  apply P_proper in H.\n  apply H.\n  assumption.\nQed.\n\nLemma subset_op_inv_closed_inv_closed:\n  (exists (x: Carrier), P x) ->\n  (forall (a b: Carrier),\n    P a -> P b -> P (a <o> inv b)) ->\n  (forall (a: Carrier), P a -> P (inv a)).\nProof.\n  intros Hx Hop_inv a HPa.\n  assert (P ident)\n    as HPident\n    by apply (subset_op_inv_closed_ident Hx Hop_inv).\n  specialize (Hop_inv ident a HPident HPa).\n  assert (ident <o> inv a == inv a)\n    by apply (monoid_ident_l equiv op ident).\n  apply P_proper in H.\n  apply H.\n  assumption.\nQed.\n\nLemma subset_op_inv_closed_op_closed:\n  (exists (x: Carrier), P x) ->\n  (forall (a b: Carrier),\n    P a -> P b -> P (a <o> inv b)) ->\n  (forall (a b: Carrier), P a -> P b -> P (a <o> b)).\nProof.\n  intros Hx Hop_inv a b HPa HPb.\n  assert (P (inv b))\n    as HPb'\n    by apply (subset_op_inv_closed_inv_closed Hx Hop_inv b HPb).\n  specialize (Hop_inv a (inv b) HPa HPb').\n  assert (a <o> inv (inv b) == a <o> b)\n    by (apply (semigroup_op_l equiv op); apply group_inv_involute).\n  apply P_proper in H.\n  apply H.\n  assumption.\nQed.\n\nClass Subgroup := {\n  subgroup_op_closed:\n    forall (a b: Carrier), P a -> P b -> P (a <o> b);\n  subgroup_inv_closed:\n    forall (a: Carrier), P a -> P (inv a);\n  subgroup_ident: P ident;\n}.\n\nTheorem subset_op_inv_closed_subgroup:\n  (exists (x: Carrier), P x) ->\n  (forall (a b: Carrier),\n    P a -> P b -> P (a <o> inv b)) ->\n  Subgroup.\nProof.\n  intros Hx Hop_inv.\n  constructor.\n  { apply subset_op_inv_closed_op_closed;\n    assumption. }\n  { apply subset_op_inv_closed_inv_closed;\n    assumption. }\n  { apply subset_op_inv_closed_ident;\n    assumption. }\nQed.\n\nContext {subgroup: Subgroup}.\n\nLemma subgroup_inv_inv_closed (a: Carrier):\n  P (inv a) -> P a.\nProof.\n  intros HPa'.\n  apply subgroup_inv_closed in HPa'.\n  assert (inv (inv a) == a)\n    by apply group_inv_involute.\n  apply P_proper in H.\n  apply H.\n  assumption.\nQed.\n\nDefinition left_congru (a b: Carrier) :=\n  P (inv a <o> b).\nDefinition right_congru (a b: Carrier) :=\n  P (a <o> inv b).\n\nTheorem left_congru_proper:\n  Proper (equiv ==> equiv ==> iff) left_congru.\nProof.\n  intros a0 a1 Ha b0 b1 Hb.\n  unfold left_congru.\n  split;\n    intros HPa'b;\n  assert (inv a0 <o> b0 == inv a1 <o> b1);\n    try (apply op_proper;\n      [apply inv_proper |];\n      assumption);\n  apply P_proper in H;\n  apply H;\n  assumption.\nQed.\n\nTheorem right_congru_proper:\n  Proper (equiv ==> equiv ==> iff) right_congru.\nProof.\n  intros a0 a1 Ha b0 b1 Hb.\n  unfold right_congru.\n  split;\n    intros Hab';\n  assert (a0 <o> inv b0 == a1 <o> inv b1);\n    try (apply op_proper;\n      [| apply inv_proper];\n      assumption);\n  apply P_proper in H;\n  apply H;\n  assumption.\nQed.\n\nLemma left_congru_reflexive (a: Carrier):\n  left_congru a a.\nProof.\n  unfold left_congru.\n  assert (inv a <o> a == ident)\n    by apply group_inv_l.\n  apply P_proper in H.\n  apply H.\n  apply subgroup_ident.\nQed.\n\nLemma left_congru_symmetric (a b: Carrier):\n  left_congru a b -> left_congru b a.\nProof.\n  unfold left_congru.\n  intros HPa'b.\n  apply subgroup_inv_closed in HPa'b.\n  assert (inv (inv a <o> b) == inv b <o> a).\n  { setoid_rewrite group_inv_op.\n    setoid_rewrite group_inv_involute.\n    reflexivity. }\n  { apply P_proper in H.\n    apply H.\n    assumption. }\nQed.\n\nLemma left_congru_transitive (a b c: Carrier):\n  left_congru a b ->\n  left_congru b c ->\n  left_congru a c.\nProof.\n  unfold left_congru.\n  intros HPa'b HPb'c.\n  assert (inv a <o> b <o> (inv b <o> c) == inv a <o> c).\n  { setoid_rewrite <- (semigroup_assoc equiv op).\n    apply (semigroup_op_r equiv op).\n    setoid_rewrite (semigroup_assoc equiv op).\n    apply (monoid_op_l_solo equiv op ident).\n    apply group_inv_r. }\n  { apply P_proper in H.\n    apply H.\n    apply subgroup_op_closed;\n      assumption. }\nQed.\n\n#[global]\nInstance left_congru_equiv: Equivalence left_congru := {\n  Equivalence_Reflexive := left_congru_reflexive;\n  Equivalence_Symmetric := left_congru_symmetric;\n  Equivalence_Transitive := left_congru_transitive;\n}.\n\nLemma right_congru_reflexive (a: Carrier):\n  right_congru a a.\nProof.\n  unfold right_congru.\n  assert (a <o> inv a == ident)\n    by apply group_inv_r.\n  apply P_proper in H.\n  apply H.\n  apply subgroup_ident.\nQed.\n\nLemma right_congru_symmetric (a b: Carrier):\n  right_congru a b -> right_congru b a.\nProof.\n  unfold right_congru.\n  intros HPab'.\n  apply subgroup_inv_closed in HPab'.\n  assert (inv (a <o> inv b) == b <o> inv a).\n  { setoid_rewrite group_inv_op.\n    setoid_rewrite group_inv_involute.\n    reflexivity. }\n  { apply P_proper in H.\n    apply H.\n    assumption. }\nQed.\n\nLemma right_congru_transitive (a b c: Carrier):\n  right_congru a b ->\n  right_congru b c ->\n  right_congru a c.\nProof.\n  unfold right_congru.\n  intros HPab' HPbc'.\n  assert (a <o> inv b <o> (b <o> inv c) == a <o> inv c).\n  { setoid_rewrite <- (semigroup_assoc equiv op).\n    apply (semigroup_op_r equiv op).\n    setoid_rewrite (semigroup_assoc equiv op).\n    apply (monoid_op_l_solo equiv op ident).\n    apply group_inv_l. }\n  { apply P_proper in H.\n    apply H.\n    apply subgroup_op_closed;\n      assumption. }\nQed.\n\n#[global]\nInstance right_congru_equiv: Equivalence right_congru := {\n  Equivalence_Reflexive := right_congru_reflexive;\n  Equivalence_Symmetric := right_congru_symmetric;\n  Equivalence_Transitive := right_congru_transitive;\n}.\n\nDefinition left_cosets_eq (a b: Carrier) :=\n  forall (m: Carrier),\n    P m ->\n    exists (n: Carrier), P n /\\ a <o> m == b <o> n.\n\nLemma subgroup_equiv_left_congru_cosets_eq (a b: Carrier):\n  left_congru a b <-> left_cosets_eq a b.\nProof.\n  unfold left_congru, left_cosets_eq.\n  split;\n    [intros HPa'b m HPm | intros Hcoset].\n  { exists (inv b <o> (a <o> m)).\n    split.\n    { apply subgroup_inv_closed in HPa'b.\n      assert (inv (inv a <o> b) <o> m == inv b <o> (a <o> m)).\n      { setoid_rewrite group_inv_op.\n        setoid_rewrite group_inv_involute.\n        apply (semigroup_assoc equiv op). }\n      { apply P_proper in H.\n        apply H.\n        apply subgroup_op_closed;\n          assumption. } }\n    { setoid_rewrite <- (semigroup_assoc equiv op).\n      symmetry.\n      apply (monoid_op_r_solo equiv op ident).\n      apply group_inv_r. } }\n  { specialize (Hcoset ident subgroup_ident).\n    inversion_clear Hcoset as [n [HPn H]].\n    setoid_rewrite (monoid_ident_r equiv op ident) in H.\n    symmetry in H.\n    apply group_move_l in H.\n    assert (inv n == inv a <o> b).\n    { setoid_rewrite H.\n      setoid_rewrite group_inv_op.\n      setoid_rewrite group_inv_involute.\n      reflexivity. }\n    { apply P_proper in H0.\n      apply H0.\n      apply subgroup_inv_closed.\n      assumption. } }\nQed.\n\nDefinition right_cosets_eq (a b: Carrier) :=\n  forall (m: Carrier),\n    P m ->\n    exists (n: Carrier), P n /\\ m <o> a == n <o> b.\n\nLemma subgroup_equiv_right_congru_cosets_eq (a b: Carrier):\n  right_congru a b <-> right_cosets_eq a b.\nProof.\n  unfold right_congru, right_cosets_eq.\n  split;\n    [intros HPab' m HPm | intros Hcoset].\n  { exists (m <o> (a <o> inv b)).\n    split;\n      [apply subgroup_op_closed; assumption |].\n    setoid_rewrite <- (semigroup_assoc equiv op).\n    setoid_rewrite (semigroup_assoc equiv op).\n    symmetry.\n    apply (monoid_op_l_solo equiv op ident).\n    apply group_inv_l. }\n  { specialize (Hcoset ident subgroup_ident).\n    inversion_clear Hcoset as [n [HPn H]].\n    setoid_rewrite (monoid_ident_l equiv op ident) in H.\n    symmetry in H.\n    apply group_move_r in H.\n    setoid_rewrite <- H.\n    assumption. }\nQed.\n\nLet normal_subgroup_congru_coincide := (* 1 *)\n  forall (a b: Carrier),\n    left_congru a b <-> right_congru a b.\nLet normal_subgroup_cosets_eq_coincide := (* 2 *)\n  forall (a b: Carrier),\n    left_cosets_eq a b <-> right_cosets_eq a b.\nLet normal_subgroup_cosets_coincide := (* 3 *)\n  forall (m: Carrier),\n    P m ->\n    forall (a: Carrier),\n      exists (n: Carrier),\n        P n /\\ a <o> m == n <o> a.\nLet normal_subgroup_conj_closed := (* 4 *)\n  forall (n: Carrier),\n    P n ->\n    forall (a: Carrier), P (a <o> n <o> inv a).\nLet normal_subgroup_conj_closed_exact := (* 5 *)\n  forall (n a: Carrier),\n    P n <-> P (a <o> n <o> inv a).\n\nTheorem normal_subgroup_equiv_congru_cosets_eq:\n  normal_subgroup_congru_coincide <->\n  normal_subgroup_cosets_eq_coincide.\nProof.\n  split;\n    [intros Hcongru a b | intros Hcosets a b].\n  { specialize (Hcongru a b).\n    split;\n      [intros Hlcoset | intros Hrcoset].\n    { apply subgroup_equiv_right_congru_cosets_eq.\n      apply Hcongru.\n      apply subgroup_equiv_left_congru_cosets_eq.\n      assumption. }\n    { apply subgroup_equiv_left_congru_cosets_eq.\n      apply Hcongru.\n      apply subgroup_equiv_right_congru_cosets_eq.\n      assumption. } }\n  { specialize (Hcosets a b).\n    split;\n      [intros Hlcongru | intros Hrcongru].\n    { apply subgroup_equiv_right_congru_cosets_eq.\n      apply Hcosets.\n      apply subgroup_equiv_left_congru_cosets_eq.\n      assumption. }\n    { apply subgroup_equiv_left_congru_cosets_eq.\n      apply Hcosets.\n      apply subgroup_equiv_right_congru_cosets_eq.\n      assumption. } }\nQed.\n\nTheorem normal_subgroup_equiv_cosets_conj:\n  normal_subgroup_cosets_coincide <->\n  normal_subgroup_conj_closed.\nProof.\n  split;\n    [intros Hcosets | intros Hconj].\n  { intros n HPn a.\n    specialize (Hcosets n HPn a).\n    inversion_clear Hcosets as [m [HPm H]].\n    symmetry in H.\n    apply group_move_r in H.\n    setoid_rewrite <- H.\n    assumption. }\n  { intros m HPm a.\n    exists (a <o> m <o> inv a).\n    split.\n    { apply Hconj.\n      assumption. }\n    { setoid_rewrite (semigroup_assoc equiv op).\n      symmetry.\n      apply (monoid_op_l_solo equiv op ident).\n      apply group_inv_l. } }\nQed.\n\nTheorem normal_subgroup_equiv_conj_closed:\n  normal_subgroup_conj_closed <->\n  normal_subgroup_conj_closed_exact.\nProof.\n  split;\n    [intros H | intros Hexact].\n  { intros n a.\n    split;\n      [intros HPn | intros Hconj_n].\n    { apply H.\n      assumption. }\n    { apply H in Hconj_n.\n      specialize (Hconj_n (inv a)).\n      repeat setoid_rewrite <- (semigroup_assoc equiv op) in Hconj_n.\n      setoid_rewrite (group_inv_l a) in Hconj_n.\n      setoid_rewrite (monoid_ident_l equiv op ident) in Hconj_n.\n      setoid_rewrite (semigroup_assoc equiv op) in Hconj_n.\n      setoid_rewrite (group_inv_r (inv a)) in Hconj_n.\n      setoid_rewrite (monoid_ident_r equiv op ident) in Hconj_n.\n      assumption. } }\n  { intros n HPn a.\n    apply Hexact.\n    assumption. }\nQed.\n\nTheorem normal_subgroup_equiv_congru_conj:\n  normal_subgroup_congru_coincide <->\n  normal_subgroup_conj_closed.\nProof.\n  split;\n    [intros Hcongru | intros Hconj].\n  { intros n HPn a.\n    assert (a <o> n <o> inv a == a <o> inv (a <o> inv n)).\n    { setoid_rewrite group_inv_op.\n      setoid_rewrite group_inv_involute.\n      apply (semigroup_assoc equiv op). }\n    { apply P_proper in H.\n      apply H.\n      apply Hcongru.\n      assert (inv a <o> (a <o> inv n) == inv n).\n      { setoid_rewrite <- (semigroup_assoc equiv op).\n        apply (monoid_op_r_solo equiv op ident).\n        apply group_inv_l. }\n      { apply P_proper in H0.\n        apply H0.\n        apply subgroup_inv_closed.\n        assumption. } } }\n  { intros a b.\n    split;\n      [intros Hlcongru | intros Hrcongru].\n    { specialize (Hconj (inv a <o> b) Hlcongru b).\n      assert (b <o> (inv a <o> b) <o> inv b == b <o> inv a).\n      { setoid_rewrite (semigroup_assoc equiv op).\n        apply (semigroup_op_l equiv op).\n        setoid_rewrite (semigroup_assoc equiv op).\n        apply (monoid_op_l_solo equiv op ident).\n        apply group_inv_r. }\n      { apply P_proper in H.\n        symmetry.\n        apply H.\n        assumption. } } \n    { specialize (Hconj (a <o> inv b) Hrcongru (inv b)).\n      assert (inv b <o> (a <o> inv b) <o> inv (inv b) == inv b <o> a).\n      { setoid_rewrite (semigroup_assoc equiv op).\n        apply (semigroup_op_l equiv op).\n        setoid_rewrite (semigroup_assoc equiv op).\n        apply (monoid_op_l_solo equiv op ident).\n        apply group_inv_r. }\n      { apply P_proper in H.\n        symmetry.\n        apply H.\n        assumption. } } }\nQed.\n\nCorollary normal_subgroup_equiv_congru_cosets:\n  normal_subgroup_congru_coincide <->\n  normal_subgroup_cosets_coincide.\nProof.\n  split;\n    [intros Hcongru | intros Hcosets].\n  { apply normal_subgroup_equiv_cosets_conj.\n    apply normal_subgroup_equiv_congru_conj.\n    assumption. }\n  { apply normal_subgroup_equiv_congru_conj.\n    apply normal_subgroup_equiv_cosets_conj.\n    assumption. }\nQed.\n\nCorollary normal_subgroup_equiv_congru_conj_exact:\n  normal_subgroup_congru_coincide <->\n  normal_subgroup_conj_closed_exact.\nProof.\n  split;\n    [intros Hcongr | intros Hconj].\n  { apply normal_subgroup_equiv_conj_closed.\n    apply normal_subgroup_equiv_congru_conj.\n    assumption. }\n  { apply normal_subgroup_equiv_congru_conj.\n    apply normal_subgroup_equiv_conj_closed.\n    assumption. }\nQed.\n\nCorollary normal_subgroup_equiv_cosets_eq_cosets:\n  normal_subgroup_cosets_eq_coincide <->\n  normal_subgroup_cosets_coincide.\nProof.\n  split;\n    [intros Hcoset_eq | intros Hcosets].\n  { apply normal_subgroup_equiv_congru_cosets.\n    apply normal_subgroup_equiv_congru_cosets_eq.\n    assumption. }\n  { apply normal_subgroup_equiv_congru_cosets_eq.\n    apply normal_subgroup_equiv_congru_cosets.\n    assumption. }\nQed.\n\nCorollary normal_subgroup_equiv_cosets_eq_conj:\n  normal_subgroup_cosets_eq_coincide <->\n  normal_subgroup_conj_closed.\nProof.\n  split;\n    [intros Hcoset_eq | intros Hconj].\n  { apply normal_subgroup_equiv_congru_conj.\n    apply normal_subgroup_equiv_congru_cosets_eq.\n    assumption. }\n  { apply normal_subgroup_equiv_congru_cosets_eq.\n    apply normal_subgroup_equiv_congru_conj.\n    assumption. }\nQed.\n\nCorollary normal_subgroup_equiv_cosets_eq_conj_exact:\n  normal_subgroup_cosets_eq_coincide <->\n  normal_subgroup_conj_closed_exact.\nProof.\n  split;\n    [intros Hcoset_eq | intros Hconj_exact].\n  { apply normal_subgroup_equiv_conj_closed.\n    apply normal_subgroup_equiv_cosets_eq_conj.\n    assumption. }\n  { apply normal_subgroup_equiv_cosets_eq_conj.\n    apply normal_subgroup_equiv_conj_closed.\n    assumption. }\nQed.\n\nCorollary normal_subgroup_equiv_cosets_conj_exact:\n  normal_subgroup_cosets_coincide <->\n  normal_subgroup_conj_closed_exact.\nProof.\n  split;\n    [intros Hcosets | intros Hconj_exact].\n  { apply normal_subgroup_equiv_conj_closed.\n    apply normal_subgroup_equiv_cosets_conj.\n    assumption. }\n  { apply normal_subgroup_equiv_cosets_conj.\n    apply normal_subgroup_equiv_conj_closed.\n    assumption. }\nQed.\n\nSection NormalSubgroups.\nLemma quotient_op_proper:\n  normal_subgroup_congru_coincide ->\n  Proper (left_congru ==> left_congru ==> left_congru) op.\nProof.\n  intros congru_coincide a0 a1 Ha b0 b1 Hb.\n  assert (inv (a0 <o> b0) <o> (a1 <o> b1) == inv b0 <o> (inv a0 <o> a1 <o> b1)).\n  { setoid_rewrite group_inv_op.\n    setoid_rewrite (semigroup_assoc equiv op).\n    reflexivity. }\n  { apply P_proper in H.\n    apply H; clear H.\n    apply congru_coincide.\n    assert (b0 <o> inv (inv a0 <o> a1 <o> b1) == b0 <o> inv b1 <o>\n      inv (inv a0 <o> a1)).\n    { repeat setoid_rewrite group_inv_op.\n      setoid_rewrite (semigroup_assoc equiv op).\n      reflexivity. }\n    { apply P_proper in H.\n      apply H; clear H.\n      apply subgroup_op_closed;\n        [apply congru_coincide | apply subgroup_inv_closed];\n        assumption. } }\nQed.\n\nLemma quotient_inv_proper:\n  normal_subgroup_congru_coincide ->\n  Proper (left_congru ==> left_congru) inv.\nProof.\n  intros congru_coincide a0 a1 Ha.\n  assert (inv (inv a0) <o> inv a1 == a0 <o> inv a1).\n  { apply group_op_r.\n    apply group_inv_involute. }\n  { apply P_proper in H.\n    apply H.\n    apply congru_coincide.\n    assumption. }\nQed.\n\nLemma quotient_semigroup:\n  normal_subgroup_congru_coincide ->\n  Semigroup left_congru op.\nProof.\n  intros congru_coincide.\n  constructor.\n  intros a b c.\n  assert (inv (a <o> b <o> c) <o> (a <o> (b <o> c)) == ident);\n    [| apply P_proper in H; apply H; apply subgroup_ident].\n  symmetry.\n  apply group_move_l.\n  setoid_rewrite (monoid_ident_r equiv op ident).\n  apply (semigroup_assoc equiv op).\nQed.\n\nLemma quotient_monoid:\n  normal_subgroup_congru_coincide ->\n  Monoid left_congru op ident.\nProof.\n  intros congru_coincide.\n  constructor;\n    [ apply quotient_semigroup;\n      apply congru_coincide | |];\n    intros a.\n  { assert (inv (ident <o> a) <o> a == ident).\n    { symmetry.\n      apply group_move_l.\n      setoid_rewrite (monoid_ident_r equiv op ident).\n      apply (monoid_ident_l equiv op ident). }\n    { apply P_proper in H.\n      apply H.\n      apply subgroup_ident. } }\n  { assert (inv (a <o> ident) <o> a == ident).\n    { symmetry.\n      apply group_move_l.\n      repeat setoid_rewrite (monoid_ident_r equiv op ident).\n      reflexivity. }\n    { apply P_proper in H.\n      apply H.\n      apply subgroup_ident. } }\nQed.\nEnd NormalSubgroups.\nEnd Subgroups.\nEnd Groups.\n\nSection NormalSubgroups.\nContext {Carrier: Type}.\nContext (equiv: relation Carrier).\nContext {R_equiv: Equivalence equiv}.\nContext (op: Carrier -> Carrier -> Carrier).\nContext {op_proper: Proper (equiv ==> equiv ==> equiv) op}.\nContext (ident: Carrier).\nContext (inv: Carrier -> Carrier).\nContext {inv_proper: Proper (equiv ==> equiv) inv}.\nContext {group: Group equiv op ident inv}.\nContext (P: Carrier -> Prop).\nContext {P_proper: Proper (equiv ==> iff) P}.\nContext {subgroup: Subgroup op ident inv P}.\n\nInfix \"==\" := equiv (at level 60, no associativity).\nInfix \"<o>\" := op (at level 40, left associativity).\n\nLet normal_subgroup_congru_coincide :=\n  forall (a b: Carrier),\n    left_congru op inv P a b <->\n    right_congru op inv P a b.\n\nTheorem quotient_normal_subgroup_group:\n  normal_subgroup_congru_coincide ->\n  Group (left_congru op inv P) op ident inv.\nProof.\n  intros congru_coincide.\n  constructor;\n    [apply (quotient_monoid equiv op ident inv P P_proper);\n      apply congru_coincide | |];\n    intros a.\n  { assert (inv (inv a <o> a) <o> ident == ident).\n    { symmetry.\n      apply (group_move_l equiv op ident inv).\n      setoid_rewrite (monoid_ident_r equiv op ident).\n      apply (group_inv_l equiv op ident inv). }\n    { apply P_proper in H.\n      apply H.\n      apply (subgroup_ident op ident inv P). } }\n  { assert (inv (a <o> inv a) <o> ident == ident).\n    { symmetry.\n      apply (group_move_l equiv op ident inv).\n      setoid_rewrite (monoid_ident_r equiv op ident).\n      apply (group_inv_r equiv op ident inv). }\n    { apply P_proper in H.\n      apply H.\n      apply (subgroup_ident op ident inv P). } }\nQed.\nEnd NormalSubgroups.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/theories/Groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8140137102222157}}
{"text": "(****** Formalizing certain properties from combinatorics ***************)\nRequire Import Reals Psatz.\nRequire Import Omega Init.Nat Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat Coq.Structures.Equalities.\n\nOpen Scope R_scope.\n\nDefinition nchoosek (n k: nat) : R := INR (fact n) / (INR (fact k) * INR (fact (n-k))).\n\n\nLemma nplus1cr: forall (r n :nat), (r <=n)%nat -> nchoosek (n+1) r = (INR (n+1) * (/ INR (n-r+1))) * nchoosek n r.\nProof.\nintros.\nunfold nchoosek.\nassert ( fact (n+1)= ((n+1)%nat * fact n)%nat). \n{ assert (S n = (n+1)%nat). { omega. }rewrite <-H0. apply fact_simpl. } rewrite H0.\nassert ( fact (n + 1 - r)= ((n-r+1)%nat * fact (n-r))%nat).\n{ assert ((n + 1 - r)%nat = S (n-r)). { omega. } rewrite H1. \n  assert ((n - r + 1)%nat = S (n-r)). { omega. } rewrite H2. apply fact_simpl.\n} rewrite H1.\nassert (INR ((n + 1) * fact n) = INR (n+1) * INR (fact n)). { apply mult_INR. } rewrite H2.\nassert (INR ((n - r + 1) * fact (n - r))= INR (n-r+1) * INR (fact (n-r))). { apply mult_INR. } rewrite H3. \nassert (INR (fact n) / (INR (fact r) * INR (fact (n - r)))= INR (fact n) * (/ INR (fact r)) * (/INR (fact (n - r)))).\n{ assert (/ (INR (fact r) * INR (fact (n - r)))=(/ INR (fact r)) * (/INR (fact (n - r)))).\n  { apply Rinv_mult_distr. apply INR_fact_neq_0. apply INR_fact_neq_0. }\n  assert (INR (fact n) / (INR (fact r) * INR (fact (n - r)))= INR (fact n) * (/ (INR (fact r) * INR (fact (n - r))))). { nra. } rewrite H5.\n  rewrite H4. nra.\n} rewrite H4.\nassert (INR (n + 1) * / INR (n - r + 1) * (INR (fact n) * / INR (fact r) * / INR (fact (n - r)))=\n          (INR (n + 1) * INR (fact n) ) * (/ INR (fact r) *  / INR (n - r + 1) * / INR (fact (n - r)))). { nra. } rewrite H5.\nassert (INR (n + 1) * INR (fact n) / (INR (fact r) * (INR (n - r + 1) * INR (fact (n - r))))=\n          (INR (n + 1) * INR (fact n)) * (/ (INR (fact r) * (INR (n - r + 1) * INR (fact (n - r)))))). { nra. } rewrite H6.\nassert (/ (INR (fact r) * (INR (n - r + 1) * INR (fact (n - r))))=(/ INR (fact r) * / INR (n - r + 1) * / INR (fact (n - r)))).\n{ assert (/ (INR (fact r) * (INR (n - r + 1) * INR (fact (n - r)))) = (/INR (fact r)) * (/ (INR (n - r + 1) * INR (fact (n - r))))). \n  { apply Rinv_mult_distr. apply INR_fact_neq_0. rewrite <-H3. rewrite <-H1. apply INR_fact_neq_0. } rewrite H7.\n  assert ( / (INR (n - r + 1) * INR (fact (n - r))) = (/ INR (n - r + 1) ) * (/  INR (fact (n - r)))). \n  { apply Rinv_mult_distr. \n    assert ( 0< INR (n - r + 1) -> INR (n - r + 1) <> 0). { nra. } apply H8. apply lt_0_INR. omega. apply INR_fact_neq_0. } rewrite H8. nra. \n} rewrite H7. nra.\nQed.\n\nLemma comb_prop_1: forall (n:nat), nchoosek n 0%nat= 1.\nProof.\nintros.\nassert (n=0%nat \\/ (0<n)%nat). { omega. } destruct H.\n+ rewrite H.\n  unfold nchoosek.\n  assert ( (0-0)%nat = 0%nat). { omega. } rewrite H0.\n  assert (fact 0=1%nat). { auto. } rewrite H1.\n  assert (INR 1=1). { reflexivity. }rewrite H2. nra.\n+ unfold nchoosek.\n  assert ((n - 0)%nat=n). { omega. } rewrite H0.\n  assert (fact 0=1%nat). { auto. }rewrite H1.\n  assert (INR 1=1). { reflexivity. }rewrite H2. \n  assert ((1 * INR (fact n))=INR (fact n)). { nra. } rewrite H3.\n  assert (INR (fact n) / INR (fact n)= INR (fact n) * (/ INR (fact n))). { nra. }rewrite H4.\n  apply Rinv_r. assert ( 0< INR (fact n) -> INR (fact n) <> 0). { nra. }  apply H5. \n  apply lt_0_INR. apply lt_O_fact. \nQed.\n\n\nLemma comb_prop_2: forall (n:nat), (1<=n)%nat -> nchoosek n 1%nat=INR n.\nProof.\nintros.\nunfold nchoosek.\nassert ((fact 1)=1%nat). { auto. } rewrite H0. assert (INR 1=1). { reflexivity. }rewrite H1.\nassert (1 * INR (fact (n - 1))= INR (fact (n - 1))). { nra. } rewrite H2.\nassert ( fact n = (n* fact (n-1))%nat).\n{ induction n.\n  + contradict H1. omega. \n  + assert ((S n - 1)%nat = n). { omega. }rewrite H3.\n    auto.\n} rewrite H3. \nassert (INR (n * fact (n - 1))= INR n * INR (fact(n-1)) ). { apply mult_INR. } rewrite H4.\nassert (INR n * INR (fact (n - 1)) / INR (fact (n - 1))= INR n * (INR (fact (n - 1)) * (/INR (fact (n - 1))))). { nra. }rewrite H5.\nassert ((INR (fact (n - 1)) * / INR (fact (n - 1)))=1). { apply Rinv_r. assert ( 0< INR (fact (n - 1)) -> INR (fact (n - 1)) <> 0). { nra. } apply H6.\napply lt_0_INR. apply lt_O_fact. } rewrite H6. nra.\nQed. \n\n", "meta": {"author": "mohittkr", "repo": "Lax_equivalence", "sha": "c19b626513ce8ec1a6426f2364e6c45e8caa85ae", "save_path": "github-repos/coq/mohittkr-Lax_equivalence", "path": "github-repos/coq/mohittkr-Lax_equivalence/Lax_equivalence-c19b626513ce8ec1a6426f2364e6c45e8caa85ae/combinatorics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8139918100361}}
{"text": "From Coq Require Export List NArith.\nFrom Coq Require Import Lia.\n\nImport ListNotations.\n\n#[global] Open Scope N_scope.\n\nNotation \"'input' x .. y\" := (cons x .. (cons y nil) ..) (at level 200, x at level 0, only parsing).\n\nDefinition example : list N := input\n199\n200\n208\n210\n200\n207\n240\n269\n260\n263\n.\n\n(* Part 1 *)\n\n(* Count the number of consecutive increasing pairs *)\nFixpoint count_increases_ (xs : list N) (acc : N) : N :=\n  match xs with\n  | [] | _ :: [] => acc\n  | x :: (y :: _) as xs =>\n    count_increases_ xs (if x <? y then 1 + acc else acc)\n  end.\n\nDefinition count_increases (xs : list N) : N := count_increases_ xs 0.\n\nDefinition solve : list N -> N := count_increases.\n\n(* Compute solve example.  (* 7 *) *)\n\n(* Seems as simple as could be. *)\n\n(* Part 2 *)\n\n(* Count the number of consecutive increasing sums in a sliding window of length 3 *)\nFixpoint count_increases2_ (xs : list N) (acc : N) : N :=\n  match xs with\n  | x :: (_ :: _ :: y :: _) as xs =>\n    count_increases2_ xs (if x <? y then 1 + acc else acc)\n  | _ => acc\n  end.\n\nDefinition count_increases2 (xs : list N) : N := count_increases2_ xs 0.\n\nDefinition solve2 : list N -> N := count_increases2.\n\n(* Compute solve2 example. (* 5 *) *)\n\nDefinition solve12 (i : list N) : N * N := (solve i, solve2 i).\n\n(* This solution avoids computing the sums. We can prove that it's equivalent to a more literal\n   solution that does the sums. *)\n\nFixpoint sum3 (xs : list N) : list N :=\n  match xs with\n  | x :: (y :: z :: _) as xs => (x + y + z) :: sum3 xs\n  | _ => []\n  end.\n\nTheorem count_increases2_correct xs : count_increases (sum3 xs) = count_increases2 xs.\nProof.\n  unfold count_increases, count_increases2. generalize 0.\n  induction xs as [ | x xs IH]; cbn [sum3]; intros n; [ reflexivity | ].\n  destruct xs as [ | y [ | z [ | t xs_ ] ] ]; [ reflexivity .. | ].\n  change\n    ( count_increases_ (sum3 (y :: z :: t :: xs_)) (if x + y + z <? y + z + t then 1 + n else n)\n    = count_increases2_ (y :: z :: t :: xs_) (if x <? t then 1 + n else n)).\n  destruct (N.ltb_spec x t);\n  destruct (N.ltb_spec (x + y + z) (y + z + t)); [ apply IH | lia | lia | apply IH ].\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/aoc01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.8139654028661739}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nPrint even.\n(* ==>\n  Inductive even : nat -> Prop :=\n    | ev_0 : even 0\n    | ev_SS : forall n, even n -> even (S (S n)).\n*)\n(*\u67ef\u91cc-\u970d\u534e\u5fb7\u540c\u6784\uff1a\u65e2\u5728\u7c7b\u578b\u5c42\u9762\u8868\u8fbe\u5177\u6709\u4ec0\u4e48\u7c7b\u578b\uff0c\u53c8\u5728\u547d\u9898\u5c42\u9762\u4e0a\u8868\u793a\u5f0f\u4ec0\u4e48\u7684\u8bc1\u660e*)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  even n ->\n                  even (S (S n)) *)\n(*ev_SS\u6784\u9020\u5b50\u8868\u793a\u63a5\u53d7\u4e24\u4e2a\u53c2\u6570-\u6570\u5b57n\u4ee5\u53ca\u547d\u9898ev n\u7684\u8bc1\u660e\uff0c\u4ea7\u751fev(S (S n))\u7684\u8bc1\u660e*)\n\nTheorem ev_4 : even 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nPrint ev_4.\n\n(** Indeed, we can also write down this proof object _directly_,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n\nTheorem ev_4': even 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\nTheorem ev_4'' : even 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(*\u7b56\u7565\u8bc1\u660e\u5e76\u4e0d\u662f\u5fc5\u8981\u7684\uff0c\u53ef\u624b\u52a8\u6784\u9020\u60f3\u8981\u7684\u8bc1\u636e\uff0c\u901a\u8fc7Definition\u76f4\u63a5\u7ed9\u8bc1\u636e\u4e00\u4e2a\u5168\u5c40\u540d\u79f0*)\nDefinition ev_4''' : even 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(**\u6784\u9020\u65b9\u5f0f\u867d\u7136\u4e0d\u540c\uff0c\u4f46\u662f\u5b58\u50a8\u5728\u5168\u5c40\u73af\u5883\u4e2d\u7684\u8bc1\u660e\u662f\u4e00\u81f4\u7684*)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)  \n\n    Give a tactic proof and a proof object showing that [even 8]. *)\n\nTheorem ev_8 : even 8.\nProof.\n  apply (ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0)))).\nQed.\n\nDefinition ev_8' : even 8 :=\n  (ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0)))).\n(** [] *)\n\n(* ################################################################# *)\nTheorem ev_plus4 : forall n, even n -> even (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\nDefinition ev_plus4' : forall n, even n -> even (4 + n) :=\n  fun (n : nat) => fun (H : even n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nDefinition ev_plus4'' (n : nat) (H : even n)\n                    : even (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===>\n     : forall n : nat, even n -> even (4 + n) *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : even n), even (n + 2).\n(*\u8be5\u4f8b\u5b50\u4e2d\uff0cforall\u65f6\u5e76\u6ca1\u6709\u4f9d\u8d56\uff0c\u53ef\u4ee5\u7b80\u5199\u6210->\uff0c\u6211\u4eec\u6ca1\u6709\u5fc5\u8981\u7ed9\u7bad\u5934\u5de6\u8fb9\u7684\u7c7b\u578b\u4e00\u4e2a\u540d\u5b57*)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : even n), even (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, even n -> even (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n(*\u4f7f\u7528Defined\u800c\u4e0d\u662fQed\u6765\u7ec8\u6b62\u8bc1\u660e\uff0c\u5b83\u53ef\u4ee5\u5728\u8ba1\u7b97\u4e2d\u5c31\u50cf\u6b63\u5e38\u5b9a\u4e49\u7684\u51fd\u6570\u4e00\u6837\u88ab\u4f7f\u7528,\u800c\u901a\u8fc7Qed\u5b9a\u4e49\u7684\u5bf9\u8c61\n\u5728\u8ba1\u7b97\u4e2d\u662f\u4e0d\u900f\u660e\u7684*)\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\nModule Props.\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\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(*split\u7b56\u7565\u80fd\u7528\u4e8e\u6240\u6709\u53ea\u6709\u4e00\u4e2a\u6784\u9020\u5b50*)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, standard, optional (conj_fact) *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun( P Q R:Prop) => fun(H1 : P/\\Q) => fun(H2 :Q/\\R) =>\n  match H1,H2 with\n  |conj p q,conj q' r => conj p r\n  end.\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(** **** Exercise: 2 stars, standard, optional (or_commut'') *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun(P Q:Prop) => fun(H: P\\/Q) =>\n  match H with\n  |or_introl P=> or_intror P\n  |or_intror Q=> or_introl Q\nend.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\nCheck ex (fun n => even n).\n(* ===> exists n : nat, even n\n        : Prop *)\n\nDefinition some_nat_is_even : exists n, even n :=\n  ex_intro even 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, standard, optional (ex_ev_Sn) *)\n\nDefinition ex_ev_Sn : ex (fun n => even (S n)) :=\n  ex_intro (fun n => even (S n)) 1 (ev_SS 0 (ev_0)).\n(** [] *)\n\nInductive True : Prop :=\n  | I : True.\n\nInductive False : Prop := .\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\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\nLemma four: 2 + 2 == 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] == x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality) *)\n(*\u76f8\u7b49\u7684\u5f52\u7eb3\u5b9a\u4e49\u8574\u542b\u4e86Leibniez\u76f8\u7b49\u5173\u7cfb*)\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall P:X->Prop, P x -> P y.\nProof.\n  intros.\n  inversion H.\n  rewrite H2 in H0.\n  apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (leibniz_equality__equality)  *)\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x == y.\nProof.\n  intros.\n  assert(H1: x=x -> x=y). {apply H. }\n  assert(H2: x=x). {reflexivity. }\n  assert(H3: x=y). {apply H1 in H2. apply H2. }\n  subst.\n  apply eq_refl.\nQed.\n(** [] *)\n\nEnd MyEquality.\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797063939128, "lm_q2_score": 0.8933094053442511, "lm_q1q2_score": 0.8139654016804955}}
{"text": "Module CustomInteger.\n\n(** Peano arithmetic of natural numbers *)\nInductive nat : Type :=\n  | O: nat  (** Zero value *)\n  | S: nat -> nat. (** Successor *)\n\n(** Predecessor *)\nDefinition pred (n: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\n(** Check whether n is even. Introduce concept of recursive definition. *)\nFixpoint evenb (n: nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nEnd CustomInteger.\n\n(** Arithmetic. *)\nFixpoint plus (n m: nat): nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m: nat): nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n\nFixpoint exp(base power: nat): nat :=\n  match power with\n  | O => S O\n  | S power' => mult base (exp base power')\n  end.\n\nFixpoint factorial(n: nat): nat :=\n  match n with\n  | O => S O\n  | S n' => mult n (factorial n')\n  end.\n\n(** TODO: div, gcd, comparison *)", "meta": {"author": "lvnguyen", "repo": "coq_sample", "sha": "0fe6d1a1203166bda9990ad5a61ef11c9734c794", "save_path": "github-repos/coq/lvnguyen-coq_sample", "path": "github-repos/coq/lvnguyen-coq_sample/coq_sample-0fe6d1a1203166bda9990ad5a61ef11c9734c794/custom_sources/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.8135814403624888}}
{"text": "(* Final Exam --- January 7, 2019 *)\nRequire Import Nat.\nRequire Import List.\n\nNotation \"[ ]\" := nil. \nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nDefinition admit {T: Type} : T.  Admitted.\n\n\n(* 1. Prove the following two facts about natural numbers. *)\n\nLemma mul_0_r : forall n : nat, n * 0 = 0.\nProof. \n   intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\nLemma mul_1_r : forall n : nat, n * 1 = n.\nProof. \n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\n(* 2. Complete the following definition so that (div5 n) returns true \niff n is divisible by 5. *)\n\nFixpoint div5 (n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S(S O) => false\n  | S(S(S O)) => false\n  | S(S(S(S O))) => false\n  | S(S(S(S(S O)))) => true\n  | S(S(S(S(S n')))) => div5 n'\n  end.\n\nExample test1: div5 15 = true.\nProof. reflexivity. Qed.\n\nExample test2: div5 23 = false.\nProof. reflexivity. Qed.\n\n\n(* 3. Define a function createList such that (createList n) returns \na list of n numbers from 2n to 1. *)\n\n\nFixpoint createList (n : nat) : list nat :=\n  match n with\n  | O => nil\n  | S n' => (n+n)::(n+n-1)::createList n'\n  end.\n\nExample test3 : createList 4 = [8;7;6;5;4;3;2;1].\nProof. reflexivity. Qed. \n\n\n(* 4. (1) Define the relation gtodd between odd numbers such that \n   (gtodd m n) holds if and only if m is greater than n for odd numbers m and n.\n(2) Show the transitivity of the relation gtodd. *)\n\n(* lemmas *)\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\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o E1 E2.\n  induction E2.\n  - apply E1.\n  - apply le_S. apply IHE2 in E1. apply E1. Qed.\n\nTheorem lt_trans: forall m n o, m < n -> n < o -> m < o.\nProof.\n  unfold lt.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (m := (S n)) (n := (S m)) (o := o).\n  apply Hnm.\n  apply Hmo. 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(* end of lemmas *)\n\n\nInductive gtodd : nat -> nat -> Prop :=\n  | gt_odd : forall m n, (oddb m = true) /\\ (oddb n = true) /\\ n < m -> gtodd m n.\n \nExample test4 : gtodd 3 1.\nProof.\n  apply gt_odd. \n  split.\n  - reflexivity.\n  - split.\n    + reflexivity.\n    + unfold lt. apply le_S. apply le_n. Qed.\n\nExample test5 : ~ (gtodd 4 3).\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  destruct H0.\n  inversion H0. Qed.\n\nTheorem gtodd_trans : forall m n p,\n  gtodd m n -> gtodd n p -> gtodd m p.\nProof.\n  intros.\n  inversion H. inversion H0.\n  apply gt_odd. destruct H1. destruct H7.\n  destruct H4. destruct H9.\n  split.\n  - apply H1.\n  - split.\n    + apply H9.\n    + apply lt_trans with (m := p) (n := n) (o := m).\n      * apply H10.\n      * apply H8. Qed.\n\n(* 5. Write a function (partition):\n\n      partition : list nat -> list (list nat )\n\n   which partitions a list into a list of 3 sublists. The first sublist\n   contains all even numbers in the original list. The second sublist \n   contains all odd numbers divisible by 5 in the original list. The last \n   sublist contains all other elements. The order of elements in the\n   three sublists should be the same as their order in the original list. \n\n   Hint: You can make use of the Coq function (filter).\n*)\n\n(* lemmas *)\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(* end of lemmas *)\n\nDefinition partition (l : list nat) : list (list nat) :=\n  [(filter evenb l); (filter div5 l); (filter (fun a=> andb (oddb a) (negb (div5 a))) l)].\n\n\nExample test6: partition [1;2;3;9;4;5;6;15] = [[2;4;6]; [5;15]; [1;3;9]].\nProof. reflexivity. Qed.\n\n\n(* 6. Prove that the excluded middle axiom implies the Peirce's law. *)\n\nTheorem peirce : \n  (forall P, P \\/ ~P) -> (forall P Q : Prop, ((P->Q)->P)->P).\nProof.\n  intros.\n  assert (P \\/ ~P) as H1.\n  apply H.\n  inversion H1.\n  - apply H2.\n  - apply H0. intros. unfold not in H2. apply H2 in H3. inversion H3. Qed.\n  \n\n\n(* 7. Let a sequence of numbers F(n) be given as follows.\n   F(0) = 0\n   F(1) = 1\n   F(2) = 1\n   F(n) = F(n-1) + F(n-2) + F(n-3)   for n > 2.\n\nDefine the function Seq such that (Seq n) returns the sequence.\n\n[0; F(0); 1; F(1); 2; F(2); 3; F(3); ... ; n; F(n)].\n*)\n\n(* lemmas *)\nFixpoint SeqNum (n: nat) : nat :=\n  match n with\n  | O => 0\n  | S n' => match n' with\n            | O => 1\n            | S m => match m with\n                     | O => 1\n                     | S m' => SeqNum m' + SeqNum m + SeqNum n'\n                     end\n            end\n  end.\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n(* end of lemmas *)\n\nFixpoint Seq (n: nat) : list nat :=\n  match n with\n  | O => [0; 0]\n  | S n' => Seq n' ++ [n; SeqNum n]\n  end.\n\nExample test7 :  Seq 10 = \n[0; 0; 1; 1; 2; 1; 3; 2; 4; 4; 5; 7; 6; 13; 7; 24; 8; 44; 9; 81; 10; 149].\nProof. reflexivity. Qed.\n\n\n\n(* 8. Consider the following type:\n\nInductive btree : Set :=\n | leaf : btree \n | node : nat->btree->btree->btree.\n\nDefine a function taking as argument a natural number n\nand a tree t and returning the number of occurrences of n in t.\n\nHint: You may use the function (eqb n m) which returns true iff the two natural\nnumbers n and m are equal.\n*)\n\nInductive btree : Set :=\n | leaf : btree \n | node : nat->btree->btree->btree.\n\nFixpoint occur (n: nat)(t: btree) : nat :=\n  match t with\n  | leaf => 0\n  | node m b1 b2 => if eqb n m then 1+(occur n b1)+(occur n b2)\n                    else (occur n b1)+(occur n b2)\n  end.\n\n\nExample test8 : occur 2 (node 1 (node 2 leaf (node 2 leaf leaf)) (node 3 (node 2 leaf leaf) leaf)) = 3.\nProof. reflexivity. Qed.\n\n\n(* 9 Design a sorting algorithm which transforms a list of natural numbers into \na list sorted in ascending oder. *)\n\n(* lemmas *)\nFixpoint gea (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 => true\n            | S m' => gea n' m'\n            end\n  end.\n\nFixpoint insert (n:nat)(l: list nat) : list nat :=  \n  match l with\n  | nil => n :: nil\n  | h :: t => match gea n h with\n              | true => n :: h :: t\n              | false => h :: (insert n t)\n              end\n  end.\n\nFixpoint insertion_sort (l: list nat) : list nat := \n  match l with\n  | nil => nil\n  | h :: t => insert h (insertion_sort t)\n  end.\n\nFixpoint rev (l:list nat) : list nat :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n(* end of lemmas *)\n\nDefinition transform (l: list nat) : list nat :=\n  rev (insertion_sort l).\n\nExample test10 : transform [2;4;1;6;9;6;4;1;3;5;10] = [1;1;2;3;4;4;5;6;6;9;10].\nProof. reflexivity. Qed.\n\n(* 10. The following definitions specify the abstract syntax of\n    some arithmetic expressions and an evaluation function. *)\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\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(* Suppose we define a function that takes an arithmetic expression \n   and slightly simplifies it, changing every occurrence of [e * 1] \n   (i.e., [(AMult e (ANum 1)]) into just [e]. *)\n\nFixpoint optimize_mult1 (a:aexp) : aexp :=\n  match a with\n  | ANum n => ANum n\n  | APlus e1 e2 => APlus (optimize_mult1 e1) (optimize_mult1 e2)\n  | AMinus e1 e2 => AMinus (optimize_mult1 e1) (optimize_mult1 e2)\n  | AMult e1 (ANum 1) => optimize_mult1 e1\n  | AMult e1 e2 => AMult (optimize_mult1 e1) (optimize_mult1 e2)\n  end.\n\n(* Prove the following theorem that states the correctness of the \noptimization with respect to the evaluation of arithmetic expressions. *)\n\nTheorem optimize_mult1_sound: forall a,\n  aeval (optimize_mult1 a) = aeval a.\nProof.\n  intros. induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - destruct a2.\n    + destruct n.\n      * simpl. rewrite mul_0_r. symmetry. rewrite mul_0_r. reflexivity.\n      * destruct n. simpl. rewrite mul_1_r. apply IHa1.\n        simpl. rewrite IHa1. reflexivity.\n    + simpl. simpl in IHa2. rewrite IHa2. rewrite IHa1. reflexivity. \n    + simpl. simpl in IHa2. rewrite IHa2. rewrite IHa1. reflexivity.\n    + simpl. simpl in IHa2. rewrite IHa2. rewrite IHa1. reflexivity. Qed.\n \n", "meta": {"author": "Golden-Slumber", "repo": "coq", "sha": "b2af577054157a167c0755ee15b8b664740726dd", "save_path": "github-repos/coq/Golden-Slumber-coq", "path": "github-repos/coq/Golden-Slumber-coq/coq-b2af577054157a167c0755ee15b8b664740726dd/exam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.8135295144286102}}
{"text": "(* Homework 01 *)\n\n(* include some library code *)\nRequire Import List.\nRequire Import NPeano.\n\n(* decide if two nats are equal *)\nFixpoint nat_eq (m n: nat) : bool :=\n  match m, n with\n    | O, O => true\n    | S mp, S np => nat_eq mp np\n    | _, _ => false\n  end.\n\n(* [PROBLEM 1]\n\nDefine nat_le to decide if one nat is less than or equal to another.\n\nHint: You do not need to use any form of disjunction.\n*)\nFixpoint nat_le (m n: nat) : bool :=\n  match m, n with\n    | O, _ => true\n    | S mp, O => false\n    | S mp, S np => nat_le mp np\n  end.\n\nEval cbv in (nat_le 5 5). (* true *)\nEval cbv in (nat_le 3 5). (* true *)\nEval cbv in (nat_le 5 3). (* false *)\n\n(* [PROBLEM 2]\n\nUset nat_le to define nat_lt which should decide if one nat is less than another.\n\nFor full credit, do not use other boolean functions.\n*)\nDefinition nat_lt (m n: nat) : bool :=\n  match m, n with\n    | _, O => false\n    | O, _ => true\n    | S _, S np => nat_le m np\n  end.\n\nEval cbv in (nat_lt 5 5). (* false *)\nEval cbv in (nat_lt 3 5). (* true *)\nEval cbv in (nat_lt 5 3). (* false *)\n\n(* binary trees of nats *)\nInductive nat_tree : Set :=\n| Leaf : nat_tree\n| Branch : nat -> nat_tree -> nat_tree -> nat_tree.\n\n(* ordered insertion *)\nFixpoint insert (n: nat) (nt: nat_tree) : nat_tree :=\n  match nt with\n    | Leaf => Branch n Leaf Leaf\n    | Branch m tl tr =>\n        if nat_lt n m then\n          Branch m (insert n tl) tr\n        else\n          Branch m tl (insert n tr)\n  end.\n\nEval cbv in (insert 3 Leaf).\nEval cbv in (insert 5 (insert 7 (insert 3 Leaf))).\n\n(* [PROBLEM 3]\n\nDefine of_list to produce an ordered tree containing all elements from the list.\n\nUse insert to help with sorting. Do not worry about duplicates in the list.\n*)\nFixpoint of_list (ns: list nat) : nat_tree :=\n  match ns with\n    | nil => Leaf\n    | x::xs => (insert x (of_list xs))\n  end.\n\nEval cbv in (of_list (5::7::3::nil)).\nEval cbv in (of_list (3::7::5::nil)).\nEval cbv in (of_list (nil)).\nEval cbv in (of_list (1::1::nil)).\n\n(* [PROBLEM 4]\n\nDefine to_list, which provides a list of elements generated by an in-order traversal of the tree nt.\n\nFor the difference between in-order, post-order, and pre-order traversals, see:\n    http://en.wikipedia.org/wiki/Tree_traversal\n\nRecall from lecture that we can append with the ++ operator.\n*)\nFixpoint to_list (nt: nat_tree) : list nat :=\n  match nt with\n    | Leaf => nil\n    | Branch m tl tr => to_list tl ++ m::nil ++ to_list tr\n  end.\n\n(* Should be: 3::5::7::nil *) \nEval cbv in (to_list (Branch 3 Leaf (Branch 7 (Branch 5 Leaf Leaf) Leaf))).\nEval cbv in (to_list (Branch 5 (Branch 3 Leaf Leaf) (Branch 7 Leaf Leaf))).\nEval cbv in (to_list (of_list (3::7::5::nil))).\nEval cbv in (to_list (of_list (7::3::5::nil))).\nEval cbv in (to_list (of_list (5::3::7::nil))). \n\n(* [PROBLEM 5]\n\nDefine sum to add up all the nats in a nat_tree.\n*)\nFixpoint sum (nt: nat_tree) : nat :=\n  match nt with\n    | Leaf => 0\n    | Branch m tl tr => m + (sum tl) + (sum tr)\n  end.\n\nEval cbv in (sum (of_list (1::2::3::nil))).\nEval cbv in (sum (of_list (99::1::nil))).\nEval cbv in (sum (of_list (nil))).\n\n(* [PROBLEM 6]\n\nDefine prod to multiply up all the nats in a nat_tree.\n*)\nFixpoint prod (nt: nat_tree) : nat :=\n  match nt with\n    | Leaf => 1\n    | Branch m tl tr => m * (prod tl) * (prod tr)\n  end.\n\nEval cbv in (prod (of_list (1::2::3::nil))).\nEval cbv in (prod (of_list (9::1::nil))).\nEval cbv in (prod (of_list (9::0::nil))).\nEval cbv in (prod (of_list (nil))).\n\n(* [PROBLEM 7]\n\nDefine size to produce the number of nats in a nat_tree.\n\nNote that Leaf should have size 0.\n*)\nFixpoint size (nt: nat_tree) : nat :=\n  match nt with\n    | Leaf => 0\n    | Branch m tl tr => 1 + (size tl) + (size tr)\n  end.\n\nEval cbv in (size (of_list (1::2::3::nil))).\nEval cbv in (size (of_list (9::1::nil))).\nEval cbv in (size (of_list (9::0::nil))).\nEval cbv in (size (of_list (nil))).\n\n(* [PROBLEM 8]\n\nDefine avg to compute the arithmetic mean of all the nats in a nat_tree.\n\nNotes: Infix / is nat division. The average of an empty tree will be 0.\n*)\nDefinition avg (nt: nat_tree) : nat :=\n  (sum nt) / (size nt).\n\nEval cbv in (avg (of_list (1::2::3::nil))).\nEval cbv in (avg (of_list (9::1::nil))).\nEval cbv in (avg (of_list (9::0::nil))).\nEval cbv in (avg (of_list (nil))).\n\n(* [PROBLEM 9]\n\nDefine map to apply a function of type nat -> nat to every nat in a nat_tree.\n\nThe resulting tree should have exactly the same structure as the initial tree.\n*)\nFixpoint map (f: nat -> nat) (nt: nat_tree) : nat_tree :=\n  match nt with\n    | Leaf => Leaf\n    | Branch m tl tr => Branch (f m) (map f tl) (map f tr)\n  end.\n\nEval cbv in (to_list (map (fun a => a + 1) (of_list (1::2::3::nil)))). (* 2::3::4::nil *)\nEval cbv in (to_list (map (fun a => a * a) (of_list (1::2::3::nil)))). (* 1::4::9::nil *)\n\n(* [PROBLEM 10]\n\nDefine increment_all to add one to all the nats in a nat_tree.\n\nFor full credit, do not use recursion (keep the Definition, don't change to Fixpoint).\n*)\nDefinition increment_all (nt: nat_tree) : nat_tree :=\n  map (fun a => a + 1) nt.\n\nEval cbv in (to_list (increment_all (of_list (1::2::3::nil)))). (* 2::3::4::nil *)\n\n(* fold over nat_trees *)\nFixpoint fold {T: Type} (base: T) (f: T -> nat -> T) (nt: nat_tree) : T :=\n  match nt with\n    | Leaf => base\n    | Branch n l r => f (fold (fold base f l) f r) n\n  end.\n\n(* [PROBLEM 11]\n\nDefine sum' to add up all the nats in a nat_tree.\n\nFor full credit, do not use recursion (keep the Definition, don't change to Fixpoint).\n*)\nDefinition sum' := fold 0 (fun a b => a + b).\n\nEval cbv in (sum' (of_list (1::2::3::nil))).\nEval cbv in (sum' (of_list (99::1::nil))).\nEval cbv in (sum' (of_list (nil))).\n\n(* [PROBLEM 12]\n\nDefine prod' to multiply up all the nats in a nat_tree.\n\nFor full credit, do not use recursion (keep the Definition, don't change to Fixpoint).\n*)\nDefinition prod' := fold 1 (fun a b => a * b).\n\nEval cbv in (prod' (of_list (1::2::3::nil))).\nEval cbv in (prod' (of_list (9::1::nil))).\nEval cbv in (prod' (of_list (9::0::nil))).\nEval cbv in (prod' (of_list (nil))).\n\n(* [PROBLEM 13]\n\nDefine avg' to compute the arithmetic mean of all the nats in a nat_tree.\n\nFor full credit, use fold.\n\nHint: Use let and a pair.\n*)\n\nEval cbv in (pair 1 2).\n\nDefinition avg' (nt: nat_tree) : nat :=\n  (let (totalSum, totalSize) := \n      (fold \n        (pair 0 0)\n        (fun sumAndSize n => \n          let (sum, size) := sumAndSize in (pair (sum + n) (size + 1)))\n        nt)\n    in (totalSum / totalSize)).\n\nEval cbv in (avg' (of_list (1::2::3::nil))).\nEval cbv in (avg' (of_list (9::1::nil))).\nEval cbv in (avg' (of_list (9::0::nil))).\nEval cbv in (avg' (of_list (nil))).\n\n(* [PROBLEM 14]\n\nDefine mirror to flip all the branches in the tree:\n\n       5              5\n      / \\            / \\\n     3   4     =>   4   3\n    / \\                / \\\n   1   6              6   1\n\n(leaves are not displayed above)\n*)\nFixpoint mirror (nt: nat_tree) : nat_tree :=\n  match nt with\n    | Leaf => Leaf\n    | Branch m lt rt => Branch m (mirror rt) (mirror lt)\n  end.\n\nEval cbv in (to_list (mirror (of_list (1::2::3::nil)))).\n\n(* test if a nat appears in a given tree *)\nFixpoint mem (n: nat) (nt: nat_tree) : bool :=\n  match nt with\n    | Leaf => false\n    | Branch m l r =>\n      if nat_eq n m then\n        true\n      else if nat_lt n m then\n        mem n l\n      else\n        mem n r\n  end.\n\nEval cbv in (mem 2 (of_list (1::2::3::nil))).\nEval cbv in (mem 4 (of_list (1::2::3::nil))).\n\n(* prove all the following lemmas *)\n\n(* Warning!  This first one may be tricky... *)\nLemma nat_eq_ok:\n  forall m n, nat_eq m n = true -> m = n.\nProof.\n  intro. induction m.\n  { intros. destruct n.\n    { reflexivity. }\n    { discriminate. }\n  }\n  { intro. induction n.\n    { discriminate. }\n    { firstorder. }\n  }\nQed.\n\nLemma nat_le_ok:\n  forall m n, nat_le m n = true -> m <= n.\nProof.\n  intro. induction m.\n  { firstorder. }\n  { intro. induction n.\n    { discriminate. }\n    { firstorder. }\n  }\nQed.\n\n(* Hint: use nat_le_ok *)\nLemma nat_lt_ok:\n  forall m n, nat_lt m n = true -> m < n.\nProof.\n  intro. induction m.\n  { intro. induction n.\n    { discriminate. }\n    { firstorder. }\n  }\n  { intro. induction n.\n    { discriminate. }\n    { intro. destruct m.\n      { firstorder. }\n      { firstorder. }\n    }\n  }\nQed.\n\n(* Show that our nat equality decider is reflexive. *)\nLemma nat_eq_refl : forall n, nat_eq n n = true.\nProof.\n  intro. induction n.\n  { reflexivity. }\n  { firstorder. }\nQed.\n\nTheorem map_size : forall f t, size (map f t) = size t.\nProof.\n  intros. induction t.\n  { reflexivity. }\n  { simpl. firstorder. }\nQed.\n\nTheorem mirror_size : forall t, size (mirror t) = size t.\nProof.\n  intro. induction t.\n  { reflexivity. }\n  { simpl. rewrite -> IHt1. rewrite -> IHt2. firstorder. }\nQed.\n\n(*\nWe define the custom tactic break_if to help with some proofs below.\n\nDon't worry about understanding the details for now.\n\nJust remember that if you see an if-then-else, break_if will do case analysis on the branch condition and give you two subgoals: one where the branch condition was true and so the then branch was taken, and another where the branch condition was false and so the else branch was taken.\n*)\nLtac break_if :=\n  match goal with\n    | |- context [ if ?cond then _ else _ ] => destruct cond as [] eqn:?\n  end.\n\nLemma mem_left : forall v l r, mem v l = true -> mem v (Branch v l r) = true.\nProof.\n  intros. simpl. rewrite -> nat_eq_refl. reflexivity.\nQed.\n\nLemma mem_right : forall v l r, mem v r = true -> mem v (Branch v l r) = true.\nProof.\n  intros. simpl. rewrite -> nat_eq_refl. reflexivity.\nQed.\n\n(* using the previous lemmas and tactics, prove that insertion implies membership *)\nTheorem insert_mem :\n  forall v t, mem v (insert v t) = true.\nProof.\n  intros. induction t.\n  { simpl. rewrite -> nat_eq_refl. reflexivity. }\n  { simpl. break_if.\n    { simpl. rewrite -> Heqb. break_if.\n      { reflexivity. }\n      { firstorder. }\n    }\n    { simpl. rewrite -> Heqb. break_if.\n      { reflexivity. }\n      { firstorder. }\n    }\n  }\nQed.\n\n\n(* [PROBLEM 24]\n\nConsider this alternate definition of fold:\n*)\nFixpoint fold' {T: Type} (base: T) (f: T -> nat -> T) (nt: nat_tree) : T :=\n  match nt with\n    | Leaf => base\n    | Branch n l r => fold' (f (fold' base f l) n) f r\n  end.\n\nCheck fold.\nCheck fold'.\nPrint fold.\n\n(*\nFor reference, the definition of fold:\nfold = \nfix fold (T : Type) (base : T) (f : T -> nat -> T) (nt : nat_tree)\n         {struct nt} : T :=\n  match nt with\n  | Leaf => base\n  | Branch n l r => f (fold T (fold T base f l) f r) n\n  end\n     : forall T : Type, T -> (T -> nat -> T) -> nat_tree -> T\n\nArgument T is implicit and maximally inserted\nArgument scopes are [type_scope _ _ _]\n*)\n\n(*\nIn a short English paragraph, describe how fold and fold' differ.\n\nFold's recurse looks like:  Branch n l r => f (fold (fold base f l) f r) n\nFold''s recurse looks like: Branch n l r => fold' (f (fold' base f l) n) f r\n\nFold traverses in \"post-order\". Aka it first does fold down the left sub tree, then down the right sub tree, then the current node.\nFold' traverses \"in-order\". Aka it first does fold down the left sub tree, then on the current node, then down the right sub tree.\n\nOptional Bonus (5 points):\n\nWhat should be true about a particular f for the following to hold:\n\n  forall b nt, fold b f nt = fold' b f nt\n\n  So long as f doesn't care about the order in which it visits nodes, fold and fold'\n  will behave the same. For example, if f is used to compute size, sum, or mem, \n  they'll behave identically. However, if for example f uses the traverse order\n  to find the smallet number > 10, you may get different behavior. See the Eval\n  examples below.\n\n*)\n\n(* sum works for both *)\nEval cbv in (fold 0 (fun b n => b + n) (of_list (1::2::3::nil))).\nEval cbv in (fold' 0 (fun b n => b + n) (of_list (1::2::3::nil))).\n\n(* smallest num greater than 10 only works with this particular f with fold'\n   because f uses knowledge of the traverse order. *)\nEval cbv in (fold' 0 (fun b n => if (andb (nat_le b 10) (nat_lt 10 n)) then n else b) (of_list (5::12::11::nil))). (* returns 11 *)\n\nEval cbv in (fold 0 (fun b n => if (andb (nat_le b 10) (nat_lt 10 n)) then n else b) (of_list (5::12::11::nil))). (* returns 12 *)\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/web/coq/darylbug.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.8134231993594631}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling    [*]              *)\n(*             Jean-Fran\u00e7ois Monin           [+]              *)\n(*                                                            *)\n(*           [*] Affiliation Univ. Lorraine - CNRS - LORIA    *)\n(*           [+] Affiliation VERIMAG - Univ. Grenoble Alpes   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*        CeCILL v2.1 FREE SOFTWARE LICENSE AGREEMENT         *)\n(**************************************************************)\n\n(** Textbook reference:\n    [BBJ2002]: Computability and Logic\n               Boolos, G.S. and Burgess, J.P. and Jeffrey, R.C.\n               4th Edition, Cambridge University Press, 2002.\n*)\n\nFrom Coq Require Import Utf8.\n\nFrom MuRec Require Import relations arith_mini between.\n\nSection primitive_recursion.\n\n  (** The fixpoint computing primitive recursion following [BBJ2002] pp 67\n      where H := prim_rec, F and G represent respectively the (to be proved\n      functional) relations h, f and g, ie. for \u21c0 denoting partial functions\n      we have the following encoding of types\n\n        f : Xa \u21c0 Y             ~~>  F : Xa \u2192 Y \u2192 Prop\n        g : Xa \u2a2f nat \u2a2f Y \u21c0 Y   ~~>  G : Xa \u2192 nat \u2192 Y \u2192 Y \u2192 Prop\n        h : Xa \u2a2f nat \u21c0 Y       ~~>  H : Xa \u2192 nat \u2192 Y \u2192 Prop\n\n      and the following encoding for the recursive equations\n\n         h (x\u2080, 0)   = f(x\u2080)              ~~>  H x\u2080 0 = F x\u2080\n         h (x\u2080, S n) = g(x\u2080, n, h(x\u2080,n))  ~~>  H x\u2080 (S n) = (G x\u2080 n) \u22c4 (H x\u2080 n)\n\n      Notice that in [BBJ2002], Xa := nat^a and Y := nat but the definition\n      can be made more polymorphic.\n\n      In [BBJ2002] the primitive recursive scheme is written as follows,\n      with x in place of x\u2080 and y in place of n:\n         h(x\u2080, 0) = f(x),  h(x\u2080, n') = g(x\u2080, n, h(x\u2080,n))    (Pr)\n\n     *)\n\n  Context   {Xa Y : Type}\n            (F : Xa \u2192 Y \u2192 Prop)\n            (G : Xa \u2192 nat \u2192 Y \u2192 Y \u2192 Prop).\n\n  Definition prim_rec x\u2080 := nat_rect (\u03bb _, Y \u2192 Prop) (F x\u2080) (\u03bb n p, (G x\u2080 n) \u22c4 p).\n\n  Definition prim_rec_alt x\u2080 :=\n    fix loop n :=\n      match n with\n      | 0   => F x\u2080\n      | S n => (G x\u2080 n) \u22c4 (loop n)\n      end.\n\n  Goal prim_rec = prim_rec_alt.\n  Proof. reflexivity. Qed.\n\n  Hypothesis Ffun : functional F.\n  Hypothesis Gfun : \u2200 x\u2080 n, functional (G x\u2080 n).\n\n  Fact prim_rec_fun x\u2080 : functional (prim_rec x\u2080).\n  Proof.\n    intros n; induction n; cbn.\n    + apply Ffun.\n    + now apply rel_subst_fun.\n  Qed.\n\nEnd primitive_recursion.\n\nArguments prim_rec_fun {Xa Y F G} Ffun Gfun {_ _ _ _}.\n\nSection unbounded_minimisation.\n\n  (** In [BBJ2002] pp 70 unbounded minimization is written as follows:\n\n                          / y         if f(x\u2081,...,x\u2099, y) = 0, and for all t < y,\n      Mn[f](x\u2081,...,x\u2099) = {               f(x\u2081,...,x\u2099, t) is defined and \u2260 0\n                          \\ undefined if there is no such y.\n\n      This definition is adapted here as follows:\n      - at this stage, x\u2081,...,x\u2099 are ignored;\n      - we consider unbounded minimization from a starting number denoted by s\n        ([BBJ2002] corresponds to the special case where s = 0);\n        the reason is that, even if the semantics of (AST of) mu-recursive algorithms,\n        consideres only s = 0, the intended minimization algorithm is actually able to\n        start at any s, a fact to be used when reasoning about this algorithm.\n\n      Altogether, we state that F is 0 at y and strictly positive (ie a successor)\n      from s (included) to y (excluded).\n   *)\n\n  Variable (F : nat \u2192 nat \u2192 Prop).\n\n  Definition ze_at y  :=     F y 0.\n  Definition def_at t := \u2203k, F t k.\n  Definition pos_at t := \u2203k, F t (S k).\n\n  Fact ze_at_def_at : ze_at \u2286\u2081 def_at.\n  Proof. now intros n ?; exists 0. Qed.\n  Fact pos_at_def_at : pos_at \u2286\u2081 def_at.\n  Proof. now intros n (k & ?); exists (S k). Qed.\n\n  Definition umin s y := ze_at y \u2227 btwn pos_at s y.\n  Definition umin\u2080 y := ze_at y \u2227 \u2200n, n < y \u2192 pos_at n.\n\n  Fact umin_umin\u2080 y : umin 0 y \u2192 umin\u2080 y.\n  Proof.\n    intros (H1 & H2 & H3); split.\n    + exact H1.\n    + intro; apply H3, le_0_n.\n  Qed.\n\n  Fact umin\u2080_umin y : umin\u2080 y \u2192 umin 0 y.\n  Proof.\n    intros (H1 & H2); repeat split.\n     + exact H1.\n     + apply le_0_n.\n     + intros ? ?; apply H2.\n  Qed.\n\n  Hypothesis Ffun : functional F.\n\n  Arguments Ffun {_ _ _}.\n\n  Fact umin_fun : functional umin.\n  Proof.\n    intros s y\u2081 y\u2082 [z1 py\u2081] [z2 py\u2082].\n    destruct (btwn_eq_or_holds py\u2081 py\u2082) as [ [] | [ [? FS] | [? FS] ] ].\n    - reflexivity.\n    - discriminate (Ffun z1 FS).\n    - discriminate (Ffun z2 FS).\n  Qed.\n\n  Fact umin\u2080_fun : functional\u2080 umin\u2080.\n  Proof.\n    intros y1 y2 H1 H2.\n    apply (umin_fun 0); now apply umin\u2080_umin.\n  Qed.\n\nEnd unbounded_minimisation.\n\nArguments umin_umin\u2080 {F}.\nArguments umin\u2080_umin {F}.\n\n", "meta": {"author": "DmxLarchey", "repo": "Murec_Extraction", "sha": "73681e2a65bd3fc04e03e9ef835a351b44860125", "save_path": "github-repos/coq/DmxLarchey-Murec_Extraction", "path": "github-repos/coq/DmxLarchey-Murec_Extraction/Murec_Extraction-73681e2a65bd3fc04e03e9ef835a351b44860125/theories/schemes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8723473713594992, "lm_q1q2_score": 0.8134231961747321}}
{"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.\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\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  (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 b1 (andb b2 b3)).\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\n\nCheck (negb true).\n\nCheck negb.\n\n\nModule Playground1.\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nEnd Playground1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCheck (S (S (S (S O)))).\nEval simpl in (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\nExample test_oddb1: (oddb (S O)) = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nEval simpl in (plus (S (S (S O))) (S (S O))).\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\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.\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\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n  match  (beq_nat n m) with\n    | true => false\n    | false => (ble_nat n m)\n  end.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. compute. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. compute. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. compute. reflexivity. Qed.\n\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  simpl. reflexivity.  Qed.\n\nTheorem plus_O_n' : forall n:nat, 0 + n = n.\nProof.\n  reflexivity.  Qed.\n\nEval simpl in (forall n:nat, n + 0 = n).\n\nEval simpl in (forall n:nat, 0 + n = n).\n\nTheorem plus_O_n'' : forall n:nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m. intros H. rewrite <- H. 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. intros H. intros M.\n  rewrite -> H. rewrite -> M.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\n  intros n m. reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.  destruct n as [| n'].\n    reflexivity.\n    reflexivity.\nQed.\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n    reflexivity.\n    reflexivity. Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n    reflexivity.\n    reflexivity. Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n. destruct n as [| n'].\n  reflexivity. reflexivity. Qed.\n\n(* Case nameing *)\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n  | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n  assert (x = v) as H by reflexivity;\n  clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n    set (x := name); move_to_top x\n  | assert_eq x name; move_to_top x\n  | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nTheorem andb_true_elim1 : forall b c : bool,\n  andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n  rewrite <- H. reflexivity. Qed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros\n    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\n(* Induction *)\nTheorem plus_0_r_firsttry : forall n:nat,\n  n + 0 = n.\nProof.\n  intros n.\n  simpl. Admitted.\n\nTheorem plus_0_r_secondtry : forall n:nat,\n  n + 0 = n.\nProof.\n  intros n. destruct n as [| n'].\n  Case \"n = 0\".\n    reflexivity.   Case \"n = S n'\".\n    simpl. Admitted.\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"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'].\n  Case \"n = 0\".\n  simpl. reflexivity.\n  Case \"n = S n'\".\n  simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = 0\".\n  simpl. reflexivity.\n  Case \"n = S n'\".\n  simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n'].\n  Case \"n = 0\".\n  induction m as [|m'].\n  SCase \"m = 0\".\n  reflexivity.\n  SCase \"m = S m'\".\n  simpl. rewrite <- IHm'. simpl. reflexivity.\n  Case \"n = S n'\".\n  simpl. rewrite -> IHn'.\n  rewrite -> plus_n_Sm. reflexivity. Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n  simpl. reflexivity.\n  Case \"n = S n'\".\n  simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n    Case \"Proof of assertion\". reflexivity.\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  Case \"Proof of assertion\".\n  rewrite -> plus_comm. reflexivity.\n  rewrite -> H. reflexivity. Qed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  assert (H : p + n = n + p).\n  Case \"Proof of assertion\".\n  rewrite -> plus_comm. reflexivity.\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem mult_help : forall n m: nat,\n    n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [| n'].\n  SCase \"n = 0\".\n  simpl. reflexivity.\n  SCase \"n = S n'\".\n  simpl. rewrite <- plus_swap. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem mult_comm : forall m n : nat,\n    m * n = n * m.\nProof.\n  intros n m.\n  induction m as [| m'].\n  Case \"m = 0\".\n  simpl. induction n as [| n'].\n  SCase \"n = 0\".\n  reflexivity.\n  SCase \"n = S n'\".\n  simpl. rewrite -> IHn'. reflexivity.\n  Case \"m = S m'\".\n  simpl. rewrite <- IHm'. rewrite <- mult_help. reflexivity. Qed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  replace (n + m) with (m + n).\n  reflexivity.\n  rewrite -> plus_comm. 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/Basics_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.8134129314920885}}
{"text": "Require Export TopologicalSpaces.\nRequire Export EnsemblesSpec.\n\nSection interior_closure.\n\nVariable X:TopologicalSpace.\nVariable S:Ensemble (point_set X).\n\nDefinition interior := FamilyUnion\n  [ U:Ensemble (point_set X) | open U /\\ Included U S ].\nDefinition closure := FamilyIntersection\n  [ F:Ensemble (point_set X) | closed F /\\ Included S F ].\n\nLemma interior_open : open interior.\nProof.\napply open_family_union.\nintros.\ndestruct H as [[]]; trivial.\nQed.\n\nLemma interior_deflationary : Included interior S.\nProof.\nred; intros.\ndestruct H.\ndestruct H as [[]]; auto with sets.\nQed.\n\nLemma interior_fixes_open: open S -> interior = S.\nProof.\nintros.\napply Extensionality_Ensembles; split.\napply interior_deflationary.\nred; intros.\nexists S; trivial.\nconstructor; auto with sets.\nQed.\n\nLemma interior_maximal: forall U:Ensemble (point_set X),\n  open U -> Included U S -> Included U interior.\nProof.\nintros.\nred; intros.\nexists U; trivial.\nconstructor; split; trivial.\nQed.\n\nLemma closure_closed : closed closure.\nProof.\napply closed_family_intersection.\nintros.\ndestruct H as [[]]; trivial.\nQed.\n\nLemma closure_inflationary : Included S closure.\nProof.\nred; intros.\nconstructor; intros.\ndestruct H0 as [[]].\nauto with sets.\nQed.\n\nLemma closure_fixes_closed : closed S -> closure = S.\nProof.\nintro.\napply Extensionality_Ensembles; split.\nred; intros.\ndestruct H0.\napply H0; split; auto with sets.\napply closure_inflationary.\nQed.\n\nLemma closure_minimal: forall F:Ensemble (point_set X),\n  closed F -> Included S F -> Included closure F.\nProof.\nintros; red; intros.\ndestruct H1.\napply H1.\nconstructor; split; trivial.\nQed.\n\nEnd interior_closure.\n\nArguments interior [X].\nArguments closure [X].\nArguments interior_open [X].\nArguments interior_deflationary [X].\nArguments interior_fixes_open [X].\nArguments interior_maximal [X].\nArguments closure_closed [X].\nArguments closure_inflationary [X].\nArguments closure_fixes_closed [X].\nArguments closure_minimal [X].\n\nSection interior_closure_relations.\n\nVariable X:TopologicalSpace.\n\nLemma interior_increasing: forall S T:Ensemble (point_set X),\n  Included S T -> Included (interior S) (interior T).\nProof.\nintros.\napply interior_maximal.\napply interior_open.\nassert (Included (interior S) S).\napply interior_deflationary.\nauto with sets.\nQed.\n\nLemma interior_intersection: forall S T:Ensemble (point_set X),\n  interior (Intersection S T) =\n  Intersection (interior S) (interior T).\nProof.\nintros.\napply Extensionality_Ensembles; split.\nassert (Included (interior (Intersection S T)) (interior S)).\napply interior_increasing.\nauto with sets.\nassert (Included (interior (Intersection S T)) (interior T)).\napply interior_increasing.\nauto with sets.\nauto with sets.\n\napply interior_maximal.\napply open_intersection2; apply interior_open.\npose proof (interior_deflationary S).\npose proof (interior_deflationary T).\nred; intros x H1; constructor; (apply H || apply H0);\ndestruct H1; trivial.\nQed.\n\nLemma interior_union: forall S T:Ensemble (point_set X),\n  Included (Union (interior S) (interior T))\n           (interior (Union S T)).\nProof.\nintros.\napply interior_maximal.\napply open_union2; apply interior_open.\npose proof (interior_deflationary S).\npose proof (interior_deflationary T).\nauto with sets.\nQed.\n\nLemma complement_inclusion: forall {Y:Type} (S T:Ensemble Y),\n  Included S T -> Included (Complement T) (Complement S).\nProof.\nintros.\nred; intros.\nred; intro.\ncontradiction H0.\nauto with sets.\nQed.\n\nLemma interior_complement: forall S:Ensemble (point_set X),\n  interior (Complement S) = Complement (closure S).\nProof.\nintros.\napply Extensionality_Ensembles; split.\nrewrite <- Complement_Complement with (A:=interior (Complement S)).\napply complement_inclusion.\napply closure_minimal.\nred.\nrewrite Complement_Complement.\napply interior_open.\npattern S at 1;\nrewrite <- Complement_Complement with (A:=S).\napply complement_inclusion.\napply interior_deflationary.\n\napply interior_maximal.\napply closure_closed.\napply complement_inclusion.\napply closure_inflationary.\nQed.\n\nLemma closure_increasing: forall S T:Ensemble (point_set X),\n  Included S T -> Included (closure S) (closure T).\nProof.\nintros.\napply closure_minimal.\napply closure_closed.\npose proof (closure_inflationary T).\nauto with sets.\nQed.\n\nLemma closure_complement: forall S:Ensemble (point_set X),\n  closure (Complement S) = Complement (interior S).\nProof.\nintros.\npose proof (interior_complement (Complement S)).\nrewrite Complement_Complement in H.\nrewrite H.\nrewrite Complement_Complement; reflexivity.\nQed.\n\nLemma closure_union: forall S T:Ensemble (point_set X),\n  closure (Union S T) = Union (closure S) (closure T).\nProof.\nintros.\napply Extensionality_Ensembles; split.\napply closure_minimal.\napply closed_union2; apply closure_closed.\npose proof (closure_inflationary S).\npose proof (closure_inflationary T).\nauto with sets.\n\nassert (Included (closure S) (closure (Union S T))).\napply closure_increasing; auto with sets.\nassert (Included (closure T) (closure (Union S T))).\napply closure_increasing; auto with sets.\nauto with sets.\nQed.\n\nLemma closure_intersection: forall S T:Ensemble (point_set X),\n  Included (closure (Intersection S T))\n           (Intersection (closure S) (closure T)).\nProof.\nintros.\nassert (Included (closure (Intersection S T)) (closure S)).\napply closure_increasing; auto with sets.\nassert (Included (closure (Intersection S T)) (closure T)).\napply closure_increasing; auto with sets.\nauto with sets.\nQed.\n\nLemma meets_every_open_neighborhood_impl_closure:\n  forall (S:Ensemble (point_set X)) (x:point_set X),\n  (forall U:Ensemble (point_set X), open U -> In U x ->\n                                Inhabited (Intersection S U)) ->\n  In (closure S) x.\nProof.\nintros.\napply NNPP; intro.\npose proof (H (Complement (closure S))).\ndestruct H1.\napply closure_closed.\nexact H0.\ndestruct H1.\ncontradiction H2.\napply closure_inflationary.\nassumption.\nQed.\n\nLemma closure_impl_meets_every_open_neighborhood:\n  forall (S:Ensemble (point_set X)) (x:point_set X),\n  In (closure S) x ->\n  forall U:Ensemble (point_set X), open U -> In U x ->\n    Inhabited (Intersection S U).\nProof.\nintros.\napply NNPP; intro.\nassert (Included (closure S) (Complement U)).\napply closure_minimal.\nunfold closed.\nrewrite Complement_Complement; assumption.\nred; intros.\nintro.\ncontradiction H2.\nexists x0; constructor; trivial.\n\ncontradict H1.\napply H3.\nassumption.\nQed.\n\nDefinition dense (S:Ensemble (point_set X)) : Prop :=\n  closure S = Full_set.\n\nLemma dense_meets_every_nonempty_open:\n  forall S:Ensemble (point_set X), dense S ->\n    forall U:Ensemble (point_set X), open U -> Inhabited U ->\n    Inhabited (Intersection S U).\nProof.\nintros.\ndestruct H1.\napply closure_impl_meets_every_open_neighborhood with x; trivial.\nrewrite H; constructor.\nQed.\n\nLemma meets_every_nonempty_open_impl_dense:\n  forall S:Ensemble (point_set X),\n  (forall U:Ensemble (point_set X), open U -> Inhabited U ->\n   Inhabited (Intersection S U)) ->\n  dense S.\nProof.\nintros.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\napply meets_every_open_neighborhood_impl_closure.\nintros.\napply H; trivial.\nexists x; trivial.\nQed.\n\nEnd interior_closure_relations.\n\nArguments interior_increasing [X].\nArguments interior_intersection [X].\nArguments interior_union [X].\nArguments interior_complement [X].\nArguments closure_increasing [X].\nArguments closure_complement [X].\nArguments closure_union [X].\nArguments closure_intersection [X].\nArguments dense [X].\n\nSection Build_from_closure.\n\nVariable X:Type.\nVariable cl : Ensemble X -> Ensemble X.\nHypothesis cl_inflationary: forall S:Ensemble X,\n  Included S (cl S).\nHypothesis cl_respects_union: forall S1 S2:Ensemble X,\n  cl (Union S1 S2) = Union (cl S1) (cl S2).\nHypothesis cl_empty: cl Empty_set = Empty_set.\nHypothesis cl_idempotent: forall S:Ensemble X,\n  cl (cl S) = cl S.\n\nLemma cl_increasing: forall S1 S2:Ensemble X,\n  Included S1 S2 -> Included (cl S1) (cl S2).\nProof.\nintros.\nreplace S2 with (Union S1 S2).\nrewrite cl_respects_union.\nauto with sets.\napply Extensionality_Ensembles; split; auto with sets.\nQed.\n\nDefinition Build_TopologicalSpace_from_closure_operator : TopologicalSpace.\nrefine (Build_TopologicalSpace_from_closed_sets\n  (fun F => cl F = F) _ _ _).\napply cl_empty.\nintros.\nrewrite cl_respects_union; congruence.\nintros.\napply Extensionality_Ensembles; split; try apply cl_inflationary.\nred; intros.\nconstructor; intros.\nrewrite <- (H S H1).\napply cl_increasing with (FamilyIntersection F); trivial.\nred; intros.\ndestruct H2.\napply H2; trivial.\nDefined.\n\nLemma Build_TopologicalSpace_from_closure_operator_closure:\n  forall S:Ensemble (point_set Build_TopologicalSpace_from_closure_operator),\n    closure S = cl S.\nProof.\nintros.\napply Extensionality_Ensembles; split.\napply closure_minimal.\napply <- Build_TopologicalSpace_from_closed_sets_closed.\napply cl_idempotent.\ntrivial.\nreplace (closure S) with (cl (closure S)).\napply cl_increasing.\napply (closure_inflationary S).\npose proof (closure_closed S).\napply -> Build_TopologicalSpace_from_closed_sets_closed in H.\nexact H.\nQed.\n\nEnd Build_from_closure.\n\nArguments Build_TopologicalSpace_from_closure_operator [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/InteriorsClosures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.8128100271254822}}
{"text": "\n\nInductive nat : Set :=  | O : nat | S : nat -> nat.\n\nDefinition prim_rec := nat_rec (fun i : nat => nat).\n\nDefinition addition (n m : nat) := prim_rec m (fun p rec:nat => S rec) n.\n\nEval compute in (addition (S (S O)) (S (S (S O)))).\n\nFixpoint plus (n m:nat) {struct n} : nat :=\n  match n with \n    | O => m\n    | S p => S (plus p m)\n  end.\n\n\n\nInductive bool : Set := true | false.\nCheck bool_ind.\nCheck bool_rec.\nCheck bool_rect.\n\nLemma duality : forall b:bool, b =true \\/ b = false.\nintro b.\nelim b.\nleft; trivial.\nright; trivial.\nQed.\n\n", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.8128100259427168}}
{"text": "(* Discrete Mathematics in Coq, based on definitions in Epp, 4th Edition *)\n\nRequire Import Omega.\nRequire Import Nat.\nRequire Import List.\nRequire Import Arith.\nRequire Import Coq.Program.Wf.\n\n(* Section 2.1 *)\n\n(* This is the encoding of a definition of a statement, p. 24.\n   It's called \"lem\" because the formal name for this property is the\n   \"Law of the Excluded Middle.\"\n\n   Not all logics include this notion, so it's not built into Coq. Instead,\n   we declare it as an axiom. A logic that doesn't have L.E.M. is called\n   constructive. A logic that does include L.E.M. is called classical. *)\nAxiom lem : forall p, p \\/ ~p.\n\nTheorem and_comm : forall p q, p /\\ q <-> q /\\ p.\nProof.\n  intro p. intro q. (* Suppose we have propositions p and q *)\n  split. (* Two cases for the two directions of the arrow *)\n  - intro p_and_q. (* Assume p /\\ q *)\n    destruct p_and_q. (* Decompose to reveal p and q. *)\n    split. (* Prove q and p separately. *)\n    + assumption. (* We've assumed q. *)\n    + assumption. (* We've assumed p. *)\n  - intro q_and_p.  (* similar *)\n    destruct q_and_p.\n    split.\n    + assumption.\n    + assumption.\nQed. (* QED *)\n\nTheorem or_comm : forall p q, p \\/ q <-> q \\/ p.\nProof.\n  intro p. intro q.\n  split.\n  - intro p_or_q.\n    destruct p_or_q. (* Decompose into two possible cases: either p, or q. *)\n    + right. (* We will prove the *right* choice of q \\/ p. *)\n      assumption.\n    + left.\n      assumption.\n  - intro q_or_p.\n    destruct q_or_p.\n    + right.\n      assumption.\n    + left.\n      assumption.\nQed.\n\nTheorem and_assoc : forall p q r, (p /\\ q) /\\ r <-> p /\\ (q /\\ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro pq_r.\n    destruct pq_r.\n    destruct H.\n    split.\n    + assumption.\n    + split.\n      * assumption.\n      * assumption.\n  - intro p_qr.\n    destruct p_qr.\n    destruct H0.\n    split.\n    + split.\n      * assumption.\n      * assumption.\n    + assumption.\nQed.\n\nTheorem or_assoc : forall p q r, (p \\/ q) \\/ r <-> p \\/ (q \\/ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro pq_r.\n    destruct pq_r.\n    + destruct H.\n      * left.\n        assumption.\n      * right.\n        left.\n        assumption.\n    + right.\n      right.\n      assumption.\n  - intro p_qr.\n    destruct p_qr.\n    + left.\n      left.\n      assumption.\n    + destruct H.\n      * left.\n        right.\n        assumption.\n      * right.\n        assumption.\nQed.\n\nTheorem and_distrib : forall p q r, p /\\ (q \\/ r) <-> (p /\\ q) \\/ (p /\\ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro and_or.\n    destruct and_or.\n    destruct H0.\n    + left.\n      split.\n      * assumption.\n      * assumption.\n    + right.\n      split.\n      * assumption.\n      * assumption.\n  - intro and_or_and.\n    destruct and_or_and.\n    + destruct H.\n      split.\n      * assumption.\n      * left.\n        assumption.\n    + destruct H.\n      split.\n      * assumption.\n      * right.\n        assumption.\nQed.\n\nTheorem or_distrib : forall p q r, p \\/ (q /\\ r) <-> (p \\/ q) /\\ (p \\/ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro or_and.\n    destruct or_and.\n    + split.\n      * left.\n        assumption.\n      * left.\n        assumption.\n    + destruct H.\n      split.\n      * right.\n        assumption.\n      * right.\n        assumption.\n  - intro or_and_or.\n    destruct or_and_or.\n    destruct H.\n    + left.\n      assumption.\n    + destruct H0.\n      * left.\n        assumption.\n      * right.\n        split.\n        -- assumption.\n        -- assumption.\nQed.\n\nTheorem and_ident : forall p, p /\\ True <-> p.\nProof.\n  intro p.\n  split.\n  - intro p_and_True.\n    destruct p_and_True.\n    assumption.\n  - intro pf_p.\n    split.\n    + assumption.\n    + constructor. (* This proves True. *)\nQed.\n\nTheorem or_ident : forall p, p \\/ False <-> p.\nProof.\n  intro p.\n  split.\n  - intro p_or_False.\n    destruct p_or_False.\n    + assumption.\n    + contradiction. (* If you've assumed False, then you're in an impossible case. *)\n  - intro pf_p.\n    left.\n    assumption.\nQed.\n\nTheorem and_neg : forall p, p /\\ ~p <-> False.\nProof.\n  intro p.\n  split.\n  - intro p_and_not_p.\n    destruct p_and_not_p.\n    contradiction. (* This tactic also looks for two contradictory hypotheses. *)\n  - intro false.\n    contradiction.\nQed.\n\nTheorem or_neg : forall p, p \\/ ~p <-> True.\nProof.\n  intro p.\n  split.\n  - intro p_or_not_p.\n    constructor.\n  - intro true.\n    apply lem. (* Here, we have to use our L.E.M. axiom. That's what \"apply\" does. *)\nQed.\n\nTheorem double_neg : forall p, ~(~p) <-> p.\nProof.\n  intro p.\n  split.\n  - intro not_not_p.\n    (* Negations aren't useful for much, other than providing contradictions. So,\n       we need to use L.E.M. *)\n    pose proof (lem p) as lem_p. (* pose proof brings an existing proof into scope. *)\n    destruct lem_p.\n    + assumption.\n    + contradiction.\n  - intro pf_p.\n    (* To prove a negation, we assume the opposite and find a contradiction. This\n       is done with intro. *)\n    intro not_p.\n    contradiction.\nQed.\n\nTheorem and_idempotent : forall p, p /\\ p <-> p.\nAdmitted. (* This is what you tell Coq when you don't want to prove it.\n             Here, I'm leaving this as an exercise. *)\n\nTheorem or_idempotent : forall p, p \\/ p <-> p.\nAdmitted.\n\nTheorem and_bound : forall p, p /\\ False <-> False.\nAdmitted.\n\nTheorem or_bound : forall p, p \\/ True <-> True.\nAdmitted.\n\nTheorem and_deMorgan : forall p q, ~(p /\\ q) <-> ~p \\/ ~q.\nProof.\n  intro p. intro q.\n  split.\n  - intro not_p_and_q.\n    pose proof (lem p) as lem_p.\n    pose proof (lem q) as lem_q.\n    destruct lem_p.\n    + destruct lem_q.\n      * exfalso. (* Use this when you know you have a contradiction *)\n        apply not_p_and_q. (* If you're proving False, you can apply a ~(...) to\n                              change the goal to prove (...). *)\n        split.\n        -- assumption.\n        -- assumption.\n      * right.\n        assumption.\n    + left.\n      assumption.\n  - intro not_p_or_not_q.\n    destruct not_p_or_not_q.\n    + intro p_and_q.\n      destruct p_and_q.\n      contradiction.\n    + intro p_and_q.\n      destruct p_and_q.\n      contradiction.\nQed.\n\nTheorem or_deMorgan : forall p q, ~(p \\/ q) <-> ~p /\\ ~q.\nProof.\n  intro p. intro q.\n  split.\n  - intro not_p_or_q.\n    split.\n    + intro pf_p.\n      apply not_p_or_q.\n      left.\n      assumption.\n    + intro pf_q.\n      apply not_p_or_q.\n      right.\n      assumption.\n  - intro not_p_and_not_q.\n    destruct not_p_and_not_q.\n    intro p_or_q.\n    destruct p_or_q.\n    + contradiction.\n    + contradiction.\nQed.\n\nTheorem and_absorption : forall p q, p /\\ (p \\/ q) <-> p.\nAdmitted.\n\nTheorem or_absorption : forall p q, p \\/ (p /\\ q) <-> p.\nAdmitted.\n\nTheorem not_true : ~ True <-> False.\nProof.\n  split.\n  - intro not_true.\n    contradiction.\n  - intro false.\n    contradiction.\nQed.\n\nTheorem not_false : ~ False <-> True.\nProof.\n  split.\n  - intro not_false.\n    constructor.\n  - intro true.\n    intro false.\n    contradiction.\nQed.\n\nTheorem problem_2_1_53 : forall p q, ~((~p /\\ q) \\/ (~p /\\ ~q)) \\/ (p /\\ q) <-> p.\nProof.\n  intro p. intro q.\n  rewrite or_deMorgan. (* rewrite uses a proof of equivalence to rewrite the goal *)\n  rewrite and_deMorgan.\n  rewrite and_deMorgan.\n  rewrite double_neg.\n  rewrite double_neg.\n  rewrite <- or_distrib. (* this variant rewrites right-to-left *)\n  rewrite and_comm.\n  rewrite and_neg.\n  rewrite or_ident.\n  rewrite or_absorption.\n  reflexivity. (* this solves a reflexive equivalence goal *)\nQed.\n\nTheorem problem_2_1_52 : forall p q, ~(p \\/ ~q) \\/ (~p /\\ ~q) <-> ~p.\nAdmitted. (* Exercise *)\n\n(* Section 2.2 *)\n\nTheorem implication : forall (p q : Prop), (p -> q) <-> (~p \\/ q).\n(* Note that Coq allows us to say what we're quantifying over. Above, it could\n   always infer it. But, (->) is overloaded, so we need to tell Coq. *)\nProof.\n  intro p. intro q.\n  split.\n  - intro implic.\n    pose proof (lem p) as lem_p.\n    destruct lem_p.\n    + right.\n      (* Here, we know (p -> q) and we're trying to prove q. If we `apply implic`, then\n         our goal will reduce to just p. *)\n      apply implic.\n      assumption.\n    + left.\n      assumption.\n  - intro or.\n    intro pf_p. (* we can assume p here, because we're proving (p -> q) *)\n    destruct or.\n    + contradiction.\n    + assumption.\nQed.\n\nTheorem neg_implication : forall (p q : Prop), ~(p -> q) <-> p /\\ ~q.\nAdmitted.\n\nTheorem contrapositive : forall (p q : Prop), (p -> q) <-> (~q -> ~p).\nProof.\n  intro p. intro q.\n  rewrite implication.\n  rewrite implication.\n  rewrite double_neg.\n  rewrite or_comm.\n  reflexivity.\nQed.\n\n(* Section 3.2 *)\n\nTheorem forall_deMorgan : forall {A} {P : A -> Prop}, ~(forall x, P x) <-> exists y, ~(P y).\nProof.\n  intro A. intro P.\n  split.\n  - intro not_forall.\n    rewrite <- double_neg.\n    intro not_exists.\n    apply not_forall.\n    intro x.\n    rewrite <- double_neg.\n    intro not_pred.\n    apply not_exists.\n    exists x. (* This is how we choose the value of an existential variable. *)\n    assumption.\n  - intro ex.\n    destruct ex. (* You can use destruct to get a given existential variable. *)\n    intro all.\n    specialize (all x). (* instantiate a forall *)\n    contradiction.\nQed.\n\nTheorem exists_deMorgan : forall {A} {P : A -> Prop}, ~(exists x, P x) <-> forall y, ~(P y).\nProof.\n  intro A. intro P.\n  split.\n  - intro not_exists.\n    intro y.\n    intro pred_y.\n    apply not_exists.\n    exists y.\n    assumption.\n  - intro all.\n    intro ex.\n    destruct ex.\n    specialize (all x).\n    contradiction.\nQed.\n\n(* Section 3.3 *)\n\n(* There exists a positive integer m such that for all positive integers n, m <= n. *)\nTheorem example_3_3_5 : exists m, m > 0 /\\ forall n, n > 0 -> m <= n.\nProof.\n  exists 1. (* Choose the value for the existential. *)\n  split.\n  - omega. (* This solves most basic arithmetic problems. *)\n  - intro n.\n    intro pos.\n    omega.\nQed.\n \n(* Section 4.1 *)\nDefinition even n := exists k, n = 2 * k.\nDefinition odd n  := exists k, n = 2 * k + 1.\n\nDefinition prime n := n > 1 /\\ forall r s, (r > 0 /\\ s > 0 /\\ n = r * s) -> (r = n \\/ s = n).\nDefinition composite n := exists r s, r > 0 /\\ s > 0 /\\ n = r * s /\\ 1 < r < n /\\ 1 < s < n.\n\nTheorem two_prime : prime 2.\nProof.\n  unfold prime. (* This unfolds a definition in the goal. *)\n  split.\n  - omega.\n  - intro r.\n    intro s.\n    intro Hyp.\n    destruct Hyp.\n    destruct H0.\n    destruct r. (* either r is 0 or greater than 0. *)\n    + omega.\n    + destruct s.\n      * omega.\n      * destruct r.\n        -- destruct s.\n           ++ omega.\n           ++ destruct s.\n              ** omega.\n              ** omega.\n        -- destruct s.\n           ++ omega.\n           ++ simpl in H1.\n              rewrite <- plus_n_Sm in H1.\n              inversion H1.\nQed.\n(* That proof got a little ugly, because we had to look at all possibilities for r and s\n   below two. *)\n\nTheorem six_composite : composite 6.\nProof.\n  unfold composite.\n  exists 2.\n  exists 3.\n  split.\n  - omega.\n  - split.\n    + omega.\n    + split.\n      * omega.\n      * split.\n        -- omega.\n        -- omega.\nQed.\n\n(* Coq can do induction! *)\nTheorem even_or_odd : forall n, even n \\/ odd n.\nProof.\n  intro n.\n  induction n. (* This performs natural number induction on n. *)\n  - left.\n    exists 0.\n    omega.\n  - destruct IHn.\n    * right.\n      destruct H.\n      exists x.\n      omega.\n    * left.\n      destruct H.\n      exists (x+1).\n      omega.\nQed.\n\nTheorem not_odd__even : forall n, ~ (odd n) <-> even n.\nProof.\n  intro n.\n  split.\n  * intro not_odd.\n    pose proof (even_or_odd n).\n    destruct H.\n    - assumption.\n    - contradiction.\n  * intro pf_even.\n    intro pf_odd.\n    destruct pf_even.\n    destruct pf_odd.\n    subst. (* This performs all substitutions Coq can find. *)\n    omega.\nQed.\n\nTheorem problem_4_1_28 : forall n, odd n -> odd (n * n).\nProof.\n  intro n. intro Hodd.\n  unfold odd in *. (* unfold everywhere *)\n  destruct Hodd.\n  (* (2x+1)(2x+1) = 4x^2 + 4x + 1 = 2(2*x^2 + 2*x) + 1 *)\n  exists (2 * x * x + 2 * x).\n  subst.\n  ring. (* like omega, but works better with multiplication *)\nQed.\n\nTheorem problem_4_1_27 : forall n m, (odd m /\\ odd n) -> odd (m + n).\nAdmitted.\n\nTheorem problem_4_1_30 : forall m, even m -> odd (3 * m + 5).\nAdmitted.\n\n", "meta": {"author": "goldfirere", "repo": "cs231", "sha": "127294cc0d7a3369b3bd437b49eef3660179b57d", "save_path": "github-repos/coq/goldfirere-cs231", "path": "github-repos/coq/goldfirere-cs231/cs231-127294cc0d7a3369b3bd437b49eef3660179b57d/21_coq/demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8872045944627057, "lm_q1q2_score": 0.8127766541438954}}
{"text": "Module NaturalNumPlayground.\n\nInductive nat : Type :=\n    | O\n    | S (n : nat).\n\n\nCheck S ( S O) : nat.\n\nDefinition pred (n : nat) := \n    match n with\n    | O => O\n    | S n' => n'\n    end.\n\nCompute pred (S (S (S O))).\n\n\nEnd NaturalNumPlayground.\n\nCheck (S (S (S O))).\n\nDefinition minustwo (n : nat) : nat := \n    match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n    end.\n\nCompute (minustwo 4).\n\nFixpoint iseven (n : nat) : bool :=\n    match n with\n    | O => true\n    | S O => false\n    | S ( S n') => iseven (n')\n    end.\n\n\nDefinition isodd (n : nat) : bool :=\n    match n with\n    | n => negb(iseven n) \n    end.\n\nExample check_is_even : (iseven 16) = true.\nProof. simpl. reflexivity. Qed.\n\nExample check_is_odd : (isodd 17) = true.\nProof. simpl. reflexivity. Qed.\n\n\nModule NaturalPlayground2.\n\nFixpoint plus (n m : nat) : nat :=\n    match n with\n    | O => m\n    | S n' => (plus n' m)\n    end.\n \n    \nEnd NaturalPlayground2.\n\n", "meta": {"author": "shashwat1002", "repo": "coq_notebook", "sha": "b3eb9736bc928c787535ffce09c7250734e34181", "save_path": "github-repos/coq/shashwat1002-coq_notebook", "path": "github-repos/coq/shashwat1002-coq_notebook/coq_notebook-b3eb9736bc928c787535ffce09c7250734e34181/code_snippets/natural_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8127756169701859}}
{"text": "Require Import Coq.Arith.PeanoNat.\n\n(* is_even and is_odd (recursive definition) *)\nFixpoint\n  is_odd (n:nat) : bool :=\n  match n with\n  | 0 => false\n  | S x => is_even x\n  end\n\n  with\n\n  is_even (n:nat) : bool := \n  match n with\n  | 0 => true\n  | S x => is_odd x\n  end.\n\n(* if n is odd, it is not even *)\nTheorem odd_is_not_even :\n  forall n, (is_odd n = true) -> (is_even n = false).\nintros.\nreplace false with (negb true) by reflexivity.\nrewrite <- H.\nclear H.\ninduction n.\n- reflexivity.\n- simpl. rewrite IHn. destruct (is_odd n); reflexivity.\nQed.", "meta": {"author": "serid", "repo": "coq-theories", "sha": "8401361ad241f3188f4c1a61060114c646f935e4", "save_path": "github-repos/coq/serid-coq-theories", "path": "github-repos/coq/serid-coq-theories/coq-theories-8401361ad241f3188f4c1a61060114c646f935e4/Functor/Even2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.8124026892687967}}
{"text": "Require Import Lia.\n\n(* Un if con ambas ramas iguales es igual al resultado de las ramas. *)\nLemma obvious_if: forall (A: Type) (b:bool) (x: A), (if b then x else x) = x.\nProof.\nintros.\ndestruct b; reflexivity.\nQed.\n\n(* 2n es par para toda n... *)\nLemma even_2n: forall (n:nat), Nat.even(2*n) = true.\nProof.\ninduction n.\n+ simpl; trivial.\n+ simpl.\n  assert (n + S (n + 0) = S (2 * n)).\n  * lia.\n  * rewrite H.\n    trivial.\nQed.\n", "meta": {"author": "victorz3", "repo": "CoqPatriciaTrees", "sha": "8ffecd6276845d20b954283f08936367e87eed1d", "save_path": "github-repos/coq/victorz3-CoqPatriciaTrees", "path": "github-repos/coq/victorz3-CoqPatriciaTrees/CoqPatriciaTrees-8ffecd6276845d20b954283f08936367e87eed1d/Props_Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.812172718375488}}
{"text": "(* Here we'll prove properties of your function-based implementation of dictionary. *)\nRequire Import b1.\n(* If you find out that your implementation is incorrect, \n   go back to the previous file, fix it, \n   then run 'make' and restart this proof to load the new implementation. *)\n\n(* You can do the exercises in the order they appear\n   or jump straight into the NatDictProofs section\n   and prove the previous statements when needed. *)\n\n(* Tacticts needed for this exercises:\n   - General-purpose tactics usable both in goal and premises\n     - rewrite\n     - apply\n     - destruct\n     - unfold\n   - Tactics working with the goal:\n     - intros   \n     - left / right\n     - exfalso   \n     - split\n     - simpl\n   - Tactics that finish the proof (besides 'apply'):\n     - inversion\n       this is a general tactic, but for now we just derive contradictions with it\n     - reflexivity\n *)\n\n(* Tactics cheatsheet:\n   https://www.cs.cornell.edu/courses/cs3110/2018sp/a5/coq-tactics-cheatsheet.html\n*)\n\n\nSection IfProofs.\n\n  (* Show the following helper lemmas. *)\n  (* Use 'rewrite' tactic to simplify the 'if' expression *)\n  \n  Lemma if_true_helper {A: Type} (b: bool) (a1 a2: A) (TRUE: b = true):\n    (if b then a1 else a2) = a1.\n  Proof.\n  rewrite TRUE.\n  reflexivity.\n  Qed.\n\n  Lemma if_false_helper {A: Type} (b: bool) (a1 a2: A) (FALSE: b = false):\n    (if b then a1 else a2) = a2.\n  Proof.\n  rewrite FALSE.\n  reflexivity.\nQed.\n\nEnd IfProofs.\n\nSection LogicProofs.\n\n  Lemma neg_equiv (P Q: Prop) (EQUIV: P <-> Q):\n    not P <-> not Q.\n  Proof.\n    Locate \"<->\".\n    Print iff.\n    unfold iff.\n    unfold iff in EQUIV.\n\n    Restart.\n\n    unfold iff in *.\n    destruct EQUIV as [pq qp].\n    split.\n    { intros np.\n      Locate \"~\".\n      Print not.\n      unfold not in *. intros q.\n      apply np. apply qp. apply q. }\n\n    intros nq p. apply nq, pq, p.\n  Qed.\n\n  (* Show that boolean has only two values. \n     Use 'destruct' tactic to perform case splitting. \n     It will generate one goal per splitting result.\n     To select the next goal, use '-' (see the proof above). *)\n  Lemma bool_true_or_false (b: bool):\n    b = true \\/ b = false.\n  Proof.\n  destruct b.\n  { left. \n  reflexivity.\n  }\n  right. \n  reflexivity.\nQed.\n(*  unfold or *)\n\n  \n  (* Show the equivalence of two notions of boolean being false. \n     An equivalence can be proven by showing two corresponding implications.\n     To introduce the premise of an implication, use 'intros name' (picking the 'name' appropriately). \n     Remember that you can use general-purpose tactics with 'in' modifier\n     which allows to perform the corresponding action in the proof context. \n*)\n  Lemma false_is_not_true (b: bool):\n    b = false <-> b <> true.\n  Proof.\n  unfold not.\n  unfold iff.\n  split.\n  {destruct b.\n    {\n    intros h1.\n    intros h2.\n    inversion h1.\n    }\n    {intros h1.\n    intros h2.\n    inversion h2.\n    }\n  }\n  {destruct b.\n    {\n    intros h1.\n    destruct h1.\n    reflexivity.\n    }\n    {\n    intros h1.\n    reflexivity.\n    }\n  }\nQed.\n\n  \nEnd LogicProofs.   \n\nSection NatEqProofs.\n\n  (* This proof involves induction which we'll cover at the next seminar. *)\n  Lemma nat_eq_refl (n: nat):\n    nat_eq n n = true.\n  Proof.\n    induction n as [| n IHn].\n    { simpl. reflexivity. }\n    simpl. apply IHn. \n  Qed.\n        \n  (* Here we give the specification to the 'nat_eq' function.\n     That is, we precisely relate the output of 'nat_eq' function \n     and properties of its arguments. *)\n\n  (* So far we're only able to prove the half of the specification. *)\n  Lemma eq_implies_nat_eq (n1 n2: nat):\n    n1 = n2 -> nat_eq n1 n2 = true.\n  Proof.\n  intros h1.\n  rewrite h1.\n  apply nat_eq_refl.\nQed.\n  \n  (* This part of the specification, again, involves induction. *)\n  Lemma nat_eq_implies_eq (n1 n2: nat):\n    nat_eq n1 n2 = true -> n1 = n2.\n  Proof.\n    generalize dependent n2. induction n1.\n    { intros. simpl in H. destruct n2; auto. inversion H. }\n    intros. destruct n2; simpl in H. \n    { inversion H. }\n    apply IHn1 in H. rewrite H. reflexivity.\n  Qed.\n\n  (* Finally, this is the specification of 'nat_eq'. *)\n  Lemma nat_eq_spec (n1 n2: nat):\n    nat_eq n1 n2 = true <-> n1 = n2.\n  Proof.\n  unfold iff.\n  split.\n  {apply nat_eq_implies_eq. }\n  {apply eq_implies_nat_eq. }\nQed.\n\n\n  (* This is an obvious reformulation of 'nat_eq' specification.\n     The specification, however, cannot be directly applied to prove this version.\n     Fortunately, by this moment we have auxiliary statements\n     that will eventually allow to reuse the specification.\n     One way to prove this will be to show equivalence \n     via an intermediate assertion.\n     To do this, start with the 'iff_trans' lemma in this way:\n     'apply (@iff_trans P Q R)' replacing P, Q and R with statements you need.\n     To find out what Q should be, \n     look at negation-related lemmas we've proved before.\n *)\n  Lemma nat_eq_neg_spec (n1 n2: nat):\n    nat_eq n1 n2 = false <-> n1 <> n2.\n  Proof.\n\n  apply (@iff_trans (nat_eq n1 n2 = false) (nat_eq n1 n2 <> true) (n1 <> n2)).\n  { apply false_is_not_true. }\n  { apply neg_equiv.\n  apply nat_eq_spec. }\nQed.\n    \n  (* After you've proved the statement above, read about the 'eapply' tactic.\n     The usage of 'eapply' allows to avoid specifying \n     all the parameters of a lemma you've been applying.\n     Replace the 'apply (@iff_trans P Q R)' with simply 'eapply iff_trans' \n     and analyze how the proof proceeds.\n     You can use 'eapply' in the subsequent proofs as well. *)\n  \nEnd NatEqProofs. \n\nSection UpdProofs.\n  Context {V: Type}. \n\n  (* Prove that the updated function applied to the changed key is the new value. *)\n  (* To exploit the term definition, use 'unfold' tactic. *)\n  Lemma update_latest (f: nat -> V) (n: nat) (v: V):\n    (upd f n v) n = v.\n  Proof.\n  unfold upd.\n  rewrite nat_eq_refl.\n  reflexivity.\nQed.\n\n\n  (* Prove that update affect only one value *)\n  (* Use the helper lemma for 'if'.  *)\n  Lemma update_others (f: nat -> V) (n: nat) (v: V) (n': nat) (NEQ: n <> n'):\n    (upd f n v) n' = f n'.    \n  Proof.\n  unfold upd.\n  apply nat_eq_neg_spec in NEQ.\n  rewrite NEQ.\n  reflexivity.\nQed.\n\nEnd UpdProofs. \n\nSection NatDictProofs.\n\n  Context {V: Type}. \n\n  (* Prove that new dictionary actually contains nothing. *)\n  Lemma new_dict_empty (n: nat):\n    contains' (@new_dict' V) n = false.\n  Proof.\n  unfold new_dict'.\n  unfold contains'.\n  unfold get'.\n  reflexivity.\nQed.\n\n  (* Prove that the inserted value gets retrieved *)\n  Lemma insert_latest (d: @nat_dict_fun V) (n: nat) (v: V):\n    get' (insert' d n v) n = Some v.\n  Proof.\n  unfold insert'.\n  unfold get'.\n  apply update_latest.\nQed.\n\n  (* Prove that removed key is no more contained in the dict *)\n  Lemma removed_not_contained (d: @nat_dict_fun V) (n: nat):\n    contains' (remove' d n) n = false.\n  Proof.\n  unfold remove'.\n  unfold contains'.\n  unfold get'.\n  rewrite update_latest.\n  reflexivity.\nQed.\n\n\n  (* Prove that insert doesn't affect other values *)\n  Lemma insert_others (d: @nat_dict_fun V) (n: nat) (v: V) (n': nat) (NEQ: n <> n'):\n    get' (insert' d n v) n' = get' d n'. \n  Proof.\n  unfold insert'.\n  unfold get'.\n  apply update_others, NEQ.\nQed.\n\n  (* Prove that updating a dictionary with a value it already has yields the same dictionary *)\n  (* You may want to prove an helper lemma beforehand. *)\n  (* Also, remember that 'destruct' can be used not only on variables, \n     but also on an arbitrary term.\n     It can be used to separate cases when insert does matter and doesn't. *)\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\n  \n\n    \n  Lemma insert_same (d: @nat_dict_fun V) (n: nat) (v: V)\n        (HAD_V: get' d n = Some v):\n    forall n', get' (insert' d n v) n' = get' d n'. \n  Proof.\n  intros n'.\n  remember (n=n' \\/ n<>n') as n_eq_n'.\n  \n  destruct (n_eq_or_neq n n').\n  {\n    rewrite H.\n  unfold insert'.\n  unfold get' in *.\n  unfold upd.\n  rewrite H in HAD_V.\n  rewrite HAD_V.\n  rewrite nat_eq_refl.\n  reflexivity.\n  }\n  unfold insert'.\n  unfold get'.\n  apply insert_others.\n  apply H.\nQed.\n  \n\n  (* Prove that inserting a value twice is the same as inserting it once *)\n  Lemma insert_twice (d: @nat_dict_fun V) (n: nat) (v: V):\n    forall n', get' (insert' (insert' d n v) n v) n' = get' (insert' d n v) n'. \n  Proof.\n  remember (insert' d n v) as d'.\n  apply insert_same.\n  rewrite Heqd'.\n  apply insert_latest.\nQed.\n\nEnd NatDictProofs. \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/b2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.9046505447409665, "lm_q1q2_score": 0.8121005449204233}}
{"text": "From LF Require Export Lists.\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(* polymorphic inductive type definitions *)\nInductive list (X: Type) : Type :=\n  | nil\n  | cons (x: X) (l : list X).\n\n(*\n  The definition of list is a function from Types to \n  Inductive definitions.\n  A list is a function from Types to Types.\n  For any particular type X, the type list X is the\n  Inductively defined set of lists whose elements are\n  of type X.\n*)\n\nCheck list: Type -> Type.\n\n(*\n  The X is now a parameter for the constructors nil and cons,\n  what means they are now polymorphic constructors. When we\n  use them, we must provide a first argument that is the\n  type of the list they are building. For example, nil nat\n  constructs the empty list of type nat. \n*)\n\nCheck (nil nat) : list nat.\nCheck (cons nat 3 (nil nat)) : list nat.\n\nCheck nil : forall X : Type, list X.\n\nCheck cons : forall X: Type, X -> list X -> list X.\n\n(* polymorphic version of the repeat function *)\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\n(* mumble grumble *)\nModule MumbleGrumble.\n\n(* mumble is a Set that contains a, b, or c*)\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\n(* grumble is Type -> Type *)\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, you have to add the type argument\n      - [d mumble (b a 5)] YES\n      - [d bool (b a 5)] YES (it returns grumble bool)\n      - [e bool true] YES\n      - [e mumble (b c 0)] YES\n      - [e bool (b c 0)] NO, because the e constructor must have the \n                        same argument that is binded to X, but we are\n                        using X = bool and b c 0 is of type mumble.\n      - [c] YES *)\n\n\nCheck mumble.\nCheck grumble.\n\nCheck d bool (b a 5).\nCheck e mumble (b c 0).\nCheck c.\nCheck d (nat). (* mumble -> grumble nat *)\n(* mumble is the type argument*)\nCheck d mumble (b a 5).\n\nEnd MumbleGrumble.\n\n(* Type annotation inference *)\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\n\n\n(*\n It has exactly the same type as repeat. Coq was able to use type inference to deduce what the types of X, x, and count must be, based on how they are used. For example, since X is used as an argument to cons, it must be a Type, since cons expects a Type as its first argument; matching count with 0 and S means it must be a nat; and so on.\nThis powerful facility means we don't always have to write explicit type annotations everywhere, although explicit type annotations can still be quite useful as documentation and sanity checks, so we will continue to use them much of the time.\n\n*)\n\n(* Type argument synthesis *)\n(* similar to type annotation inference. we use \"holes\"\n  totell Coq to attempt to infer the missing information.\n*)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n\n(* Implicit arguments *)\n(* we can avoid writing _'s by telling Coq to always\n  infer the type arguments of a given function. \n  The Arguments directive specifies the name of the\n  function (or constructor) then lists the (leading)\n  argument names to be treated as implicit, each\n  surrounded by curly braces.\n*)\n\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\n(* now we dont' have to supply any type arguments *)\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(*Alternatively, we can declare an argument to be \n  implicit when defining the function itself, by \n  surrounding it in curly braces instead of parens.  *)\n\n\nFixpoint repeat''' {X : Type} (x: X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n\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\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(* Supplying type arguments explicitly *)\n\n(* The example below fails because nil is a constructor\nof Type list. However, even though list has implicit type\narguments, Coq has no info available to infer the type of nil below. *)\nFail Definition mynil := nil.\n\n\n(* @ is used to force implicit arguments to be explicit*)\n\nCheck @nil : forall X : Type, list X.\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(* Exercises *)\nTheorem app_nil_r : forall (X:Type), forall l: list X,\n  l ++ [] = l.\nProof.\n  intros T l.\n  induction l as [| h t 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 T l m n.\n  induction l as [| h t IHl].\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 T l1 l2.\n  induction l1 as [| h1 t1 IHl1].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros T l1 l2.\n  induction l1 as [| h1 t1 IHl1].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite app_assoc. rewrite IHl1. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros T l.\n  induction l as [| h t IHl].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. simpl.\n    rewrite IHl. reflexivity.\nQed.\n\n(* Polymorphic Pairs or products *)\nInductive prod (X Y : Type) : Type :=\n  | pair (x : X) (y: Y).\n\nArguments pair {X} {Y}.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(* (x,y) is a value built from two other values, while\n  x*y is a type built from two other types. *)\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(* zip takes two lists and combine them\n  into a list of pairs *)\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.\nCompute (combine [1;2] [false;false;true;true]).\n\n(* split takes a list of pairs and returns a pair\n  of lists. it is also called unzip *)\n\nFixpoint split {X Y : Type} (l: list (X*Y)) : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: l' => match (split l') with\n                    | (x', y') => (x::x', y::y')\n                    end\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  reflexivity. Qed.\n\n\n(* Polymorphic Options *)\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\nFixpoint nth_error {X : Type} (l : list X) (n : nat) :=\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\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | h :: t => Some h\n  end.\n\nCheck @hd_error : forall X : Type, list X -> option X.\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(* Functions as Data *)\nDefinition doit3times {X : Type} (f: X->X) (n : X): X :=\n  f (f (f n)).\n(* applies f three times to some value n *)\n\n Fixpoint filter {X:Type} (test: X->bool) (l:list X) : list X :=\n  match l with\n  | [] => []\n  | h :: t =>\n    if test h then h :: (filter test t)\n    else filter test t\n  end.\n\nExample test_filter1: filter 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.\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter odd l).\nExample test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (7 <=? n) && even 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\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(* we create a pair with the resulting lists\n  from applying filter with test to each element\n  and from applying filter with the negb of test\n  to each element of the list (using an anonymous\n  function \n*)\n\n\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\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\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n\n(* The element types of the input and output lists need not\n   be the same, since map takes two type arguments, X and Y. \n*)\n\nExample test_map2:\n  map odd [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(*\n  It can even be applied to a list of numbers and a \n  function from numbers to lists of booleans to yield\n  a list of lists of booleans: \n*)\n\n Example 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(* map and rev are commutative *)\n\n(* Auxiliar theorem: distributive on map app *)\n\n(* both have type X as this is the type of the input list. \n   we apply a function X->Y to each element of each list, so\n   in the end we append two lists of type Y.*)\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 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 IHl].\n  - reflexivity.\n  - simpl. rewrite <- IHl. rewrite map_app_distr.\n    simpl. reflexivity.\nQed.   \n\n(* flat_map: a map that uses a function of type X->list Y *)\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)\n                      : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\n\n(* Fold *)\n Fixpoint fold {X Y: Type} (f : X->Y->Y) (l : list X) (b : Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold andb) : list bool -> bool -> bool.\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(* functions that construct functions *)\n\nDefinition constfun {X: Type} (x: X) : nat -> X :=\n  fun (k: nat) => x.\n\n(* ftrue is built from constfun *)\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: nat -> nat -> nat.\n\n(*\n  The function \"plus\" by itself has three binary operators.\n  As it is right-associative, it is the same as writing\n  nat -> (nat -> nat).\n  Plus is a one-argument function that takes nat and returns\n  a one-argument function that takes another nat and returns\n  a nat.\n  \n  Basically: one argument -> function (partial application)\n  two arguments -> number \n*)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n\n(* Additional exercises *)\nModule Exercises.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| h t IHl].\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed.\n\n(* fold applies a binary operator between every two elements of a list *)\n(* the return of our anonymous function should be a list *)\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\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.\n  induction l as [| h t IHl].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed.\n\n\n(* 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\n(* To uncurry, we need to \"destruct\" the pair from\n  p. *)\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  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  reflexivity.\nQed.\n\n\n\n\n", "meta": {"author": "wrongbyte", "repo": "software-foundations", "sha": "c1721a53d73f9ce405537ff974b7a11edf2bbc63", "save_path": "github-repos/coq/wrongbyte-software-foundations", "path": "github-repos/coq/wrongbyte-software-foundations/software-foundations-c1721a53d73f9ce405537ff974b7a11edf2bbc63/lf/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.9059898127684335, "lm_q1q2_score": 0.8119946237813667}}
{"text": "Require Import List String Omega ZArith.\n\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nLocal Open Scope Z_scope.\n\nDefinition channel : Type := list string.\nDefinition msg : string := \" \"\"Message.\"\" \".\nRecord netstate := NetState {t : Z; r : Z; c1 : channel; c2 : channel}.\nDefinition initial := {| t := 5 ; r := 5 ; c1 := nil ; c2 := nil |}.\n\nInductive netEvalR : netstate -> netstate -> Prop :=\n| Initial : (netEvalR initial initial)\n| Step1 : forall st st',\n    netEvalR st st' ->\n    st'.(t) > 0 ->\n    (netEvalR st' {| t := st'.(t) - 1 ; r := st'.(r) ;\n                     c1 := msg :: st'.(c1) ; c2 := st'.(c2) |})\n| Step2 : forall st st',\n    netEvalR st st' ->\n    st'.(c2) <> nil ->\n    (netEvalR st' {| t := st'.(t) + 1 ; r := st'.(r) ;\n                     c1 := st'.(c1) ; c2 := (tl st'.(c2)) |})\n| Step3 : forall st st',\n    netEvalR st st' ->\n    st'.(c1) <> nil ->\n    (netEvalR st' {| t := st'.(t) ; r := st'.(r) + 1 ;\n                    c1 := (tl st'.(c1)) ; c2 := st'.(c2) |})\n| Step4 : forall st st',\n    netEvalR st st' ->\n    st'.(r) > 0 ->\n    (netEvalR st' {| t := st'.(t) ; r := st'.(r) - 1 ;\n                     c1 := st'.(c1) ; c2 := (msg :: st'.(c2)) |}).\n\nDefinition safety1 (st' : netstate) : Prop := st'.(t) >= 0 /\\ st'.(r) >= 0.\n      \nLemma safety1_holds: forall st st' : netstate,\n         (netEvalR st st') ->\n         safety1 st'.\nProof.\n  intros st st' H. split; induction H; simpl; omega.\nQed.\n\nDefinition safety2 (st' : netstate) : Prop :=\n  Zlength st'.(c1) + Zlength st'.(c2) + st'.(t) + st'.(r) = 10.\n\nLemma safety2_holds : forall st st' : netstate,\n    (netEvalR st st') ->\n    safety2 st'.\nProof.\n  intros st st' H. unfold safety2. induction H; simpl;\n    try reflexivity;                           (* Initial state *)\n    try (rewrite Zlength_cons; omega);         (* Steps 1 and 4 *)\n    [destruct (c2 st') | destruct (c1 st')];   (* Steps 2 and 3 *)\n      try contradiction;\n      (simpl; rewrite Zlength_cons in IHnetEvalR; omega).\nQed.\n\nTheorem safety_holds : forall st st' : netstate,\n      (netEvalR st st') -> safety1 st' /\\ safety2 st'.\nProof.\n  intros st st' H. split;\n  [apply (safety1_holds st st') | apply (safety2_holds st st')];\n    assumption.\nQed.", "meta": {"author": "mattjquinn", "repo": "distsyscoq", "sha": "815906ff12881c26010dd8312a3bcb94fc45fe9a", "save_path": "github-repos/coq/mattjquinn-distsyscoq", "path": "github-repos/coq/mattjquinn-distsyscoq/distsyscoq-815906ff12881c26010dd8312a3bcb94fc45fe9a/dualprocess/DualProcess.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.8119604350007026}}
{"text": "Require Import Problem.\n\nLemma plus_n_0: forall n, n + 0 = n.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nLemma plus_n_Sm: forall n m, n + S m = S (n + m).\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed. \n\nTheorem plus_comm_proof: plus_comm.\nProof.\n  unfold plus_comm.\n  intros.\n  induction n.\n  - rewrite -> plus_n_0. reflexivity.\n  - simpl. rewrite -> plus_n_Sm. rewrite -> IHn. reflexivity.\nQed.\n", "meta": {"author": "matonix", "repo": "topprover", "sha": "c98d06ead25b865ef4b92313ef2a0d7f73422c33", "save_path": "github-repos/coq/matonix-topprover", "path": "github-repos/coq/matonix-topprover/topprover-c98d06ead25b865ef4b92313ef2a0d7f73422c33/2/Example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235896, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.8119034548600178}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nInductive evenP: nat -> Prop :=\n| EvenO  : evenP 0\n| EvenSs : forall n, evenP n -> evenP (n + 2).\n\nFixpoint evenb n := if n is n'.+2 then evenb n' else n == 0.\n\nLemma even_4: evenb 4.\nProof. done. Qed.\n\nTheorem even_3_contra: ~evenb 3.\nProof. done. Qed.\n\n(*Proof by induction on the rule (for evenP) *)\nLemma evenP_plus n m : evenP n -> evenP m -> evenP (n + m).\nProof.\nelim=>//; move=>k Ek Hk Hm=>/=; rewrite -(addnC m) addnA; constructor. \nby rewrite addnC; apply: Hk. \nQed.\n\n(* TODO: How to build induction on recursive function? *)\nLemma evenb_plus m n : evenb m -> evenb n -> evenb (m + n).\nProof.\nelim: m {-2}m (leqnn m)=>[|m IH]; case=>//.\nby case=>// m' /ltnW /IH.\nQed.\n\nInductive evenP1 n : Prop :=\n  Even01 of n = 0 | EvenSs1 m of n = m.+2 & evenP1 m.\n\nLemma evenP_contra': forall n', evenP n' -> forall n, n' = (n + 1 + n) -> False.\nProof.\nmove=>k; elim=>[n|]=>{k}.\n-rewrite addnC addnA addn1.\n move=> E. move:(ltn0Sn (n+n))=>H; rewrite E in H.\n by move:(ltnn ((n+n).+1)); rewrite H. case. \n-move=>_ _ n. rewrite addnC addn0; case:n=>[|n]//=.\n+by rewrite addn1 addnS addnC !addnS; move/eqP; rewrite !eqSS; move/eqP.\n (* TODO: what exactly is happened here? *)\nmove=>n H IHEven. case.\n+by rewrite !addn0 (addnC 0) addn0 addnC add2n. \n (* TODO: what exactly is happened here? *)\nmove=>n0; rewrite addn2 addn1 addnS addnC !addnS. \nmove/eqP; rewrite !eqSS; move/eqP=>E; subst n. \nby apply: (IHEven n0); rewrite addnC addn1 addnS.\nQed.\n\n\nLemma evenP_contra: forall n, evenP (n + 1 + n) -> False.\nProof.\nmove=>n. move:(@evenP_contra' (n + 1 + n))=>H.\nmove/H=>H1. move:(H1 n)=> H2. apply:H2. done.\nQed.\n\n(* TODO: How to characterize this general pattern when inducing of n<=n *)\nLemma even_contra n: evenb (n + 1 + n) -> False.\nProof.\nProof. by elim: n=>[|n IH] //; rewrite addSn addnS. Qed.\n\n(*\nProof.\nelim: n {-2}n (leqnn n)=>[|n IH]; elim=>//.\ncase=>// m H1 H3; rewrite ltnS in H3.\nmove:(ltn_trans H3 (ltnSn n))=>/H1=> H4.\nrewrite 2!addnS=>/=. \nby rewrite addnS addnC -(addnC 1) addnS addnS addnA /= in H4. \nQed.\n*)\n\n(* Emulating discriminate *)\nLemma one_isnt_zero: 1 <> 0.\nProof.\nmove=>E. \nhave X: if 1 == 0 then True else False by rewrite E; constructor.\nexact X.\nQed.\n\nLemma leqD n m: n <= m -> exists p, m = n + p. \nProof.\nelim: m; first by rewrite leqn0; move/eqP=>->; eexists _.\nmove=> m Hm.\nelim: n m Hm=>//; first by move=>m _ _; exists m.+1. \nmove=> n Hn m Hm. rewrite ltnS leq_eqVlt; case/orP.\n- by move/eqP=>->; exists 0.\nby case/Hm=>p E; subst m; exists p.+1. \nQed", "meta": {"author": "ilyasergey", "repo": "coq-exercises", "sha": "97b610ca2a654b6edd329f3791cab5534ddc1cb2", "save_path": "github-repos/coq/ilyasergey-coq-exercises", "path": "github-repos/coq/ilyasergey-coq-exercises/coq-exercises-97b610ca2a654b6edd329f3791cab5534ddc1cb2/cptd-ssr/cpdt-chapter4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.8118678214605773}}
{"text": "(* Solutions provided by B.Pierce et al, with my \nnote regarding plus_n_O *)\n\nPrint plus_n_O.  (* apparently BUILT IN *)\n\nLemma plus_n_0 : forall n:nat,\n   n+0=n.\nProof.\n   intros. induction n.\n   reflexivity.\n   simpl. rewrite -> IHn. reflexivity.\nQed.\nTheorem plus_n_Sm : forall n m : nat, \n  S (n + m) = n + (S m).\nProof. \n  (* ADMITTED *)\n  intros n m. induction n as [| n'].\n  (* Case \"n = 0\". *)\n    simpl. reflexivity.\n  (* Case \"n = S n'\". *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n(* /ADMITTED *)\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* ADMITTED *)\n  intros n m. induction m as [| m'].\n  (* Case \"m = 0\". *)\n    simpl. (* rewrite -> plus_n_O. *)\n      rewrite -> plus_n_0.  reflexivity.\n  (* Case \"m = S m'\". *)\n    simpl. rewrite <- IHm'. rewrite <- plus_n_Sm.\n    reflexivity.  Qed.\n(* /ADMITTED *)\n\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ADMITTED *)\n  intros n m p. induction n as [| n']. \n  (* Case \"n = 0\". *)\n    reflexivity. \n  (* Case \"n = S n'\". *)\n    simpl. rewrite -> IHn'. reflexivity.   Qed.\n(* /ADMITTED *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  (* ADMITTED *)\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(* /ADMITTED *)\n\nTheorem plus_swap : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.\n  (* ADMITTED *)\n  intros n m p.\n  rewrite -> plus_assoc.\n  assert (H: n + m = m + n).\n    (* Case \"Proof of assertion\". *)\n    rewrite <- plus_comm. reflexivity.\n  rewrite -> H. rewrite -> plus_assoc. reflexivity.  Qed.\n(* /ADMITTED *)\n(* QUIETSOLUTION *)\n\nTheorem mult_m_Sn : forall m n : nat,\n m * (S n) = m + (m * n).\nProof.\n  induction m as [| m'].\n  (* Case \"m = 0\". *)\n    intros n. simpl. reflexivity.\n  (* Case \"m = S m'\". *)\n    intros n.\n    simpl.\n    rewrite -> IHm'.\n    rewrite -> plus_swap.\n    reflexivity.  Qed.\n(* /QUIETSOLUTION *)\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n  (* ADMITTED *)\n  induction m as [| m'].\n  (* Case \"m = 0\". *)\n    intros n. simpl. rewrite mult_0_r. reflexivity.\n  (* Case \"m = S m'\". *)\n    intros n.\n    simpl.\n    rewrite -> mult_m_Sn.\n    rewrite -> IHm'.\n    reflexivity.  Qed.\n(* /ADMITTED *)\n", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/plus_and_mult_comm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8118534121847844}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions\n    ([forall x, P]).\n*)\n\n\n(** In Coq, the type of things that can (potentially)\n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated\n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P].\n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat\n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.\n*)\n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining Propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?\n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other datatype.\n\n    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.\n\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q].\n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" Conjuctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H. apply H1. Qed.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n    Case \"left\". apply HQ.\n    Case \"right\". apply HP.  Qed.\n\n\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  repeat (split; try (assumption)). Qed.\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P.\n  unfold iff.\n  split; intros H; apply H. Qed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  unfold iff.\n  intros P Q R H1 H2.\n  inversion H1 as [PQ QP]. inversion H2 as [QR RQ].\n  split; intros H.\n  Case \"left\". apply QR. apply PQ. apply H.\n  Case \"right\". apply QP. apply RQ. apply H.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\n\n\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H as [[HP | HQ] [HPP | HR]];\n  repeat (try (left; assumption)).\n  right. split; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. unfold iff.\n  split.\n    Case \"left\". apply or_distributes_over_and_1.\n    Case \"right\". apply or_distributes_over_and_2.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b, c; try (left; reflexivity); try (right; reflexivity).\n  Case \"tt\". inversion H. (* contra *)\nQed.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b, c; try (left; reflexivity); try (right; reflexivity).\n  Case \"ff\". inversion H.\nQed.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b, c; inversion H.\n  Case \"ff\". split; reflexivity.\nQed.\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := .\n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := True_.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to\n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q HPQ.\n  unfold not. intros HQ HP.\n  apply HQ. apply HPQ. apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. intros H. inversion H.\n  apply H1. apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H.\n  (* But now what? There is no way to \"invent\" evidence for [~P]\n     from evidence for [P]. *)\n  Abort.\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := forall P:Prop,\n  P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable) *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).\nProof.\n  intros P. unfold not. intros H. apply H. right. intros HP. apply H. left. apply HP.\nQed.\n\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** **** Exercise: 2 stars (false_beq_nat) *)\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof.\n  induction n; intros m H; destruct m.\n    Case \"n = 0\".\n      SCase \"m = 0\". simpl. apply ex_falso_quodlibet. apply H. reflexivity.\n      SCase \"m = Sm\". reflexivity.\n    Case \"n = Sn'\".\n      SCase \"m = 0\". reflexivity.\n      SCase \"m = Sm\". simpl. apply IHn. unfold not. intros H1. apply H. rewrite H1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_false) *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  unfold not.\n  induction n; destruct m; simpl; intros H0 H1; inversion H0; inversion H1.\n  Case \"n=Sn,m=Sm\". rewrite H3 in H2. rewrite <- beq_nat_refl in H2.  inversion H2.\nQed.\n(** [] *)\n\n\n\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n", "meta": {"author": "IgnoredAmbience", "repo": "software-foundations", "sha": "e1e75f8bdfd83979b13f5ce7574659c7925a6cf6", "save_path": "github-repos/coq/IgnoredAmbience-software-foundations", "path": "github-repos/coq/IgnoredAmbience-software-foundations/software-foundations-e1e75f8bdfd83979b13f5ce7574659c7925a6cf6/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.9304582554941719, "lm_q1q2_score": 0.8116828164280074}}
{"text": "Require Export D.\n\n\n\n(** 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 [pal_app_rev] that \n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that \n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X: Type} : list X -> Prop :=\n| pal_nil: pal []\n| pal_sgl: forall (x:X), pal [x]\n| pal_rcs: forall (x:X) (l:list X), pal l -> pal (x::(snoc l x)).\n\nExample test_pal_1: pal [0; 1; 0].\nProof. apply pal_rcs with (x:=0) (l:=[1]). apply pal_sgl. Qed.\n\nTheorem pal_app_rev: forall (X: Type) (l: list X),\n  pal (l ++ rev l).\nProof.\n  intros. induction l.\n  Case \"[]\". simpl. apply pal_nil.\n  Case \"x::l\". simpl. replace (x :: l ++ snoc (rev l) x) with (x :: snoc (l ++ rev l) x). apply pal_rcs. apply IHl.\n    Lemma snoc_app_lem : forall (X:Type) (x:X) l1 l2, snoc (l1 ++ l2) x = l1 ++ snoc l2 x.\n    Proof. intros. induction l1. reflexivity.\n    simpl. rewrite IHl1. reflexivity. Qed.\n  rewrite snoc_app_lem with (l2:=(rev l)). reflexivity.\nQed.\n\nTheorem pal_rev: forall (X: Type) (l: list X),\n  pal l -> l = rev l.\n Proof. intros. induction H.\n  Case \"[]\". reflexivity.\n  Case \"[x]\". reflexivity.\n  Case \"x::l\". simpl.\n    Lemma x_snoc_lem : forall (X:Type) (x y:X) l,\n      x :: snoc l y = snoc (x::l) y.\n    Proof. intros. simpl. reflexivity. Qed.\n    rewrite x_snoc_lem.\n    Lemma snoc_rev_lem : forall (X:Type) (x:X) l,\n       x :: (rev l)  = rev (snoc l x).\n    Proof. intros.  induction l.\n      Case \"[]\". simpl. reflexivity.\n      Case \"x0::l\". simpl. rewrite<-IHl. simpl. reflexivity. Qed.\n    assert (Hrev : x::l = x::(rev l)).\n    Proof.  rewrite<-IHpal. reflexivity.\n    rewrite -> Hrev. rewrite->snoc_rev_lem. reflexivity.\nQed.\n\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/P11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118215, "lm_q2_score": 0.8902942370375485, "lm_q1q2_score": 0.8112180447290693}}
{"text": "Section PropositionalLogic.\n\nVariables A B C : Prop.\n\nDefinition anb1 :\n  A /\\ B -> A\n:= fun pAandB =>\n    match pAandB with\n    | conj pA pB => pA\n    end.\n\nDefinition impl_trans :\n  (A -> B) -> (B -> C) -> A -> C\n:= fun pAB : A -> B => fun pBC : B -> C => fun a : A =>\n    pBC (pAB a).\n\nDefinition HilbertS :\n  (A -> B -> C) -> (A -> B) -> A -> C\n:= fun pABC : A -> B -> C =>\n    fun pAB : A -> B =>\n        fun a : A =>\n            pABC a (pAB a).\n\nDefinition double_negation_introduction :\n    A -> ~ ~ A\n:= fun pa : A => fun pna : ~ A => pna pa. \n\nDefinition DNE_triple_neg :\n  ~ ~ ~ A -> ~ A\n(* (((A -> False) -> False) -> False) -> (A -> False) *)\n:= fun f : ~ ~ ~ A =>\n    fun pA =>\n        f (double_negation_introduction pA).\n\nDefinition or_comm :\n  A \\/ B -> B \\/ A\n:= fun AorB : A \\/ B =>\n    match AorB with\n    | or_introl pA => or_intror pA\n    | or_intror pB => or_introl pB\n    end.\n\nEnd PropositionalLogic.\n\n\n\nSection Quantifiers.\n\nVariable T : Type.\nVariable A : Prop.\nVariable P Q : T -> Prop.\nDefinition forall_conj_comm :\n  (forall x, P x /\\ Q x) <-> (forall x, Q x /\\ P x)\n:= conj\n    (fun allx_PQ => fun x => match allx_PQ x with conj px qx => conj qx px end) \n    (fun allx_QP => fun x => match allx_QP x with conj qx px => conj px qx end). \n\nDefinition forall_disj_comm :\n  (forall x, P x \\/ Q x) <-> (forall x, Q x \\/ P x)\n:= conj\n    (fun allx_PQ =>\n    fun x =>\n        match allx_PQ x with\n        | or_introl px => or_intror px\n        | or_intror qx => or_introl qx\n        end)\n    (fun allx_QP =>\n    fun x =>\n        match allx_QP x with\n        | or_introl qx => or_intror qx\n        | or_intror px => or_introl px\n        end).\nDefinition not_exists_forall_not :\n  ~(exists x, P x) -> forall x, ~P x\n:= fun not_existPx : (exists x, P x) -> False =>\n    fun x => fun px : P x =>\n        not_existPx (ex_intro P x px).\n\nDefinition exists_forall_not_ :\n(exists x, A -> P x) -> (forall x, ~P x) -> ~A\n:= fun exAPx : exists x, A -> P x =>\n    fun allxPx : forall x, ~P x =>\n        fun a : A =>\n            match exAPx with\n            | (ex_intro _ x apx) => (allxPx x) (apx a)\n            end.\n\n(*\n(** Extra exercise (feel free to skip): the dual Frobenius rule *)\nDefinition LEM :=\n  forall P : Prop, P \\/ ~ P.\n\nDefinition Frobenius2 :=\n  forall (A : Type) (P : A -> Prop) (Q : Prop),\n    (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x).\n\nDefinition lem_iff_Frobenius2 :\n  LEM <-> Frobenius2\n:=\n*)\nEnd Quantifiers.\n\n\n\n\n\nSection Equality.\n\n(** exercise: *)\nDefinition f_congr {A B} (f : A -> B) (x y : A) :\n  x = y  ->  f x = f y\n:= fun xy : x = y =>\n    match\n      xy in (_ = b)\n      return (f x = f b)\n    with\n    | eq_refl => eq_refl (f x)\n    end.\n\nDefinition f_congr' A B (f g : A -> B) (x y : A) :\n  f = g  ->  x = y  ->  f x = g y\n:= fun fg : f = g =>\n      match fg in (_ = b)\n        return (x = y -> f x = b y) (* \"return\" specifies type of expression after \"with\" *)\n        with | eq_refl =>\n        (* at this stage we unificate f&g. Now we can use only f *)\n          fun xy : x = y => \n            match xy in (_ = a)\n              return (f x = f a)\n              with | eq_refl => eq_refl (f x) end end.\n(*\n(** extra exercise *)\nDefinition congId A {x y : A} (p : x = y) :\n  f_congr (fun x => x) p = p :=\n*)\n(* exercise *)\nDefinition pair_inj A B (a1 a2 : A) (b1 b2 : B) :\n  (a1, b1) = (a2, b2) -> (a1 = a2) /\\ (b1 = b2)\n:= fun a1b1a2b2 : (a1, b1) = (a2, b2) =>\n    match a1b1a2b2 in (_ = (aa, bb))\n      return (a1 = aa) /\\ (b1 = bb)\n      with | eq_refl =>\n      conj (eq_refl a1) (eq_refl b1) \n      end.\n\nEnd Equality.\n\n\n\nSection ExtensionalEqualityAndComposition.\n\nVariables A B C D : Type.\n\n(** Exercise 2a *)\n(** [\\o] is a notation for function composition in MathComp, prove that it's associative *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool.\n(*\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x : A => g (f x).\n\nNotation \" g \\o f \" := (compose g f)\n  (at level 40, left associativity) : type_scope.\n*)\nDefinition compA (f : A -> B) (g : B -> C) (h : C -> D) :\n  (h \\o g) \\o f = h \\o (g \\o f)\n:= eq_refl (fun x => h (g (f x))).\n\n\n(** [=1] stands for extensional equality on unary functions,\n    i.e. [f =1 g] means [forall x, f x = g x].\n    This means it's an equivalence relation, i.e. it's reflexive, symmetric and transitive.\n    Let us prove a number of facts about [=1]. *)\n\n(** Exercise: Reflexivity *)\nDefinition eqext_refl :\n  forall (f : A -> B), f =1 f\n:= fun f => fun x => eq_refl (f x).\n\n(** Exercise: Symmetry *)\nDefinition eqext_sym :\n  forall (f g : A -> B), f =1 g -> g =1 f\n:= fun f => fun g => fun pfg : f =1 g =>\n    fun x => match pfg x in (_ = h) return (h = f x) with\n    | eq_refl => eq_refl (f x) end.\n\n(** Exercise: Transitivity *)\nDefinition eqext_trans :\n  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h\n:= fun f => fun g => fun h =>\n    fun fg : f =1 g =>\n      fun gh : g =1 h =>\n        fun x =>\n          (* first - we eat fx, only g x exists after this step *)\n          match ((eqext_sym f g fg) x) : (g x = f x) in (_ = a) return (a = h x) with | eq_refl =>\n          (* now we eat hx, only g x still exists *)\n          match                 (gh x) : (g x = h x) in (_ = b) return (g x = b) with | eq_refl =>\n              eq_refl (g x)\n          end end.\n\n(** Exercise: left congruence *)\nDefinition eq_compl :\n  forall (f g : A -> B) (h : B -> C),\n    f =1 g -> h \\o f =1 h \\o g\n:= fun f => fun g => fun h => fun fg1_proof =>\n  fun x => match fg1_proof x in (_ = gx) return (h \\o f) x = (h gx)\n  with | eq_refl => eq_refl (h (f x)) end.\n\n(** Exercise: right congruence *)\nDefinition eq_compr :\n  forall (f g : B -> C) (h : A -> B),\n    f =1 g -> f \\o h =1 g \\o h\n:= fun f => fun g => fun h => fun fg1_proof =>\n    fun x => match fg1_proof (h x) in (_ = ghx) return (f \\o h) x = ghx\n    with | eq_refl => eq_refl (f (h x)) end.\n\nEnd ExtensionalEqualityAndComposition.\n\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype.\n\n(* After importing `eqtype` you need to either use a qualified name for\n`eq_refl`: `Logic.eq_refl`, or use the `erefl` notation.\nThis is because `eqtype` reuses the `eq_refl` identifier for a\ndifferent lemma.\n *)\n\nDefinition iff_is_if_and_only_if :\n  forall a b : bool, (a ==> b) && (b ==> a) = (a == b)\n:= fun a => fun b => \n\nDefinition negbNE :\n  forall b : bool, ~~ ~~ b = true -> b = true\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/seminar02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8110288516164439}}
{"text": "\nRequire Export Basics.\n\nTheorem plus_n_O : forall n : nat,\n  n = n + 0.\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n : nat,\n  n * 0 = 0.\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity. Qed.\n\n\nTheorem plus_n_Sm : forall n m : nat,\nS (n + m) = n + (S m).\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity. Qed.\n\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [|n' IHn'].\n  - induction m as [|m' IHm'].\n    + reflexivity.\n    + simpl. rewrite <- IHm'. simpl. reflexivity.\n  - induction m as [|m' IHm'].\n    + simpl. rewrite IHn'. simpl. reflexivity.\n    + simpl. rewrite IHn'. simpl. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\nn + (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. Qed.\n\nFixpoint double (n:nat) :=\nmatch n with\n| O => O\n| S n' => S (S (double n' ))\nend.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. rewrite plus_n_Sm. reflexivity. Qed.\n\n\n(* Fixpoint evenb (n:nat) : bool := *)\n(*   match n with *)\n(*     | O => true *)\n(*     | S O => false *)\n(*     | S (S m) => evenb m *)\n(*   end. *)\n\n(* Theorem evenb_S : forall n : nat, *)\n(*   evenb (S n) = negb (evenb n). *)\n(* Proof. *)\n(*   induction n as [|n' IHn']. *)\n(*   - simpl. reflexivity. *)\n(*   - induction n' as [| n'']. *)\n\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H : n + m = m + n).\n    { rewrite -> plus_comm. reflexivity. }\n    rewrite -> H. reflexivity. Qed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite plus_assoc.\n  assert (H : n + m = m + n).\n         { rewrite plus_comm. reflexivity. }\n         rewrite H. rewrite plus_assoc. reflexivity. Qed.\n\n\nTheorem mult_Sm_n : forall m n : nat,\n        S m * n = n * m + n.\nProof.\n  intros m n.\n  induction n as [|n' IHn'].\n  - simpl. rewrite <- mult_n_O. reflexivity.\n  - rewrite <- mult_n_Sm.\n    rewrite <- plus_n_Sm.\n    rewrite IHn'. simpl.\n    rewrite <- plus_n_Sm.\n    assert (H : m + (n' * m) + n' = (n' * m) + n' + m).\n    { rewrite plus_comm.\n      rewrite plus_assoc.\n      rewrite plus_comm.\n      rewrite plus_assoc.\n      reflexivity. }\n    rewrite H.\n    reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m as [|m' IHm'].\n  - rewrite mult_0_l. rewrite mult_0_r. reflexivity.\n  - rewrite <- mult_n_Sm. rewrite mult_Sm_n. reflexivity. Qed.\n\n(* bin to nat pres incr  *)\n\nTheorem bin_to_nat_pres_incr : forall m : bin,\n    bin_to_nat (incr m) = bin_to_nat m + 1.\nProof.\n  induction m as [|dm IHdm|sdm IHsdm].\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. repeat (rewrite <- plus_n_O).\n    rewrite IHsdm.\n    symmetry.\n    rewrite <- plus_assoc.\n    rewrite <- plus_assoc.\n    rewrite <- plus_assoc.\n    rewrite plus_Sn_m. simpl.\n    rewrite plus_n_Sm. reflexivity.\nQed.", "meta": {"author": "robkorn", "repo": "coq-software-foundations", "sha": "95522c89a964ee00b68cb0e1f7f1600943a95936", "save_path": "github-repos/coq/robkorn-coq-software-foundations", "path": "github-repos/coq/robkorn-coq-software-foundations/coq-software-foundations-95522c89a964ee00b68cb0e1f7f1600943a95936/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.810989691875529}}
{"text": "Require Import Bool.\nRequire Import Setoid.\nRequire Import Ring.\nRequire Import Field.\nRequire Coq.Program.Tactics.\nRequire Import ssreflect ssrfun ssrbool.\n\n\n(** We start by defining a Monoid *)\n\nClass Monoid (A:Set)(dot : A -> A -> A)(one : A)(bool_eq : A-> A-> bool) := {\n\n    dot_assoc : forall x y z : A, dot x (dot y z) = dot (dot x y) z;\n    one_left : forall x : A, dot one x = x;\n    one_right : forall x : A, dot x one = x;\n\n    (** The set equality should be boolean decidable\n        pretty sure ssreflect provides a better way to do this *)\n\n    bool_eq_corr: forall a b : A, bool_eq a b = true <-> a=b;\n    bool_neq_corr: forall a b : A, bool_eq a b = false <-> a <> b;\n}.\n\n(** We now extend Monoids to various types of groups *)\n\nClass Group (A:Set)(dot : A -> A -> A) (one : A) (bool_eq : A-> A-> bool) (inv : A -> A) := {\n  grp_mon :> Monoid A dot one bool_eq;\n  inv_left: forall x : A, one =  dot (inv x) x;\n  inv_right: forall x : A, one =  dot x (inv x);\n}.\n\nClass AbeGroup (A:Set)(dot : A -> A -> A) (one : A) (bool_eq : A-> A-> bool) (inv : A -> A) := {\n  abegrp_grp :> Group A dot one bool_eq inv;\n  comm : forall a b : A, dot a b = dot b a;\n}.\n\nSection AdditionalGroupProperties. \n\nGeneralizable Variables A dot Aone Ainv bool_equal.\nContext `{AbeGroup A dot Aone bool_equal Ainv}.\n\nDefinition abegop `{AbeGroup A dot Aone bool_equal Ainv} := dot.\nDefinition abegone `{AbeGroup A dot Aone bool_equal Ainv} := Aone.\n\nInfix \"*\" := abegop.\nNotation \"1\" := Aone.\n\nNotation \"- x\" :=  (Ainv x).\n\n(** The next three Lemmas simply following proofs *)\n\nLemma comm_inv : forall a b c x :A,\n  a * x * b * -x * c = a * b * c.\nProof. \n  intros. replace (a * x * b) with (a * (x * b)).  replace (x * b) with (b * x).\n  rewrite dot_assoc. replace (a * b * x * - x * c) with (a * b * (x * -x * c)).\n  rewrite <- inv_right. replace (1 * c) with c. trivial. rewrite one_left.\n  trivial. rewrite dot_assoc. rewrite dot_assoc. trivial. apply comm. apply dot_assoc.\nQed.\n\nLemma comm_inv_wa : forall b c x :A,\n  x * b * -x * c =  b * c.\nProof. \n  intros. replace (x * b * - x * c) with (1 * (x * b * - x * c)).\n  replace (b * c) with (1 * (b * c)). rewrite dot_assoc. rewrite dot_assoc. rewrite dot_assoc.\n  rewrite dot_assoc. apply comm_inv. apply one_left. apply one_left.\nQed.\n\nLemma comm_inv_wc : forall a b x :A,\n  a * x * b * - x = a * b.\nProof. \n  intros. replace (a * x * b * - x ) with (a * x * b * - x * 1).\n  replace (a * b) with (a * b * 1). apply comm_inv. apply one_right.\n  apply one_right.\nQed.\n\nLemma left_cancel : forall x y z:A,\n (x * y = x * z) <-> (y = z).\nProof.\n  intros. unfold iff. refine (conj _ _). \n  (*Case 1 *)\n  intros. assert (- x * (x * y) = - x * (x * z)). rewrite H0. trivial.\n  rewrite dot_assoc in H1. rewrite dot_assoc in H1. replace (- x * x) with 1 in H1.\n  rewrite one_left in H1. rewrite one_left in H1. apply H1. apply inv_left.\n  (*Case 2 *)\n  intros.  rewrite H0. trivial.\nQed.\n  \nLemma left_cancel_neq : forall x y z:A,\n (x * y <> x * z) <-> (y <> z).\nProof.\n  intros. unfold iff. refine (conj _ _). \n  (*Case 1 *)\n  intros. unfold not. intros. rewrite H1 in H0. apply H0. trivial. \n  (*Case 2 *)\n  intros. unfold not in *. intros. apply left_cancel in H1.  rewrite H1 in H0. apply H0. trivial.\nQed.\n\nLemma right_cancel :  forall x y z:A,\n (y * x = z * x) <-> (y = z).\nProof.\n  intros. unfold iff. refine (conj _ _). \n  (*Case 1 *)\n  intros. assert (((y * x) * -x ) = ((z * x) * -x)). rewrite H0. trivial.\n  replace (y * x * - x) with (y * (x * - x)) in H1. replace (z * x * - x) with (z * (x * - x)) in H1.\n  replace (x * -x) with 1 in H1. rewrite one_right in H1.\n  rewrite one_right in H1. apply H1. apply inv_right.\n  apply dot_assoc. apply dot_assoc.\n  (*Case 2 *)\n  intros.  rewrite H0. trivial.\nQed.\n\nLemma comm_inv_wb : forall a c x :A,\n  a * x * -x * c = a * c.\nProof. \n  intros. apply right_cancel. rewrite <- dot_assoc. rewrite <- inv_right.\n  rewrite one_right. trivial.\nQed.\n\nLemma comm_inv_wac : forall b x :A,\n  x * b *  -x  = b.\nProof. \n  intros. rewrite <- dot_assoc. replace (b * -x) with (-x * b) by apply comm.\n  rewrite dot_assoc. rewrite <- one_right. symmetry. rewrite comm.\n  apply right_cancel. apply inv_right.\nQed.\n\n\nLemma eqImplProd:\n  forall a b c d : A,\n  a = b /\\ c = d -> a * c = b * d.\nProof.\n  intros. destruct H0. rewrite H0. rewrite H1. trivial.\nQed.\n\nLemma dob_neg : forall a : A,\n  a = - - a.\nProof.\n  intros. apply right_cancel with (x:= -a).\n  rewrite <- inv_left. symmetry. apply inv_right.\nQed.\n\nLemma minus_one : forall a : A,\n  a = a * (Ainv 1).\nProof.\n  intros. apply right_cancel with (x:=1).\n  rewrite one_right. rewrite <- dot_assoc. rewrite <- inv_left.\n  rewrite one_right. trivial.\nQed.\n\nLemma inv_dist : forall a b : A,\n  -a * -b = -(a * b).\nProof.\n  intros. assert (a * b * -a * -b = a * b * -(a*b)).\n  rewrite comm_inv_wa. rewrite <- inv_right. rewrite <- inv_right. \n  trivial. apply left_cancel with (x := a * b).\n  rewrite dot_assoc. apply H0.\nQed. \n\nLemma inv_dist2 : forall a b : A,\n  - a * b = - (a * - b).\nProof.\n  intros. remember (-b) as c.\n  rewrite <- inv_dist. rewrite Heqc.\n  simpl. rewrite <- dob_neg. trivial.\nQed.\n\nLemma b_equal : forall a b c : A,\n  (a = b * c) <-> (a * - c = b).\nProof.\n  intros.\n  intros. unfold iff. refine (conj _ _).   \n  (* case 1 *)\n  intros. rewrite H0. rewrite <- dot_assoc.\n  rewrite <- inv_right. rewrite one_right. trivial.\n  (* case 2 *)\n  intros. symmetry in H0. rewrite H0. rewrite <- dot_assoc.\n  rewrite <- inv_left. rewrite one_right. trivial.\nQed.\n\n\nLemma double_chall :  forall (c a : A),\n  c * - (c * - a) = a.\nProof.\n  intros. replace (- (c * - a)) with (-c * a).\n  replace (c * (- c * a)) with (c * -c * a).\n  rewrite <- inv_right. rewrite one_left. trivial.\n  rewrite dot_assoc. trivial. apply inv_dist2.\nQed.\n\nLemma bool_true : forall (c : A),\n   (bool_equal c c) = false  -> False.\nProof.\n  intros. assert (c <> c).\n  apply bool_neq_corr. apply H0. assert False.\n  apply H1. trivial. congruence.\nQed.\n\nLemma chall_dist : forall (c1 c2 e1 e2 e3 e4 : A),\n  bool_equal c1 c2 = false ->\n  c1 = e1 * e2 ->\n  c2 = e3 * e4 ->\n   bool_equal e1 e3 = false \\/\n   bool_equal e2 e4 = false.\nProof.\n  intros. case_eq (bool_equal e1 e3).\n  (* Case 1 *)  intros. right. apply bool_neq_corr in H0. apply bool_neq_corr.\n  apply bool_eq_corr in H3. rewrite H3 in H1. rewrite H2 in H0. rewrite H1 in H0.\n  apply left_cancel_neq in H0. apply H0.\n  (* Case 2 *)\n  intros. left. trivial.\nQed.\n\nLemma zero2 : forall (a b : A),\n  a <> b ->\n  a * - b <> 1.\nProof.\n  intros. unfold not. replace 1 with (b * - b).  \n  intros. apply right_cancel in H1.\n  rewrite H1 in H0. apply H0. trivial. rewrite <- inv_right.\n  trivial.\nQed. \n\nLemma inv_not_equal_zero : forall (a b :A),\n  a <> 1 ->\n  - a <> 1.\nProof.\n  intros. unfold not in *. intros. \n  apply left_cancel with (x:= a) in H1.\n  rewrite <- inv_right in H1. rewrite one_right in H1.\n  symmetry in H1. apply H0 in H1. apply H1.\nQed.\n\nLemma commHack :\n  forall a b c d : A,\n   (a * b) * (c * d) = \n    (a * c) * (b * d).\nProof.\n  intros. do 2 rewrite <- dot_assoc. apply left_cancel.\n  do 2 rewrite dot_assoc. apply right_cancel. apply comm.\nQed.\n\nLemma commHackEq :\n  forall a b c d : A,\n  a * b = c * d <-> a * - c = d * -b.\nProof.\n  intros. unfold iff. refine (conj _ _).   \n  (* part 1 *)\n  intros. apply b_equal. rewrite <- dob_neg.\n  rewrite comm. rewrite dot_assoc. symmetry. \n  apply b_equal. rewrite <- dob_neg. symmetry.\n  rewrite comm. rewrite H0. apply comm.\n  (* part 2 *) \n  intros. apply b_equal in H0. rewrite comm in H0. \n  rewrite dot_assoc in H0. symmetry in H0. apply b_equal in H0.\n  symmetry in H0. apply H0.\nQed.\n\n\nLemma field_additive_abegrp (F:Set)(Fadd : F -> F -> F) (Fzero : F) \n  (Fbool_eq : F-> F-> bool) (Fsub : F -> F -> F)(Finv : F -> F)\n  (Fmul : F -> F -> F) (Fone : F)(FmulInv : F -> F)(Fdiv : F-> F-> F) :\n  field_theory Fzero Fone Fadd Fmul Fsub Finv Fdiv FmulInv (@eq F) ->\n  (forall a b : F, Fbool_eq a b = true <-> a=b) ->\n  (forall a b : F, Fbool_eq a b = false <-> a <> b) ->\n  AbeGroup F Fadd Fzero Fbool_eq Finv.\nProof.\n  intros. constructor. constructor. constructor. \n  intros; rewrite (Radd_assoc (rO := Fzero)); trivial; apply H0.\n  intros; rewrite (Radd_0_l); trivial; apply H0.\n  intros. rewrite (Radd_comm). rewrite (Radd_0_l). trivial. apply H0. apply H0.\n  apply H1. apply H2. intros. rewrite (Radd_comm). rewrite (Ropp_def). trivial.\n  apply H0. apply H0.\n  intros. rewrite (Ropp_def). trivial. apply H0. intros. rewrite (Radd_comm). trivial. apply H0.\nQed. \n\nEnd AdditionalGroupProperties.\n\n(* We define a group as a module here *)\n\nModule Type GroupSig.\n  Parameter G : Set.\n  Parameter Gdot : G -> G -> G.\n  Parameter Gone : G.\n  Parameter Gbool_eq : G-> G-> bool.\n  Parameter Ginv : G -> G.\n\n  Axiom module_abegrp : AbeGroup G Gdot Gone Gbool_eq Ginv.\n\n  Infix \"o\" := Gdot (at level 50) .\n  Notation \"- x\" := (Ginv x).\nEnd GroupSig.\n\n\n", "meta": {"author": "gerlion", "repo": "Exponentially-Secure-Cut-and-Choose", "sha": "19a40efc220833fcc7ec3d238c616f64590e9e2f", "save_path": "github-repos/coq/gerlion-Exponentially-Secure-Cut-and-Choose", "path": "github-repos/coq/gerlion-Exponentially-Secure-Cut-and-Choose/Exponentially-Secure-Cut-and-Choose-19a40efc220833fcc7ec3d238c616f64590e9e2f/Groups/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8109129953725808}}
{"text": "(*Taller 1 L\u00f3gica Computacional*)\n(*Autor: Guido Salazar*)\n\n(*Variables auxiliares*)\n\nDefinition cons1 := 5.\n\n(*Punto 1*)\n\n(*Funcion que me devuelve el cuadrado de un numero*)\nDefinition cuadrado (n : nat) := n*n.\n\n(*Funcion que me devuelve el cubo de un numero*)\nDefinition cubo (n : nat) := n*n*n.\n\nCompute cubo 5.\nCompute cuadrado 5.\n\n(*Punto 2*)\n\n(*Funcion que me devuelve el cuadrado de de un numero sumado a una constante*)\nDefinition punto2 (n: nat) := cuadrado (n + cons1).\n\nCompute punto2 0.\n\n(*Punto 3*)\n\n(*Funcion que me devuelve la suma de los cubos de dos numeros*)\nDefinition punto3 (n1 n2: nat) := (cubo n1) + (cubo n2).\n\nCompute punto3 2 3.\n\n(*Punto 4*)\n\n(*Funcion que me devuelve la suma y el producto de los cuatro numeros*)\nDefinition punto4 (n1 n2 n3 n4: nat) := (n1+n2+n3+n4, n1*n2*n3*n4).\n\nCompute punto4 1 2 3 4.\n\n(*Punto 5*)\n\nCompute Nat.leb 8 7.\nCompute Nat.leb 6 7.\nCompute Nat.leb 7 7.\n(*La funci\u00f3n Nat.double recibe un numero Nat y me devuelve el dobre de ese numero*)\n(*La funci\u00f3n Nat.div2 recibe un numero Nat y devuelve la mitad del numero con la forma floor(n/2)*)\n(*La funci\u00f3n Nat.leb recibe dos numero y me devuelve un balor booleano. 0 en caso de que el primer numero sea mayor que el segundo y 1 en caso contario.\n  Es decir, la funci\u00f3n leb representa x1 <= x2.*)\n\nPrint Nat.double.\nPrint Nat.div2.\nPrint Nat.leb.\n\n(*Punto 6*)\n\n(*Funcion que recibe un numero y me dice si el numero es par o impar*)\nDefinition esPar (n : nat) : bool := \n  Nat.leb (Nat.div2 (n + 1)) (Nat.div2 n).\n\nCompute esPar 8.\nCompute esPar 9.\n\n(*Punto 7*)\n\nDefinition iter2p (f : (nat*nat) -> (nat*nat)) (p : nat*nat) := f (f p).\n\nCompute (iter2p (fun p => (snd p, fst p)) (1, 2),\niter2p (fun p => (fst p + 1, snd p + fst p + 1)) (0,0)).\n\n\n(*Punto 8*)\n\nDefinition componerFunc (f : nat -> nat) (g : (nat -> nat) -> (nat -> nat)) : nat -> nat :=\n g f.\n\nCompute componerFunc (fun a => a + 2) (fun f => f).\n\nPrint componerFunc.\n\n(*Punto 9*)\n\n(*Funcion que recibe una parejar de numeros y me devuelve la suma*)\nDefinition sumaParejas (p : nat*nat) : nat :=\n  (fst p) + (snd p).\n\nCompute sumaParejas (5, 4).\n\n(*Punto 10*)\n\n(*Funcion que recibe una terna de numeros y me devuelve la suma*)\nDefinition sumaTernas (p : nat*nat*nat) : nat :=\n  (cubo (fst (fst p))) + (cubo (snd (fst p))) + (cubo (snd p)).\n\nCompute sumaTernas (1, 2, 3).\n\n(*Punto 11*)\n\n(*Funcion que recibe un numero y me devuelve el doble del numero si es par o n + 1 si es impar*)\nDefinition punto11 (n : nat) : nat :=\n  match (esPar n) with\n  | true => n + n\n  | false => n + 1\n  end.\n\nCompute punto11 6.\nCompute punto11 7.\n\n(*Punto 12*)\n\n(*Funcion que recibe una pareja y me una pareja con la suma y el producto*)\nDefinition punto12 (p : nat*nat) : nat*nat :=\n  ((fst p) + (snd p), (fst p) * (snd p)).\n\nCompute punto12 (3, 5).\n\n(*Punto 13*)\n\nDefinition punto13 (f : nat -> nat -> nat) (g : nat -> nat) (p : nat*nat) : nat*nat :=\n  (g (fst p), f (snd p) (fst p)).\n\nCompute punto13 punto3 cuadrado  (3, 4). \n\n(*Punto 14*)\n\nDefinition punto14 (f : nat -> nat) (p : nat*nat) : nat :=\n  match (Nat.leb (snd p) (fst p)) with\n  | true => f ((fst p) - (snd p))\n  | false => f ((snd p) + 1)\n  end.\n\nCompute punto14 (fun x => x) (4, 5).\nCompute punto14 (fun x => x) (5, 4).\n\n(*Punto 15*)\n\nInductive LP : Set := \n  |p : LP\n  |q : LP\n  |r : LP.\n\n\n\n\n\n\n", "meta": {"author": "GAOV13", "repo": "Logica-Computacional", "sha": "384ef4fac3f9a02a16f0655f95e16215c41e6cc3", "save_path": "github-repos/coq/GAOV13-Logica-Computacional", "path": "github-repos/coq/GAOV13-Logica-Computacional/Logica-Computacional-384ef4fac3f9a02a16f0655f95e16215c41e6cc3/Taller 1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.8108973554267541}}
{"text": "Require Import Arith.\n\nFixpoint exp2 (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S p => 2 * exp2 p\n  end.\n\n(** Tests: *)\n\nLemma test: exp2 5 = 32.\nProof. reflexivity. Qed.\n\n\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch6_inductive_data/SRC/two_power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.810794912096686}}
{"text": "(** * Prop: Propositions and Evidence *)\n\n(*Require Export Logic.\n*)\n(* ####################################################### *)\n(** * Inductively Defined 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\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 even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  \n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nFixpoint double (n:nat) : nat :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros. induction n.\n  simpl. apply ev_0.\n  simpl. apply ev_SS. apply IHn.\nQed.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    intros. simpl. apply b_sum with (m:=n+0).\n    apply H.\n    rewrite <- plus_n_O. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  induction n. intros. rewrite <- mult_n_O. apply H.\n  induction m. intros. simpl.  apply b_0. \n  intros. simpl. rewrite <- plus_Sn_m.\n  apply b_sum. apply H. apply IHm. apply H.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n   intros. apply g_plus3. apply g_plus5. apply g_plus5. apply H.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   (*Case \"n = O\"*)apply b_0.\n   (*Case \"n = S n'\".*) (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\n\n(** **** Exercise: 2 stars (gorgeous_sum)  *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n intros. induction H. \n simpl. apply H0. revert IHgorgeous. apply g_plus3.\n revert IHgorgeous. apply g_plus5.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous)  *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n intros. induction H. apply g_0. apply g_plus3. apply g_0. apply g_plus5.\n apply g_0. revert IHbeautiful1 IHbeautiful2. apply gorgeous_sum.\nQed.\n(** [] *)\n\n\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros. induction n as [| n'].\n  (*Case \"n = 0\".*)\n    simpl. \n    induction m as [| m'].\n    (*Case \"m = 0\".*)\n      simpl. reflexivity.\n    (*Case \"m = S m'\".*)\n      simpl. rewrite <- IHm'. reflexivity.\n  (*Case \"n = S n'\".*) \n    simpl. rewrite -> IHn'. \n    rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [| n'].\n  (*Case \"n = 0\".*)\n  simpl. reflexivity.\n \n  (*Case \"n = S n'\".*)\n  simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n   intros. induction x. simpl. rewrite <- plus_n_O. reflexivity.\n   rewrite <- plus_n_Sm. simpl. apply f_equal. apply IHx. \nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H. \n   simpl. apply g_0.\n   rewrite helper_g_times2. rewrite helper_g_times2. rewrite helper_g_times2.\n   simpl. apply g_plus3. apply g_plus3. rewrite <- helper_g_times2. apply IHgorgeous. \n   rewrite helper_g_times2. rewrite helper_g_times2. rewrite helper_g_times2.\n   simpl. apply g_plus5. apply g_plus5. rewrite <- helper_g_times2. apply IHgorgeous. \nQed.\n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *) \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(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  intros. induction H.\n  simpl. apply H0.\n  simpl. apply ev_SS. apply IHev.\nQed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we \n   can _look_ at that evidence for more information. For example, consider \n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead \n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)). \nProof.\n  intros n E. inversion E as [| n' E'].\n  (*Case \"E = ev_0\".*) simpl. apply ev_0. \n  (*Case \"E = ev_SS n' E'\".*) simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice)  *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n\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. inversion H. inversion H1. inversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros. induction H0. simpl in H. apply H. \n  apply IHev. simpl in H. inversion H. apply H2.\nQed. \n  \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. *)\nLemma double_plus : forall n, double n = n + n .\nProof.  \n  intros. induction n as [| n'].\n  simpl. reflexivity.\n \n  simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros. revert H0. apply ev_ev__ev.\n  rewrite <- plus_assoc. rewrite (plus_comm p (m + p)).\n  rewrite <- plus_assoc.\n  rewrite plus_assoc.\n  apply ev_sum.  apply H.\n  rewrite <- double_plus.\n  apply double_even.\nQed.\n\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However, \n   we can define inductive predicates about any type of data. For example, \n   suppose we would like to characterize lists of _even_ length. We can \n   do that with the following definition.  *)\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof. \n    intros X l H. induction H.\n    (*Case \"el_nil\".*) simpl. apply ev_0.\n    (*Case \"el_cc\".*)  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H. \n  induction H.\n  (*Case \"ev_0\".*) intros l H. destruct l.\n    (*SCase \"[]\".*) apply el_nil. \n    (*SCase \"x::l\".*) inversion H.\n  (*Case \"ev_SS\".*) intros l H2. destruct l. \n    (*SCase \"[]\".*) inversion H2. destruct l.\n    (*SCase \"[x]\".*) inversion H2.\n    (*SCase \"x :: x0 :: l\".*) apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n    \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*)\nFixpoint snoc {X:Type} (l:list X) (v:X) : (list X) :=\n  match l with\n  | nil      => cons v (nil)\n  | cons h t => cons h (snoc t v)\n  end.\n\nFixpoint 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 => snoc (rev t) h\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nInductive pal {X:Type} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_x :  forall x, pal [x]\n  | pal_xx :  forall x l, pal l -> pal (x :: snoc l x).\n\nLemma 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))%list.\nProof.\n  intros. induction l1 as [|n l1'].\n  (*l1=nil*)\n  simpl. reflexivity.\n  (*l1=n l1'*)\n  simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nLemma pal_xx_apply : forall (X:Type) (l:list X) (x:X), \n  pal (l ++ rev l) -> pal (x :: (l ++ snoc (rev l) x)%list).\nProof. \n  intros. rewrite <- snoc_with_append. apply pal_xx.\n  apply H.\nQed.\n\nTheorem pal_app_rev: forall (X: Type) (l: list X),\n  pal (l ++ rev l).\nProof.\n  intros. induction l. \n  simpl. apply pal_nil.\n  simpl. apply pal_xx_apply. apply IHl.\nQed.\n\nLemma snoc_rev : forall (X : Type) (l : list X) (n : X),\n  rev(snoc l n) = n :: (rev l).\nProof.\n  intros. induction l as [|m l'].\n  (*l=nil*)\n  simpl. reflexivity.\n  (*l=m l'*)\n  simpl. rewrite -> IHl'. \n  simpl. reflexivity.\nQed.\n\nTheorem pal_rev: forall (X: Type) (l: list X),\n  pal l -> l = rev l.\nProof.\n  intros. induction H.\n  reflexivity.\n  reflexivity.\n  simpl. rewrite snoc_rev. \n  rewrite <- IHpal. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n*)\n(*\nTheorem rev_pal : forall (X: Type) (l: list X),\n  l = rev l -> pal l.\nProof.\n\nQed.\n*)\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros. induction H0. apply H. apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n. apply le_n. apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  intros. induction H. apply le_n. apply le_S. apply IHle.\nQed.\n\n\nLemma le_succ : forall n m,\n  S n <= m -> n <= m.\nProof.\n  intros. assert(H0: n <= S n).\n  apply le_S. apply le_n.\n  apply le_trans with (m:=n) (n:=S n) (o:=m).\n  apply H0. apply H.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros. inversion H.\n  apply le_n. apply le_succ. apply H1.\nQed. \n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  intros. induction b. \n  rewrite <- plus_n_O. apply le_n.\n  rewrite <- plus_n_Sm. apply le_S. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n  unfold lt. \n  intros. split. induction H.\n  rewrite <- plus_Sn_m. apply le_plus_l.\n  apply le_S. apply IHle.\n  induction H.\n  rewrite plus_n_Sm. rewrite plus_comm. apply le_plus_l.\n  apply le_S. apply IHle.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply le_S. apply H.\nQed.\n\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 ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  induction n as [| n'].\n  intros. apply O_le_n.\n  destruct m as [| m'].\n  intros. inversion H.\n  intros.\n  apply n_le_m__Sn_le_Sm.\n  apply IHn'. simpl in H. apply H.\nQed.\n\nLemma ble_nat_refl : forall n,\n  ble_nat n n = true.\nProof.\n  intros. induction n as [| n'].\n  reflexivity.\n  simpl. apply IHn'.\nQed.\n\nLemma ble_nat_succ : forall n m,\n  ble_nat n m = true -> ble_nat n (S m) = true.\nProof.\n  induction n. reflexivity.\n  intros. destruct m.\n  inversion H.\n  simpl. apply IHn. simpl in H. apply H.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  induction m.\n  intros. inversion H. reflexivity.\n  intros. inversion H. apply ble_nat_refl.\n  destruct n. reflexivity.\n  subst. apply ble_nat_succ. apply IHm. apply H1.\nQed.  \n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                               \nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  intros. apply ble_nat_true in H. apply ble_nat_true in H0.\n  apply le_ble_nat. apply le_trans with (m:=n) (n:=m). \n  apply H. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros. unfold not. intros.\n  apply le_ble_nat in H0.\n  rewrite H in H0. inversion H0.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n(** **** 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 [subseq_refl] that subsequence is reflexive, that is, \n      any list is a subsequence of itself.  \n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3], \n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is \n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2] \n      is a subsequence of [l3], then [l1] is a subsequence of [l3].  \n      Hint: choose your induction carefully!\n*)\n\n(* FILL IN HERE *)\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(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n(* \nFixpoint true_upto_n__true_everywhere\n(* FILL IN HERE *)\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n*)\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n\n\n", "meta": {"author": "Sooram", "repo": "Software-Foundations", "sha": "9c668f5c8395919645406855cdc78a214afdafd1", "save_path": "github-repos/coq/Sooram-Software-Foundations", "path": "github-repos/coq/Sooram-Software-Foundations/Software-Foundations-9c668f5c8395919645406855cdc78a214afdafd1/7. Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.9046505331728752, "lm_q1q2_score": 0.8107942925899922}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export exercise7.\n\n(** **** Exercise: 2 stars, standard (eight_is_even) *)\n(* Give a tactic proof and a proof object showing that ev 8. *)\nTheorem ev_8 : ev 8.\nProof.\n  repeat apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : ev 8 := ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n\nDefinition add1 : nat -> nat.\n  intros n.\n  apply S.\n  apply n.  Defined.\n\n(** **** Exercise: 2 stars, standard (conj_fact) *)\n(* Construct a proof object for the following proposition. *)\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) (H1: P /\\ Q) (H2: Q /\\ R) =>\n    match H1, H2 with\n    | conj p q, conj q' r => conj p r\n    end.\n\n(** **** Exercise: 2 stars, standard (or_commut') *)\n(* Construct a proof object for the following proposition. *)\nDefinition or_commut: forall P Q, P \\/ Q -> Q \\/ P :=\n  fun (P Q : Prop) (H: P \\/ Q) =>\n    match H with\n    | or_introl p => or_intror p (* Extract and then apply reversely. *)\n    | or_intror q => or_introl q\n    end.\n\n(* Inductive ex {A : Type} (P : A \u2192 Prop) : Prop :=\n  | ex_intro : \u2200 x : A, P x \u2192 ex P.\n  \n  First, ex_intro (P) will introduce a universal quantifier forall x : Type, P(x)\n  so that we need to find the specific value for proving P(x).\n\n  Then we fill the value and the evidence.\n\n  *)\n\n(** **** Exercise: 2 stars, standard (ex_ev_Sn) *)\n(* Construct a proof object for the following proposition. *)\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  (* Prop + existential value + evidence. *)\n  ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n\n(** **** Exercise: 1 star, standard (p_implies_true)\nConstruct a proof object for the following proposition. *)\nDefinition p_implies_true : forall P, P -> True :=\n  fun P H => I.\n\n(** **** Exercise: 1 star, standard (ex_falso_quodlibet') *)\n(* Construct a proof object for the following proposition. *)\nDefinition ex_falso_quodlibet' : forall P, False -> P :=\n  fun P H => match H with end.\n\nModule EqualityPlayground.\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\nDefinition singleton : forall (X : Type) (x : X), [ ] ++ [x] == x :: [ ] :=\n  fun (X : Type) (x : X) => eq_refl [x].\n\nDefinition eq_add : forall (n1 n2 : nat), n1 == n2 -> (S n1) == (S n2) :=\nfun n1 n2 Heq =>\n  match Heq with\n  | eq_refl n => eq_refl (S n)\n  end.\n\n(** **** Exercise: 2 stars, standard (eq_cons) *)\n(* Construct the proof object for this theorem. Use pattern matching against the equality hypotheses. *)\nDefinition eq_cons : forall (X : Type) (h1 h2 : X) (t1 t2 : list X),\n    h1 == h2 -> t1 == t2 -> h1 :: t1 == h2 :: t2 :=\n  fun (X : Type) (h1 h2 : X) (t1 t2 : list X) H1 H2 =>\n    match H1, H2 with\n    | (eq_refl h), (eq_refl t) => eq_refl (h :: t)\n    end.\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality) *)\n(* The inductive definition of equality implies Leibniz equality: what we mean when we say \"x and y are \nequal\" is that every property on P that is true of x is also true of y. Prove that. *)\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall (P : X -> Prop), P x -> P y.\nProof.\n  intros.\n  destruct H. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality_term) *)\n(* Construct the proof object for the previous exercise. All it requires is anonymous functions and\npattern-matching; the large proof term constructed by tactics in the previous exercise is needessly\ncomplicated. Hint: pattern-match as soon as possible. *)\nDefinition equality__leibniz_equality_term : forall (X : Type) (x y: X),\n    x == y -> forall P : (X -> Prop), P x -> P y :=\n  fun X x y H =>\n    match H with\n    | eq_refl x =>\n      fun P H0 => H0\n    end.\n\n\n(** **** Exercise: 3 stars, standard, optional (leibniz_equality__equality) *)\n(* Show that, in fact, the inductive definition of equality is equivalent to Leibniz equality. Hint: the\nproof is quite short; about all you need to do is to invent a clever property P to instantiate the\nantecedent. *)\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P : X -> Prop, P x -> P y) -> x == y.\nProof.\n  intros.\n  apply (H (eq x)). apply (eq_refl x).\nQed.\n\nEnd EqualityPlayground.\n\nDefinition propositional_extensionality : Prop :=\n  forall (P Q : Prop), (P <-> Q) -> P = Q.\n\nTheorem pe_implies_or_eq :\n  propositional_extensionality ->\n  forall (P Q : Prop), (P \\/ Q) = (Q \\/ P).\nProof.\n  unfold propositional_extensionality.\n  intros. apply H. split.\n  - intros. destruct H0. right. apply H0. left. apply H0.\n  - intros. destruct H0. right. apply H0. left. apply H0.\nQed.\n\nLemma pe_implies_true_eq :\n  propositional_extensionality ->\n  forall (P : Prop), P -> True = P.\nProof.\n  unfold propositional_extensionality.\n  intros.\n  apply H. split.\n  - intros. apply H0.\n  - apply p_implies_true.\nQed.\n\nDefinition proof_irrelevance : Prop :=\n  forall (P : Prop) (pf1 pf2 : P), pf1 = pf2.\n\nTheorem pe_implies_pi :\n  propositional_extensionality -> proof_irrelevance.\nProof.\n  unfold proof_irrelevance. intros.\n  apply pe_implies_true_eq with P in pf1 as H'. destruct H'.\n  - destruct pf1, pf2. trivial.\n  - apply H.\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/exercise9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.939024817002038, "lm_q1q2_score": 0.8107461551582203}}
{"text": "Require Import Arith Lia.\n\nDefinition iffT (X Y : Type) : Type := (X -> Y) * (Y -> X).\nNotation \"X <=> Y\" := (iffT X Y) (at level 95, no associativity).\n\n\nDefinition inj {X Y} (f : X -> Y) :=\n  forall x x', f x = f x' -> x = x'.\n  \nDefinition inv {X Y} (g : Y -> X) (f : X -> Y) :=\n  forall x, g (f x) = x.\n\nDefinition bijection X Y :=\n  { f : X -> Y & { g & inv g f /\\ inv f g }}.\n\n\nLemma size_rect {X} \u03c3 f : \n  (forall x, (forall y : X, \u03c3 y < \u03c3 x -> f y) -> f x) -> forall x, f x.\nProof.\n  intros H x. apply H.\n  induction (\u03c3 x).\n  - intros y. now intros F % PeanoNat.Nat.nlt_0_r. \n  - intros y Hy. apply H.\n    intros z Hz. apply IHn. lia.\nDefined.\n\n\n\nSection Cantor.\n\nDefinition next '(x,y) := \n  match x with\n  | O => (S y, O)\n  | S x' => (x', S y)\n  end.\n\nFact n00_next : forall p, (0,0) <> next p.\nProof. destruct p as [[] ]; intuition discriminate. Qed.\n\nFact inj_next : inj next.\nProof. intros [[] ][[] ]; cbn; congruence. Qed.\n\n\n\nFixpoint decode n := \n  match n with\n  | 0 => (0,0)\n  | S x => next (decode x)\n  end.\n\n\nLemma inj_decode : inj decode.\nProof.\n  intros n. induction n; intros []; auto.\n  - now intros ?%n00_next.\n  - now intros ?%eq_sym%n00_next.\n  - intros [=?%inj_next%IHn]. congruence.\nQed.\n\n(* show that next is almost surj. *)\nFact zero_or_next : forall p, {a | p = next a} + {p = (0,0)}.\nProof.\n  intros [x []].\n  - destruct x. now right. left; now exists (0,x).\n  - left; now exists (S x, n).\nDefined.\n\n\nFixpoint \u03a3 n := match n with 0 => 0 | S x => n + \u03a3 x end. \n\nDefinition code '(x,y) := \u03a3(x+y)+y.\n\nLemma code_next : forall p, code(next p) = S(code p).\nProof.\n  intros [[|x] y]; cbn.\n  - rewrite <-!plus_n_O, Nat.add_comm. auto.\n  - rewrite !Nat.add_succ_r. cbn. auto.\nQed.\n\nLemma inv_dc : inv decode code.\nProof.\n  unfold inv.\n  apply (size_rect code). intros p rec.\n  destruct (zero_or_next p) as [[? ->] | ->].\n  - rewrite code_next. cbn. f_equal. apply rec.\n    rewrite code_next; auto.\n  - reflexivity.\nQed.\n\nFact inv_cd : inv code decode.\nProof.\n  intros ?. apply inj_decode. now rewrite inv_dc.\nQed.\n\n\nCorollary Bij_Nat_NatNat : bijection nat (nat * nat).\nProof.\n  exists decode, code. split. apply inv_cd. apply inv_dc.\nQed.\n\n\nFact bound x y n : code (x, y) = n -> y < S n.\nProof. cbn. lia. Qed.\n\n\nSection Cantor.\n\n\n\nSection Cantor2.\n\nDefinition Cantor x y z := (x + y)*S (x + y) + 2*y = 2*z.\nDefinition Next x y u v :=\n     (x = 0 -> u = S y /\\ v = 0) \n  /\\ (x <> 0 -> (exists p, S p = x /\\ u = p) /\\ v = S y).\n\nFact C01 z :\n  Cantor 0 0 z <-> z = 0.\nProof. unfold Cantor; lia. Qed.\n\nFact C02 x y : \n  Cantor x y 0 <-> x = 0 /\\ y = 0.\nProof. unfold Cantor; lia. Qed.\n\nFact C1 {y z} : \n  Cantor 0 y z <-> Cantor (S y) 0 (S z).\nProof. unfold Cantor; lia. Qed.\n\nFact C2 {x y z} : \n  Cantor (S x) y z <-> Cantor x (S y) (S z).\nProof. unfold Cantor; lia. Qed.\n\nLemma Code_Next {x y u v z} :\n  Next x y u v -> Cantor x y z <-> Cantor u v (S z).\nProof. \n  unfold Next. destruct x.\n  - intros [H _].\n    unshelve refine (let H := H _ in _); auto.\n    destruct H as [-> ->]. apply C1.\n  - intros [_ H].\n    unshelve refine (let H := H _ in _); auto.\n    destruct H as [[? [<- ->]] ->]. apply C2.\nQed.\n\nLemma Zero_or_Next u v :\n  (u = 0 /\\ v = 0) \\/ (exists x y, Next x y u v).\nProof.\n  destruct v as [|v].\n  - destruct u. \n    + now left. \n    + right; exists 0, u. unfold Next. lia.\n  - right; exists (S u), v.\n    unfold Next. repeat split; try lia.\n    now exists u.\nQed.\n\nLemma Next_inj x y u v u' v' :\n  Next x y u v -> Next x y u' v' -> u = u' /\\ v = v'.\nProof.\n  unfold Next. intros [? H] [? H']. \n  destruct x; [lia|].\n  destruct H as [[p [? ->]] ->], H' as [[p' [? ->]] ->]; lia.\nQed.\n\nFact Cantor_inj1 x y z z' :\n  Cantor x y z -> Cantor x y z' -> z = z'.\nProof. unfold Cantor; lia. Qed.\n\n\n(* This served as a guide for the proof of Cantor_inj2 *)\nGoal inj code.\nProof.\n  intros a; pattern a; apply (size_rect code).\n  intros p rec p'.\n  destruct \n    (zero_or_next p) as [[? ->] | ->], \n    (zero_or_next p') as [[? ->] | ->].\n  {\n    rewrite !code_next. intros [=]. f_equal. apply rec. \n    rewrite code_next. all: auto.\n  }\n  all: rewrite ?code_next; cbn; auto; lia.\nQed.\n\n\nGoal inj code.\nProof.\n  unfold inj.\n  enough (forall n x x', code x = n -> code x' = n -> x = x').\n  { \n    intros a b E. eapply H; auto.\n  }\n  induction n.\n  - admit.\n  - intros p p'.\n    destruct \n    (zero_or_next p) as [[a ->] | ->],\n    (zero_or_next p') as [[b ->] | ->].\n    { rewrite !code_next. intros [=][=]. f_equal.\n      now apply IHn. }\n    all: cbn; lia. \nAdmitted.\n\n\nLemma Cantor_inj2 z :\n  forall x x' y y', Cantor x y z -> Cantor x' y' z -> x = x' /\\ y = y'.\nProof.\n  pattern z; revert z; apply (size_rect id).\n  intros z rect u u' v v'.\n  destruct \n    (Zero_or_Next u v) as [[-> ->] | [x [y N]] ], \n    (Zero_or_Next u' v') as [[-> ->] | [x' [y' N']] ]. \n  - auto.\n  - unfold Cantor; intros ->%C01 ?; lia.\n  - unfold Cantor; intros ? ->%C01; lia.\n  - destruct z.\n    { intros []%C02 []%C02; lia. }\n    unshelve refine (fun H H' => \n      let C := proj2 (Code_Next N) H  in\n      let C' := proj2 (Code_Next N') H'  in\n      let E := rect _ _ _ _ _ _  C C' in _\n    ); auto.\n    destruct E as [-> ->].\n    eapply Next_inj; eauto.\nQed.\n\n\nFact Gauss n : {k & n*(S n) = 2*k}.\nProof.\n  induction n.\n  - now exists 0.\n  - destruct IHn as [k ]. \n    exists (n + k + 1); lia.\nDefined.\n\n(* Define coding and projection functions *)\n\nLemma Coding x y : {z & Cantor x y z}.\nProof.\n  unfold Cantor.\n  destruct (Gauss (x + y)) as [z ].\n  exists (z + y); lia.\nDefined.\n\nDefinition code' x y := projT1 (Coding x y).\nDefinition code_ x y : Cantor x y (code' x y) := projT2 (Coding x y).\n\nLemma Decoding z : {x & {y & Cantor x y z}}.\nProof.\n  induction z.\n  - exists 0, 0. unfold Cantor; lia.\n  - destruct IHz as [x [y IH]], x as [|x].\n    + eexists; eexists. erewrite <-C1; eauto.\n    + eexists; eexists. erewrite <-C2; eauto. \nDefined.\n\nDefinition pi1 n := projT1 (Decoding n).\nDefinition pi2 n := projT1 (projT2 (Decoding n)).\nDefinition projections n : Cantor (pi1 n) (pi2 n) n := (projT2 (projT2 (Decoding n))).\n\n\nLemma code_pi n :\n  code' (pi1 n) (pi2 n) = n.\nProof.\n  eapply Cantor_inj1.\n  apply code_. apply projections.\nQed.\n\nLemma pi_code x y :\n  pi1 (code' x y) = x /\\ pi2 (code' x y) = y.\nProof.\n  eapply Cantor_inj2.\n  apply projections. apply code_.\nQed.\n\n\n\nEnd Cantor2.", "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/PredCantorPairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.8105046125055857}}
{"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    FGroup.v                        \n                                                                     \n    Defintion and properties of finite groups                         \n                                                                     \n    Definition: FGroup              \n  **********************************************************************)\nRequire Import List.\nRequire Import UList.\nRequire Import Tactic.\nRequire Import ZArith.\n\nOpen Scope Z_scope. \n\nSet Implicit Arguments.\n\n(************************************** \n  A finite group is defined for an operation op\n  it has a support  (s)\n  op operates inside the group (internal)\n  op is associative (assoc)\n  it has an element (e) that is neutral (e_is_zero_l e_is_zero_r)\n  it has an inverse operator (i)\n  the inverse operates inside the group (i_internal)\n  it gives an inverse (i_is_inverse_l is_is_inverse_r)\n **************************************)\n \nRecord FGroup (A: Set) (op: A -> A -> A): Set := mkGroup\n  {s : (list A);\n   unique_s: ulist s;\n   internal: forall a b, In a s -> In b s -> In (op a b) s;\n   assoc: forall a b c, In a s -> In b s -> In c s -> op a (op b c) = op (op a b) c;\n   e: A;\n   e_in_s: In e s;\n   e_is_zero_l:  forall a, In a s ->  op e a = a;\n   e_is_zero_r:  forall a, In a s ->  op a e = a;\n   i: A -> A;\n   i_internal: forall a, In a s -> In (i a) s;\n   i_is_inverse_l:  forall a, (In a s) -> op (i a) a = e;\n   i_is_inverse_r:  forall a, (In a s) -> op a (i a) = e\n}.\n\n(************************************** \n   The order of a group is the lengh of the support\n **************************************)\n \nDefinition g_order  (A: Set) (op: A -> A -> A) (g: FGroup op)  := Z_of_nat (length g.(s)).\n\nUnset Implicit Arguments.\n\nHint Resolve unique_s internal e_in_s e_is_zero_l e_is_zero_r i_internal\n  i_is_inverse_l i_is_inverse_r assoc.\n\n\nSection FGroup.\n\nVariable A: Set.\nVariable op: A -> A -> A.\n\n(************************************** \n   Some properties of a finite group\n **************************************)\n\nTheorem g_cancel_l: forall (g : FGroup op), forall a b c, In a g.(s) -> In b g.(s) -> In c g.(s) -> op a b = op a c -> b = c.\nintros g a b c H1 H2 H3 H4; apply trans_equal with (op g.(e) b); sauto.\nreplace (g.(e)) with (op (g.(i) a)  a); sauto.\napply trans_equal with (op (i g a) (op a b)); sauto.\napply sym_equal; apply assoc with g; auto.\nrewrite H4.\napply trans_equal with (op (op  (i g a) a) c); sauto.\napply assoc with g; auto.\nreplace (op (g.(i) a)  a) with g.(e); sauto.\nQed.\n\nTheorem g_cancel_r: forall (g : FGroup op), forall a b c, In a g.(s) -> In b g.(s) -> In c g.(s) -> op b a = op c a -> b = c.\nintros g a b c H1 H2 H3 H4; apply trans_equal with (op b g.(e)); sauto.\nreplace (g.(e)) with (op a (g.(i) a)); sauto.\napply trans_equal with (op (op b  a) (i g a)); sauto.\napply assoc with g; auto.\nrewrite H4.\napply trans_equal with (op c (op  a (i g a))); sauto.\napply sym_equal; apply assoc with g; sauto.\nreplace (op a (g.(i) a)) with g.(e); sauto.\nQed.\n\nTheorem e_unique: forall (g : FGroup op), forall e1, In e1 g.(s) ->  (forall a, In a g.(s) -> op e1 a = a) -> e1 = g.(e). \nintros g e1 He1 H2.\napply trans_equal with (op e1 g.(e)); sauto.\nQed.\n\nTheorem inv_op: forall (g: FGroup op) a b, In a g.(s) -> In b g.(s) ->  g.(i) (op a b) = op (g.(i) b) (g.(i) a).\nintros g a1 b1 H1 H2; apply g_cancel_l with (g := g) (a := op a1 b1); sauto.\nrepeat rewrite g.(assoc); sauto.\napply trans_equal with g.(e); sauto.\nrewrite <- g.(assoc) with (a := a1); sauto.\nrewrite g.(i_is_inverse_r); sauto.\nrewrite g.(e_is_zero_r); sauto.\nQed.\n\nTheorem i_e: forall (g: FGroup op), g.(i) g.(e) = g.(e).\nintro g; apply g_cancel_l with (g:= g) (a := g.(e)); sauto.\napply trans_equal with g.(e); sauto.\nQed.\n\n(************************************** \n   A group has at least one element\n **************************************)\n\nTheorem g_order_pos: forall g: FGroup op, 0 < g_order g.\nintro g; generalize g.(e_in_s); unfold g_order; case g.(s); simpl; auto with zarith.\nQed.\n\n\n\nEnd FGroup.\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/FGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8104925652774392}}
{"text": "Require Import Coq.Arith.Mult.\nRequire Import Coq.Arith.Plus.\n\nDefinition divides (n m:nat) : Prop := exists (k:nat), k * n = m.\n\nNotation \"n | m\" := (divides n m) (at level 50).\n\nDefinition prime (p:nat) : Prop :=\n    (p <> 1) /\\ forall (n:nat), n | p -> (n = 1) \\/ (n = p).\n\nLemma div_n_0 : forall (n:nat), n | 0.\nProof. intros n. exists 0. reflexivity. Qed.\n\nLemma div_0_n : forall (n:nat), 0 | n <-> n = 0.\nProof.\n    intros. split; intros H.\n    - destruct H as [k H]. \n      rewrite mult_comm in H. simpl in H. symmetry. assumption.\n    - rewrite H. exists 0. reflexivity.\nQed.\n\nLemma div_n_1 : forall (n:nat), n | 1 <-> n = 1.\nProof.\n    intros n. split.\n    - intros [k H]. destruct n as [|n].\n        + simpl in H. rewrite <- mult_n_O in H. inversion H.\n        + destruct n as [|n].\n            { reflexivity. }\n            { destruct k as [|k].\n                { simpl in H. inversion H. }\n                { simpl in H. inversion H. }\n            }\n    - intros H. exists 1. rewrite H. 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/hol/euclid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.8104440794680712}}
{"text": "Require Import Arith.\nRequire Import Monoid.\n\n(* a monoid can be defined from nat 0 and plus *)\nDefinition NatPlus : Monoid nat := monoid \n    0           (* identity  *) \n    plus        (* product   *) \n    plus_0_l    (* proof_idl *) \n    plus_0_r    (* proof_idr *)\n    plus_assoc  (* proof_asc *)\n    .\n\n(* a monoid can be defined from nat 1 and mult *)\nDefinition NatMult : Monoid nat := monoid\n    1\n    mult\n    mult_1_l\n    mult_1_r\n    mult_assoc\n    .\n\n(*\nCheck NatPlus.\nCheck identity  NatPlus.\nCheck product   NatPlus.\nCheck proof_idl NatPlus.\nCheck proof_idr NatPlus.\nCheck proof_asc NatPlus.\n\nCheck NatMult.\nCheck identity  NatMult.\nCheck product   NatMult.\nCheck proof_idl NatMult.\nCheck proof_idr NatMult.\nCheck proof_asc NatMult.\n*)\n\nExample plus_identity_test : identity NatPlus = 0.\nProof. reflexivity. Qed. \n\nExample plus_product_test : forall n m: nat, product NatPlus n m = n + m. \nProof. reflexivity. Qed. \n\nExample mult_identity_test : identity NatMult = 1.\nProof. reflexivity. Qed. \n\nExample mult_product_test : forall n m: nat, product NatMult n m = n * m. \nProof. reflexivity. Qed. \n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cat/natAsMonoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.8103221429039758}}
{"text": "Require Import Arith JMeq FiniteTypes Substitution.\nRequire Import Containers Max Eqdep. \n\n(** * Vectors - lists with finite length *)\n\nSet Implicit Arguments.\n\nSection Vectors.\n \n Variable X : Type.\n\n Inductive Vec  : nat -> Type :=\n  | vnil : Vec 0\n  | vcons : forall (n : nat) , X ->  Vec n -> Vec (S n).\n\n (** concatenating two vectors *)\n Fixpoint vPlus (n m : nat)(i : Vec n) (j :  Vec m) {struct i}:  Vec (n + m) := \n match i as e in (Vec n) return (Vec (n + m)) with\n | vnil => j\n | vcons _ x i' => vcons  x (vPlus i' j)\n end.\n\n (** concatenation is commutative  *)\n Lemma vPlus_comm (n m nm : nat) (i : Vec n) (j : Vec m) (k : Vec nm) :\n  JMeq (vPlus (vPlus i j) k) (vPlus i (vPlus j k)).\n Proof.\n  induction i; simpl; auto.\n  intros j k. \n  exact (dp_rwt Vec \n         (fun (z : nat)  (px : Vec z) => \n             JMeq (vcons x px)\n                      (vcons x (vPlus i (vPlus j k))) )\n         (plus_assoc n m nm) (sym_JMeq (IHi j k))\n        (JMeq_refl (vcons x (vPlus i (vPlus j k))))\n         ).\n Qed.\n\n (** case non-standard eliminators for Vec 0 and Vec (S n)  *)\n Inductive VNil : Vec 0 -> Type := isvnil : VNil vnil.\n\n  Inductive VCons (n : nat) : Vec (S n) -> Type :=\n   isvcons : forall (a :X ) (i : Vec n), VCons (vcons a i) .\n\n  Definition vNil (i : Vec 0): VNil i :=\n  match i in Vec t return match t return Vec t -> Set with\n                               | O => @VNil\n                               | _ => fun _ => unit\n                               end i with\n  | vnil => isvnil\n  | _ => tt\n  end.\n\n  Definition vCons (n : nat) (i : Vec (S n)) : VCons i :=\n   match i in Vec t return match t return Vec t -> Type with\n                           | S _ => @VCons _\n                           | _   => fun _ => unit\n                           end i with\n  | vcons _ x j => isvcons x j\n  | _ => tt\n  end.\n\n\n (** compute a constant vector of some required size*)\n Fixpoint vec (n : nat) (x: X) : Vec n :=\n   match n as e return (Vec e) with\n   | O => vnil\n   | S n' => vcons x (vec n' x) \n   end.\n\n (** head and tail  *)\n Definition vhead n (i : Vec (S n)) : X :=\n    match vCons i with\n    | isvcons a _ => a\n    end.\n\n Definition vtail n (i : Vec (S n)) :  Vec n :=\n  match vCons i with\n  | isvcons _ a => a\n  end.\n\n (** and dually, first and last *)\n  Fixpoint vfirst_aux n a (v : Vec n) : Vec n :=\n    match v in Vec e return (Vec e)  with\n    | vnil => vnil\n    | vcons _ x xs => vcons a (vfirst_aux x xs)\n    end.\n\n  (* removes the last element of a vector *)\n  Definition vfirst n (v : Vec (S n)) := vfirst_aux (vhead v) (vtail v).\n \n  Fixpoint vlast_aux n a (v : Vec n) :=\n    match v with\n    | vnil => a\n    | vcons _ x xs => vlast_aux x xs\n    end.\n\n  (* returns the last element of a vector  *)\n  Definition vlast n (v : Vec (S n)) := vlast_aux (vhead v) (vtail v).\n\n  (* Vsnoc - adds an element to the end of a vector  *)\n  Fixpoint vSnoc n (a : X) (v : Vec n) : Vec (S n) :=\n     match v in Vec n return Vec (S n) with\n     | vnil => vcons a vnil  \n     | vcons _ x xs => vcons x (vSnoc a xs)\n     end.\n\n (** reverse a vector  *)\n  Fixpoint vrev n (v : Vec n) : Vec n :=\n    match v in Vec n return Vec n with\n    | vnil => vnil\n    | vcons _ b bs => vSnoc b (vrev bs)\n    end.\n\n (**  \n-----\nSome properties of vrev, vSnoc, vfirst and vlast *)\n(* vrev is involutive *)\n  Lemma vrevSnoc : forall  n (x : X) (v : Vec n), vrev (vSnoc x v) = vcons x (vrev v).\n  Proof.\n    induction v; simpl; auto.\n    rewrite IHv; simpl; trivial.\n  Qed.\n\n (** vrev is involutive  *)\n Lemma vrev_inv : forall n (v : Vec n), vrev (vrev v) = v.\n Proof. \n   induction v; simpl; trivial.\n   rewrite (vrevSnoc x (vrev v)); rewrite IHv; trivial.\n Qed.\n\n Lemma vlast_vcons : forall  n (x : X) (v : Vec (S n)), vlast (vcons x v) = vlast v. \n Proof.\n   intros. destruct (vCons v); unfold vlast; unfold vhead; unfold vtail; simpl; trivial.\n Qed.\n\n Lemma vfirst_vcons : forall  n (x : X) (v : Vec (S n)), vfirst (vcons x v) = vcons x (vfirst v). \n Proof.\n   intros. destruct (vCons v); unfold vfirst; unfold vhead; unfold vtail; simpl; trivial.\n Qed.\n \n Lemma vlast_vSnoc : forall  n (x : X) (v : Vec n), vlast (vSnoc x v) = x.\n  induction v; simpl; trivial;  rewrite (vlast_vcons x0 (vSnoc x v)); trivial.\n Qed.\n\n Lemma vfirst_vSnoc : forall  n (x : X) (v : Vec n), vfirst (vSnoc x v) = v.\n  induction v; simpl; trivial. rewrite (vfirst_vcons x0 (vSnoc x v)); \n  rewrite IHv; trivial.\n Qed.\n\n Lemma vlast_rev n (v : Vec (S n)):  vhead v = vlast (vrev v).\n Proof. \n    intros n v; unfold vhead;  destruct (vCons v);  simpl.\n    rewrite (vlast_vSnoc a (vrev i));  trivial.\n Qed.\n\n Lemma vfirst_rev n (v : Vec (S n)):  vrev (vtail v) = vfirst (vrev v).\n Proof. \n   intros n v; unfold vtail; destruct (vCons v); simpl. rewrite (vfirst_vSnoc a  _); trivial.\n Qed.\n  \n (** fold for vectors *)\n Fixpoint vfold n ( B : Type) (f : X -> B -> B) (b : B) (v : Vec  n) : B :=\n   match v with\n   | vnil => b\n   | vcons _ a ass => f a (vfold f b ass)\n   end.\n\n  \n  (** Non-standard eliminator for  View (n + m) *)\n  Inductive vPlusView (n m : nat) : Vec (n + m) -> Type :=\n   | vplus : forall (i : Vec n) (j : Vec m), vPlusView n m (vPlus i j).\n  \n  Fixpoint vplusView (n m : nat) : forall i : Vec (n + m), vPlusView n m i :=\n    match n as e return (forall i : Vec (e + m), vPlusView e m i) with\n    | O    => fun i => vplus vnil i\n    | S n' => fun i => \n          match (vCons i) in (VCons k) return (vPlusView (S n') m k) with\n          | isvcons a i0 => let v0 := vplusView _ m i0 in\n             match\n             v0 in (vPlusView _ _ v1) return (vPlusView (S n') m (vcons a v1))\n             with\n             | vplus i1 j => vplus (vcons a i1) j\n             end\n         end\n    end.\n\n\n (* Definition vTimes n m (i : Vec n) (j :  Vec m) : Vec (n * m).\n    intros n m i; induction i; simpl.\n    exact (fun _ => vnil ).\n    intros h. exact (vPlus h (IHi h)).\n  Defined. *)\n\n (*\n  Fixpoint vTimes n m (i : Vec n) (j : Vec m)  : Vec (n * m) :=\n    match i in Vec e return  Vec (e * m) with\n    | vnil =>  vnil\n    | vcons _ _ i1 =>  vPlus j (vTimes  i1 j)\n    end.              \n  \nInductive VecTimes (n m : nat)  : Vec (n * m) -> Type :=\n  |isVecPair : forall (i : Vec n) (j : Vec m) , VecTimes n m (vTimes i j).\n\n Definition vectimes ( n m : nat)  : forall i : Vec (n * m), VecTimes n m i.\n    cut (forall m  (i : Vec 0), VecTimes 0 m i). intro.\n    induction n. simpl in *.  exact (X0 ).\n    intros. cut (Vec (S n * m) -> Vec (S (n * m))). \n    intro H. simpl in *. destruct (vCons (H i)). clear i0.\n    destruct (vplusView m (n * m) i).\n    destruct (IHn m j).  set  (isVecPair (m :=m)  (vcons a i0) ). simpl in v.\n    exact v. \n    simpl in i.\n    \n    cut ( forall   (i : Vec 0) ( j : Vec m) , VecTimes 0 m (vTimes i j)  -> VecTimes 0 m i).\n    intros. induction m; simpl.\n    exact (X0 i vnil (isVecPair (m := 0)  i vnil) ).\n\n  *)\n\n (* decomposiiton i nterms of vhead and vtail *)\n Lemma vec_decompose : forall n (v : Vec (S n)), v = vcons (vhead v) (vtail v).\n Proof.\n   intros n v; destruct (vCons v); auto.\n Qed.  \n\n  (* decompositon in terms of vSnoc, vlast and vfirst *)\n   Lemma vVsnoc n (v : Vec (S n)) : v = vSnoc (vlast v) (vfirst v).\n   Proof.\n     intros n v; destruct (vCons v) . generalize a; unfold vlast; unfold vfirst;\n     unfold vhead; unfold vtail; simpl. \n    induction i ; simpl; trivial. intros; rewrite (IHi x); trivial.\n  Qed.\n\n\n (** * Equality  *)\n Definition vecEq1 (n : nat) (H : forall x y : X, {x = y}+{x <> y}) (i j: Vec n) : bool.\n  intros n H i; induction i. intro j; destruct  j.\n  exact true. exact false. intro j; destruct (vCons j).\n  destruct (H x a) as [l | r]. exact (IHi i0). exact false.\n Defined.\n\n Lemma VecEq1_sym (n : nat) (H : forall x y : X, {x = y}+{x <> y}) (i j: Vec n) :\n   vecEq1 H i j = true -> vecEq1 H j i = true.\n Proof.\n   induction i. intro j; destruct (vNil j); trivial.\n   intro j; destruct (vCons j); simpl.\n   destruct (H x a); subst. intros. destruct ( H a a).\n   apply (IHi i0 H0). case (n0 (refl_equal a)).\n   intro h; discriminate h.\n Qed.\n\n Lemma vecEq1_and (n m : nat) (H :forall x y : X, {x = y}+{x <> y}) (i i1 : Vec n) (j j1 : Vec m) :\n  vecEq1 H i i1 = true -> vecEq1 H j j1 = true -> vecEq1 H (vPlus i j) (vPlus i1 j1) = true.\n Proof.\n   induction i. intros. destruct (vNil i1); simpl in *. trivial.\n   intros. destruct (vCons i1); simpl in *.\n   destruct ( H x a). exact (IHi i0 j j1 H0 H1). exact H0.\n Qed.\n\n Lemma vec_and_Eq1 (n m : nat) (H :forall x y : X, {x = y}+{x <> y}) (i i1 : Vec n) (j j1 : Vec m) :\n  vecEq1 H (vPlus i j) (vPlus i1 j1) = true -> vecEq1 H i i1 = true /\\ vecEq1 H j j1 = true .\n Proof.\n   induction i. intros. destruct (vNil i1); simpl in *. auto.\n   intros. destruct (vCons i1); simpl in *.\n   destruct ( H x a). exact (IHi i0 j j1 H0). \n   discriminate  H0.\n Qed.\n\n Fixpoint vecEqBool (n : nat) ( H : X -> X -> bool) (i  : Vec n) {struct i} : Vec n -> bool :=\n   match i in Vec e return Vec e -> bool with\n   | vnil => fun _ => true\n   | vcons _ a ls => fun x => match vCons x with \n                            | isvcons b bs => if H a b then \n                                                 vecEqBool H ls bs\n                                               else false\n                            end\n   end. \n\n Lemma vecEqBool_and (n m : nat) (H : X -> X -> bool) (i i1 : Vec n) (j j1 : Vec m) :\n  vecEqBool H i i1 = true -> vecEqBool H j j1 = true ->  vecEqBool H (vPlus i j) (vPlus i1 j1) = true.\n Proof.\n   induction i. intros. destruct (vNil i1); simpl in *. trivial.\n   intros. destruct (vCons i1); simpl in *.\n   destruct ( H x a). exact (IHi i0 j j1 H0 H1). exact H0.\n Qed.\n\n Lemma VecInj1 : forall (n : nat) (a a1 : X) (i j : Vec n), vcons a i = vcons a1 j -> a = a1.\n  Proof. \n    intros. injection H; auto.\n  Qed.\n\n Definition vecEqDec (n : nat) (H : forall x y : X, {x = y}+{x <> y}): forall (i j: Vec n), {i = j}+{i <> j} .\n   induction i. intro j; destruct (vNil j).\n   left; trivial. intro j; destruct (vCons j).\n   destruct (H x a); subst. destruct (IHi i0); subst. left ;trivial. \n   right. \n    cut (forall (n : nat) (i j : Vec (S n)),\n    i = j -> vtail i = vtail j). intros.\n   intro h;  set (r := H0 n (vcons a i) (vcons a i0) h); simpl in r.\n   case (n0 r). intros. case H0; trivial.\n   right. intro h; case (n0 (VecInj1 h)). \n Defined.\n \n Definition vecEq (n m : nat) (H : forall x y : X, {x = y}+{x <> y}) (i : Vec n) (j : Vec m) : bool.\n  intros n m; destruct (eq_nat_dec n m) as [l | r].\n  destruct l. exact (fun H i j => vecEq1 H i j).\n  intros; exact false.\n Defined.\n\n  Definition vecEq_bool (n m : nat)  (H : X -> X -> bool) (i : Vec n) (j : Vec m) : bool.\n  intros n m; destruct (eq_nat_dec n m) as [l | r].\n  destruct l. exact (fun H i j => vecEqBool H i j).\n   exact (fun _ _ _ => false).\n Defined.\n\n Definition VecEQt (n  : nat) (H : forall x y : X, {x = y}+{x <> y})(i j: Vec n) :  vecEq1 H i j = true -> vecEq H i j = true.\n Proof.   \n  intros. unfold vecEq. replace (eq_nat_dec n n) with (left (n <> n) (refl_equal n)); auto. \n  destruct (eq_nat_dec n n); trivial. rewrite (UIP_refl nat n e); trivial.\n  case (n0 (refl_equal n)).\n Defined.\n\n Definition eqvecEqn (n : nat) (H : forall x y : X, {x = y} + {x <> y}) (i j : Vec n) : vecEq H i j = true -> i = j.\n Proof.\n   induction i. intro j;  destruct (vNil j); trivial. \n   intros. destruct (vCons j). unfold vecEq in H0.\n   destruct (eq_nat_dec (S n) (S n)).\n   rewrite  (UIP_refl nat (S n) e) in H0.\n   destruct (H x a); simpl in *; subst.\n   destruct (H a a). case (IHi i0 (VecEQt H i i0 H0)); trivial.\n   discriminate H0. destruct (H x a) as [l | r ]. case (n0 l).\n   discriminate H0.\n   discriminate H0.\n Defined.\n \n  Definition eqvecEq (n m : nat) (H : n = m) (H : forall x y : X, {x = y} + {x <> y})\n   (i : Vec n) (j : Vec  m) : vecEq H i j  =  true ->  JMeq i  j.\n    intros n m H; case H. intros. case (eqvecEqn H0 i j H1); trivial.\n  Defined.\n\n    \n  Lemma VeqInj2 : forall (n : nat) (v1 v2 : Vec (S n)), v1 = v2 -> vhead v1 = vhead v2 /\\ vtail v1 = vtail v2.\n  Proof. \n    intros until v2. intro H; destruct H. \n    destruct (vCons v1); simpl. auto.\n  Qed.\n\nEnd Vectors.\n\n  Fixpoint vmap (n : nat)  (A B : Set) (f : A -> B) (i : Vec A n) {struct i} :\n     Vec B n :=\n   match i in (Vec _ e) return (Vec B e) with\n   | vnil => vnil B\n   | vcons _ x xs => vcons (f x) (vmap f xs)\n   end.\n \n Lemma vplusMap  (A B : Set) (n m : nat)  (f : A -> B)\n  (i : Vec A n) (j : Vec A m) :  vPlus (vmap f i) (vmap f j) = vmap f (vPlus i j).\n Proof. \n   induction i; simpl; trivial.\n   intros. rewrite (IHi j); trivial.\n Qed.\n\n Fixpoint vApp (X Y : Type) (n : nat) (i :  Vec (X -> Y) n ) {struct i} :\n      Vec X n -> Vec Y n :=\n   match i in (Vec _ e) return Vec X e -> Vec Y e with\n   | vnil => fun _ => vnil Y\n   | vcons _ F fi => fun i => \n                  match vCons i with\n                  | isvcons x xs => vcons (F x) (vApp fi xs)\n                  end\n   end. \n\n (** Matrix transpose*)\n Fixpoint vXpose (X : Type) (i j :nat) (a : Vec (Vec X j) i) {struct a} : Vec (Vec X i) j :=\n  match a in (Vec _ e1) return Vec (Vec X e1) _ with\n  | vnil => vec j (vnil X)\n  | vcons n x xs => \n       vApp (vApp (vec j (vcons (X := X) (n := n) )) x) (vXpose xs)\n  end. \n\n\nSection VecFin.\n(** Vectors and Finite Sets *) \n Fixpoint vecfin (A : Type) (n : nat) (i : Vec A n) {struct i} :  Fin n -> A :=\n   match i in (Vec _ e) return (Fin e -> A) with\n   | vnil  => fun x =>  match (fin_0_empty x) return A with end\n   | vcons _ a i => fun j =>  match finSN j with\n                            | isfz => a\n                            | isfs j' => vecfin i j'\n                            end\n   end.\n  \n Fixpoint finVec A (n : nat) {struct n} : (Fin n -> A) -> Vec A n :=\n  match n as e return ((Fin e -> A) -> Vec A e) with\n  | O => fun _ => (vnil A)\n  | S n'  => fun f => vcons (f (fz n')) (finVec (fun i => f (fs i)))\n  end.\n\n\n(* Isomorphism extends to dependent sums : \\Sigma n : nat. Fin n -> X *)\n(* Here we use the extension of a container for lists *)\n Definition extVec (i : Ext (ucont Fin) nat) : Vec nat (u i) := finVec (f i).\n\n Definition vecExt  (n: nat) (i : Vec nat n) := uext (ucont Fin) n (vecfin i) .\n\n Lemma finVecfin A (n : nat) : forall (i : Vec A n), finVec (vecfin i) = i.\n Proof.\n   induction i; simpl; trivial.\n   rewrite <- (extensionality (vecfin i) (fun i0 => vecfin i i0) (fun x => refl_equal (vecfin i x))). \n   pattern i at 2; rewrite <- IHi; trivial.\n Qed.\n\n Lemma vecFinVec A (n : nat):\n   forall (i : Fin n -> A), vecfin (finVec i) = i.\n   induction n; simpl; auto.\n   intros.  apply (extensionality (fun x : Fin 0 => match fin_0_empty x return A with\n                     end) i).\n   intro a; inversion a. intros.  apply extensionality .\n   intro a; destruct (finSN a); trivial.\n   rewrite (IHn (fun x => i (fs x))); subst; trivial. \n Qed.\n\n Lemma finVecEQ A (n : nat): forall  (i j : Fin n -> A), (finVec i) = (finVec j) ->  i = j.\n   intros A n i j H; set (r := f_equal (vecfin (A := A) (n := n)) H); simpl in r.\n   rewrite (vecFinVec i) in r; rewrite (vecFinVec j) in r; trivial.\n Qed.\n\n Lemma vecJmeq X (n m : nat) (h : n = m)  (F : Fin n -> X) (G : Fin m -> X) : JMeq (finVec F) (finVec G) -> JMeq F G.\n  intros X n m h; destruct h. intros F G h.\n  replace F with (vecfin (finVec F)).  replace G with (vecfin (finVec G)).\n  case (JMeq_eq h); trivial. apply vecFinVec. apply vecFinVec.\n Defined.\n\n Lemma ExtVecN X (n m : nat) (H : n = m) (F : Fin n -> X) (G : Fin m -> X) :\n   (forall (x : Fin n) (x1 : Fin m), JMeq x x1 -> JMeq (finVec F) (finVec G))-> JMeq F G.\n   intros X n m h; destruct h.\n   intros F G H. apply (dextensionality Fin (refl_equal n) F G) .\n   intros x y h; case (JMeq_eq h). case (finVecEQ F G (JMeq_eq (H x y h))); trivial.\n  Qed.\n\n Lemma finVecJMeq A (n m : nat) (H : n = m)\n                 (i : Fin n -> A) (j : Fin m -> A)\n                 (H0 : JMeq (finVec i) (finVec j)) (ix : Fin n) (jx : Fin m):\n                 JMeq ix jx -> i ix = j jx.\n Proof.\n   intros A n m H; case H. intros F G H0; case (finVecEQ F G (JMeq_eq H0)).\n   intros i j H1; case (JMeq_eq H1); trivial.\n Qed.\n\n  (** Indexing a vector by a fnite type *)\n  Fixpoint vecIn X n (i : Fin n) : Vec X n -> X :=\n    match i in (Fin e) return Vec _ e -> X with\n    | fz _ => fun v => match vCons v with\n                       | isvcons x _ => x\n                       end\n    | fs _ i => fun v => match vCons v with\n                       | isvcons _ j => vecIn i j\n                       end\n    end.\n\n   (** indexing a vector from the last element *)\n  Definition rev_ind X  (n : nat) (i : Fin n) (v : Vec X n) := vecIn (rv i) v.\n\n  (* this belongs to the vectors file *)\n  Lemma vecfin_emb A n (i : Fin n) (v : Vec A (S n)) : vecfin v (emb i) = vecfin (vfirst v) i.\n    induction i; intros; repeat (match goal with\n                                | [ v : Vec _ (S _ ) |- _ ] =>  destruct (vCons v)\n                                end); simpl. unfold vhead; simpl; trivial.\n     generalize (IHi (vcons a0 i0)); simpl. intro h; rewrite h.\n    unfold vfirst; unfold vhead; unfold vtail; simpl; trivial.\n  Qed.\n\n  Lemma vecfin_tp A n  (v : Vec A (S n)) : vecfin v (tp n) =  vlast v.\n  Proof.\n    induction n; intros ; repeat (match goal with\n                                | [ v : Vec _ (S _ ) |- _ ] =>  destruct (vCons v)\n                                | [ v : Vec _ 0 |- _ ] =>  destruct (vNil v)\n                                end); simpl.  unfold vlast; simpl; trivial.\n    generalize (IHn (vcons a0 i)); simpl. intro h; rewrite h.\n   unfold vlast; unfold vhead; unfold vtail; simpl; trivial.\n  Qed.\n\nEnd VecFin.\n\nSection Tuples.\n\n Variable A: Type.\n (** * Vectors as Tuples *)\n  Fixpoint Tuple (n:nat){struct n}: Type :=\n  match n with\n  O => unit\n  | (S n') => (A*(Tuple n'))%type\n  end.\n\n (* Vector is a n-tuple *)\n Fixpoint tup2vec n :  Tuple n -> Vec A n :=\n   match n as n return Tuple n -> Vec A n with\n   | O => fun _ => vnil _\n   | S m => fun tp => vcons (fst tp) (tup2vec _ (snd tp))\n   end.\n\n Fixpoint vec2tup n (i : Vec A n) : Tuple n :=\n    match i in (Vec _ e) return Tuple e with\n    | vnil => tt\n    | vcons _ x xs => (x, (vec2tup xs))\n   end.\n  \n Fixpoint tuple_proj (n:nat){struct n}: forall k:nat, k<n -> Tuple n -> A :=\n  match n return (forall k:nat, k<n -> Tuple n -> A) with\n  O => fun (k:nat)(h:k<O)(v:Tuple 0) =>\n         match (lt_n_O k h) return A with end\n  | (S n') => fun k:nat =>\n              match k return (k<(S n') -> Tuple (S n') -> A) with\n                O => fun (h:0<(S n'))(v:Tuple (S n')) => (fst v)\n              | (S k') => fun (h:S k' < S n')(v:Tuple (S n')) =>\n                            (tuple_proj (lt_S_n k' n' h) (snd v))\n              end\n end.\n\nEnd Tuples.\n\nSection Function_Tuples.\n\n   Variables A B: Type.\n\n   Fixpoint mult_app (n:nat){struct n}: Tuple (A->B) n -> A -> Tuple B n :=\n     match n return Tuple (A->B) n -> A -> Tuple B n with\n       0 => fun (f:unit)(a:A) => tt\n       | (S n') => fun (f:(A->B)*(Tuple (A->B) n')) (a:A)\n                     => let (f0,f'):=f in (f0 a, mult_app n' f' a)\n     end.\n\nEnd Function_Tuples.\n\n (** * Exporting notations and tactics *)\n \n (* Infix \" >>> \" := vmap (at level 20) : Vec_scope.\n  Infix \" `+` \" := vPlus (at level 20) : Vec_scope.\n  Notation \"v !! i\" := (vecfin v i) (at level 20) : Vec_scope. \n  Open Scope Vec_scope. *)\n\n  (* decompose vCons, VNil and Vplus automatically *)\n  Ltac vNil_vcons H x  :=\n        match x with\n        | context [?a + ?b] =>  destruct (vplusView a b H)\n        | 0    => destruct (vNil H)\n        | _ => destruct (vCons H)\n        end.\n  \n   Ltac vecRwt :=\n      match goal with\n      | [ |- context[vrev (vrev ?v)]] => let R := constr:(vrev_inv v) in rewrite R\n      | [|- context[vrev (vSnoc ?x ?v)]] => let R := constr:(vrevSnoc x v) in rewrite R\n      | [ |- context[vlast (vcons ?x ?v)]] => let R := constr:(vlast_vcons x v) in rewrite R\n      | [ |- context[vlast (vSnoc ?x ?v)]] => let R := constr:(vlast_vSnoc x v) in rewrite R\n      | [ |- context[vfirst (vcons ?x ?v)]] => let R := constr:(vfirst_vcons v) in rewrite R\n      | [ |- context[vfirst (vSnoc ?x ?v)]] => let R := constr:(vfirst_vSnoc x v) in rewrite R\n      | [ |- context[vlast (vrev ?v)]] => let R := constr:(vlast_rev v) in rewrite <- R\n      | [ |- _] => \n            match goal with\n            | [ |- context[vPlus (vmap ?F v) (vmap _ ?h)]] =>\n                     let R := constr:(vplusMap F v h) in rewrite R\n             end\n      end. \n\n   (* simpliy cases with vhead, vtail, vplus and do rewrites *)\n  \n   Ltac vSimp_aux :=\n        match goal with\n       | [ H : Vec _ ?n |- _ ] => vNil_vcons H n\n       | [ |- context[vhead v]] =>  unfold vhead; simpl\n       | [ |- context[vtail v]] =>  unfold vhead; simpl\n       | [ H : ?X |- _ ] => match X with\n                            | context[vhead] =>  unfold vhead in *; simpl in *\n                            | context[vtail] =>  unfold vhead in *; simpl in *\n                            | context[vfirst] =>  unfold vfirst in *; simpl in *\n                            | context[vlast] =>  unfold vlast in *; simpl in *\n                            end\n       end. \n   Ltac vSimp := repeat vecRwt; repeat vSimp_aux.\n", "meta": {"author": "rawlep", "repo": "ArithmeticAnaysisOfPolymorphicPrograms", "sha": "1e7919ade56888a7134597e25d9fb1438e24a75b", "save_path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms", "path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms/ArithmeticAnaysisOfPolymorphicPrograms-1e7919ade56888a7134597e25d9fb1438e24a75b/Vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8103043567871476}}
{"text": "(* 1.1 *)\n\nDefinition negb (b: bool) := if b then false else true.\n\nDefinition andb (b1 b2: bool) := if b1 then b2 else false.\n\nEval compute in  (fun x:bool => negb (andb false x)).\nEval compute in  (fun x:bool => negb (andb x false)).\n\n(* 1.2 *)\n\nParameter (A B : Type) (t1:A) (t2:B).\n\nFail Definition g {A B} (b:bool) := match b with true => t1 | false => t2 end.\n\nDefinition g (b:bool)  := \n\tmatch b return (if b then A else B) with true => t1 | false => t2 \nend.\n\nEval compute in (g true).\nEval compute in (g false).\n\nDefinition g2 (b:bool) := \n\tmatch negb b as b0 return (if b0 then B else A) with true => t2 | false => t1 \nend.\n\n(* 1.3 *)\n\nInductive even : nat -> Prop :=\n| even0 : even 0\n| evenS n : even n -> even (S (S n)).\n\nLemma even_is_double : forall n, even n -> exists m, n=m+m.\nProof.\n\tintros.\n\tinduction H.\n\t- exists 0.\n\t  intuition.\n\t- destruct IHeven.\n\t  exists (S x).\n\t  rewrite H0.\n    simpl.\n    intuition.\nQed.\n\nLemma even_is_double' : forall n,\n(even n -> exists m, n=m+m) /\\ (even (S n) -> exists m, n=S(m+m)).\nProof.\n  intro.\n  induction n; split; intro.\n  - exists 0. intuition.\n  - inversion H.\n  - destruct IHn.\n    specialize (H1 H).\n    destruct H1.\n    exists (S x).\n    simpl.\n    rewrite H1.\n    intuition.\n  - destruct IHn.\n    inversion H.\n    specialize (H0 H3).\n    destruct H0.\n    exists (x).\n    f_equal.\n    assumption.\nQed.\n    \nRequire Import List.\nImport ListNotations.\n\nFixpoint belast (x:nat) (l: list nat) : list nat := \n  match l with \n  |[] => []\n  |y::l => x::(belast y l)\n  end.\n\nLemma length_belast (x : nat) (s : list nat) : length (belast x s) = length s.\nProof.\n  revert x.\n  induction s.\n  - unfold belast. reflexivity.\n  - intro. \n    simpl.\n    specialize (IHs a). \n    f_equal.\n    assumption.\nQed.\n\nFixpoint skip (l : list nat) : list nat := \n  match l with \n  |x::(y::ll) => x:: skip (ll)\n  |_=> []\nend.\n\nParameter (x y z : nat).\nEval compute in (skip [x;y;z]).\nEval compute in (belast y (skip [x;y;z])).\n\nRequire Import Lia.\n\nLemma length_skip :\nforall l, 2 * length (skip l) <= length l.\nProof.\n  fix H 1.\n  intro.\n  destruct l; simpl. \n  - trivial.\n  - destruct l; simpl. \n    * auto.\n    * specialize (H l).\n      lia.\nQed.\n    \nFixpoint prodn (A:Type) (n:nat) : Type := \n  match n with \n  |0 => unit\n  |1 => A\n  |S n => prod A (prodn A n)\n  end.\n\nEval compute in (prodn nat 10).\n\nFixpoint length {A:Type} (l:list A) : nat := \n  match l with \n  |[] => 0\n  |h::t => S (length t)\n  end.\n\nFixpoint embed {A:Type} (l:list A) : prodn A (length l) :=\n  match l return prodn A (length l) with \n  |[] => tt\n  |x::l' => \n    let p' : prodn A (length l') := embed l' in\n    let h : prodn A (length l') -> prodn A (length (x::l')) :=\n      match l' with \n      |[] => fun _:unit => x\n      |x2::ll => \n        fun p' : prodn A (length (x2::ll)) => \n        (x,p')\n      end\n    in \n    h p' \n  end.\n\nEval compute in (embed [1;5;6;8;7;6;3;4]).\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/tp3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8103043483999278}}
{"text": "Require Import ssreflect.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive natural : Set :=\n  | O : natural\n  | S : natural -> natural.\n\nFixpoint plus (a : natural) (b : natural) : natural :=\n  match a with\n  | O => b\n  | S n => S (plus n b)\n  end.\nNotation \"a +++ b\" := (plus a b) (at level 50, left associativity).\n\nAxiom a_plus_one : forall a, a +++ S O = S a.\nAxiom a_plus_s_b : forall a b, a +++ S b = S (a +++ b).\n\nLemma o_plus_a : forall a, O +++ a = a.\nProof. done. Qed.\n\nLemma a_plus_o : forall a, a +++ O = a.\nProof. by elim => > //= ->. Qed.\n\nExample two_plus_two : S (S O) +++ S (S (S O)) = S (S (S (S (S O)))).\nProof. done. Qed.\n\nLemma plus_comm : forall a b, a +++ b = b +++ a.\nProof.\n  elim => [| a IHa] b;\n    by [rewrite a_plus_o | rewrite a_plus_s_b -IHa].\nQed.\n\nLemma s_a_plus_b : forall a b, S a +++ b = S (a +++ b).\nProof. done. Qed.\n\nLemma plus_assoc : forall a b c, a +++ (b +++ c) = (a +++ b) +++ c.\nProof.\n  move => a + c; elim=> /= [| b IHb].\n  - by rewrite a_plus_o.\n  - by rewrite a_plus_s_b IHb a_plus_s_b s_a_plus_b.\nQed.\n\nLemma s_a_eq_s_b : forall a b, S a = S b -> a = b.\nProof.\n  (* TODO: replace inversion by ssreflect more natural (haha) approach *)\n  move => > succ_eq; by inversion succ_eq.\nQed.\n\nLemma a_eq_b : forall a b, a = b -> S a = S b.\nProof. by move => > ->. Qed.\n\nFixpoint mul (n : natural) (m : natural) : natural :=\n  match n with\n  | O => O\n  | S num => m +++ (mul num m)\n  end.\nNotation \"A *** B\" := (mul A B) (at level 40, left associativity).\n\nAxiom a_mul_o : forall a, a *** O = O.\nAxiom a_mul_s_b : forall a b, a *** S b = a +++ (a *** b).\n\nLemma o_mul_a : forall a, O *** a = O.\nProof. done. Qed.\n\nLemma a_mul_s_o : forall a, a *** S O = a.\nProof.\n  elim => [| a IHa]; by [|rewrite -{2}IHa].\nQed.\n\nLemma s_o_mul_a : forall a, S O *** a = a.\nProof.\n  move => > //=; by rewrite a_plus_o.\nQed.\n\nLemma mul_comm : forall a b, a *** b = b *** a.\nProof.\n  elim => [| a IHa] b; by [rewrite a_mul_o | rewrite a_mul_s_b -IHa].\nQed.\n\nLemma s_a_mul_b : forall a b, S a *** b = b +++ (b *** a).\nProof.\n  elim => /= [| a IHa] b;\n    by [rewrite a_mul_o | rewrite a_mul_s_b mul_comm].\nQed.\n\nLemma mul_distr : forall a b c, a *** (b +++ c) = a *** b +++ a *** c.\nProof.\n  move => a + c; elim => [| b IHb].\n  - by rewrite a_mul_o.\n  - by rewrite a_mul_s_b -plus_assoc -IHb -a_mul_s_b -s_a_plus_b.\nQed.\n\nLemma mul_assoc : forall a b c, a *** (b *** c) = (a *** b) *** c.\nProof.\n  move => a b +; elim => [| c IHc].\n  - by rewrite 3! a_mul_o.\n  - by rewrite 2! a_mul_s_b; symmetry; rewrite mul_comm mul_distr mul_comm IHc.\nQed.\n", "meta": {"author": "remimimimimi", "repo": "peano", "sha": "873e59e71519ed4af7c9fd897ffdc1a5676f9604", "save_path": "github-repos/coq/remimimimimi-peano", "path": "github-repos/coq/remimimimimi-peano/peano-873e59e71519ed4af7c9fd897ffdc1a5676f9604/theorems/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.810256318272127}}
{"text": "(* chapter 2 of \"coq in a hurry\" *)\n\n(* Constants are defined with the Definition keyword *)\n\nDefinition example1anon := fun x : nat => x*x+2*x+1.\n\n(* alternative definition, without an anonymous function: *)\n\nDefinition example1 (x : nat) := x * x+2 * x+1.\n\nCheck example1anon.\nCheck example1.\n(* nat -> nat *)\n\nCompute example1 1.\n(* = 4 : nat *)\n\n(* the \"Reset\" command will force Coq to forget a definition you just made *)\n\n(* Reset example1. *)\n\n(* I'm assuming this is more useful in an interpreter, rather than executing lines in a file *)\n\n(* \"Print\" will show you the definition of a command *)\n\nPrint example1.\n\n(*\n  example1\u00a0=\u00a0fun\u00a0x\u00a0:\u00a0nat\u00a0=>\u00a0x\u00a0*\u00a0x\u00a0+\u00a02\u00a0*\u00a0x\u00a0+\u00a01\n\u00a0\u00a0\u00a0\u00a0\u00a0:\u00a0nat\u00a0->\u00a0nat\n\n  Argument\u00a0scope\u00a0is\u00a0[nat_scope]\n*)\n\n(* booleans are \"true\" and \"false\" *)\n\nRequire Import Bool.\n\nCompute if true then 3 else 5.\n\n(* = 3 : nat *)\n\nSearchPattern bool.\n\n(*\n  \"SearchPattern\" takes a pattern and returns any symbol whose type finishes with that pattern\n  \"Search\" takes a list of patterns and returns any symbol whose type contains all the patterns in the list\n\n  kind of like a regex search on function signatures\n*)\n\n\nRequire Import Arith.\n\n(*\n  For natural numbers, we can think of each number as satisfying one of two properties:\n  - it is 0\n  - it is a successor of some natural number P\n\n  For example, see the is_zero function below, which uses pattern matching to identify if a number is zero or not:\n*)\n\nDefinition is_zero (n:nat) :=\n  match n with\n    0 => true\n    | S p => false\n  end.\n\n\n(* Recursive functions need to be declared using the keyword \"Fixpoint\" *)\n\nFixpoint sum_n n :=\n  match n with\n    0 => 0\n  | S p => p + sum_n p\n  end.\n\nCompute sum_n 4.\n(*  = 6 : nat *)\n\n(*\n  Coq will check that the recursive call to a function occurs on a subterm of the initial argument\n\n  Calling sum_n on (S p) would have thrown an error, instead of running forever\n*)\n\n(* We can also use ~deep~ pattern matching: *)\n\nFixpoint evenb n :=\n  match n with\n    0 => true\n  | 1 => false\n  | S (S p) => evenb p\n  end.\n\nCompute evenb 6. (* true *)\nCompute evenb 7. (* false *)\n\n(* Lists *)\n\nRequire Import List.\n\nCheck 1::2::3::nil. (* : list nat *)\n\n(* list concatenation: ++ or app *)\n\nCheck 1::2::nil ++ 3::nil.\nCompute 1::2::nil ++ 3::nil. (* 1::2::3::nil : list nat *)\n\n(* map does what you'd expect *)\n\nCompute map (fun x => x + 3) (1::2::3::nil). (* 4::5::6::nil *)\nCompute map S (1::22::3::nil). (* 2::23::4::nil *)\n\nCompute let l := (1::2::3::nil) in l ++ map (fun x => x + 3) l.\n(* 1::2::3::4::5::6::nil *)\n\n(* \"Search\" can give us all known theorems (in scope) that mention a given symbol *)\nSearch Nat.eqb.\n\nLocate \"_ =? _\".\n(* \"x\u00a0=?\u00a0y\"\u00a0:=\u00a0Nat.eqb\u00a0x\u00a0y\u00a0:\u00a0nat_scope\u00a0(default\u00a0interpretation) *)\n\n(* exercise: write a function that takes an input n and returns a list with elements 0 through n - 1 *)\n\nFixpoint list_n n :=\n  match n with\n    0 => nil\n  | S p => p :: list_n p\n  end.\n\nCompute list_n 4.\n\n(* Gah! it's backwards. turns out the solution was this: *)\nFixpoint list_n_aux (n:nat)(m:nat) :=\n  match n with\n    0 => nil\n  | S p => m :: list_n_aux p (m+1)\n  end.\n\nDefinition list_n_solution n := list_n_aux n 0.\n\nCompute list_n_solution 4.\n\n(*\n  Exercise on sorting: write two functions:\n  - return true if:\n    - list length < 2\n    - given a :: b :: tail, a < b\n  - return true if input list is sorted\n*)\n\nFixpoint first_two_ordered list :=\n  match list with\n    nil => true\n  | head :: nil => true\n  | frst :: scnd :: tail => frst <? scnd\n  end.\n\nCompute first_two_ordered (1::2::nil).\nCompute first_two_ordered (2::nil).\nCompute first_two_ordered (3::2::nil).\n\nSearch andb.\n\nFixpoint is_sorted list :=\n  match list with\n    nil => true\n  | head :: nil => true\n  | frst :: tail => andb (first_two_ordered list) (is_sorted tail)\n  end.\n\n\nCompute is_sorted (1::2::3::nil).\nCompute is_sorted (1::2::3::1::nil).\nCompute is_sorted (1::2::nil).\nCompute is_sorted (1::nil).\n\n\n(* Example: count occurrences of element in list *)\nFixpoint count list n :=\n  match list with\n    nil => 0\n  | head :: tail => (if (head =? n) then 1 else 0) + (count tail n)\n  end.\n\nCompute count (1::2::3::nil) 1.\nCompute count (1::2::3::1::3::4::nil) 3.\n\n", "meta": {"author": "SoryRawyer", "repo": "coq-hurry-notes", "sha": "50fc2a1643b6adc01b9da4788efee1b929619e13", "save_path": "github-repos/coq/SoryRawyer-coq-hurry-notes", "path": "github-repos/coq/SoryRawyer-coq-hurry-notes/coq-hurry-notes-50fc2a1643b6adc01b9da4788efee1b929619e13/ch2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.9099070097026719, "lm_q1q2_score": 0.81008495704625}}
{"text": "\nModule Playground1.\n\nInductive bool : Type :=\n  | False\n  | True\n.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat\n.\n\nDefinition one := S O.\n\nDefinition pred (n: nat) := \n  match n with \n  | O => O\n  | S n => n\n  end.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\n\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\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\nFixpoint eq (n m : nat) : bool :=\n  match n, m with\n  | O, O => True\n  | O, S _ => False\n  | S _, O => False\n  | S n', S m' => eq n' m'\n  end.\n\nFixpoint leq (n m : nat) : bool :=\n  match n,m with \n  | O, O => True\n  | O, S _ => True\n  | S _, O => False\n  | S n', S m' => leq n' m'\n  end.\n\nDefinition andb ( n m : bool) : bool := \n  match n,m with\n  | True, True => True\n  | _, _ => False\n  end.\nDefinition notb (n:bool) : bool :=\n  match n with\n  | True => False\n  | False => True\n  end.\nDefinition orb (n m: bool) : bool :=\n  match n,m with\n    |False,False => False\n    |_,_ => True\n  end.\n\nDefinition less (n m: nat) : bool :=\n  andb  (leq n m) (notb (eq n m ) ).  \n\n\nExample test_less: (less (S(S(S(S O)))) (S(S(S O) ))) = False.\nProof.\nsimpl.\ncompute.\nreflexivity.\nQed.\n\n\n(*Now, the real deal!*)\n\nTheorem zero_absorption_l: forall n: nat , O + n = n.\nProof.\nintros n.\nreflexivity.\nQed.\n\nTheorem one_absorption_l: forall n: nat ,\n                            mult  O n = O.\nProof.\nintros n.\nsimpl.\ncompute.\nreflexivity.\nQed.\n\nTheorem plus_id_example: forall n m : nat , \n                           n = m -> n + n = m + m.\nProof.\nintros n m.\nintros H.\nrewrite <- H.\nreflexivity.\nQed.\n\n(* Exercise *)\n\n\nTheorem plus_id_exercise: forall n m o: nat, \n                            n=m -> m = o -> n + m = m + o.\nintros n m o.\nintros H1 H2.\nrewrite -> H1.\nrewrite -> H2.\nreflexivity.\nQed.\n\n(* Exercise *)\n\n\nTheorem mult_S_1 : forall n m : nat,\n                     m = S n -> \n                     m * (S O + n) = m * m.\nProof.\nintros n m H.\nsimpl.\nrewrite -> H.\nreflexivity.\nQed.\n\n\nTheorem plus_1_neq_0: forall n : nat, \n                        eq  (n + one) O = False.\nProof.\nintros n.\ndestruct n as [| n'].\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\n\nTheorem double_negation: forall b : bool,\n                           notb (notb b) = b.\nProof.\ndestruct b as [|b'].\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\n(* Exercise *)\nTheorem identity_fn_applied_twice: forall \n                                     ( f : bool -> bool ), \n                                     ( forall (x:bool), f x = x ) ->\n                                     forall (b: bool), f (f b) = b.\nProof.\nintros f H b.\nrewrite -> H.\nrewrite -> H.\nreflexivity.\nQed.\n\n(* Exercise *)\n\nTheorem not_fn_applied_twice: forall \n                                     ( f : bool -> bool ), \n                                     ( forall (x:bool), f x = notb x ) ->\n                                     forall (b: bool), f (f b) = b.\nProof.\nintros f H b.\nrewrite -> H.\nrewrite -> H.\ndestruct b as [|b'].\nreflexivity.\nreflexivity.\nQed.\n\n\n(* Exercise  i  failed\n\nLemma and_with_false: forall (b: bool), \n                        and False b = False.\nProof.\nintro b.\nreflexivity.\nQed.\n\n\n\n\nLemma or_with_true: forall (b: bool),\n                      or True b = True.\nProof.\nintro b.\nreflexivity.\nQed.\n\n\nTheorem andb_eq_orb :   forall (b c : bool),\n                          (and b c = or b c) ->\n                          b = c.\n\nProof.\n  destruct b.\n  intros c.\n  intros H.\n  rewrite <- or_with_true with c.\n  rewrite <- H.\n  destruct c.\n  reflexivity.\n  reflexivity.\n  intros c.\n  intros H.\n  rewrite <- andb_always_false with c.\n  rewrite -> H.\n  destruct c.\n  reflexivity.\n  reflexivity.\nQed.\n\nProof.\n  destruct b.\nintros c H.\nrewrite <- and_with_false with c.\n\n\n  intros b c.\n  destruct b. destruct c.\n  reflexivity.\n  simpl.\n  intro H.\nreflexivity.\n  intro H. \n  rewrite H.\nreflexivity.\nsimpl.\n\nreflexivity.\n\nTheorem zero_absorption_r: forall n: nat, n + O = n.\nintros n.\n\ncompute.\nreflexivity.\nQed.\n\nTheorem plus_comm: forall (n m: nat), n + m = m + n.\nProof.\n\nintros n m.*)\n\n\n\n\nEnd Playground1.\n", "meta": {"author": "sayon", "repo": "software-foundations", "sha": "2579082ebc2e9b77365ff57d6857c98dc93d5aa2", "save_path": "github-repos/coq/sayon-software-foundations", "path": "github-repos/coq/sayon-software-foundations/software-foundations-2579082ebc2e9b77365ff57d6857c98dc93d5aa2/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.809968396911477}}
{"text": "Inductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday    => tuesday\n  | tuesday   => wednesday\n  | wednesday => thursday\n  | thursday  => friday\n  | friday    => monday\n  | saturday  => monday\n  | sunday    => monday\n  end.\n\nCompute (next_weekday friday).\n\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\n\nCheck (negb true).\n\nCheck negb.\n\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\n\nInductive color : Type :=\n  | black : color\n  | white : color\n  | primary : rgb -> color.\n\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\nDefinition isred (c : color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\n  end.\n\n\nModule NatPlayground.\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 NatPlayground.\n\nCheck (S (S (S (S O)))).\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nCompute (minustwo 4).\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatPlayground2.\n\n  Fixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n  Compute (plus 3 2).\n  \nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n  match (n, m) with\n  | (O , _) => O\n  | (S _ , O) => n\n  | (S n', S m') => minus n' m'\n  end.\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 beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\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\" := (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\nTheorem plus_O_n : forall (n : nat), 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall  n:nat, 1 + n = S n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_0_l : forall  n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m:nat, n = m -> n + n = m + m.\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite <- H.\n  reflexivity. Qed.\n\n\nTheorem mult_0_plus : forall n m : nat, (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat, beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  simpl. (* does nothing! *)\nAbort.\n\nTheorem plus_1_neq_0 : forall n : nat, beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem negb_involutive : forall b : bool, negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity. Qed.\n\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b.\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\nTheorem plus_1_neq_0' : forall n : nat, beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nRequire Export Basics.", "meta": {"author": "anindoasaha", "repo": "software_foundations", "sha": "74d227d5d3eb41b1ce69b2786adfa2cddbefb44f", "save_path": "github-repos/coq/anindoasaha-software_foundations", "path": "github-repos/coq/anindoasaha-software_foundations/software_foundations-74d227d5d3eb41b1ce69b2786adfa2cddbefb44f/logical_foundations/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.8099454376188172}}
{"text": "Inductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b : bool) : bool := \n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b_1 : bool) (b_2 : bool) : bool := \n  match b_1 with\n  | true => b_2\n  | false => false\n  end.\n\nDefinition orb (b_1 : bool) (b_2 : bool) : bool := \n  match b_1 with\n  | true => true\n  | false => b_2\n  end.\n\nCompute negb true.\nCompute andb true false.\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(* Notation \"! x\" := (negb x). *)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nCompute true && false.\n\nDefinition andb3 (b_1 : bool) (b_2 : bool) (b_3 : bool) : bool := \n  andb b_1 (andb b_2 b_3).\n\nExample test_andb31: andb3 true true true = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: andb3 false true true = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: andb3 true false true = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: andb3 true true false = false.\nProof. simpl. reflexivity. Qed.\n\nCheck andb3.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary _ => false\n  end.\n\nCompute monochrome (primary blue).\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nCheck S.\n\nInductive bit : Type :=\n  | B_0\n  | B_1.\n\nInductive nybble : Type :=\n  | bits (b_0 b_1 b_2 b_3 : bit).\n\nCheck bits B_0 B_0 B_0 B_0.\n\nDefinition all_zero (bits : nybble) : bool := \n  match bits with\n  | bits B_0 B_0 B_0 B_0 => true\n  | bits _ _ _ _ => false\n  end.\n\nCompute all_zero (bits B_0 B_0 B_0 B_0).\nCompute all_zero (bits B_0 B_0 B_0 B_1).\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/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.9005297914570319, "lm_q1q2_score": 0.8096855961044719}}
{"text": "Require Export Induction.\nModule NatList.\n\nInductive natprod : Type := \n  | pair : nat->nat->natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat := \n  match p with \n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat := \n  match p with \n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with \n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with \n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with \n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\n  Qed.\n\nTheorem surjective_pairing_stuck : \n  forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. Abort.\n\nTheorem surjective_pairing : \n  forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\n  Qed.\n\n(* Exercise snd_fst_is_swap *)\n\nTheorem snd_fst_is_swap : \n  forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\n  Qed.\n\n(* Exercise fst_swap_is_snd *)\nTheorem fst_swap_is_snd : \n  forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m].\n  simpl.\n  reflexivity.\n  Qed.\n\nInductive natlist : Type := \n  | nil : natlist\n  | cons : nat->natlist->natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nNotation \"x :: l\" := (cons x l)\n                    (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := \n  (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nFixpoint repeat (n count : nat) : natlist := \n  match count with \n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat := \n  match l with \n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with \n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                  (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat)(l:natlist) : nat\n  := \n  match l with \n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with \n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(* Exercise list_funs *)\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with \n  | nil => nil\n  | O :: t => nonzeros t\n  | (S n') :: t => (S n') :: (nonzeros t)\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nSearch oddb.\n\nCompute (oddb 0).\n\nFixpoint oddmembers (l:natlist) : natlist\n  := match l with \n  | nil => nil\n  | h :: t =>\n    match (oddb h) with \n    | true => h :: (oddmembers t)\n    | false => oddmembers t\n    end\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat\n  := length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(* Exercise alternate *)\nFixpoint alternate (l1 l2 : natlist) : natlist\n  := match l1 with \n  | nil => l2\n  | h::t => \n    match l2 with \n    | nil => l1\n    | h2::t2 => h :: h2 :: (alternate t 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 beq_nat (n m : nat) : bool := \n  match n with \n  | O => match m with \n        | O => true\n        | S m' => false\n        end\n  | S n' => match m with  \n        | O => false\n        | S m' => beq_nat n' m'\n        end\n  end.\n\nCompute (beq_nat 3 2).\nCompute (1 + 2).\n\n(* Exercise bag_functions *)\nFixpoint count(v:nat)(s:bag) : nat\n  := \n  match s with \n  | nil => 0\n  | h :: t => \n    match (beq_nat h v) with \n    | true => 1 + count v t\n    | false => count v t\n    end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\nDefinition sum(b1:bag)(b2:bag) : bag :=\n  match b1 with \n  | nil => b2\n  | _ => b1 ++ b2\n  end.\n\nExample test_sum1: count 1 (sum [1;2;3][1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add(v:nat)(s:bag) : bag :=\n  v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member(v:nat)(s:bag) : bool \n  := negb (beq_nat (count v s) 0).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* Exercise bag more functions *)\nFixpoint remove_one(v:nat)(s:bag) : bag :=\n  match s with \n  | nil => nil\n  | h :: t => \n    match (beq_nat h v) with \n    | true => t\n    | false => h :: (remove_one v t)\n    end\n  end. \n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all(v:nat)(s:bag) : bag :=\n  match s with \n  | nil => nil\n  | h :: t => \n    match (beq_nat h v) with \n    | true => remove_all v t\n    | false => h :: (remove_all v t)\n    end\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\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\nCompute (member 2 [1;2;3]).\n\nFixpoint subset (s1:bag)(s2:bag) : bool :=\n  match s1 with \n  | nil => true\n  | h :: t => \n    match (member h s2) with \n    | true => subset t (remove_one h s2)\n    | false => false\n    end\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l : natlist, \n  pred (length l) = length (tl l).  \nProof.\n  intros l. destruct l as [| n l'].\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nTheorem app_assoc: forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl.\n  rewrite -> IHl1'.\n  reflexivity.\n  Qed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with \n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem rev_length_firsttry: forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl.\n  rewrite <- IHl'. \n  Abort.\n\nTheorem app_length: forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\n  Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> app_length.\n  rewrite -> plus_comm.\n  simpl.\n  rewrite <- IHl'.\n  reflexivity.\n  Qed.\n\nSearch rev.\n\n(* Exercise list_exercise *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'.\n  reflexivity.\n  Qed.\n\nSearch app.\n\nTheorem rev_app_distr : forall l1 l2 : natlist, \n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1 as [| n l' H].\n  - simpl. rewrite -> app_nil_r.\n  reflexivity.\n  - simpl. rewrite -> H.\n  rewrite -> app_assoc.\n  reflexivity.\n  Qed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l' H].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n  rewrite -> H.\n  simpl.\n  reflexivity.\n  Qed.\n\nTheorem app_assoc4: forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  induction l1 as [| n l' H].\n  - simpl.\n  rewrite <- app_assoc.\n  reflexivity.\n  - simpl.\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nLemma nonzeros_app: forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n l' H].\n  - simpl. reflexivity.\n  - destruct n.\n    + simpl. rewrite H. reflexivity.\n    + simpl. rewrite H. reflexivity.\n  Qed.\n\n(* Exercise beq_natlist *)\n\nFixpoint beq_natlist(l1 l2 : natlist) : bool\n  := \n  match l1 with \n  | nil => \n    match l2 with\n    | nil => true\n    | _ => false\n    end\n  | h :: t => \n    match l2 with \n    | nil => false\n    | h2 :: t2 => \n      match (beq_nat h h2) with \n      | true => beq_natlist t t2\n      | false => false\n      end\n    end\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l : natlist,\n  true = beq_natlist l l.\nProof.\n  intros l. induction l as [| n l' H].\n  - reflexivity.\n  - induction n as [| n'' In].\n    + simpl. rewrite H. reflexivity.\n    + rewrite In. simpl. rewrite <- H.\n    reflexivity.\n  Qed.\n\n(* Exercise bag proofs *)\nTheorem count_member_nonzero: forall s : bag,\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. induction s as [| n s' H].\n  - reflexivity.\n  - simpl. reflexivity.\n  Qed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' H].\n  - simpl. reflexivity.\n  - simpl. rewrite H. reflexivity.\n  Qed.\n\nTheorem remove_decreases_count: forall (s:bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. induction s as [| n s' H].\n  - simpl. reflexivity.\n  - induction n as [| n' Hn'].\n    + simpl. rewrite ble_n_Sn. reflexivity.\n    + simpl. rewrite H. reflexivity.\n  Qed.\n\n(* Exercise rev injective *)\nTheorem rev_injective: forall l1 l2 : natlist,\n  rev l1 = rev l2 ->\n  l1 = l2.\nProof.\n  intros l1 l2.\n  intros H.\n  Search rev.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\n  Qed.\n\nFixpoint nth_bad(l:natlist)(n:nat) : nat :=\n  match l with \n  | nil => 42\n  | a :: l' => match beq_nat n O with \n              | true => a\n              | false => nth_bad l' (pred n)\n              end\n  end.\n\nInductive natoption : Type :=\n  | Some : nat->natoption\n  | None : natoption.\n\nFixpoint nth_error(l:natlist)(n:nat) : natoption \n  := match l with \n  | nil => None\n  | a :: l' => \n    match beq_nat n O with \n    | true => Some a\n    | false => nth_error l' (pred n)\n    end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\nFixpoint nth_error' (l:natlist)(n:nat) : natoption :=\n  match l with \n  | nil => None\n  | a :: l' => \n    if beq_nat 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\n(* Exercise hd error *)\n\nDefinition hd_error(l:natlist) : natoption :=\n  match l with \n  | nil => None\n  | h :: _ => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(* Exercise option elim hd *)\nTheorem option_elim_hd : forall (l:natlist)(default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default.\n  induction l as [| n l' H].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  Qed.\n\nEnd NatList.\n\nInductive id : Type := \n  | Id : nat->id.\n\nDefinition beq_id(x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(* Exercise beq_id_refl *)\nTheorem beq_id_refl : forall x : id,\n  true = beq_id x x.\nProof.\n  intros x. destruct x as [n].\n  simpl. \n  induction n as [| n' H].\n  + reflexivity.\n  + simpl. rewrite H.\n  reflexivity.\n  Qed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id->nat->partial_map->partial_map.\n\nDefinition update (d:partial_map)\n  (x:id)(value:nat) : partial_map :=\n  record x value d.\n\nFixpoint find(x:id)(d:partial_map) : natoption :=\n  match d with \n  | empty => None\n  | record y v d' =>\n    if beq_id x y \n    then Some v\n    else find x d'\n  end.\n\n\n(* Exercise update_eq *)\nTheorem update_eq:\n  forall (d:partial_map)(x:id)(v:nat),  \n  find x (update d x v) = Some v.\nProof.\n  intros d x v. simpl. rewrite <- beq_id_refl.\n  reflexivity.\n  Qed.\n\n(* Exercise update_neq *)\nTheorem update_neq:\n  forall (d:partial_map)(x y : id)(o:nat),\n  beq_id x y = false -> \n  find x (update d y o) = find x d.\nProof.\n  intros d x y o eq.\n  simpl. rewrite -> eq.\n  reflexivity.\n  Qed.  \n\nEnd PartialMap.\n\n", "meta": {"author": "rpgzysb", "repo": "SoftwareFoundation", "sha": "4f987efcec24d880908edcb4f1c1cd3926c60291", "save_path": "github-repos/coq/rpgzysb-SoftwareFoundation", "path": "github-repos/coq/rpgzysb-SoftwareFoundation/SoftwareFoundation-4f987efcec24d880908edcb4f1c1cd3926c60291/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8991213711878918, "lm_q1q2_score": 0.8096855832906596}}
{"text": "Require Import ZArith Div2 Even.\nRequire Import Psatz.\nRequire Import Recdef.\nRequire Import Coq.NArith.BinNat.\nRequire Import Coq.Program.Wf.\nRequire Import Coq.NArith.BinNat.\n\nSection Expo.\n\n \n\n  Fixpoint power (x : Z) (n : nat) : Z :=\n    match n with\n    | O => 1%Z\n    | S n' => Z.mul x (power x n')\n    end.\n\n \n  Function fast_expo_acc (x acc : Z) (n : nat) {measure (fun i => i) n} : Z :=\n    match n with\n    | O => acc\n    | _ => match even_odd_dec n with\n          | left _ => fast_expo_acc (Z.mul x x) acc (div2 n)\n          | right _ => fast_expo_acc (Z.mul x x) (Z.mul x acc) (div2 n)\n          end\n    end.\n  Proof.\n    intros; apply lt_div2; lia.\n    intros; apply lt_div2; lia.\n  Defined.\n\n  Definition fast_expo (a : Z) (n : nat) : Z :=\n    fast_expo_acc a 1%Z n.\n\n\n  \n\n  Lemma power_unit :\n    forall m, power 1 m = 1%Z.\n  Proof.\n    induction m.\n    cbn.  auto.\n    cbn.  rewrite IHm.\n    auto.\n  Qed.\n\n  Lemma power_add_dist :\n    forall (x : Z) (n m : nat),\n      power x (n + m) = Z.mul (power x n) (power x m).\n  Proof.\n    intros.\n    induction n. \n    assert (power x 0 = 1%Z). cbn. auto.\n    rewrite H.\n    replace (0 + m)\n      with m by lia.\n    lia. \n    cbn. rewrite IHn. lia. \n  Qed.\n  \n  Lemma power_distribute :\n    forall (x : Z) (n m : nat),\n      power (power x n) m = power x (Nat.mul n m).\n  Proof.\n    intros x n m.\n    revert x n.\n    induction m.\n    + cbn. intros x n. replace (n * 0) with 0 by lia. \n      cbn.  auto.\n    + intros x n. cbn.\n      replace (n * S m) with (n + n * m) by lia.\n      rewrite power_add_dist.\n      f_equal. apply IHm.\n  Qed.\n  \n   \n       \n    \n  Lemma fast_power_acc :\n    forall (n : nat) (x ret : Z),\n      fast_expo_acc x ret n = Z.mul ret (power x n).\n  Proof.\n    Opaque Nat.div2.\n    induction n using lt_wf_ind; intros.  \n    rewrite fast_expo_acc_equation.\n    destruct n.\n    + cbn. lia.  \n    + destruct (even_odd_double (S n)) as [[H1 H2] [H3 H4]]. \n      unfold Nat.double in * |-.\n      destruct (even_odd_dec (S n)) as [Hl | Hr].\n      pose proof (lt_div2 (S n) (Nat.lt_0_succ n)).\n      pose proof (H (Nat.div2 (S n)) H0).\n      rewrite H5. f_equal.\n      assert (Hm : Z.mul x x = power x 2).\n      cbn. lia. rewrite Hm.\n      rewrite power_distribute.\n      replace (2 * Nat.div2 (S n)) with (double (Nat.div2 (S n))).\n      pose proof (even_double (S n) Hl). rewrite <- H6. auto. \n      unfold double. lia. \n      pose proof (lt_div2 (S n) (Nat.lt_0_succ n)).\n      pose proof (H (Nat.div2 (S n)) H0 (Z.mul x x) (Z.mul x ret)).\n      rewrite H5.\n      replace (x * ret * power (x * x) (Nat.div2 (S n)))%Z with\n          (ret * (x * power (x * x) (Nat.div2 (S n))))%Z by lia.\n      f_equal. cbn. f_equal.\n      assert (Hm : Z.mul x x = power x 2).\n      cbn. lia. rewrite Hm.\n      rewrite power_distribute.\n      pose proof (odd_double (S n) Hr).\n      assert (n = Nat.double (Nat.div2 (S n))) by lia.\n      replace (2 * Nat.div2 (S n)) with (double (Nat.div2 (S n))).\n      rewrite <- H7. auto.  \n      unfold Nat.double.  lia.\n  Qed.\n\n  Lemma slow_is_equal_to_fast :\n    forall a n, fast_expo a n = power a n.\n  Proof.\n    unfold fast_expo.\n    intros. rewrite fast_power_acc.\n    lia.\n  Qed.\n\n  \n  Fixpoint expo_recursive (m acc : Z) (p : positive) :=\n    match p with\n    | xH => Z.mul m acc\n    | xO w => expo_recursive (Z.mul m m) acc w\n    | xI w => expo_recursive (Z.mul m m) (Z.mul acc m) w\n    end.\n     \n     \n  Definition expo_acc (m acc : Z) (n : N) : Z :=\n    match n with\n    | N0 => acc \n    | Npos p => expo_recursive m acc p\n    end.\n\n  Eval compute in expo_acc 2 1 10.\n\n  Lemma binexpo_equal_power :\n    forall a acc n , expo_acc a acc n = Z.mul acc (power a (nat_of_N n)).\n  Proof.\n    intros a acc n.\n    revert a acc.\n    destruct n.\n    + intros a acc.\n      cbn. lia.\n    + induction p.\n      ++  intros a acc. cbn in *.\n          assert (Hm : Z.mul a a = power a 2).\n          cbn. lia.\n          pose proof (IHp (Z.mul a a) (Z.mul acc a)).\n          rewrite H.\n          replace (acc * a * power (a * a) (Pos.to_nat p))%Z\n            with (acc * (a * power (a * a) (Pos.to_nat p)))%Z by lia.\n          f_equal. rewrite Pos2Nat.inj_xI.\n          cbn. f_equal.  rewrite Hm.\n          rewrite power_distribute.\n          replace ((Pos.to_nat p + (Pos.to_nat p + 0))) with\n              (2 * Pos.to_nat p) by lia.  auto.\n      ++ intros a acc. cbn in *.\n         assert (Hm : Z.mul a a = power a 2).\n         cbn. lia.\n         pose proof (IHp (Z.mul a a) acc).\n         rewrite H. f_equal.\n         rewrite Pos2Nat.inj_xO.\n         rewrite Hm. rewrite power_distribute.\n         auto.\n      ++ intros a acc. cbn in *.\n         rewrite Pos2Nat.inj_1. cbn.\n         lia.\n  Qed.\n\n  Definition expo (a : Z) (m : N) : Z :=\n    expo_acc a 1 m.\n    \n\n  (* Fairly fast. I can't believe Coq is so good at computing stuff. \n     Kudos to Inria *)\n  Eval compute in expo 2 10000.\n\n  Lemma expo_is_equal_to_power :\n    forall a n, expo a n = power a (nat_of_N n).\n  Proof.\n    intros a n. unfold expo. \n    pose proof (binexpo_equal_power a 1 n).\n    lia.\n  Qed.\n  \n  \nEnd Expo.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtility", "sha": "3a25343d0a77177adb7530a08b0c7854bb1ed02f", "save_path": "github-repos/coq/mukeshtiwari-CoqUtility", "path": "github-repos/coq/mukeshtiwari-CoqUtility/CoqUtility-3a25343d0a77177adb7530a08b0c7854bb1ed02f/Binarypow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.8096609997175986}}
{"text": "(* Chapter 7: Properties of relations *)\n\nRequire Export SfLib.\n\nDefinition relation (X:Type) := X -> X -> Prop.\n\n(* le:  x <= y *)\nPrint le.\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\n\n(* Basic properties of relations *)\nDefinition partial_function {X:Type} (R:relation X) := forall x y1 y2 : X,\n  R x y1 -> R x y2 -> y1 = y2.\n\nTheorem le_not_partial_function: ~ (partial_function le).\nProof.\n  unfold not, partial_function. intros.\n  assert (0 = 1) as contra.\n  Case \"proof of contra\".\n    apply H with (x:=0). apply le_n. apply le_S. apply le_n.\n  inversion contra.\nQed.\n\n\nDefinition reflexive {X:Type} (R:relation X) :=\n  forall a:X, R a a.\n\nTheorem le_reflexive: reflexive le.\nProof.\n  unfold reflexive. intros.\n  apply le_n.\nQed.\n\n\nDefinition transitive {X:Type} (R:relation X) :=\n  forall a b c : X, R a b -> R b c -> R a c.\n\nTheorem le_transitive: transitive le.\nProof.\n  unfold transitive. intros. induction H0.\n  Case \"b<=c\". apply H.\n  Case \"b<=S c\". apply le_S. apply IHle.\nQed.\n\n\nTheorem lt_trans: transitive lt.\nProof.\n  unfold lt, transitive. intros a b c Hab Hbc.\n  apply le_S in Hab. apply le_transitive with (a := (S a)) (b := (S b)) (c := c).\n  apply Hab. apply Hbc.\nQed.\n\nTheorem lt_trans': transitive lt.\nProof.\n  unfold lt, transitive. intros a b c Hab Hbc. induction Hbc.\n  Case \"b<=0\". apply le_S. apply Hab.\n  Case \"b<=S\". apply le_S. apply IHHbc.\nQed.\n\nTheorem lt_trans'': transitive lt.\nProof.\n  unfold lt, transitive. intros n m o Hnm Hmo. induction o.\n  Case \"o=0\". inversion Hmo. apply le_S. apply IHo. inversion Hmo.\nAdmitted.\n\n\nTheorem le_Sn_le: forall n m, S n <= m -> n <= m.\nProof.\n  intros. apply le_transitive with (S n).\n  Case \"n<=S n\". apply le_S. reflexivity.\n  Case \"S n <= m\". apply H.\nQed.\n\n(* Exercise: * *)\nTheorem le_S_n: forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros. inversion H. reflexivity.\n  apply le_Sn_le. apply H1.\nQed.\n\n(* Exercise: * *)\nTheorem le_Sn_n: forall n,\n  ~ (S n <= n).\nProof.\n  unfold not. intros.\n  apply le_Sn_n in H. apply H.\nQed.\n\nDefinition symmetric {X:Type} (R:relation X) :=\n  forall a b : X, R a b -> R b a.\n\n(* Exercise: ** *)\nTheorem le_not_symmetric: ~ (symmetric le).\nProof.\n  unfold not, symmetric.\n  intros. assert (1 <= 0) as contra.\n  Case \"proof of assert\".\n    apply H with (b:=1). apply H. apply H. apply le_S. reflexivity.\n  inversion contra.\nQed.\n\nDefinition antisymmetric {X:Type} (R:relation X) := forall a b : X,\n  R a b -> R b a -> a = b.\n\n(* Exercise: ** *)\nTheorem le_antisymmetric: antisymmetric le.\nProof.\n  unfold antisymmetric. intros a b Hab Hba.\nAdmitted.\n\n\n(* Exercise: ** *)\nTheorem le_step: forall n m p,\n  n < m -> m <= S p -> n <= p.\nProof.\n  intros. apply le_transitive with n.\n  Case \"n<=n\". reflexivity.\n  Case \"n<=Sn\". unfold \"<\" in H. rewrite H0 in H. apply le_S_n. apply H.\nQed.\n\nDefinition preorder {X:Type} (R:relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nDefinition equivalence {X:Type} (R:relation X) :=\n  (preorder R) /\\ (symmetric R).\n\n(* Really a partial order. Coq stdlib calls it order *)\nDefinition order {X:Type} (R:relation X) :=\n  (preorder R) /\\ (antisymmetric R).\n\nTheorem le_order: order le.\nProof.\n  unfold order, preorder. split. split.\n  Case \"refl\". apply le_reflexive.\n  Case \"trans\". apply le_transitive.\n  Case \"antisymmetric\". apply le_antisymmetric.\nQed.\n\n\n\n(* Reflexive, transitive closure *)\nInductive clos_refl_trans {A:Type} (R:relation A) : relation A :=\n  | rt_step  : forall x y, R x y -> clos_refl_trans R x y\n  | rt_refl  : forall x, clos_refl_trans R x x\n  | rt_trans : forall x y z, clos_refl_trans R x y ->\n                             clos_refl_trans R y z ->\n                             clos_refl_trans R x z.\n\nTheorem next_nat_closure_is_le : forall n m,\n  n <= m <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n  Case \"->\".\n    intro H. induction H.\n    SCase \"le_n\". apply rt_refl.\n    SCase \"le_S\". apply rt_trans with m. apply IHle. apply rt_step. apply nn.\n  Case \"<-\".\n    intro H. induction H.\n    SCase \"rt_step\". inversion H. apply le_S. apply le_n.\n    SCase \"rt_refl\". apply le_n.\n    SCase \"rt_trans\".\n      apply le_transitive with y. apply IHclos_refl_trans1. apply IHclos_refl_trans2.\nQed.\n\n\n\n(* more useful definition of reflexive, transitive closure *)\nInductive refl_step_closure {X:Type} (R:relation X) : relation X :=\n| rsc_refl : forall x:X, refl_step_closure R x x\n| rsc_step : forall x y z : X, R x y ->\n                               refl_step_closure R y z ->\n                               refl_step_closure R x z.\n\n\nTactic Notation \"rt_cases\" tactic(first) ident(c) :=\n  first; [\n    Case_aux c \"rt_step\"\n  | Case_aux c \"rt_refl\"\n  | Case_aux c \"rt_trans\"\n  ].\n\nTactic Notation \"rsc_cases\" tactic(first) ident(c) :=\n  first; [\n    Case_aux c \"rsc_refl\"\n  | Case_aux c \"rsc_step\"\n  ].\n\n\n(* Need to check that the 2 definitions of reflexive, transitive closure are the\n   same\n*)\nTheorem rsc_R: forall (X:Type) (R:relation X) (x y : X),\n  R x y -> refl_step_closure R x y.\nProof.\n  intros.\n  apply rsc_step with y. apply H. apply rsc_refl.\nQed.\n\n\n(* Exercise: ** *)\nTheorem rsc_trans : forall (X:Type) (R:relation X) (x y z : X),\n  refl_step_closure R x y ->\n  refl_step_closure R y z ->\n  refl_step_closure R x z.\nProof.\n  intros. induction H.\n  Case \"refl\". apply H0.\n  Case \"step\". apply IHrefl_step_closure in H0.\nAdmitted.\n\n\n(* Exercise: *** *)\nTheorem rtc_rsc_coincide: forall (X:Type) (R:relation X) (x y : X),\n  clos_refl_trans R x y <-> refl_step_closure R x y.\nProof.\n  unfold iff. split. intros.\n  Case \"->\".\nAdmitted.", "meta": {"author": "bishboria", "repo": "software-foundations", "sha": "48da9007beb2e6692bab277c12ddc8e1a6c56b2c", "save_path": "github-repos/coq/bishboria-software-foundations", "path": "github-repos/coq/bishboria-software-foundations/software-foundations-48da9007beb2e6692bab277c12ddc8e1a6c56b2c/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8095059491582304}}
{"text": "Set Warnings \"-notation-overriden, -parsing\".\nRequire Export Tactics.\nCheck 3=3.\nCheck forall n m: nat, n + m = m + n.\nCheck 2=2.\nCheck forall n:nat, n = 2.\nCheck 3 = 4.\nTheorem plus_2_2_is_4:\n  2+2=4.\nProof. reflexivity. Qed.\nDefinition plus_fact: Prop := 2 + 2 = 4.\nCheck plus_fact.\nTheorem plus_fact_is_true: plus_fact.\nProof. reflexivity. Qed.\nDefinition is_three (n:nat): Prop := n = 3.\nCheck is_three.\nDefinition injective {A B} (f: A -> B) :=\n  forall x y: A, f x = f y -> x = y.\n\nLemma succ_inj: injective S.\nProof. intros n m H. inversion H. reflexivity. Qed.\nCheck @eq.\n\nExample and_example: 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\nLemma and_intro: forall A B: Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\nExample and_example': 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof. apply and_intro; reflexivity. Qed.\n\n(** *Exercise and_exercise *)\nExample and_exercise:\n  forall n m: nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  destruct n as [|n]; destruct m as [|m]; intros H; try inversion H.\n  split; reflexivity.\nQed.\n\nLemma and_example2: forall n m: nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H. destruct H as [Hn Hm]. rewrite Hn, Hm. reflexivity. Qed.\n\nLemma and_example2': forall n m: nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof. intros n m [Hn Hm]. rewrite Hn, Hm. reflexivity. Qed.\nLemma and_example2'': forall n m: nat, n = 0 -> m = 0 -> n + m = 0.\nProof. intros n m Hn Hm. rewrite Hn, Hm. reflexivity. Qed.\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.\nLemma proj1: forall P Q: Prop, P /\\ Q -> P.\nProof. intros P Q [HP HQ]. exact HP. Qed.\n(** *Exercise proj2 *)\nLemma proj2: forall P Q: Prop, P /\\ Q -> Q.\nProof. intros P Q [_ HQ]. exact HQ. Qed.\nTheorem and_commit: forall P Q: Prop, P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ]. split.\n  - exact HQ.\n  - exact HP.\nQed.\n(** *Exercise and_assoc *)\nTheorem and_assoc: forall P Q R: Prop,\n    P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]]. split.\n  - split.\n    + exact HP.\n    + exact HQ.\n  - exact HR.\nQed.\nCheck and.\n\nLemma or_example:\n  forall n m: nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn. reflexivity.\n  - rewrite Hm. symmetry. apply mult_n_O.\nQed.\nLemma or_intro: forall A B: Prop, A -> A \\/ B.\nProof. intros A B HA. left. exact HA. Qed.\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(** *Exercise mult_eq_0 *)\nLemma mult_eq_0: forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. destruct n.\n  - left. reflexivity.\n  - simpl in H. apply and_exercise in H. destruct H as [H _].\n    right. exact H.\nQed.\n\n(** *Exericse or_commut *)\nTheorem or_commut: forall P Q: Prop, P \\/ Q -> Q \\/ P.\nProof. intros P Q [p|q].\n       - right. exact p.\n       - left. exact q.\nQed.\nModule MyNot.\n  Definition not (P:Prop) := P -> False.\n  Notation \"~ x\" := (not x): type_scope.\n  Check not.\nEnd MyNot.\nTheorem ex_falso_quodlibet: forall P: Prop, False -> P.\nProof. intros P contra. destruct contra. Qed.\nFact not_implies_our_not: forall P : Prop,\n    ~ P -> (forall Q: Prop, P -> Q).\nProof.\n  intros P H Q p. apply H in p. destruct p. Qed.\nTheorem zero_not_one: ~(0 = 1).\nProof. intros contra. inversion contra. Qed.\nCheck (0 <> 1).\nTheorem zero_not_one': 0 <> 1.\nProof.\n  intros H. inversion H. Qed.\n\nTheorem not_False: ~ False.\nProof. unfold not. intros H. destruct H. Qed.\nTheorem contradiction_implies_anything: forall P Q: Prop,\n    P /\\ ~P -> Q.\nProof.\n  intros P Q [p np]. apply np in p. destruct p. Qed.\n\nTheorem double_neg: forall P: Prop, P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\n(** *Exercise double_neg_inf \nP implies ~~P for any P.\nAssume P. We need to prove ~~P, or that ~P doesn't hold.\nIndeed, if ~P holds, then P taken with ~P is a contradiction. *)\n(** *Exercise contrapositive *)\nTheorem contrapositive: forall P Q: Prop,\n    (P -> Q) -> (~Q -> ~P).\nProof. intros P Q H NQ p. apply NQ. apply H. exact p. Qed.\n(** *Exercise not_both_true_and_false *)\nTheorem not_both_true_and_false: forall P: Prop, ~ (P /\\ ~P).\nProof. intros P [p np]. apply np. exact p. Qed.\n(** *Exercise informal_not_PNP *)\nDefinition informal_not_PNP_TODO := 1.\n(* for any proposition P, ~(P /\\ ~ P).\n   That is, P /\\ ~P implies anything.\n   Indeed P /\\ ~P contrains both P and ~P, which give False term. *)\nTheorem not_true_is_false: forall b: bool, b <> true -> b = false.\nProof. intros [|] H.\n       - exfalso. apply H. reflexivity.\n       - reflexivity. Qed.\nLemma True_is_true: True.\nProof. apply I. Qed.\n\nModule MyIff.\n  Definition iff (P Q: Prop) := (P -> Q) /\\ (Q -> P).\n  Notation \"P <-> Q\" := (iff P Q) (at level 95, no associativity): type_scope.\nEnd MyIff.\nTheorem iff_sym: forall P Q: Prop, (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA]. split.\n  - apply HBA.\n  - apply HAB.\nQed.\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\n(** *Exercise or_distributes_over_and *)\nTheorem or_distributes_over_and: forall P Q R: Prop, P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split; intros H.\n  - destruct H as [p|H2]; split; try destruct H2 as [q r].\n    + left. exact p.\n    + left. exact p.\n    + right. exact q.\n    + right. exact r.\n  - destruct H as [H1 H2]. destruct H1 as [p|q].\n    + left. exact p.\n    + destruct H2 as [p|r].\n      * left. exact p.\n      * right. split. exact q. exact r.\nQed.\n\nRequire Import Coq.Setoids.Setoid.\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.\nLemma or_assoc: forall P Q R: Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H|[H|H]]; [left;left|left;right|right]; exact H.\n  - intros [[H|H]|H]; [left|right;left|right;right]; exact H.\nQed.\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. rewrite mult_0, mult_0, or_assoc.\n  reflexivity. Qed.\n\nLemma four_is_even: exists n: nat, 4 = n + n.\nProof. exists 2. reflexivity. Qed.\n\nTheorem exists_example_2: forall n, (exists m, n = 4 + m) -> exists o, n = 2 + o.\nProof.\n  intros n [m Hm]. exists (2+m). apply Hm. Qed.\n(** *Exercise dist_not_exist *)\nTheorem dist_not_exist: forall (X: Type)(P: X -> Prop),\n    (forall x, P x) -> ~(exists x, ~ P x).\nProof.\n  intros X P H E. destruct E as [e p]. apply p. apply H.\nQed.\n(** *Exercise dist_exists_or *)\nTheorem dist_exists_or: forall (X: Type)(P Q: X -> Prop),\n    (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros X P Q. split.\n  - intros [x [p|q]].\n    + left. exists x. exact p.\n    + right. exists x. exact q.\n  - intros [[x p]|[x q]]; exists x.\n    + left. exact p.\n    + right. exact q.\nQed.\n\nFixpoint In {A: Type}(x: A)(l: list A): Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1: In 4 [1;2;3;4;5].\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2: forall n, 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.\nQed.\n\nLemma In_map: forall (A B: Type)(f: A -> B) (l: list A)(x: A),\n    In x l -> In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - simpl. intros [].\n  - simpl. intros [H|H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** *Exercise in_map_iff *)\nLemma and_distributes_over_or: forall P Q R: Prop, P /\\ (Q \\/ R) <-> (P /\\ Q) \\/ (P /\\ R).\nProof.\n  intros P Q R. split.\n  - intros [p [q|r]].\n    + left. split; [exact p|exact q].\n    + right. split; [exact p|exact r].\n  - intros [[p q]|[p r]].\n    + split; [exact p|left;exact q].\n    + split; [exact p|right;exact r].\nQed.\nLemma In_map_iff:\n  forall (A B: Type) (f: A -> B) (l: list A) (y: B),\n    In y (map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n  intros A B f. induction l as [|h t I]; intros y; simpl; split.\n  - intros [].\n  - intros [_ [_ []]].\n  - intros [H|H].\n    + exists h. split; [exact H|left;reflexivity].\n    + apply I in H. destruct H as [m H]. exists m.\n      rewrite -> and_distributes_over_or. right. exact H.\n  - intros [m [H [H'|H']]].\n    + rewrite H'. left. exact H.\n    + right. apply I. exists m. split; [exact H|exact H'].\nQed.\n\n(** *Exersie In_app_iff *)\nLemma In_app_iff: forall A l l' (a: A),\n    In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a. generalize dependent l'. induction l as [|h t IH].\n  - intros l'. simpl. split.\n    + intros H; right; exact H.\n    + intros [H|H]; [inversion H|exact H].\n  - intros l'. simpl. split.\n    + intros [H|H].\n      * left. left. exact H.\n      * rewrite <- or_assoc. right. apply IH. exact H.\n    + intros [[H|H]|H].\n      * left. exact H.\n      * right. apply IH. left. exact H.\n      * right. apply IH. right. exact H.\nQed.\n\n(** *Exercise All *)\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.\nLemma All_in: forall T (P: T -> Prop)(l: list T),\n    (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l. induction l as [|h t IH].\n  - simpl. split.\n    + intros _. apply I.\n    + intros _ x [].\n  - simpl. split.\n    + intros H. split.\n      * apply H. left. reflexivity.\n      * apply IH. intros x H1. apply H. right. exact H1.\n    + intros [H1 H2] x [H3|H3].\n      * rewrite <- H3. exact H1.\n      * apply IH. exact H2. exact H3.\nQed.\n\n(** *Exercise combine_odd_even *)\nDefinition combine_odd_even (Podd Peven: nat -> Prop): nat -> Prop :=\n  fun n: nat => if oddb n then Podd n else Peven n.\n\nTheorem combine_odd_even_intro:\n  forall (Podd Peven: nat -> Prop)(n:nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n Ho He. unfold combine_odd_even.\n  destruct (oddb n).\n  - apply Ho. reflexivity.\n  - apply He. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd: forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n -> oddb n = true -> Podd n.\nProof.\n  intros Podd Peven n H H'. unfold combine_odd_even in H.\n  destruct (oddb n).\n  - exact H.\n  - inversion H'.\nQed.\n\nTheorem combine_odd_even_elim_even: forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n -> oddb n = false -> Peven n.\nProof.\n  unfold combine_odd_even. intros Podd Peven n H H'. destruct (oddb n).\n  - inversion H'.\n  - exact H.\nQed.\n\nCheck plus_comm.\n\nLemma plus_comm3:\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z. rewrite plus_comm. rewrite plus_comm. Abort.\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 plu_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\nExample lemma_application_ex:\n  forall {n: nat} {ns: list nat},\n    In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1  _ _ (In_map_iff _ _ _ _ _) H) as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\nExample function_equality_ex1: plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2:\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\nAbort.\n\nAxiom functional_extensionality: forall {X Y: Type} {f g: X -> Y},\n    (forall x, f x = g x) -> f = g.\n\nExample function_equality_ex2:\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality.\n  intros x. apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n(** *Exercise tr_rev_correct *)\nFixpoint rev_append {X} (l1 l2: list X): list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l: list X): list X :=\n  rev_append l [].\n\nLemma tr_rev_correct: forall X, @tr_rev X = @rev X.\nProof.\n  assert (L: forall X (l1 l2: list X), rev_append l1 l2 = rev l1 ++ l2).\n  {\n    intros X. induction l1 as [|h t IH].\n    - simpl. intros. reflexivity.\n    - intros l2. simpl. rewrite <- app_assoc. simpl. apply IH.\n  }\n  intros X. apply functional_extensionality. unfold tr_rev.\n  destruct x as [|h t].\n  - reflexivity.\n  - simpl. apply L.\nQed.\n\nTheorem evenb_double: forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(** *Exercise evenb_double_conv *)\nTheorem evenb_double_conv : forall n,\n    exists k, n = if evenb n then double k else S (double k).\nProof.\n  induction n as [|n' IHn'].\n  - exists 0. reflexivity.\n  - destruct IHn' as [k H].\n    destruct (evenb (S n')) eqn:En;\n      rewrite evenb_S in En;\n      apply (f_equal _ _ negb) in En;\n      rewrite negb_involutive in En;\n      rewrite En in H;\n      simpl in H.\n    + exists (S k). rewrite H. reflexivity.\n    + exists k. rewrite H. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n    evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k' H'].\n    rewrite H in H'. exists k'. exact H'.\n  - intros [k H]. rewrite H. apply evenb_double.\nQed.\n\nTheorem beq_nat_true_iff: forall n1 n2 : nat,\n    beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros E. rewrite E. symmetry. apply beq_nat_refl.\nQed.\n\nFail Definition is_even_prime n :=\n  if n = 2 then true 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\n(** *Exercise and_true_iff *)\nLemma andb_true_iff : forall b1 b2: bool,\n    b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intros H. split.\n    + destruct b1.\n      * reflexivity.\n      * inversion H.\n    + destruct b2.\n      * reflexivity.\n      * destruct b1; inversion H.\n  - intros [H1 H2]. rewrite H1, H2. reflexivity.\nQed.\n\nLemma orb_true_iff: forall b1 b2: bool,\n    b1 || b2 = true -> b1 = true \\/ b2 = true.\nProof.\n  intros [|] [|]; simpl; intros H; try inversion H; try (left;reflexivity); try (right;reflexivity).\nQed.\n\n(** *Exercise beq_nat_false_iff *)\nTheorem beq_nat_false_iff : forall x y,\n    beq_nat x y = false <-> x <> y.\nProof.\n  intros x y. split.\n  - intros H E. apply beq_nat_true_iff in E. rewrite H in E. inversion E.\n  - intros H. destruct (beq_nat x y) eqn:E.\n    + exfalso. apply H, beq_nat_true, E.\n    + reflexivity.\nQed.\n\nFixpoint beq_list {A: Type} (beq: A -> A -> bool) (l1 l2: list A): bool :=\n  match (l1, l2) with\n  | ([] , []) => true\n  | ([] , _::_) | (_::_, []) => false\n  | (h1::t1, h2::t2) => beq h1 h2 && beq_list beq t1 t2\n  end.\n\nLemma beq_list_true_iff: forall A (beq: A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq R l1 l2. generalize dependent l2.\n  induction l1 as [|h1 t1 IH1]; destruct l2 as [|h2 t2]; split;\n    intros H; try reflexivity; try (inversion H;fail); simpl in H.\n  - rewrite andb_true_iff in H. destruct H as [H1 H2].\n    apply R in H1. apply IH1 in H2.\n    rewrite H1, H2. reflexivity.\n  - simpl. rewrite andb_true_iff. split; [apply R|apply IH1]; inversion H; reflexivity.\nQed.\n(** *Exercise All_forallb *)\nTheorem forallb_true_iff : forall X test (l : list X),\n    forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  intros X test. induction l as [|h t IH]; split; intro H; simpl; simpl in H; try reflexivity.\n  - rewrite andb_true_iff in H. destruct H as [Hl Hr]. split.\n    + exact Hl.\n    + apply IH, Hr.\n  - rewrite andb_true_iff. destruct H as [Hl Hr]. split.\n    + exact Hl.\n    + apply IH, Hr.\nQed.\n(* forallb has short circuit behavior and can be tested in match *)\n\nDefinition excluded_middle := forall P: Prop, P \\/ ~ P.\nTheorem restricted_excluded_middle: forall P b,\n    (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\nTheorem restricted_excluded_middle_eq: forall (n m : nat), n = m \\/ n <> m.\nProof.\n  intros n m. apply (restricted_excluded_middle (n=m) (beq_nat n m)). symmetry.\n  apply beq_nat_true_iff.\nQed.\n\n(** *Exercise excluded_middle_irrefutable *)\nTheorem excluded_middle_irrefutable: forall P: Prop, ~~(P \\/ ~P).\nProof.\n  intros P H. apply H. right. intro p. apply H. left. exact p.\nQed.\n\n(** *Exercise not_exists_dist *)\nTheorem net_exists_dist :\n  excluded_middle -> forall (X: Type) (P: X -> Prop),\n    ~ (exists x, ~ P x) -> forall x, P x.\nProof.\n  intros Ex X P H x.\n  destruct (Ex (P x)) as [H'|H'].\n  - exact H'.\n  - exfalso. apply H. exists x. exact H'.\nQed.\n\n(** *Exercise classical_axioms *)\nDefinition pierce := forall P Q: Prop, ((P -> Q) -> P) -> P.\nDefinition double_negation_elimination := forall P: Prop, ~~P -> P.\nDefinition de_morgan_not_and_not := forall P Q: Prop, ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q : Prop, (P -> Q) -> (~P \\/ Q).\nLemma excluded_middle_double_negation_elimination:\n  excluded_middle <-> double_negation_elimination.\nProof.\n  split; intros H.\n  - intros P nnp. destruct (H P) as [H'|H'].\n    + exact H'.\n    + exfalso. apply nnp. exact H'.\n  - intros P. apply H. apply excluded_middle_irrefutable.\nQed.\nLemma excluded_middle_pierce: excluded_middle <-> pierce.\nProof.\n  split; intros H0.\n  - intros P Q H1. destruct (H0 P) as [H2|H2].\n    + exact H2.\n    + apply H1. intros H3. exfalso. apply H2, H3.\n  - intros P. apply (H0 (P \\/ ~P) False). intros H1. exfalso.\n    apply excluded_middle_irrefutable with P. exact H1.\nQed.\nLemma excluded_middle_de_morgan_not_and_not :\n  excluded_middle <-> de_morgan_not_and_not.\nProof.\n  split; intros H0.\n  - intros P Q H1.\n    destruct (H0 P) as [H2|H2]; destruct (H0 Q) as [H3|H3];\n      try (left; exact H2); try (right; exact H3).\n    exfalso. apply H1. split; [exact H2|exact H3].\n  - intros P. apply H0. intros [H1 H2]. apply H2, H1.\nQed.\nLemma excluded_middle_implies_to_or:\n  excluded_middle <-> implies_to_or.\nProof.\n  split; intros H0.\n  - intros P Q H1. destruct (H0 P) as [H2|H2].\n    + right. apply H1, H2.\n    + left. exact H2.\n  - intros P. rewrite <- or_comm. apply H0. intro p; exact p.\nQed.\nTheorem classical_axioms:\n  (excluded_middle <-> pierce)\n  /\\ (pierce <-> double_negation_elimination)\n  /\\ (double_negation_elimination <-> de_morgan_not_and_not)\n  /\\ (de_morgan_not_and_not <-> implies_to_or).\nProof.\n  rewrite <- excluded_middle_de_morgan_not_and_not.\n  rewrite <- excluded_middle_pierce.\n  rewrite <- excluded_middle_double_negation_elimination.\n  rewrite <- excluded_middle_implies_to_or.\n  assert (L: forall P, P <-> P).\n  { intro P. split; intro p; exact p. }\n  split. apply L. split. apply L. split. apply L. apply L.\nQed.", "meta": {"author": "ia-kamog", "repo": "logical_foundations", "sha": "ce2dd0adcd5a83afd37857cbb9d8ef351cae3106", "save_path": "github-repos/coq/ia-kamog-logical_foundations", "path": "github-repos/coq/ia-kamog-logical_foundations/logical_foundations-ce2dd0adcd5a83afd37857cbb9d8ef351cae3106/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.904650536386234, "lm_q1q2_score": 0.8094717730005304}}
{"text": "(**\nObjectif de ce suppport de TD :\ninitiation aux relations ou pr\u00e9dicats d\u00e9finis inductivement,\npour pr\u00e9parer la d\u00e9finition des s\u00e9mantiques relationnelles.\n*)\n\n(* Les exercices sont faciles, progressifs, et sont pr\u00e9vus\n   pour une dur\u00e9e d'environ 1/2h).\n*)\n\n(* ------------------------------------------------------------ *)\n(** * Relations ou pr\u00e9dicats d\u00e9finis inductivement *)\n\n(** ** Pr\u00e9dicats \u00e0 1 argument sur un type \u00e9num\u00e9r\u00e9  *)\n\n(** Commen\u00e7ons par un pr\u00e9dicat tr\u00e8s simple qui indique comment\n    s\u00e9lectionner quelques valeurs dans un type \u00e9num\u00e9r\u00e9. *)\n\n\nInductive coul : Set :=\n| violet : coul\n| indigo : coul\n| bleu : coul\n| vert : coul\n| jaune : coul\n| orange : coul\n| rouge : coul\n.\n\n(** Rappel : on ne peut PAS d\u00e9finir un autre type qui partage des\n    constructeurs avec un type d\u00e9j\u00e0 d\u00e9fini. *)\nFail Inductive coulfeu : Set :=\n| vert : coulfeu\n| orange : coulfeu\n| rouge : coulfeu\n.\n\nDefinition ATTENTION_QUESTION_EN_COMMENTAIRE_1 : bool := true.\n(**\nPourquoi interdire \u00e0 un constructeur d'\u00eatre dans des types inductifs diff\u00e9rents ?\n *)\n(* Pour \u00e9viter les ambiguit\u00e9s de type quand on \u00e9crit \"vert\" (par exemple)\n *)\n\n(** Mais on peut d\u00e9finir un pr\u00e9dicat sur coul qui est d\u00e9montrable\n    pour vert orange et rouge (et seulement pour ces derniers). *)\n\nInductive estCoulfeu : coul -> Prop :=\n| Fver : estCoulfeu vert\n| Fora : estCoulfeu orange\n| Frou : estCoulfeu rouge\n.\n\n(** Par exemple on peut d\u00e9montrer que vert satisfait ce pr\u00e9dicat. *)\nExample exemple_feu_vert : estCoulfeu vert.\nProof.\n  apply Fver.\nQed.\n\n(** Certains feux de circulation ne pr\u00e9sentent que les deux couleurs\n    vert et rouge. *)\n\nInductive feu2couls : coul -> Prop :=\n| F2ver : feu2couls vert\n| F2rou : feu2couls rouge\n.\n\n(** On veut d\u00e9montrer que le second pr\u00e9dicat implique le premier. *)\n\nLemma feu2couls_estCoulfeu : forall c, feu2couls c -> estCoulfeu c.\nProof.\n  intro c.\n  (** On essaie d'abord un raisonnement par cas sur [c].*)\n  destruct c.\n  (** Beaucoup de cas inutiles (et qui requi\u00e8rent une technique sp\u00e9ciale).\n      Donc on essaye une meilleure strat\u00e9gie. *)\n  Undo 1.\n  (** Introduction de l'hypoth\u00e8se sur [c]. *)\n  intro f2c.\n  (** Il suffit de raisonner par cas sur les deux fa\u00e7ons\n      dont [f2c] peut \u00eatre construite *)\n  refine (match f2c with F2ver => _ | F2rou => _ end).\n  clear.\n  (** M\u00eame chose en utilisant la tactique destruct sur l'HYPOTH\u00c8SE [f2c] *)\n  Undo 2.\n  destruct f2c as [ (*F2ver*) | (*F2rou*) ].\n  - apply Fver.\n  - refine Frou.\nQed.\n\n(** Exercice *)\n\n(** Sur le mod\u00e8le du pr\u00e9dicat estCoulfeu, d\u00e9finir un autre pr\u00e9dicat nomm\u00e9 boivr,\n    qui s\u00e9lectionne les couleurs bleu, orange, indigo, vert et rouge. *)\n\n(* Inductive boivr \u00e0 compl\u00e9ter *)\n\nInductive boivr : coul -> Prop :=\n  | Bbleu : boivr bleu\n  | Borange : boivr orange\n  | Bindigo : boivr indigo\n  | Bvert : boivr vert\n  | Brouge : boivr rouge\n  .\n\n(** D\u00e9montrer ensuite : *)\n\nLemma estCoulfeu_boivr : forall c, estCoulfeu c -> boivr c.\nProof.\n  intros.\n  destruct H.\n  - apply Bvert.\n  - apply Borange.\n  - apply Brouge.\nQed.\n\n(** ** Relations \u00e0 2 arguments sur un type \u00e9num\u00e9r\u00e9 *)\n\n(** Les relations inductives permettent de repr\u00e9senter des fonction partielles\n    i.e., qui ne sont pas d\u00e9finies partout. Voici un exemple o\u00f9 coulsuiv\n    est d\u00e9finie pour vert, orange et rouge, mais pas pour les autres couleurs\n    pr\u00e9vues dans coul. *)\n\nInductive coulsuiv : coul -> coul -> Prop :=\n| CSv : coulsuiv vert orange\n| CSo : coulsuiv orange rouge\n| CSr : coulsuiv rouge vert\n.\n\n(** Exercice (m\u00eame technique qu'auparavant) *)\n\nLemma coulsuiv_estCoulfeu : forall c1 c2, coulsuiv c1 c2 -> estCoulfeu c1.\nProof.\n  intros.\n  destruct H.\n  - apply Fver.\n  - apply Fora.\n  - apply Frou. \nQed.\n\n(** ** Pr\u00e9dicat even sur nat *)\n\n(** De m\u00eame que les types inductifs de donn\u00e9es peuvent \u00eatre r\u00e9cursifs,\n    par exemple nat ou aexp, les pr\u00e9dicats inductifs peuvent \u00eatre\n    r\u00e9cursifs. C'est le cas de even, pr\u00e9sent\u00e9 au CM4. *)\n\nInductive even : nat -> Prop :=\n| E0 : even 0\n| E2 : forall n, even n -> even (S (S n))\n.\n\n(** Exercice : d\u00e9montrer que 6 est pair. *)\n\nExample ev10 : even 10.\nProof.\n  refine (E2 8 _).\n  apply (E2 6).\n  apply E2.\n  apply E2.\n  apply E2.\n  apply E0.\nQed.\n\nPrint ev10.\n\nDefinition ATTENTION_QUESTION_EN_COMMENTAIRE_2 : bool := true.\n(** Exercice :\n    - quel est le type et la signification de E2 4 ?\n    - quel est le type et la signification de E2 5 ?\n*)\n(*\n  E2 4 : Prop, proposition \"4 est pair\"\n  E2 5 : Prop, proposition \"5 est pair\"\n *)\n\n\n(** Entiers atteignables en ajoutant des 2 ou des 7 en partant de 0. *)\nInductive p2p7 : nat -> Prop :=\n| PP0 : p2p7 0\n| PP2 : forall n, p2p7 n -> p2p7 (2 + n)\n| PP7 : forall n, p2p7 n -> p2p7 (7 + n)\n.\n\n(** Exercice : d\u00e9montrer de 3 fa\u00e7ons que 11 est atteignable par p2p7. *)\nExample p2p7_11_methode1 : p2p7 11.\nProof.\n  apply PP7.\n  apply PP2.\n  apply PP2.\n  apply PP0.\nQed.\n\nExample p2p7_11_methode2 : p2p7 11.\nProof.\n  apply PP2.\n  apply PP2.\n  apply PP7.\n  apply PP0.\nQed.\n\nExample p2p7_11_methode23 : p2p7 11.\nProof.\n  apply PP2.\n  apply PP7.\n  apply PP2.\n  apply PP0.\nQed.\n\nPrint p2p7_11_methode2.\n\n(** D\u00e9montrer que tout entier pair satisfait p2p7. *)\n\nTheorem even_p2p7 : forall n, even n -> p2p7 n.\nProof.\n  intros n en.\n  (** Comme il y a une infinit\u00e9 d'entiers pairs, une preuve par cas\n      ne suffit pas. On proc\u00e8de par r\u00e9currence structurelle sur les\n      fa\u00e7ons de d\u00e9montrer [even n], autrement les formes possibles\n      d'arbres de preuve pour [en].\n      On a deux cas, celui o\u00f9 [en] est [E0], et celui o\u00f9 [en]\n      est de la forme [E2 n' en'], avec [en' : even n'] ;\n      dans ce dernier cas, on a droit \u00e0 une hypoth\u00e8se de r\u00e9currence\n      sur en', assurant que [n'] satisfait p2p7.\n  *)\n  induction en as [ (*E0*) | (*E2*) n' evn' Hrec_evn'].\n  - apply PP0.\n  - (** Facultatif : mise sous une forme clairement adapt\u00e9e \u00e0 p2p7 *)\n    change (p2p7 (2 + n')).\n    (** Utilisation du constructeur appropri\u00e9 de p2p7 *)\n    apply PP2.\n    (** Utilisation de l'hypoth\u00e8se de r\u00e9currence *)\n    apply Hrec_evn'.\nQed.\n\n(** Il est instructif de d\u00e9montrer le m\u00eame th\u00e9or\u00e8me par une\n    fonction r\u00e9cursive. *)\n\nFixpoint fct_even_p2p7 n (en : even n) : p2p7 n :=\n  match en with\n  | E0 => PP0\n  | E2 n' evn' => PP2 n' (fct_even_p2p7 n' evn')\n  end.\n\n(** On peut transformer un arbre de preuve de [even 4]\n    en un arbre de preuve de [p2p7 4] *)\nCompute fct_even_p2p7 4 (E2 2 (E2 0 E0)).\n\n(** La somme de deux entiers pairs est paire *)\nLemma even_plus : forall n m, even n -> even m -> even (n + m).\nProof.\n  intros n m evn evm.\n  induction evn.\n  - apply evm.\n  - apply E2. apply IHevn.\nQed.\n\n(** Exercice facultatif :\n    en donner une preuve sous forme de fonction. *)\n\nRequire Import Arith.\n\nFixpoint fct_even_plus n m (evn : even n) (evm : even m) : even (n + m) :=\n  match evn with\n    | E0 => evm\n    | E2 n' Ihn' => E2 (n' + m) (fct_even_plus n' m Ihn' evm)\n  end.\n\n(* Les multiples de 4 sont pairs *)\nInductive mul4 : nat -> Prop :=\n| M4_0 : mul4 0\n| M4_4 : forall n, mul4 n -> mul4 (S (S (S (S n))))\n.\n\nLemma mul4_even : forall n, mul4 n -> even n.\nProof.\n  intros n m4n.\n  (** Terminer par r\u00e9currence structurelle sur [m4n] *)\n  induction m4n.\n  - apply E0.\n  - apply E2. apply E2. exact IHm4n.\nQed.\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_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.9046505338155469, "lm_q1q2_score": 0.8094717707003066}}
{"text": "(*******    Mathematical Components    *******)\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Part One  : Basics for Formal Mathematics *)\n(* Chapter 1 : Functions and Computation     *)\nDefinition f (n : nat) : nat := n + 1.\nPrint f.\nEval compute in f 3.\n\nDefinition g (n m : nat) : nat := n + m * 2.\nDefinition h (n : nat) : nat -> nat := fun m => n + m * 2.\nPrint g.\nPrint h.\n\nDefinition repeat_twice (g : nat -> nat) : nat -> nat :=\n  fun x => g (g x).\nEval compute in repeat_twice f 98.\n\nInductive bool := true | false.\nDefinition twoVthree (b : bool) := if b is true then 2 else 3.\nEval compute in twoVthree true.\nEval compute in twoVthree false.\n\nInductive nat := O | S (n : nat).\n\nDefinition predn n := if n is p.+1 then p else n.\nEval compute in predn 5.\nDefinition pred5 n := if n is u.+1.+1.+1.+1.+1 then u else 0.\nEval compute in pred5 11.\n\nDefinition three_patterns n :=\n  match n with\n    u.+1.+1.+1.+1.+1 => u \n  | v.+1 => v\n  | 0 => n\n  end.\nEval compute in three_patterns 7.\n\nDefinition same_bool b1 b2 :=\n  match b1, b2 with\n    true, true => true\n  | false, false => true\n  | _, _ => false\n  end.\n\nFixpoint addn n m :=\n  match n with\n    0 => m\n  | p.+1 => (addn p m).+1 \n  end.\n\nAbout cons.\nCheck 1 :: 2 :: 3 :: nil.\n\nDefinition head T (x0 : T) (s : seq T) :=\n  if s is x :: _ then x else x0.\n\nFixpoint size A (s : seq A) :=\n  if s is _ :: tl then (size tl).+1 else 0.\n\nFixpoint map A B (f : A -> B) s :=\n  if s is e :: tl then f e :: map f tl else nil.\n\nNotation \"[ \u2019seq\u2019 E | i <- s ]\" := (map (fun i => E) s).\nEval compute in [seq i.+1 | i <- [:: 1; 2]].\n\nInductive option A := None | Some (a : A).\n\nPrint foldr.\nPrint iota.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (foldr (fun i a => F + a) 0 (iota m (n-m))).\nEval compute in \\sum_( 1 <= i < 3 ) (i * 2 - 1).\nEval compute in \\sum_( 1 <= i < 5 ) i.\n\n(* Exercise 1 The triple data type *)\n\n(* Exercise 2 Addition with iteration *)\n(* Exercise 3 Multiplication with iteration *)\n(* Exercise 4 Find the n-th element *)\n(* Exercise 5 List reversal *)\n(* ** Exercise 7 All words of size n *)\n\n(* Chapter 2 : First Steps in Formal Proofs *)\nSection Chap2.\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nCheck 3 = 3.\nCheck 3 = 4.\n\nLocate \"=\".\nAbout eq.\n\nLemma negbK b : ~~ (~~ b) = b.\nProof. \nelim b.\nby[].\nby[].\n(* by case b. *)\nQed.\n\nLemma leqn0 n : (n <= 0) = (n == 0).\nProof.\nmove: n.\nelim.\nby[].\nmove => k h.\nby[].\n(* by case: => [|k]. *)\nQed.\n\n(* Exercise 8 Truth tables *)\n(* Exercise 9 Rewriting *)\n(* * Exercise 10 Induction *)\n(* ** Exercise 11 Multiple induction *)\n\nEnd Chap2.\n(* Chapter 3 : Type Theory *)\nCheck ex.\nCheck or_ind.\n\nInductive True : Prop := I.\nInductive False : Prop := .\nPrint not.\n\nDefinition not (A : Prop) := A -> False.\nDefinition exfalso (P : Prop) (f : False) : P :=\n  match f with end. (* no constructors, no branches *)\n\n(* Chapter 4 : First Steps in Formal Proofs *)\nDefinition bool_Prop_equiv (P : Prop) (b : bool) :=\n  b = true <-> P. (* Reflection views *)\nLemma test_bool_Prop_equiv b P : bool_Prop_equiv P b -> P \\/ ~ P.\nProof.\ncase b.\ncase.\nmove => hlr hrl.\nleft.\napply: hlr.\nreflexivity.\ncase.\nmove => hlr hrl.\nright.\nmove => hP.\nmove: (hrl hP).\nby[].\nQed.\n\n(* Exercise 12 reflect *)\n(* Exercise 13 eqnP *)\n(* Exercise 14 Injectivity to nat *)\n(* Exercise 15 Characterization of max *)\n\n(* Part Two  : Formalization Techniques *)\n(* Chapter 5 : Implicit Parameters *)\nDefinition id A (a : A) : A := a.\nCheck (id _ 3).\nArguments id {A} a.\nCheck (id 3).\nCheck (@id _ 3).\n\nCheck (fun x => @id nat x).\n\nLemma example q : prime q -> 0 < q.\nProof.\nmove => pr_q.\n(* prime_gt1 : forall p : Datatypes.nat, prime p -> 1 < p *)\nhave q_gt1 := (@prime_gt1 _ pr_q).\n(* ltnW : forall m n : Datatypes.nat, m < n -> m <= n  *)\nexact (ltnW q_gt1).\nQed.\n\n(* Chapter 6 : Sub-Types *)\n(* Chapter 7. Organizing Theories *)\n(* Chapter 8 : Natural numbers *)\nExample Gauss n : \\sum_(0 <= i < n.+1) i = (n * n.+1) %/ 2.\nProof.\n(* big_nat1 :\nforall (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 *)\nelim: n =>[|n IHn]; first by apply: big_nat1.\n(* big_nat_recr :\nforall (R : Type) (idx : R) (op : Monoid.law idx) (n m : nat) (F : nat -> R),\nm <= n ->\n\\big[op/idx]_(m <= i < n.+1) F i = op (\\big[op/idx]_(m <= i < n) F i) (F n) *)\n(* addnC : commutative addn *)\n(* divnMDl : forall q m d : nat, 0 < d -> (q * d + m) %/ d = q + m %/ d *)\nrewrite big_nat_recr //= IHn addnC -divnMDl //.\n(* mulnS : forall m n : nat, m * n.+1 = m + m * n *)\nrewrite mulnS.\n(* muln1 : right_id 1 muln *)\nrewrite muln1.\n(* addnA : associative addn *)\nrewrite -addnA.\n(* mulSn : forall m n : nat, m.+1 * n = n + m * n *)\nrewrite -mulSn.\nrewrite -mulnS.\nreflexivity.\nQed.\n\n\n(* Part Three : Synopsis *)", "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/mathcomp_exer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8094651040676588}}
{"text": "From LF Require Export Basics.\n\nTheorem add_0_r : forall n : nat,\n    n + 0 = n.\nProof.\n    intros n.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. \n      rewrite -> IHn'.\n      reflexivity.\nQed.\n\nTheorem minus_n_n: forall n : nat,\n    minus n n = 0.\nProof.\n    intros n.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. \n      rewrite -> IHn'.\n      reflexivity.\nQed.\n\nTheorem mult_n_0: forall n : nat,\n  n * 0 = 0.\nProof.\n    intros n.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl.\n      rewrite -> IHn'.\n      reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m : nat,\n  S (n + m) = n + S m.\nProof.\n    intros n m.\n    induction n as [| n' IHn'].\n    - simpl.\n      reflexivity.\n    - simpl.\n      rewrite -> IHn'.\n      reflexivity.\nQed.\n\nTheorem add_comm: forall n m : nat,\n  n + m = m + n.\nProof.\n    intros n m.\n    induction n as [| n' IHn'].\n    rewrite -> add_0_r.\n    - simpl.\n      reflexivity.\n    - simpl.\n      rewrite -> IHn'.\n      rewrite -> plus_n_Sm.\n      reflexivity.\nQed.\n\nTheorem add_assoc: forall n m p : nat,\n    (n + m) + p = n + (m + p).\nProof.\n    intros n m p.\n    induction n as [| n' IHn'].\n    - simpl.\n      reflexivity.\n    - simpl. \n      rewrite -> IHn'.\n      reflexivity.\nQed.\n\nFixpoint double (n : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => S (S (double n'))\n    end.\n\nLemma double_plus : forall n : nat,\n  double n = n + n.\nProof.\n  induction n as [| n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl. \n    rewrite <- plus_n_Sm.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n  (n ?= n) = true.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\n\nTheorem even_S : forall n : nat,\n  (even (S n)) = (negb (even n)).\nProof.\n  intros n.\n  induction n as [| m IHm].\n  - simpl. reflexivity.\n  - assert (H1 : even (S (S m)) = even m).\n    { simpl. reflexivity. }\n    rewrite -> H1.\n    rewrite -> IHm.\n    rewrite -> negb_involution.\n    reflexivity.\n  Qed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (n + 0 + 0) * m = n * m.\nProof.\n  intros n m.\n  assert (H: n + 0 + 0 = n).\n    { rewrite add_comm. simpl. rewrite add_comm. reflexivity. } \n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n    { rewrite -> add_comm. reflexivity. }\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\n(*Exercise 3 : multiplicative commutative.*)\nTheorem add_shuffle3 : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (H1: n + (m + p) = n + m + p).\n    { rewrite -> add_assoc. reflexivity. }\n  rewrite -> H1.\n  assert (H2: n + m = m + n).\n    { rewrite -> add_comm. reflexivity. }\n  rewrite -> H2.\n  rewrite -> add_assoc.\n  reflexivity.\n  Qed.\n\nTheorem mult_n_Sm : forall n m : nat,\n  n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> add_shuffle3.\n    reflexivity.\n  Qed.  \n\nTheorem mult_comm : forall n m : nat,\n  n * m = m * n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - simpl. \n    rewrite -> mult_n_0.\n    reflexivity.\n  - simpl. \n    rewrite -> mult_n_Sm.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nTheorem plus_leb_compat_l : forall n m p: nat,\n  n <=? m = true ->\n    (p + n) <=? (p + m) = true.\nProof.\n  intros n m p H1.\n  induction p as [| p' IHp'].\n  - simpl.\n    rewrite -> H1.\n    reflexivity.\n  - simpl. \n    rewrite -> IHp'.\n    reflexivity.\n  Qed.\n\nTheorem mult_1_l : forall n : nat,\n  1 * n = n.\nProof.\n  intros n.\n  simpl. \n  rewrite -> add_0_r.\n  reflexivity.\n  Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = n * p + m * p.\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> add_assoc.\n    reflexivity.\n  Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> mult_plus_distr_r.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\n(*Exercise: 2 stars, standard, optional (add_shuffle3')*)\nTheorem add_shuffle3' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite <- add_assoc.\n  rewrite <- add_assoc.\n  replace (n + m) with (m + n).\n  - reflexivity.\n  - rewrite -> add_comm.\n    reflexivity.\n  Qed.\n\n(*Exercise: 3 stars, standard, especially useful (binary_commute)*)\nTheorem bin_to_nat_pres_incr : forall b : bin,\n  bin_to_nat (increase b) = 1 + bin_to_nat b.\nProof.\n  intros b.\n  induction b as [|b' IHb' | b'' IHb''].\n  - (* Case b = Z *)\n    reflexivity.\n  - (* Case b = (B0 b') *)\n    reflexivity.\n  - (* Case b = (B1 b'') *) \n    simpl.\n    repeat rewrite -> add_0_r.\n    simpl.\n    rewrite -> IHb''.\n    rewrite -> add_shuffle3.\n    repeat rewrite <- add_assoc.\n    reflexivity.\n  Qed.\n\n(* Exercise: 3 stars, standard (nat_bin_nat) *)\nFixpoint nat_to_bin (n : nat) : bin :=\n  match n with\n  | O => Z\n  | S n' => increase (nat_to_bin n')\n  end.\n\nTheorem nat_bin_nat : forall n : nat,\n  bin_to_nat (nat_to_bin n) = n.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n  - (* Case n = O *)\n    reflexivity.\n  - (* Case n = S n' *)\n    simpl.\n    rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nTheorem double_increase : forall n : nat,\n  double (S n) = S (S (double n)).\nProof.\n  intros n.\n  reflexivity.\n  Qed.\n\nDefinition double_bin (b : bin) : bin :=\n  match b with\n  | Z => Z\n  | _ => (B0 b)\n  end.\n\nExample test_double_bin_5:\n  (bin_to_nat (double_bin (B1 (B0 (B1 Z))))) = 10.\nProof.\n  reflexivity.\n  Qed.\n\nExample double_bin_zero:\n  (double_bin Z) = Z.\nProof.\n  reflexivity.\n  Qed.\n\nLemma double_increase_bin : forall b : bin,\n  double_bin (increase b) = increase (increase (double_bin b)).\nProof.\n  intros b.\n  destruct b eqn:Eqb.\n  - (* Case b = Z *)\n    reflexivity.\n  - (* Case b = (B0 b')*)\n    reflexivity.\n  - (* Case b = (B1 b') *)\n    reflexivity.\n  Qed.\n\n(* Exercise: 4 stars, advanced (bin_nat_bin) *)\n(* Trying to elimiating the redundant leading zeros in a bin expression with \n   the normalize function. \n     The root cause that (nat_to_bin (bin_to_nat b)) != b is that there are \n   infinity valid representation for Z (i.e. Z). For example \n   (B0 Z), (B0 (B0 Z)), (B0 (B0 (B0 Z))) ...... are all representing 0. *)\nFixpoint normalize (b : bin) : bin :=\n  match b with\n  | Z => Z\n  | B0 n' => (double_bin (normalize n'))\n  | B1 n' => (B1 (normalize n'))\n  end.\n\nCompute (normalize (B1 (B0 (B0 (B0 Z))))).\n\nLemma double_eq_n_plus_n : forall n : nat,\n  (double n) = n + n.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - (* Case n = O *)\n    reflexivity.\n  - (* Case n = S n' *)\n    simpl.\n    rewrite <- plus_n_Sm.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nTheorem nat_to_bin_double : forall n : nat,\n  (nat_to_bin (double n)) = (double_bin (nat_to_bin n)).\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - (* Case n = O *)\n    reflexivity.\n  - (* Case n = S n' *)\n    rewrite -> double_increase.\n    simpl.\n    rewrite -> double_increase_bin.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nTheorem increase_double_bin : forall b : bin,\n  (increase (double_bin b)) = (B1 b).\nProof.\n  intros b.\n  destruct b eqn:Eqb.\n  - (* Case b = Z *)\n    reflexivity.\n  - (* Case b = (B0 b') *)\n    reflexivity.\n  - (* Case b = (B1 b'') *)\n    reflexivity.\n  Qed.\n\nTheorem bin_nat_bin : forall b : bin,\n  (nat_to_bin (bin_to_nat b)) = (normalize b).\nProof.\n  intros b.\n  induction b as [| b' IHb'| b'' IHb''].\n  - (* Case b = Z *)\n    reflexivity.\n  - (* Case b = (B0 b') *)\n    simpl.\n    rewrite -> add_0_r. \n    rewrite <- double_eq_n_plus_n.\n    rewrite -> nat_to_bin_double.\n    rewrite -> IHb'.\n    reflexivity.\n  - (* Case b = (B1 b'') *)\n    simpl.\n    rewrite -> add_0_r.\n    rewrite <- double_eq_n_plus_n.\n    rewrite -> nat_to_bin_double.\n    rewrite -> IHb''.\n    rewrite -> increase_double_bin.\n    reflexivity.\n  Qed.", "meta": {"author": "cycloidzzz", "repo": "Cocktail", "sha": "1f43749e1cf4da9362807d6f74c2cb5fc3dc84b5", "save_path": "github-repos/coq/cycloidzzz-Cocktail", "path": "github-repos/coq/cycloidzzz-Cocktail/Cocktail-1f43749e1cf4da9362807d6f74c2cb5fc3dc84b5/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8094650944840183}}
{"text": "(** Discrete Fourier transformation can be used to compute big number's\n    multiplication. FFT is a well-known efficient algorithm to calculate\n    discrete fourier transformation. Your should learn how this algorithm works\n    and prove its correctness in Coq. You need to either define this algorithm\n    using complex numbers (you may find some library in Coq's standard library\n    or other Coq's user's contribution) or via an abstract ring with some extra\n    properties.\n\n    You only need to define this algorithm as a Coq function or a Coq relation\n    (small step description of this algorithm). You do not need to implement it\n    in a programming language like C. You do not need to verify its \n    implementation in any programming language. *)\n\n(* 2021-05-07 20:39 *)\nFrom Coq Require Import Reals ssreflect.\nRequire Import PL.Rcompute PL.Ccompute PL.Inequalities.\nRequire Import Coq.Lists.List.\n\n\nLocal Open Scope C_scope.\nDelimit Scope C_scope with C.\n\nNotation \"[ ]\" := nil (format \"[ ]\") : list_scope.\nNotation \"[ x ]\" := (cons x nil) : list_scope.\nNotation \"[ x ; y ; .. ; z ]\" := (cons x (cons y .. (cons z nil) ..)) : list_scope.\nInfix \"::\" := cons (at level 60, right associativity) : list_scope.\nInfix \"++\" := app (right associativity, at level 60) : list_scope.\n\n\n(** The function below computes the kth element of Discrete Fourier Transform of a list of complex numbers \nby DEFINITION, not FFT. *)\nFixpoint Fourier (X : list C) (n : R) (k len : nat) : C :=\n  match X with\n    | nil => (0%R , 0%R)\n    | (x :: X')%list => x * (exp_complex (-2 * PI * n * (INR k) * / (INR len))) + (Fourier X' (n + 1) k len)\n  end.\n\n\n(**  Now define the algorithm of FFT. First define some useful functions.*)\n(** Selecting the elements of even/odd indices out of a list. Used in FFT.*)\nFixpoint EvenList (l:list C) : list C := \n    match l with\n       | nil => nil\n       | (x :: l' )%list=> x :: OddList l'\n    end\n  with OddList (l:list C) : list C := \n    match l with\n       | nil => nil\n       | (_ :: l' )%list=> EvenList l'\n      end.\n\n(** Pointwise operation on two complex lists. Used in FFT.*)\nFixpoint ListOp (l1: list C) (l2: list C) (Op: C->C->C) (default: list C): list C :=\n  match l1, l2 with\n     | nil, nil => nil\n     | (x1 :: l1' ), (x2 :: l2') => (Op x1 x2) :: ListOp l1' l2' Op default\n     | nil, _ => default\n     | _, nil => default \n  end.\n\n(** Generating the phase factor used in FFT.*)\nFixpoint PhaseGen (n:nat) (m: nat): list C :=\n  match n with\n    | O => []\n    | S n' => PhaseGen n' m ++ [(exp_complex (- 2 * PI * (INR n') / (INR m)))]\n  end.\nDefinition Phase (N: nat): list C:= PhaseGen N (2*N).\n\n(** Checking the length of list X.*)\nDefinition lenX_pow_2_n_1 (X : list C) : Prop :=\n  exists N, Datatypes.length X = Init.Nat.pow 2 N.\n(* equal of nat *)\nDefinition lenX_pow_2_n_2 (X : list C) : Prop :=\n  exists N, Z.of_nat (Datatypes.length X) = Z.pow 2 N.\n(* equal of Z *)\n\n(** This function describes the algorithm of FFT. The length of list x must be 2^M. *)\nFixpoint FFT (x:list C) (M:nat): list C :=\n  match M with\n  | O => x\n  | S M' => ListOp (FFT (EvenList x) M') (ListOp (Phase (2^M')) (FFT (OddList x) M') Cmult []) Cplus [] \n                  ++ ListOp (FFT (EvenList x) M') (ListOp (Phase (2^M')) (FFT (OddList x) M') Cmult []) Cminus []\n  end.\n\n(**  Below are some useful intermediate results for the proof. These come from the derivation of the algorithm of FFT.*)\n\n(** This is the even term of the Fourier transform *)\nFixpoint Fourier_even (X : list C) (n : R) (k len : nat) : C :=\n  match X with\n    | nil => (0%R , 0%R)\n    | (x :: X')%list => x * (exp_complex (-2 * PI * 2 * n * (INR k) * / (2 * (INR len) ))) + (Fourier_even X' (n + 1) k len)\n  end.\n\n(** This is the odd term of the Fourier transform *)\nFixpoint Fourier_odd (X : list C) (n : R) (k len : nat) : C :=\n  match X with\n    | nil => (0%R , 0%R)\n    | (x :: X')%list => x * (exp_complex (-2 * PI * (2 * n + 1) * (INR k) * / (2 * (INR len) ))) + (Fourier_odd X' (n + 1) k len)\n  end.\n\nLemma Fourier_nMinus1: forall (X : list C) (n : R) (k len : nat),\n  len <> 0%nat -> Fourier X (n + 1) k len = exp_complex (-2 * PI * (INR k) * / (INR len)) * Fourier X n k len.\nProof.\n  intros.\n  revert n; induction X.\n  {\n  intros.\n  simpl.\n  pose proof exp_mult_0_1 (-2 * PI * INR k * / INR len).\n  rewrite H0.\n  reflexivity.\n  }\n  intros.\n  specialize (IHX (n + 1)%R).\n  simpl.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * INR k * / INR len)) (a * exp_complex (-2 * PI * n * INR k * / INR len)) (Fourier X (n + 1) k len).\n  rewrite H0.\n  clear H0 H.\n  rewrite <- IHX.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\n(a * exp_complex (-2 * PI * n * INR k * / INR len)) = a * exp_complex (-2 * PI * (n + 1) * INR k * / INR len)).\n  {\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * INR k * / INR len)) a (exp_complex (-2 * PI * n * INR k * / INR len)).\n  rewrite <- H.\n  pose proof Cmult_comm (exp_complex (-2 * PI * INR k * / INR len)) a.\n  rewrite H0.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\nexp_complex (-2 * PI * n * INR k * / INR len) = exp_complex (-2 * PI * (n + 1) * INR k * / INR len)).\n  {\n  clear.\n  pose proof exp_mult (-2 * PI * INR k * / INR len) (-2 * PI * n * INR k * / INR len).\n  pose proof UseByFourier_nMinus1_1 (-2 * PI)%R (INR k * / INR len) n.\n  rewrite H.\n  pose proof Rmult_assoc (-2 * PI)%R (INR k) (/ INR len).\n  rewrite <- H1 in H0.\n  pose proof Rmult_assoc (-2 * PI * n) (INR k) (/ INR len).\n  rewrite <- H2 in H0.\n  rewrite H0.\n  pose proof Rmult_assoc (-2 * PI * (n + 1)) (INR k) (/ INR len).\n  rewrite <- H3.\n  reflexivity.\n  }\n  pose proof Cmult_assoc_r a (exp_complex (-2 * PI * INR k * / INR len)) (exp_complex (-2 * PI * n * INR k * / INR len)).\n  rewrite H1 in H2.\n  exact H2.\n  }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma Fourier_even_nMinus1: forall (X : list C) (n : R) (k len : nat),\n  len <> 0%nat -> Fourier_even X (n + 1) k len = exp_complex (-2 * PI * (INR k) * / (INR len)) * Fourier_even X n k len.\nProof.\n  intros.\n  revert n; induction X.\n  {\n  intros.\n  simpl.\n  pose proof exp_mult_0_1 (-2 * PI * INR k * / INR len).\n  rewrite H0.\n  reflexivity.\n  }\n  intros.\n  specialize (IHX (n + 1)%R).\n  simpl.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * INR k * / INR len)) (a * exp_complex (-2 * PI * 2 * n * INR k * / (2 * INR len))) (Fourier_even X (n + 1) k len).\n  rewrite H0.\n  clear H0.\n  rewrite <- IHX.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\n(a * exp_complex (-2 * PI * 2 * n * INR k * / (2 * INR len))) = a * exp_complex (-2 * PI * 2 * (n + 1) * INR k * / (2 * INR len))).\n  {\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * INR k * / INR len)) a (exp_complex (-2 * PI * 2 * n * INR k * / (2 * INR len))).\n  rewrite <- H0.\n  pose proof Cmult_comm (exp_complex (-2 * PI * INR k * / INR len)) a.\n  rewrite H1.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\nexp_complex (-2 * PI * 2 * n * INR k * / (2 * INR len)) = exp_complex (-2 * PI * 2 * (n + 1) * INR k * / (2 * INR len))).\n  {\n  pose proof not_0_INR.\n  specialize (H2 len H).\n  pose proof UseByFourier_even_nMinus1_1 (-2 * PI)%R (INR k) (INR len).\n  specialize (H3 H2).\n  rewrite H3.\n  clear.\n  pose proof exp_mult (-2 * PI * 2 * INR k * / (2 * INR len)) (-2 * PI * 2 * n * INR k * / (2 * INR len)).\n  pose proof UseByFourier_nMinus1_1 (-2 * PI * 2)%R (INR k * / (2 * INR len)) n.\n  rewrite H.\n  pose proof Rmult_assoc (-2 * PI * 2)%R (INR k) (/ (2 * INR len)).\n  rewrite <- H1 in H0.\n  pose proof Rmult_assoc (-2 * PI * 2 * n) (INR k) (/ (2 * INR len)).\n  rewrite <- H2 in H0.\n  rewrite H0.\n  pose proof Rmult_assoc (-2 * PI * 2 * (n + 1)) (INR k) (/ (2 * INR len)).\n  rewrite <- H3.\n  reflexivity.\n  }\n  pose proof Cmult_assoc_r a (exp_complex (-2 * PI * INR k * / INR len)) (exp_complex (-2 * PI * 2 * n * INR k * / (2 * INR len))).\n  rewrite H2 in H3.\n  exact H3.\n  }\n  rewrite H0.\n  reflexivity.\nQed.\n\nLemma Fourier_odd_nMinus1: forall (X : list C) (n : R) (k len : nat),\n  len <> 0%nat -> Fourier_odd X (n + 1) k len = exp_complex (-2 * PI * (INR k) * / (INR len)) * Fourier_odd X n k len.\nProof.\n  intros.\n  revert n; induction X.\n  {\n  intros.\n  simpl.\n  pose proof exp_mult_0_1 (-2 * PI * INR k * / INR len).\n  rewrite H0.\n  reflexivity.\n  }\n  intros.\n  specialize (IHX (n + 1)%R).\n  simpl.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * INR k * / INR len)) (a * exp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len))) (Fourier_odd X (n + 1) k len).\n  rewrite H0.\n  clear H0.\n  rewrite <- IHX.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\n(a * exp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len))) = a * exp_complex (-2 * PI * (2 * (n + 1) + 1) * INR k * / (2 * INR len))).\n  {\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * INR k * / INR len)) a (exp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len))).\n  rewrite <- H0.\n  pose proof Cmult_comm (exp_complex (-2 * PI * INR k * / INR len)) a.\n  rewrite H1.\n  assert (exp_complex (-2 * PI * INR k * / INR len) *\nexp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len)) = exp_complex (-2 * PI * (2 * (n + 1) + 1) * INR k * / (2 * INR len))).\n  {\n  pose proof not_0_INR.\n  specialize (H2 len H).\n  pose proof UseByFourier_odd_nMinus1_1 (-2 * PI)%R (INR k) n (INR len).\n  specialize (H3 H2).\n  pose proof exp_mult (-2 * PI * INR k * / INR len) (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len)).\n  rewrite H4 H3.\n  reflexivity.\n  }\n  clear IHX H0 H1.\n  pose proof Cmult_eq_compat_l.\n  specialize (H0 a (exp_complex (-2 * PI * INR k * / INR len) *\n     exp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len))) (exp_complex (-2 * PI * (2 * (n + 1) + 1) * INR k * / (2 * INR len))) H2).\n  pose proof Cmult_assoc_r a (exp_complex (-2 * PI * INR k * / INR len)) (exp_complex (-2 * PI * (2 * n + 1) * INR k * / (2 * INR len))).\n  rewrite <- H1 in H0.\n  rewrite H0.\n  reflexivity.\n  }\n  rewrite H0.\n  reflexivity.\nQed.\n\n(* Fourier_split2_1 *)\nLemma Fourier_split2_1: forall (X : list C) (k len : nat),\n  len <> 0%nat -> Fourier_even X 0 k len = Fourier X 0 k len.\nProof.\n  intros.\n  induction X.\n  {\n  simpl.\n  reflexivity.\n  }\n  simpl.\n  pose proof compute_1 (-2 * PI * 2) (INR k) (2 * (INR len)).\n  rewrite H0.\n  pose proof compute_1 (-2 * PI) (INR k) (INR len).\n  rewrite H1.\n  clear H0 H1.\n  pose proof Rplus_0_l 1.\n  rewrite H0.\n  pose proof Fourier_even_nMinus1 X 0 k len.\n  specialize (H1 H).\n  rewrite H0 in H1.\n  rewrite H1.\n  pose proof Fourier_nMinus1 X 0 k len.\n  specialize (H2 H).\n  rewrite H0 in H2.\n  rewrite H2.\n  rewrite IHX.\n  reflexivity.\nQed.\n\n(* Fourier_split2_2 *)\nLemma Fourier_split2_2: forall (X : list C) (k len : nat),\n  len <> 0%nat -> Fourier_odd X 0 k len = (exp_complex (-2 * PI * (INR k ) * / (2 * INR len) )) * Fourier X 0 k len.\nProof.\n  intros.\n  induction X.\n  {\n  simpl.\n  pose proof exp_mult_0_1 (-2 * PI * (INR k) * / (2 * INR len)).\n  rewrite H0.\n  reflexivity.\n  }\n  simpl.\n  pose proof compute_1 (-2 * PI) (INR k) (INR len).\n  rewrite H0.\n  pose proof Rmult_0_r 2.\n  rewrite H1.\n  pose proof Rplus_0_l 1.\n  rewrite H2.\n  pose proof Rmult_1_r (-2 * PI).\n  rewrite H3.\n  clear H0 H1 H2 H3.\n  pose proof Fourier_odd_nMinus1 X 0 k len.\n  specialize (H0 H).\n  rewrite IHX in H0.\n  pose proof Rplus_0_l 1.\n  rewrite H1 in H0.\n  rewrite H0.\n  pose proof Fourier_nMinus1 X 0 k len.\n  specialize (H2 H).\n  rewrite H1 in H2.\n  rewrite H2.\n  pose proof exp_0_mult_r a.\n  rewrite H3.\n  clear.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * (INR k) * / (2 * (INR len)))) a (exp_complex (-2 * PI * (INR k) * / (INR len)) * Fourier X 0 k len).\n  rewrite H; clear.\n  pose proof Cmult_comm a (exp_complex (-2 * PI * (INR k) * / (2 * (INR len)))).\n  rewrite H; clear.\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * (INR k) * / (2 * (INR len)))) (exp_complex (-2 * PI * (INR k) * / (INR len))) (Fourier X 0 k len).\n  rewrite <- H; clear.\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * (INR k) * / (INR len))) (exp_complex (-2 * PI * (INR k) * / (2 * (INR len)))) (Fourier X 0 k len).\n  rewrite <- H; clear.\n  pose proof Cmult_comm (exp_complex (-2 * PI * (INR k) * / (INR len))) (exp_complex (-2 * PI * (INR k) * / (2 * (INR len)))).\n  rewrite H; clear.\n  reflexivity.\nQed.\n\n(** Split Fourier transform into odd and even when k < N / 2*)\nLemma Fourier_split1: forall (X : list C) (k len : nat),\n  len <> 0%nat -> Fourier X 0 k (2 * len) = Fourier_even (EvenList X) 0 k len + Fourier_odd (OddList X) 0 k len.\nProof.\n  intros.\n  induction X.\n  {\n  simpl.\n  unfold Cplus.\n  simpl.\n  pose proof Rplus_0_l 0.\n  rewrite H0.\n  reflexivity.\n  }\n  {\n  simpl.\n  pose proof compute_1 (-2 * PI)%R (INR k) (INR (2 * len)).\n  pose proof compute_1 (-2 * PI * 2)%R (INR k) (2 * (INR len)).\n  rewrite H0 H1.\n  clear H0 H1.\n  pose proof Rplus_0_l 1.\n  rewrite H0; clear H0.\n  pose proof Fourier_nMinus1 X 0 k (2 * len).\n  assert (2 <> 0)%nat.\n  congruence.\n  pose proof Nat.neq_mul_0 2 len.\n  destruct H2; clear H3.\n  assert (2 <> 0 /\\ len <> 0).\n  split; [exact H1 | exact H].\n  specialize (H2 H3).\n  specialize (H0 H2).\n  clear H1 H2 H3.\n  pose proof Rplus_0_l 1.\n  rewrite H1 in H0; clear H1.\n  assert (Fourier X 1 k (2 * len) = Fourier_even (OddList X) 1 k len + Fourier_odd (EvenList X) 0 k len).\n  2: {\n  rewrite H1.\n  pose proof Cplus_assoc_r (a * exp_complex 0) (Fourier_even (OddList X) 1 k len) (Fourier_odd (EvenList X) 0 k len).\n  rewrite H2.\n  reflexivity.\n  }\n  rewrite H0; clear H0.\n  pose proof Fourier_even_nMinus1 (OddList X) 0 k len.\n  specialize (H0 H).\n  pose proof Fourier_split2_1 (OddList X) k len.\n  specialize (H1 H).\n  rewrite H1 in H0; clear H1.\n  pose proof Fourier_split2_2 (EvenList X) k len.\n  specialize (H1 H).\n  pose proof Fourier_split2_1 (EvenList X) k len.\n  specialize (H2 H).\n  rewrite H2 in IHX; clear H2.\n  pose proof Fourier_split2_2 (OddList X) k len.\n  specialize (H2 H).\n  rewrite H2 in IHX; clear H2.\n  pose proof Rplus_0_l 1.\n  rewrite H2 in H0.\n  clear H2.\n  rewrite IHX; clear IHX.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * (INR k) * / (INR (2 * len)))) (Fourier (EvenList X) 0 k len) (exp_complex (-2 * PI * (INR k) * / (2 * (INR len))) * Fourier (OddList X) 0 k len).\n  rewrite H2; clear H2.\n  assert (2 * INR len = INR (2 * len))%R.\n  {\n  clear.\n  pose proof mult_INR 2 len.\n  rewrite H.\n  assert (2 = INR 2)%R.\n  constructor.\n  rewrite H0.\n  reflexivity.\n  }\n  rewrite H2 in H1.\n  rewrite <- H1; clear H1.\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * (INR k) * / (INR (2 * len)))) (exp_complex (-2 * PI * (INR k) * / (INR (2 * len)))) (Fourier (OddList X) 0 k len).\n  rewrite H2.\n  rewrite <- H1; clear H1.\n  assert (exp_complex (-2 * PI * (INR k) * / (INR (2 * len))) * exp_complex (-2 * PI * (INR k) * / (INR (2 * len))) = exp_complex (-2 * PI * (INR k) * / (INR len))).\n  {\n  pose proof exp_mult (-2 * PI * (INR k) * / (INR (2 * len))) (-2 * PI * (INR k) * / (INR (2 * len))).\n  pose proof UseByFourier_split1_1 (-2 * PI * (INR k)) (INR len).\n  pose proof not_INR len 0.\n  simpl in H4.\n  specialize (H4 H).\n  specialize (H3 H4).\n  rewrite H2 in H3.\n  rewrite H3 in H1.\n  apply H1.\n  }\n  rewrite H1.\n  rewrite <- H0.\n  apply Cplus_comm.\n  }\nQed.\n\n(** Split Fourier transform into odd and even when k > N / 2*)\nLemma Fourier_split3_1: forall (X : list C) (k len : nat),\n  len <> 0 -> len <= k -> Fourier_even X 0 k len = Fourier X 0 (k - len) len.\nProof.\n  intros.\n  induction X.\n  {\n  simpl.\n  reflexivity.\n  }\n  simpl.\n  pose proof compute_1 (-2 * PI * 2)%R (INR k) (2 * INR len).\n  pose proof compute_1 (-2 * PI)%R (INR (k - len)) (INR len).\n  rewrite H1 H2; clear H1 H2.\n  pose proof Fourier_nMinus1 X 0 (k - len) len.\n  pose proof Fourier_even_nMinus1 X 0 k len.\n  pose proof Rplus_0_l 1.\n  rewrite H3.\n  rewrite H3 in H1 H2; clear H3.\n  specialize (H1 H).\n  specialize (H2 H).\n  rewrite H1 H2 IHX; clear H1 H2.\n  pose proof Use_by_kMinuslen_1 k len.\n  specialize (H1 H H0).\n  rewrite H1.\n  reflexivity.\nQed.\n\nLemma Fourier_split3_2: forall (X : list C) (k len : nat),\n  len <> 0 -> len <= k -> Fourier_odd X 0 k len = (exp_complex (-2 * PI * (INR k) * / (2 * INR len)) ) * Fourier X 0 (k - len) len.\nProof.\n  intros.\n  induction X.\n  {\n  simpl.\n  pose proof exp_mult_0_1 (-2 * PI * INR k * / (2 * INR len)).\n  rewrite H1.\n  reflexivity.\n  }\n  simpl.\n  pose proof Rplus_0_l 1.\n  rewrite H1.\n  assert (2 * 0 + 1 = 1)%R.\n  ring.\n  rewrite H2; clear H2.\n  pose proof Rmult_1_r (-2 * PI)%R.\n  rewrite H2; clear H2.\n  pose proof compute_1 (-2 * PI)%R (INR (k - len)) (INR len).\n  rewrite H2; clear H2.\n  pose proof exp_0_mult_r a.\n  rewrite H2; clear H2.\n  pose proof Cmult_plus_distr_l (exp_complex (-2 * PI * INR k * / (2 * INR len))) a (Fourier X 1 (k - len) len).\n  rewrite H2; clear H2.\n  pose proof Cmult_comm (exp_complex (-2 * PI * INR k * / (2 * INR len))) a.\n  rewrite H2; clear H2.\n  pose proof Fourier_nMinus1 X 0 (k - len) len.\n  pose proof Fourier_odd_nMinus1 X 0 k len.\n  specialize (H2 H).\n  specialize (H3 H).\n  rewrite H1 in H2 H3; clear H1.\n  rewrite H2 H3 IHX; clear H2 H3 IHX.\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * INR k * / INR len)) (exp_complex (-2 * PI * INR k * / (2 * INR len))) (Fourier X 0 (k - len) len).\n  pose proof Cmult_assoc_r (exp_complex (-2 * PI * INR k * / (2 * INR len))) (exp_complex (-2 * PI * INR (k - len) * / INR len)) (Fourier X 0 (k - len) len).\n  rewrite <- H1; clear H1.\n  rewrite <- H2; clear H2.\n  pose proof Use_by_kMinuslen_1 k len.\n  specialize (H1 H H0).\n  rewrite H1.\n  pose proof Cmult_comm (exp_complex (-2 * PI * INR k * / (2 * INR len))) (exp_complex (-2 * PI * INR k * / INR len)).\n  rewrite H2.\n  reflexivity.\nQed.\n\nLemma FstHalf: forall (X: list C) (k: nat) (len: nat),\n  len <> 0 -> Fourier X 0 k (2 * len) = Fourier (EvenList X) 0 k len + (exp_complex (-2 * PI * (INR k) * / (2 * INR len) )) * Fourier (OddList X) 0 k len.\nProof.\n  intros.\n  pose proof Fourier_split1 X k len.\n  specialize (H0 H).\n  pose proof Fourier_split2_1 (EvenList X) k len.\n  specialize (H1 H).\n  pose proof Fourier_split2_2 (OddList X) k len.\n  specialize (H2 H).\n  rewrite <- H2.\n  rewrite <- H1.\n  rewrite <- H0.\n  reflexivity.\nQed.\n\nLemma SndHalf: forall (X: list C) (k: nat) (len: nat),\n  len <> 0 -> len <= k ->  Fourier X 0 k (2 * len) = Fourier (EvenList X) 0 (k - len) len - (exp_complex (-2 * PI * (INR (k - len)) * / (2 * INR len) )) * Fourier (OddList X) 0 (k - len) len.\nProof.\n  intros.\n  pose proof Fourier_split1 X k len.\n  specialize (H1 H).\n  pose proof Fourier_split3_1 (EvenList X) k len.\n  specialize (H2 H H0).\n  pose proof Fourier_split3_2 (OddList X) k len.\n  specialize (H3 H H0).\n  pose proof Use_by_kMinuslen_2 k len.\n  specialize (H4 H H0).\n  rewrite H4; clear H4.\n  pose proof Use_By_SndHalf (Fourier (EvenList X) 0 (k - len) len) (exp_complex (-2 * PI * INR k * / (2 * INR len))) (Fourier (OddList X) 0 (k - len) len).\n  rewrite H4; clear H4.\n  rewrite <- H3.\n  rewrite <- H2.\n  rewrite <- H1.\n  reflexivity.\nQed.\n\nLemma ListOpLength:forall (l1 l2 : list C)(Op : C->C->C) (default: list C),\nlength l1 = length l2 -> length (ListOp l1 l2 Op default) = length l1.\nProof.\n  induction l1, l2; intros.\n  + reflexivity.\n  + discriminate H.\n  + discriminate H.\n  + intros. simpl.\n    simpl in H. \n    rewrite <- Nat.compare_eq_iff.\n    rewrite Nat.compare_succ.\n    rewrite Nat.compare_eq_iff.\n    rewrite <- Nat.compare_eq_iff in H.\n    rewrite Nat.compare_succ in H.\n    simpl in H.\n    apply Nat.compare_eq_iff in H.\n    apply IHl1. exact H.\nQed.\n\nLemma EOListLength: forall (n: nat)(x: list C),\nlength x = (2 * n)%nat  -> length (EvenList x) = n /\\ length (OddList x) = n.\nProof.\n  induction n.\n  + intros; simpl.\n    induction x. { simpl; split; reflexivity. } \n    discriminate H.\n  + intros.\n    induction x; [ discriminate H | ].\n    induction x. \n    ++ simpl in H.    \n      rewrite <- Nat.compare_eq_iff in H;\n      rewrite Nat.compare_succ in H;\n      apply Nat.compare_eq_iff in H.\n      pose proof Nat.eq_add_0 n (S(n + 0)).\n      destruct H0. \n      assert ((n + S (n + 0))%nat = 0). rewrite <- H. reflexivity.\n      specialize (H0 H2). destruct H0. rewrite plus_0_r in H3.\n      discriminate H3.\n    ++ simpl. clear IHx IHx0.\n      simpl in H.       \n      rewrite <- Nat.compare_eq_iff in H;\n      rewrite Nat.compare_succ in H;\n      apply Nat.compare_eq_iff in H.\n      rewrite plus_comm in H.  rewrite plus_0_r in H.\n      rewrite <- Nat.compare_eq_iff in H;\n      rewrite Nat.compare_succ in H;\n      apply Nat.compare_eq_iff in H. fold Nat.add in H.\n      specialize (IHn x).\n      assert ((n + n)%nat = (2 * n)%nat). { simpl.  rewrite plus_0_r. reflexivity. }\n      rewrite H0 in H. pose proof IHn H. destruct H1.\n      split; rewrite <- Nat.compare_eq_iff ;\n      rewrite Nat.compare_succ ;\n      apply Nat.compare_eq_iff .\n      exact H1. exact H2.\nQed.\n\n\nLemma FFTSplit: forall (x:list C)(M: nat)(a: list C)(b: list C),\n(length a = 2^M /\\ length b = 2^M /\\ \nforall (k: nat), (k <= 2^M - 1) -> Fourier x 0 k (length x) = nth k a (0%R, 0%R)\n                        /\\ Fourier x 0 (k + 2^M) (length x) = nth k b (0%R, 0%R)) ->\nforall (k: nat), (k <= 2^(S M) - 1) -> Fourier x 0 k (length x) = nth k (a++b) (0%R, 0%R).\nProof.\n  intros.\n  destruct H.\n  destruct H1.\n  pose proof le_or_lt k  (2 ^ M - 1).\n  destruct H3.\n  + pose proof H2 _ H3.\n    pose proof ineq2 _ _ H3.\n    rewrite <- H in H5.\n    pose proof app_nth1 a b (0%R, 0%R) H5.\n    rewrite H6.\n    destruct H4. exact H4.\n  + \n    pose proof ineq3 _ _ H3.\n    assert (k >= 2 ^ M).\n\n    {unfold \">=\". exact H4. }\n    rewrite <- H in H5.\n    pose proof app_nth2 a b (0%R, 0%R) H5.\n    rewrite H6.\n    pose proof ineq4 _ _ H0.\n    pose proof H2 (k - 2 ^ M)%nat H7.\n    rewrite H.\n    destruct H8.\n    rewrite plus_comm in H9. rewrite <- le_plus_minus in H9.\n    exact H9. exact H4.\nQed.\n\nLemma nthListOp: forall (l1: list C) (l2: list C) (Op: C->C->C) (default: list C) (default0: C) (k: nat),\nlength l1 = length l2 -> \ndefault0 = Op default0 default0 ->\nnth k (ListOp l1 l2 Op default) default0 = Op (nth k l1 default0) (nth k l2 default0).\nProof.\n  induction l1, l2. intros.\n  + intros. simpl. induction k; exact H0.\n  + intros. simpl in H. discriminate H.\n  + intros. simpl in H. discriminate H.\n  + intros. induction k.\n    ++ simpl. reflexivity.\n    ++ simpl. apply IHl1. simpl in H.\n          rewrite <- Nat.compare_eq_iff in H;\n          rewrite Nat.compare_succ in H;\n          apply Nat.compare_eq_iff in H.\n          exact H. exact H0.\nQed.\n\n\n(** Some equalities about lengths*)\nLemma PhaseGenLength: forall (n m: nat),\nlength (PhaseGen n m) = n.\nProof.\n  intros.\n  induction n.\n  + reflexivity.\n  + simpl. rewrite app_length. simpl.\n    rewrite plus_comm. simpl.\n    rewrite <- Nat.compare_eq_iff;\n    rewrite Nat.compare_succ;\n    rewrite Nat.compare_eq_iff.\n    exact IHn.\nQed.\n\nLemma PhaseLength: forall (N: nat),\nlength (Phase N) = N.\nProof.\n  unfold Phase.\n  intros.\n  apply PhaseGenLength.\nQed.\n\nLemma FFTLength: forall(M: nat)(x: list C),\nlength x = 2 ^ M -> length (FFT x M) = 2 ^ M.\nProof.\n  induction M.\n  + simpl. intros. exact H.\n  + intros. simpl. rewrite app_length. \n    pose proof PhaseLength (2 ^ M).\n    pose proof IHM (OddList x). \n    pose proof IHM (EvenList x).\n    pose proof EOListLength (2^M) x.\n    assert(length x = (2 * 2 ^ M)%nat  ).\n    { simpl. simpl in H. rewrite H. reflexivity. }\n    specialize (H3 H4); clear H4. \n    destruct H3.\n    specialize (H1 H4); clear H4.\n    specialize (H2 H3); clear H3.\n    rewrite <- H0 in H1, H2.\n    pose proof ListOpLength (Phase (2 ^ M)) (FFT (OddList x) M) Cmult [].\n    pose proof ListOpLength (Phase (2 ^ M)) (FFT (EvenList x) M) Cmult [].\n    assert (length (Phase (2 ^ M)) = length (FFT (OddList x) M) ). rewrite H1; reflexivity.\n    assert (length (Phase (2 ^ M)) = length (FFT (EvenList x) M) ). rewrite H2; reflexivity.\n    specialize (H3 H5); specialize(H4 H6).\n    rewrite <- H1 in H3; rewrite <- H2 in H4.\n    pose proof ListOpLength (FFT (EvenList x) M) (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Cmult []) Cplus [].\n    pose proof ListOpLength (FFT (EvenList x) M) (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Cmult []) Cminus [].\n    rewrite H3 in H7, H8. rewrite <- H5, H6 in H7, H8. \n    assert (length (FFT (EvenList x) M) = length (FFT (EvenList x) M) ). reflexivity.\n    specialize (H7 H9). rewrite H7.\n    specialize (H8 H9). rewrite H8.\n    rewrite H2 H0. rewrite plus_0_r. reflexivity.\nQed.\n\nLemma Length1: forall (M: nat)(x: list C),\nlength x = 2 ^ (S M) ->\nlength (FFT (EvenList x) M)  = 2 ^ M /\\ length (FFT (OddList x) M) = 2 ^ M.\nProof.\n    intros.\n    pose proof EOListLength (2^M) x.\n    assert( length x = (2 * 2 ^ M)%nat  ).\n    { simpl. simpl in H. rewrite H. reflexivity. }\n    specialize (H0 H1); clear H1.\n    destruct H0.\n    pose proof FFTLength M (EvenList x) H0.\n    pose proof FFTLength M (OddList x) H1.\n    split. exact H2. exact H3.\nQed.\n\nLemma Length2: forall (M: nat)(x: list C),\nlength x = 2 ^ (S M) -> length (Phase (2 ^ M)) = 2 ^ M.\nProof.\n  intros.\n  pose proof PhaseLength (2 ^ M).\n  exact H0.\nQed.\n\nLemma Length3: forall (M: nat)(x: list C)(Op : C -> C -> C),\nlength x = 2 ^ (S M) ->\nlength (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Op []) = 2 ^ M.\nProof.\n  intros.\n  pose proof Length2 _ _ H.\n  pose proof Length1 _ _ H.\n  destruct H1.\n  pose proof ListOpLength (Phase (2 ^ M)) (FFT (OddList x) M) Op [].\n  rewrite H0 H2 in H3.\n  assert (2 ^ M = 2 ^ M). reflexivity.\n  specialize (H3 H4).\n  exact H3.\nQed.\n\nLemma Length4: forall (M: nat)(x: list C)(Op : C -> C -> C),\nlength x = 2 ^ (S M) ->\nlength\n  (ListOp (FFT (EvenList x) M) (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Cmult []) Op []) =\n2 ^ M.\nProof.\n  intros.\n  pose proof Length2 _ _ H.\n  pose proof Length1 _ _ H.\n  pose proof Length3 _ _ Cmult H.\n  destruct H1.\n  pose proof ListOpLength (FFT (EvenList x) M) (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Cmult []) Op [].\n  assert (length (FFT (EvenList x) M) =\n  length (ListOp (Phase (2 ^ M)) (FFT (OddList x) M) Cmult [])). rewrite H2 H1. reflexivity.\n  specialize (H4 H5).\n  rewrite H4. rewrite H1. reflexivity.\nQed.\n\nLemma PhaseGen_k: forall(n k m: nat),\nk < n -> nth k (PhaseGen n m) (0%R, 0%R) = exp_complex (-2 * PI * INR k * / INR (m)).\nProof.\n  induction n.\n  + intros. pose proof lt_n_0 k. contradiction.\n  + intros. pose proof lt_n_Sm_le k n. specialize (H0 H).\n      pose proof le_lt_or_eq k n. specialize(H1 H0). destruct H1.\n      ++ specialize (IHn k m H1). simpl. \n            pose proof PhaseGenLength n m.\n            rewrite <- H2 in H1.\n            pose proof app_nth1 (PhaseGen n m) ([exp_complex (-2 * PI*INR n  / INR m)]) (0%R, 0%R) H1.\n            rewrite H3. exact IHn.\n      ++ simpl. pose proof PhaseGenLength n m. rewrite <- H2 in H1.\n            pose proof le_refl k.\n            assert (k >= length (PhaseGen n m)).\n            { unfold \">=\". rewrite <- H1. exact H3. }\n            pose proof app_nth2 (PhaseGen n m) ([exp_complex (-  2 * PI * INR n/ INR m)]) (0%R, 0%R) H4.\n            rewrite H5. rewrite <- H1. rewrite minus_diag. simpl.\n            rewrite H1. rewrite H2. reflexivity.\nQed.\n\nLemma Phase_k: forall(k : nat) (M: nat),\nk < 2 ^ M -> nth k (Phase (2 ^ M)) (0%R, 0%R) = exp_complex (-2 * PI * INR k * / (INR (2 * 2 ^ M))).\nProof.\n  intros.\n  unfold Phase.\n  apply PhaseGen_k.\n  exact H.\nQed.\n\n(**  This is our ultimate goal.*)\nDefinition FFTCorrect : forall (M:nat) (x:list C) (k:nat),\n  (length x = 2 ^ M /\\ k <= 2 ^ M - 1) -> \n  Fourier x 0 k (length x) = nth k (FFT x M) (0%R, 0%R).\nProof.\n  induction M.\n  + intros. simpl. simpl in H.\n    destruct H. rewrite H. destruct x.\n    ++ unfold Fourier. destruct k; simpl; reflexivity.\n    ++ destruct x. \n          2:{simpl in H. discriminate H. }\n          simpl.\n          pose proof compute_1 (-2*PI) (INR k) 1%R .\n          rewrite H1. rewrite expcomplex_0. \n          destruct k. destruct c. unfold Cmult, Cplus. simpl. repeat rewrite Rmult_0_r. \n          repeat rewrite Rmult_1_r. repeat rewrite Rplus_0_r. repeat rewrite Rminus_0_r.\n          repeat rewrite Rplus_0_l. reflexivity. \n          simpl in H0. apply le_n_0_eq in H0. discriminate H0.\n  + intros. destruct H. simpl. revert H0. apply FFTSplit. split.\n    ++ simpl. rewrite Length4. exact H. pose proof minus_n_O M. reflexivity.\n    ++ split. rewrite Length4. exact H. pose proof minus_n_O M. simpl. reflexivity.\n          split.\n    +++ repeat rewrite nthListOp. \n          { pose proof Length1 _ _ H. pose proof Length3 _ _ Cmult H. destruct H1. rewrite H2 H1. reflexivity. }\n          { rewrite Cplus_0_r. reflexivity. }          \n          { pose proof Length1 _ _ H. pose proof Length2 _ _ H. destruct H1. rewrite H2 H3. reflexivity. }\n          { rewrite Cmult_0_r. reflexivity. }\n          assert (M = (S M - 1)%nat). { simpl. rewrite <- minus_n_O. reflexivity. } rewrite H1 in H0. clear H1.\n          pose proof ineq5 (S M - 1).\n          pose proof FstHalf x k0 (2^(S M - 1)) H1.\n          clear H1.\n          rewrite H. simpl; rewrite Nat.add_0_r.\n          simpl in H2; rewrite Nat.sub_0_r in H2. rewrite Nat.add_0_r in H2. \n          pose proof IHM (EvenList x) k0. pose proof IHM (OddList x) k0.\n          pose proof EOListLength _ _ H. fold Nat.pow in H4. destruct H4.\n          simpl in H0; rewrite Nat.sub_0_r in H0. \n          assert(Fourier (EvenList x) 0 k0 (length (EvenList x)) = nth k0 (FFT (EvenList x) M) (0%R, 0%R)).\n          apply H1. split. exact H4. exact H0.\n          assert(Fourier (OddList x) 0 k0 (length (OddList x)) = nth k0 (FFT (OddList x) M) (0%R, 0%R)).\n          apply H3. split. exact H5. exact H0.\n          pose proof ineq2 k0 M H0.\n          pose proof Phase_k k0 M.\n          pose proof H9 H8.\n          rewrite H10. rewrite H2. rewrite <- H6. rewrite <- H7. rewrite H4 H5. rewrite eq0. \n          reflexivity.\n    +++ repeat rewrite nthListOp.\n          { pose proof Length1 _ _ H. pose proof Length3 _ _ Cmult H. destruct H1. rewrite H2 H1. reflexivity. }\n          { unfold Cminus. rewrite Cplus_0_l. unfold Copp. simpl. assert(0%R = (-0)%R). ring. rewrite <- H1. reflexivity. }          \n          { pose proof Length1 _ _ H. pose proof Length2 _ _ H. destruct H1. rewrite H2 H3. reflexivity. }\n          { rewrite Cmult_0_r. reflexivity. }\n          pose proof ineq k0 M.\n          pose proof SndHalf x (k0 + 2 ^ (S M - 1)) (2^(S M - 1)) .\n          rewrite H. simpl in H1; rewrite Nat.sub_0_r in H1; rewrite plus_comm in H1.\n          simpl in H2; rewrite Nat.sub_0_r in H2; rewrite Nat.add_0_r in H2.\n          rewrite plus_comm in H2. rewrite minus_plus in H2.\n          pose proof IHM (EvenList x) k0. pose proof IHM (OddList x) k0.\n          pose proof EOListLength _ _ H. fold Nat.pow in H5. destruct H5.\n          simpl in H0. \n          assert(Fourier (EvenList x) 0 k0 (length (EvenList x)) = nth k0 (FFT (EvenList x) M) (0%R, 0%R)).\n          apply H3. split. exact H5. exact H0.\n          assert(Fourier (OddList x) 0 k0 (length (OddList x)) = nth k0 (FFT (OddList x) M) (0%R, 0%R)).\n          apply H4. split. exact H6. exact H0.\n          pose proof Phase_k k0 M.\n          pose proof ineq5 M.\n          pose proof ineq6 k0 M.\n          pose proof H2 H10 H11.\n          rewrite H5 in H7; rewrite H6 in H8; rewrite H7 H8 in H12; rewrite H9.\n          apply ineq2. exact H0.\n          simpl; rewrite Nat.add_0_r. rewrite plus_comm.\n          rewrite H12. rewrite eq0. simpl. rewrite Nat.add_0_r.\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/F0503_Discrete_Fourier_Transform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8856314858927012, "lm_q1q2_score": 0.8091807012196401}}
{"text": "\nCompute S O.\n\nFixpoint add (m: nat) (n: nat) : nat :=\n  match m with\n    | S m' => S (add m' n)\n    | O => n\n  end.\n\nTheorem plus_O_n: forall n:nat,\n    n = 0 + n.\nProof.\n  reflexivity.\nQed.           \n\nTheorem plus_n_O: forall n:nat,\n    n = n + 0.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nFixpoint minus (m: nat) (n: nat) : nat :=\n  match m, n with\n      | S m', S n' => (minus m' n')\n      | S m', O => S m'\n      | O, _ => O\n  end.\n\nCompute (minus 4 1).\n\nTheorem minus_n_n : forall n,\n    minus n n = 0.\nProof.\n  intros. induction n as [| n' IHn']. \n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nFixpoint mult (m:nat) (n:nat) : nat :=\n  match m with\n   | O => O\n   | S m' => (mult m' n) + n\n  end.\n\n\nTheorem mult_0_r : forall n:nat,\n    (mult n 0) = 0.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. simpl. reflexivity.\nQed.\n\nTheorem 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.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n    n + m = m + n.\nProof.\n  intros. induction n as [| n' IHn'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n    n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nFixpoint double (m:nat) : nat :=\n  match m with\n    | O => O\n    | S m' => S (S (double m'))\n    end.\n     \nCompute (double 0).\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\n\nFixpoint evenb (m:nat) : bool :=\n  match m with\n  | (S (S m')) => (evenb m')\n  | O => true\n  | S m' => false\n  end.\n\nCompute (evenb 3).\n\n\nTheorem evenb_S : forall n : nat,\n    evenb (S n) = negb (evenb n).\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite -> IHn'. simpl.\n    assert (H: forall b,  b = negb (negb b)).\n    { destruct b eqn:E.\n      + reflexivity.\n      + reflexivity.\n    }\n    rewrite <- H. reflexivity. \nQed.\n\n\n(* Theorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: m + n = n + m).\n\n  { rewrite -> plus_comm. simpl.}\n    rewrite -> H. reflexivity.\nQed. *)\n\nTheorem plus_swap : forall n m p : nat,\n    n + (m + p) = m + (n + p).\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem S_plus_1 : forall n : nat, S n = n + 1.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem n_opposite : forall m n : nat, m + n = m + n -> m = m.\nProof.\n  intros. reflexivity.\nQed.\n \nTheorem n_mult_1_sumk : forall n k,\n    n * (1 + k) = n + n * k.\nProof.\n  intros. simpl. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_assoc. rewrite -> plus_assoc.\n    assert (H : k + n' = n' + k).\n    { rewrite -> plus_comm. reflexivity. }\n    rewrite H. reflexivity.\nQed.\n\nTheorem mult_0_n : forall n,\n    0 = n * 0.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.  \n\nTheorem mult_comm : forall m n,\n    m * n = n * m.\nProof.\n  intros. induction n as [| n' IHn'].\n  - rewrite <- mult_0_n. reflexivity.\n  - simpl. rewrite n_mult_1_sumk. rewrite IHn'. reflexivity.\nQed.\n\nFixpoint eqb (m : nat) (n : nat) : bool :=\n  match m, n with\n  | S m', S n' => (eqb m' n')\n  | O, O => true\n  | _, _ => false     \n  end.\n\nFixpoint leb (m : nat) (n : nat) : bool :=\n  match m, n with\n  | O, O => true\n  | S m', S n' => (leb m' n')\n  | O, S n' => true\n  | _, _ => false\n  end.\n\nTheorem leb_refl : forall n : nat,\n  true = (leb n n).\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_n_0 : forall n : nat,\n    0 + n = n.\nProof.\n  intros. destruct n as [| n'] eqn: E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n : nat,\n    (eqb 0 (S n)) = false.\nProof.\n  reflexivity.\nQed.\n\n\nTheorem andb_false_r : forall b : bool,\n    andb b false = false.\nProof.\n  intros. destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem plus_ble_compat_1 : forall n m p : nat,\n    leb n m = true -> leb (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\nTheorem S_nbeq_0 : forall n : nat,\n    (eqb (S n) O) = false.\nProof.    \n  intros. reflexivity.\nQed.\n\nTheorem mult_1_1 : forall n : nat, 1 * n = n.\nProof.\n  intros. simpl. rewrite <- plus_n_O. reflexivity.\nQed.\n\nDefinition notb (b : bool) : bool :=\n  match b with\n   | true => false\n   | false => true \n  end.\n\nDefinition orb (b1 : bool) (b2 : bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n\nTheorem all3_spec : forall b c : bool,\n    orb (andb b c)\n        (orb (negb b)\n             (negb c))\n    = true.\nProof.\n  destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n    (n + m) * p = (n * p) + (m * p).\nProof.\n  intros. induction n as [| n' IHn'].\n  - destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + reflexivity.\n  - destruct m as [| m'] eqn:E.\n    + simpl. rewrite IHn'. rewrite -> plus_assoc. reflexivity.\n    + simpl. rewrite IHn'. simpl. rewrite plus_assoc. reflexivity.\nQed.\n\nTheorem mult_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 mult_plus_distr_r. rewrite IHn'. reflexivity.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n    true = eqb n n.\nProof.\n  intros. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n    n + (m + p) = m + (n + p).\nProof.\n  intros. rewrite plus_assoc. rewrite plus_assoc.\n  replace (n + m) with (m + n).\n  reflexivity.\n  rewrite plus_comm. reflexivity.\nQed.\n\n  \n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8089947104268301}}
{"text": "(* Projeto LC1*)\n(* Alunos: Vincius Lima Passos (200028545) / Marcelo Junqueira Ferreira (200023624) / Davi de Moura Amaral (200016750) *)\n\nRequire Import PeanoNat List.\nOpen Scope nat_scope.\n\n(* Defini\u00e7\u00f5es*)\n\nFixpoint insere (n:nat) (l: list nat) :=\n  match l with\n  | nil => n :: nil (* lista unit\u00e1ria *)\n  | h :: tl => if n <=? h then (n :: l) (* inser\u00e7\u00e3o de n na primeira posi\u00e7\u00e3o *)\n             else (h :: (insere n tl)) (* inser\u00e7\u00e3o de n na cauda da lista *)\n  end.\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\nLemma num_oc_S: forall n l1 l2, num_oc n (l1 ++ n :: l2) = S (num_oc n (l1 ++ l2)).\nProof.\n  induction l1.\n  - intro l2.\n    simpl.\n    rewrite Nat.eqb_refl; reflexivity.\n  - intro l2.\n    simpl.\n    destruct (n =? a); rewrite IHl1; reflexivity.\nQed.\n\nLemma num_oc_neq: forall n a l1 l2, n =? a = false -> num_oc n (l1 ++ a :: l2) = num_oc n (l1 ++ l2).\nProof.\n  induction l1.\n  - intros l2 H.\n    simpl.\n    rewrite H.\n    reflexivity.\n  - intros l2 Hfalse.\n    simpl.\n    destruct (n =? a0) eqn:H.\n    + apply (IHl1 l2) in Hfalse.\n      rewrite Hfalse; reflexivity.\n    + apply (IHl1 l2) in Hfalse.\n      assumption.\nQed.\n\nLemma num_oc_app: forall l1 l2 n, num_oc n (l1 ++ l2) = num_oc n (l2 ++ l1).\nProof.\n  induction l1.\n  - intros l2 n.\n    simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  - intros l2 n.\n    simpl.\n    destruct (n =? a) eqn:H.\n    + apply Nat.eqb_eq in H; subst.\n      rewrite num_oc_S.\n      rewrite IHl1.\n      reflexivity.\n    + rewrite num_oc_neq.\n      * rewrite IHl1.\n        reflexivity.\n      * assumption.\nQed.\n\n\n(*permutation*)\nDefinition permutation l l' := forall n:nat, num_oc n l = num_oc n l'.\n\nLemma permutation_refl: forall l, permutation l l.\nProof.\n  intro l.\n  unfold permutation.\n  intro x.\n  reflexivity.\nQed.\n\n(* Quest\u00e3o 2 ----- *)\nLemma permutation_nil: forall l, permutation nil l -> l = nil.\nProof.\n  intro l.\n  case l.\n  - intro H.\n    reflexivity.\n  - intros n l' H.\n    unfold permutation in H.\n    specialize (H n).\n    simpl in H.\n    rewrite Nat.eqb_refl in H.\n    inversion H.\nQed.\n\nLemma permutation_sym: forall l l', permutation l l' -> permutation l' l.\nProof.\n  intros l l' H.\n  unfold permutation in *.\n  intro n.\n  apply eq_sym.\n  apply H.\nQed.\n\nLemma permutation_trans: forall l1 l2 l3, permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\nProof.\n  intros.\n  induction l1.\n  -apply permutation_nil in H.\n   rewrite H in H0.\n   assumption. \n  -unfold permutation in *.\n   simpl in *.\n   intros n.\n   assert (H := H n).\n   destruct (n =? a) in *.\n   + rewrite H.\n     apply H0.\n   + rewrite H.\n     apply H0.\nQed.\n\nLemma permutation_hd: forall l l' x, permutation l l' -> permutation (x :: l) (x :: l').\nProof.\n  intros l l' x H.\n  unfold permutation in *.\n  intro x'.\n  destruct (x'=?x) eqn:H'.\n  -simpl.\n    rewrite H'.\n    rewrite H.\n    reflexivity.\n  -simpl.\n    rewrite H'.\n    rewrite H.\n    reflexivity.\nQed.\n\nLemma permutation_hd_back: forall l l' x, permutation (x::l) (x::l') -> permutation l l'.\nProof.\n  intros l l' x H.\n  unfold permutation in *. \n  intro x'.\n  specialize (H x').\n  simpl in H.\n  destruct (x' =? x)eqn: J.\n  +  apply eq_add_S in H.\n    assumption.\n  + assumption.\nQed.\n\nLemma permutation_2head: forall l x y, permutation ( x::y::l)(y::x::l).\nProof.\n  intros l x y.\n  unfold permutation.\n  intro x0.\n  simpl.\n  destruct (x0 =? x) eqn:H.\n  +destruct(x0 =? y) eqn:J.\n    -reflexivity.\n    -reflexivity.\n  +destruct(x0 =? y) eqn:J.\n    -reflexivity.\n    -reflexivity.\nQed.\n\nLemma permutation_insere: forall l l' x, permutation l l' -> permutation (x :: l) (insere x l').\nProof.\n  intros l l' x H.\n  simpl.\n  generalize dependent x.\n  generalize dependent l.\n  induction l'.\n  - intros l H x.\n    apply permutation_sym in H.\n    apply permutation_nil in H.\n    rewrite H.\n    simpl.\n    apply permutation_refl.\n  - intros l H x.\n    apply permutation_trans with (x :: a :: l').\n    +apply permutation_hd.\n      assumption.\n    +simpl.\n      destruct (x <=? a) eqn:J.\n      *apply permutation_refl.\n      *apply permutation_trans with (a :: x :: l').\n        ** unfold permutation in *.\n           apply permutation_2head.\n        **apply permutation_hd.\n           apply IHl'.\n           apply permutation_refl.\nQed.\n\n\n(*perm*)\nInductive perm: list nat -> list nat -> Prop :=\n| perm_refl: forall l, perm l l\n| perm_hd: forall x l l', perm l l' -> perm (x::l) (x::l')\n| perm_swap: forall x y l l', perm l l' -> perm (x::y::l) (y::x::l')\n| perm_trans: forall l1 l2 l3, perm l1 l2 -> perm l2 l3 -> perm l1 l3.\n\nLemma perm_app_cons: forall l1 l2 a, perm (a :: l1 ++ l2) (l1 ++ a :: l2).\nProof.\n  induction l1.\n  - intros l2 a.\n    simpl.\n    apply perm_refl.\n  - intros l2 a'.\n    simpl.\n    apply perm_trans with (a :: a' :: l1 ++ l2).\n    + apply perm_swap.\n      apply perm_refl.\n    + apply perm_hd.\n      apply IHl1.\nQed.\n\nLemma perm_insere: forall l x, perm (x :: l) (insere x l).\n Proof.\n   induction l.\n   - intro x.\n     simpl.\n     apply perm_refl.\n   - intro x.\n     simpl.\n     destruct (x <=? a).\n     + apply perm_refl.\n     + apply perm_trans with (a :: x :: l).\n       * apply perm_swap.\n         apply perm_refl.\n       * apply perm_hd.\n         apply IHl.\nQed.      \n\n(** Quest\u00e3o 1 *)\n\nLemma perm_to_permutation: forall l l', perm l l' -> permutation l l'.\nProof.\n  induction 1.\n   -apply permutation_refl.\n   -apply permutation_hd. apply IHperm.\n   -apply permutation_trans with (y::x::l).\n     +apply permutation_2head.\n     +apply permutation_hd. apply permutation_hd. apply IHperm.\n   -apply permutation_trans with l2.\n     +assumption.\n     +assumption.\nQed.\n\nLemma permutation_cons: forall n l l', permutation (n :: l) (n :: l') <-> permutation l l'.\nProof.\n  intros n l l'; split.\n  - intro H.\n    unfold permutation in *.\n    intro n'.\n    assert (H' := H n').\n    clear H.\n    simpl in *.\n    destruct (n' =? n).\n    + inversion H'.\n      reflexivity.\n    + inversion H'.\n      reflexivity.\n  - intro H.\n    unfold permutation in *.\n    intro n'.\n    simpl.\n    destruct (n' =? n).\n    + assert (H := H n').\n      rewrite H.\n      reflexivity.\n    + apply H.\nQed.\n\nLemma permutation_comm_app: forall l1 l2, permutation (l1 ++ l2) (l2 ++ l1).\nProof.\n  intros l1 l2.\n  unfold permutation.\n  apply num_oc_app.\nQed.\n\nLemma permutation_cons_num_oc: forall n l l', permutation (n :: l) l' -> exists x, num_oc  n l' = S x.\nProof.\n  intros.\n  unfold permutation in H.\n  assert (Hn := H n).\n  rewrite <- Hn.\n  simpl.\n  rewrite Nat.eqb_refl.\n  exists (num_oc n l).\n  reflexivity.\nQed.\n\n(** Quest\u00e3o 3 *)\n\nLemma num_occ_cons: forall l x n, num_oc x l = S n -> exists l1 l2, l = l1 ++ x :: l2 /\\ num_oc x (l1 ++ l2) = n.\nProof.\n  induction l.\n  -intros.\n    simpl in H.\n    inversion H.\n  -intros.\n    simpl in H.\n    destruct (x =? a) eqn: H1.\n    +specialize (IHl x n).\n      apply Nat.eqb_eq in H1.\n      rewrite H1.\n      exists nil.\n      exists l.\n      simpl.\n      rewrite H1 in H.\n      apply eq_add_S in H.\n      split.\n      *reflexivity.\n      *assumption.\n    +apply IHl in H.\n      destruct H.\n      destruct H.\n      destruct H.\n      rewrite H.\n      exists (a :: x0).\n      exists x1.\n      split.\n      *reflexivity.\n      *simpl.\n        rewrite H1.\n        assumption.\n      Qed.\n\n(** Quest\u00e3o 4 *)\n\nLemma permutation_app_cons: forall l1 l2 a, permutation (a :: l1 ++ l2) (l1 ++ a :: l2). \nProof.\n  intros.\n  apply permutation_trans with (a :: l2 ++ l1). apply permutation_hd. apply permutation_comm_app.\n  unfold permutation. \n  intros. \n  apply num_oc_app with (l1:=(a::l2)).\nQed.\n  \nLemma permutation_to_perm: forall l l', permutation l l' -> perm l l'.\nProof.\n  intro l.\n  elim l.\n  +intros.\n    apply permutation_nil in H. rewrite H.\n    apply perm_refl.\n  +intros.\n    assert (H0' := H0); apply permutation_cons_num_oc in H0'. \n    destruct H0'.\n    apply num_occ_cons in H1.\n    destruct H1. destruct H1. destruct H1. rewrite H1. \n    apply perm_trans with (a :: x0 ++ x1).\n    - apply perm_hd. apply H. apply permutation_hd_back with (x:=a).\n      apply permutation_trans with l'.\n      -- assumption.\n      -- rewrite H1. apply permutation_sym. apply permutation_app_cons.\n    - apply perm_app_cons.\nQed.\n\nTheorem perm_equiv: forall l l', perm l l' <-> permutation l l'.\nProof.\n  intros l l'.\n  split.\n  - apply perm_to_permutation.\n  - apply permutation_to_perm.\nQed.\n", "meta": {"author": "ensino-unb", "repo": "projeto-permequiv-trio", "sha": "1215ecb1e74a405ec5a2eff07ec07d815f0f4cd8", "save_path": "github-repos/coq/ensino-unb-projeto-permequiv-trio", "path": "github-repos/coq/ensino-unb-projeto-permequiv-trio/projeto-permequiv-trio-1215ecb1e74a405ec5a2eff07ec07d815f0f4cd8/PermEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8089947050589739}}
{"text": "(* ========================================================================== *]\n COQ AS A REGULAR PROGRAMMING LANGUAGE \n[* ========================================================================== *)\n\n(* We import the librariy for working with natural numbers and lists. *)\nRequire Import Nat List. \n\n(* -------------------------------------------------------------------------- *]\n To define values use the `Definition` keyword. When defining things use the\n `:=` symbol. \n\n Statements in Coq are ended with `.` (a bit similar to `;` in most languages.\n[* -------------------------------------------------------------------------- *)\nDefinition twelve := 12.\nDefinition sum_four_and_four := 4 + 4.\n\n(* You can also use `Example` instead of `Definition` for readability. *)\nExample let_statement_example := \n    let a := 2 in\n    let b := 3 in\n    a * b - 2.\n\n\n(* -------------------------------------------------------------------------- *]\n A simple way to display defined values is to use `Print`.\n[* -------------------------------------------------------------------------- *)\n\nPrint twelve.\nPrint let_statement_example.\n\n\n(* -------------------------------------------------------------------------- *]\n Coq does not evaluate unless specifically asked to. One way to do this is to\n use the `Compute` statement.\n[* -------------------------------------------------------------------------- *)\n\nCompute let_statement_example.\n\n\n(* -------------------------------------------------------------------------- *]\n Defining functions uses the same commands, with the added notation for\n defining anonymous functions `fun ??? => ???`.\n[* -------------------------------------------------------------------------- *)\n\nDefinition sum_three x y z := x + y + z.\nDefinition sum_three_anon := fun x y z => x + y + z.\n\n\n(* -------------------------------------------------------------------------- *]\n At the start of the file we also imported the module `List` for using lists.\n The empty list is `nil` and for the constructor `cons x xs` we also have the\n sugared syntax `x :: xs`.\n[* -------------------------------------------------------------------------- *)\n\nExample list_of_ones := 1 :: 1 :: 1 :: nil.\nExample raw_list_of_twos := cons 2 (cons 2 (cons 2 nil)).\n\n\n(* -------------------------------------------------------------------------- *]\n We can extract data with `match` statements, where we list the patterns for\n all constructors. The `match` statement needs to be ended with the `end`\n keyword.\n[* -------------------------------------------------------------------------- *)\n\nDefinition starts_with_0 lst :=\n    match lst with\n    | nil => false\n    | 0 :: _ => true\n    | _ :: _ => true\n    end.\n\n\n(* -------------------------------------------------------------------------- *]\n To use recursive functions we need to use `Fixpoint` instead of `Definition`.\n\n WARNING: Coq is VERY careful when it comes to recursion and requires to know\n that it will always terminate!\n[* -------------------------------------------------------------------------- *)\n\nFixpoint sum_elements lst :=\n    match lst with\n    | nil => 0\n    | x :: xs => x + sum_elements xs\n    end.\n\n(* Coq does not know how to prove that the following function terminates. *)\n(*\nFixpoint double_n_times x n := \n    if n =? 0 then x else double_n_times (2*x) (n-1).\n*)\n\n(* \n\nNOTE: `=?` is a comparison that returns a `bool`. The symbol `=` is used as\nequality in propositions when proving properties.\n\nThe definition with conditionals does not work, because Coq cannot\nautomatically detect that the recursion will terminate. \n\nWe can instead use the match statement for natural numbers. Natural numbers are\ndefined with the Peano axioms, so a natural number is either 0 or a successor\n`S` of a natural number.\n*)\n\nFixpoint double_n_times x n :=\n    match n with\n    | 0 => x\n    | S m => double_n_times (2*x) m\n    end.\n\n\n(* -------------------------------------------------------------------------- *]\n When defining custom types, we slowly move into the new and exciting Coq\n territory. First we (re)define the familiar `option` type.\n[* -------------------------------------------------------------------------- *)\n\nInductive option (A : Type) :=\n    | None : option A\n    | Some (x : A) : option A\n    .\n\n(* Why does this not work? *)\n(* Example some_one := Some 1. *)\n\n(* Let us look at a more 'raw' definition of `option`, where we explicitly\ntreat it as a function that returns a type. *)\n(*\nInductive option : Type -> Type :=\n    | None (A : Type) : option A \n    | Some (A : Type) : A -> option A\n    .\n*)\n\n(* With this notation it is clearer that we must specify the type of the\nconstructor as well. *)\n(* Example some_one := Some nat 1. *)\n\n\n(* -------------------------------------------------------------------------- *]\n Supplying types directly is often cumbersome, so let us take a peek at some\n of the mechanisms that can help with that.\n[* -------------------------------------------------------------------------- *)\n\n(* We can use `_` instead of an argument and Coq will try to figure it out. *)\nExample some_one := Some _ 1.\n\n(* We can also mark arguments as implicit by using `{}` or `[]` (there is a\ndifference but we dont have a month to learn what the difference is). *)\n\nInductive opt {A : Type} :=\n    | Non : opt\n    | Som (x : A) : opt\n    .\n\nExample som_one := Som 1.\n\n(* When we wish to directly supply type information, we do that by prefixing\n the type with `@`. *)\n\n(* Coq is confused on what type of `option` this is... *)\n(* Example non : opt := Non. *)\n\n(* So we tell it. *)\nExample non : @opt nat := Non.\nExample also_non := @Non nat.\n\n\n(* -------------------------------------------------------------------------- *]\n PRACTICE: (re)define a type for lists (use `Cons` and `Nil` for constructors).\n Then write an example (do not forget to supply types if explicit!).\n[* -------------------------------------------------------------------------- *)\n\n", "meta": {"author": "zigaLuksic", "repo": "coq-workshop", "sha": "55252d12fb7391dcf8cd6654c8f34e27017a353c", "save_path": "github-repos/coq/zigaLuksic-coq-workshop", "path": "github-repos/coq/zigaLuksic-coq-workshop/coq-workshop-55252d12fb7391dcf8cd6654c8f34e27017a353c/coq_as_language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.9086179006446221, "lm_q1q2_score": 0.8089372680502169}}
{"text": "(* ###################################################################### *)\n(** * Arithmetic Proofs *)\n\n(** (We use [admit] and [Admitted] to hide solutions from exercises.) *)\n\nAxiom admit : forall {T}, T.\n\nModule Nat.\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nCheck (S (S O)).\n\nFixpoint plus (n m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n\nNotation \"x + y\" := (plus x y) (at level 50, left associativity).\n\nNotation \"x * y\" := (mult x y) (at level 40, left associativity).\n\n\n(** Exercise: Define exponentiation *)\n\nFixpoint exp (n m : nat) : nat :=\n(* ADMIT *)\n  match m with\n  | O => S O\n  | S m' => m' * exp n m'\n  end.\n(* /ADMIT *)\n\nNotation \"x ^ y\" := (exp x y) (at level 30, right associativity).\n\n(* Let's show that O is a left and right identity for addition. *)\n\nLemma plus_0_l: forall n : nat, O + n = n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\n(* EX1 (plus_O_r) *)\nLemma plus_O_r: forall n : nat, n + O = n.\nProof.\n(* ADMITTED *)\n  intros n.\n  induction n.\n  + reflexivity.\n  + simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n(* /ADMITTED *)\n\n\n(* EX1 (n_plus_S_m) *)\nTheorem n_plus_S_m: forall n m, n + S m = S (n + m). \nProof.\n(* ADMITTED *)\n  intros n m.\n  induction n as [| n' IH].\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n(* /ADMITTED *)\n\nTheorem plus_assoc: forall m n o, m + (n + o) = (m + n) + o.\nProof.\n  intros m n o.\n  induction m as [| m' IH]. (* m is the right choice here, since [plus] is defined\n                               by recursion on the first argument. *)\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(* EX2 (plus_comm) *)\n(* Show that plus is commutative. *)\n\nTheorem plus_comm: forall n m, n + m = m + n.\nProof.\n(* ADMITTED *)\n  intros n m.\n  induction n as [|n' IH].\n  + simpl. \n    rewrite plus_O_r.\n    reflexivity.\n  + simpl.\n    rewrite IH.\n    rewrite n_plus_S_m.\n    reflexivity.\nQed.  \n(* /ADMITTED *)\n\n(** Additional exercises: Show that mult has an identity \n    [S O], a annihilator [O] and associative, commutative and\n    distributive properties. *)\n\n(** The next function tests whether a number [m] is equal to [n]. *)\n\nFixpoint beq_nat (m n : nat) : bool :=\n  match m, n with\n  | O, O => true\n  | S m', S n' => beq_nat m' n'\n  | _, _ => false\n  end.\n\nLemma beq_nat_refl : forall n, beq_nat n n = true.\nProof.\n  intros n.\n  induction n as [|n IH].\n  - reflexivity.\n  - simpl. apply IH.\nQed.\n\n(* EX2 (beq_nat_true). *)\n(* Show the reverse direction. Remember to ensure a sufficiently general \n   induction hypothesis *)\nLemma beq_nat_true :\n  forall m n, beq_nat m n = true -> m = n.\nProof.\n(* ADMITTED *)\n  intros m n. revert n.\n  induction m as [|m IH].\n  - intros n. destruct n as [|n].\n    + reflexivity.\n    + simpl. intros H. discriminate.\n  - intros n. destruct n as [|n].\n    + simpl. intros H. discriminate.\n    + simpl. intros H.\n      rewrite (IH n). (* Note that we specify an argument to the hypothesis *)\n      * reflexivity.\n      * apply H.\nQed.\n(* /ADMITTED *)\n\n\nDefinition pred (n : nat) :=\n  match n with\n  | O => O\n  | S n => n\n  end.\n\n\nFixpoint minus (m n : nat) : nat :=\n  match m, n with\n  | O, _ => m\n  | _, O => m\n  | S m', S n' => minus m' n'\n  end.\n\nNotation \"x - y\" := (minus x y) (at level 50, left associativity).\n\n(** The next function tests whether a number [m] is less than or equal\n    to [n]. *)\n\nFixpoint ble_nat (m n : nat) : bool :=\n  match m, n with\n  | O, _ => true\n  | _, O => false\n  | S n', S m' => ble_nat n' m'\n  end.\n\n(* Exercises: Show that ble_nat is reflexive, transitive and antisymmetric. *)\n\n(** The simple definition of div fails due to Coq's termination checker, \n    so we go with the more complicated one below. *)\n\nFail Fixpoint div (m n: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => if ble_nat n m then S (div (m - n) n) else O\n  end.\n\nFixpoint div (m n: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => match m with\n            | O => O\n            | S m' => S (div (S m' - S n') (S n'))\n            end\n  end.\n\n(** Here, Coq is able to figure out that [S m' - S n'] is a valid\n    recursive argument because [minus] only returns results that are\n    syntatic sub-terms of [m]. Unfortunately, this criterion is pretty\n    fragile: replacing [m] by [O] or [S m'] in the above definition of\n    [minus] causes this definition of [div] to break; try it!.\n\n    This kind of rewriting doesn't always work, alas. We can make Coq\n    accept less obvious recursive definitions by providing an\n    explicit, separate proof that they always terminate, or by\n    supplying an extra argument that gives an upper bound on how many\n    recursive calls can be performed. We won't cover this feature here\n    but you can find more about recursive definitions in Coq on the Internet. *)\n\nNotation \"x / y\" := (div x y) (at level 40, left associativity).\n\n\n(* EX2 (n_div_n) *)\n(* Show that n / n = 1, for all n > 0. \n   You will need a lemma. *)\n\n(* SOLUTION *)\nLemma n_minus_n : forall n, n - n = O.\nProof.\n  intros n.\n  induction n as [|n IH].\n  + reflexivity.\n  + simpl.\n    apply IH.\nQed.\n(* /SOLUTION *)\n    \nLemma n_div_n: forall n, ble_nat (S O) n = true -> n / n = (S O).\nProof.\n(* ADMITTED *)\n  intros n H.\n  induction n.\n  + simpl in H.\n    discriminate.\n  + simpl in *.\n    rewrite n_minus_n.\n    simpl.\n    reflexivity.\nQed.    \n(* /ADMITTED *)\n\n(* EX2 (factorial). *)\n(* The simplest version of factorial also fails. \n   Try to write a strictly decreasing factorial function. *)\nFixpoint factorial (n : nat) : nat :=\n(* ADMIT *)\n  match n with\n  | O => S O\n  | S n => S n * factorial n\n  end.\n(* /ADMIT *)\n    \n(** Well done! \n    We know that 2^n <= fact(n) <= n^n for all n>0. \n    For a challenge, try to prove both. *)\n\nEnd Nat.\n\n\n(** As mentioned previously, [nat] is already defined in Coq's\n    standard library. Coq provides special, arabic-numeral syntax for\n    [nat], which is translated in terms of the [O] and [S]\n    constructors. For instance, [3] is just special syntax for [S (S\n    (S O))]. Similarly: *)\n\nCompute (S (S O)).\nCompute (S (S O) + S O).\n\n(* Additionally nat has 'less than' and 'greater than' defined as Props in \n   addition to bool, using the standard syntax [x < y]. Check out the Coq \n   standard library for more. *)", "meta": {"author": "arthuraa", "repo": "cufp-2015-tutorial", "sha": "89e50009316a32dda75ac54aa12556ce5f9df319", "save_path": "github-repos/coq/arthuraa-cufp-2015-tutorial", "path": "github-repos/coq/arthuraa-cufp-2015-tutorial/cufp-2015-tutorial-89e50009316a32dda75ac54aa12556ce5f9df319/arithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8088083706327565}}
{"text": "\nTheorem plus_assoc : forall n m p:nat, n+(m+p)=(n+m)+p.\nProof. intros n m p. induction n. reflexivity. simpl. rewrite -> IHn. reflexivity. Qed.\nTheorem mult_0_r : forall n:nat, n*0=0.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_0_r : forall n:nat, n+0=n.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_comm : forall n m:nat, n+m=m+n.\nProof. intros n m. induction n. simpl. rewrite plus_0_r. reflexivity. simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity. Qed.\nTheorem mult_suc_r : forall n m:nat, n*(S m)=n+n*m.\nProof. induction n. reflexivity. simpl. intros m. rewrite IHn.\nrewrite plus_assoc. assert (H1:m+n=n+m). rewrite plus_comm. reflexivity.\nrewrite H1. rewrite plus_assoc. reflexivity. Qed.\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof. induction p. rewrite mult_0_r. rewrite mult_0_r. rewrite mult_0_r. reflexivity.\nrewrite mult_suc_r. rewrite mult_suc_r. rewrite mult_suc_r. rewrite IHp.\nrewrite plus_assoc. rewrite plus_assoc. \nassert (H0:m+n*p=n*p+m). rewrite plus_comm. reflexivity.\nassert (H1:n+m+n*p=n+n*p+m). rewrite <- plus_assoc. \nrewrite <- plus_assoc. rewrite H0. reflexivity.\nrewrite H1. reflexivity. Qed.\n\nInductive bin : Type :=\n | O \n | D (b : bin)\n | P (b : bin).\n\n(*Inductive bin' : Type :=\n  | stop\n  | tick (foo : bin').*)\n\nFixpoint incr_bin (b:bin) : bin :=\n  match b with\n  | O => P O\n  | D b' => P b'\n  | P b' => D (incr_bin b')\n  end.\n\nFixpoint bin_to_nat (b:bin) : nat :=\n  match b with\n  | O => 0\n  | D b' => (bin_to_nat b') * 2\n  | P b' => (bin_to_nat b') * 2 + 1\n  end.\n\nCompute bin_to_nat (P (D (P O))).\n\nTheorem incr_comm : forall b:bin, bin_to_nat(incr_bin b)=(bin_to_nat b)+1.\nProof. induction b. reflexivity. reflexivity. simpl. rewrite IHb.\nrewrite mult_plus_distr_r. assert (H1:1*2=1+1). reflexivity. rewrite H1.\nrewrite plus_assoc. reflexivity. Qed.\n\nFixpoint evenb (n:nat): bool :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S n') => evenb n'\n  end.\n\nFixpoint halve_nat (n:nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' =>\n    match n' with \n    | 0 => 0\n    | S n'' => S (halve_nat n'')\n    end\n  end.\n\nCompute halve_nat 102.\n\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with\n  | 0 => O\n  | S n' => incr_bin(nat_to_bin n')\n  end.\n\nCompute nat_to_bin 16.\n\nTheorem S_plus : forall n:nat, S n = n+1.\nProof. intros n. induction n. reflexivity. assert (H1:S(S n)=S(n+1)). rewrite IHn. reflexivity.\nrewrite H1. simpl. reflexivity. Qed.\nTheorem nat_bin_nat : forall n:nat, bin_to_nat (nat_to_bin n) = n.\nProof. induction n. reflexivity. simpl. rewrite incr_comm. rewrite IHn.\nrewrite <- S_plus. reflexivity. Qed.\n\nCompute nat_to_bin (bin_to_nat (P (P (D O)))).\n\nDefinition norm_bin (b:bin) : bin := nat_to_bin (bin_to_nat b).\n\n \n\n\n\n\n\n", "meta": {"author": "elle-et-noire", "repo": "coq", "sha": "fd253f245131883ee55ff9f1824d4bb417b6e7b7", "save_path": "github-repos/coq/elle-et-noire-coq", "path": "github-repos/coq/elle-et-noire-coq/coq-fd253f245131883ee55ff9f1824d4bb417b6e7b7/Bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.8087224473391674}}
{"text": "(*|\n#################################\nExplain a simple operation in Coq\n#################################\n\n:Link: https://stackoverflow.com/q/24177371\n|*)\n\n(*|\nQuestion\n********\n\nI have the following code, Here ``O`` is the charater ``O`` not zero\n``0``\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\nCheck (S (S (S (S O)))).\nEval compute in (minustwo 4).\n\n(*|\nI just want to know how it evaluates to ``2``? I mean how it is\nactually checking with a numeral and subtracting? I am not subtracting\nanything here, still it is working? I want to know what is the basic\nidea here? When I call ``minustwo 4`` how Coq know it is a numeral and\nhow it is returning the result? How the matching is working here?\n|*)\n\n(*|\nAnswer\n******\n\nIt is quite easy with Coq to follow step by step what is going on. But\nbefore we can do that, we need to know what your program looks like to\nCoq without all the syntactic sugar. To do that, type the following in\nyour program:\n|*)\n\nSet Printing All.\n\n(*| If you now print ``minustwo``, you will see that |*)\n\nPrint minustwo. (* .unfold *)\n\n(*|\nyour pattern match is actually broken up into two pattern matches.\n\nNot let us see step by step how Coq evaluates ``minustwo 4``. To do\nso, create the following theorem:\n|*)\n\nGoal (minustwo 4 = 2).\n\n(*|\nWe don't care that much about the theorem itself, we care more about\nthe fact that it contains the term ``minustwo 4``. We can now simplify\nthe expression step by step (you should run this in an ide to actually\nsee what is going on).\n\nFirst, we unfold the definition of ``minustwo``, using a tactic called\n``cbv delta``.\n|*)\n\n  cbv delta. (* unfold the definition of minustwo *)\n\n(*| We can now call the function, using the tactic ``cbv beta``. |*)\n\n  cbv beta. (* do the function call *)\n\n(*| We can now do the pattern match with |*)\n\n  cbv iota; cbv beta. (* pattern match *)\n\n(*|\nAnd because Coq broke up the match into two, we get to do it again\n|*)\n\n  cbv iota; cbv beta. (* pattern match *)\n\n(*| And that is why ``minustwo 4`` is ``2`` |*)\n\n  reflexivity.\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/explain-a-simple-operation-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.9099070151996073, "lm_q1q2_score": 0.8086878690621238}}
{"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\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) :=\n  match b1 with\n    | true => b2\n    | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) :=\n  match b1 with\n    | true => true\n    | false => b2\n  end.\n\nExample test_orb1: (orb true false) = true.\nProof. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. reflexivity. Qed.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n    | true => negb b2\n    | false => true\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. reflexivity. Qed.\n\nDefinition andb3 (b1: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\nCheck true.\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.\nCheck (S (S (S (S O)))).\nEval compute in (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.\nDefinition oddb (n:nat) : bool := negb (evenb n).\nExample test_oddb1: (oddb (S O)) = true.\nProof. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. reflexivity. Qed.\n\nModule Playground2.\n  Fixpoint plus (n:nat) (m:nat) : nat :=\n    match n with\n      | O => m\n      | (S n') => S (plus n' m)\n    end.\n\n  Eval compute in (plus (S (S (S O))) (S (S O))).\n\n  Fixpoint mult (n m : nat) : nat :=\n    match n with\n      | O => O\n      | S n' => plus m (mult n' m)\n    end.\n\n  Example test_mult1: (mult 3 3) = 9.\n  Proof. reflexivity. Qed.\n\n  Fixpoint minus (n m : nat) : nat :=\n    match n, m with\n      | O , _ => O\n      | S _ , O => n\n      | S n' , S m' => minus n' m'\n    end.\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => S O\n    | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\nTheorem plus_0_n: forall n : nat, 0 + n = n.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_1_1 : forall n : nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n    | O => match m with\n             | O => true\n             | S m' => false\n           end\n    | S n' => match m with\n                | O => false\n                | S m' => beq_nat n' m'\n              end\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n    | O => true\n    | S n' =>\n      match m with\n        | O => false\n        | S m' => ble_nat n' m'\n      end\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n  andb (negb (beq_nat n m)) (ble_nat n m).\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nTheorem plus_O_n: forall n : nat, 0 + n = n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem plus_1_l: forall n : nat, 1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem mult_0_l: forall n : nat, 0 * n = 0.\nProof.\n    intros n.\n    reflexivity.\nQed.\n\nTheorem plus_id_example :\n  forall (n m : nat),\n    n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise :\n  forall n m o : nat,\n    n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H.\n  rewrite -> H.\n  intros H'.\n  rewrite -> H'.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus :\n  forall n m : nat,\n    (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_0_n.\n  reflexivity.\nQed.\n                 \nTheorem mult_S_1 :\n  forall n m : nat,\n    m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_1_neg_0 :\n  forall n : nat,\n    beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [ | n'].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem negb_involutive :\n  forall b : bool,\n    negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem zero_negb_plus_1 :\n  forall n : nat,\n    beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [ | n'].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n    (forall x : bool, f x = x) -> (forall b : bool, f (f b) = b).\nProof.\n  intros f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n  forall (f : bool -> bool),\n    (forall x : bool, f x = negb x) -> (forall b : bool, f (f b) = b).\nProof.\n  intros f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n    (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  destruct b.\n  destruct c.\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | Zero : bin\n  | Odd : bin -> bin\n  | Even : bin -> bin.\n\nDefinition inc_bin (n : bin) : bin :=\n  match n with\n    | Zero => Odd Zero\n    | Odd _ => Even n\n    | Even _ => Odd n\n  end.\n\nExample inc_bin1: inc_bin Zero = Odd Zero.\nProof. reflexivity. Qed.\nExample inc_bin2: inc_bin (inc_bin Zero) = Even (Odd Zero).\nProof. reflexivity. Qed.\nExample inc_bin4: inc_bin (inc_bin (inc_bin Zero)) = Odd (Even (Odd Zero)).\nProof. reflexivity. Qed.\nExample inc_bin5: inc_bin (Even (Odd Zero)) = Odd (Even (Odd Zero)).\nProof. reflexivity. Qed. \n\nFixpoint bin_to_nat (n : bin) : nat :=\n  match n with\n    | Zero => O\n    | Odd n' => S (bin_to_nat n')\n    | Even n' => S (bin_to_nat n')\n  end.\n\nExample bin_to_nat1: bin_to_nat Zero = 0.\nProof. reflexivity. Qed.\nExample bin_to_nat2: bin_to_nat (Odd Zero) = 1.\nProof. reflexivity. Qed.\nExample bin_to_nat5: bin_to_nat (Odd (Even (Odd (Even (Odd Zero))))) = 5.\nProof. reflexivity. Qed.\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.808500763382172}}
{"text": "Require Import ZArith List Arith Bool Lia.\nImport ListNotations.\n\n(* 6.5 * Dependent Inductive Types *)\n\n(* 6.5.1 First-Order Data as Parameters *)\nInductive ltree (n : nat) : Set\n  := lleaf : ltree n\n   | lnode : forall p : nat, p <= n -> ltree n -> ltree n -> ltree n.\n\nCheck ltree_ind.\n(* ltree_ind : forall (n : nat) (P : ltree n -> Prop),\n     P (lleaf n)\n     -> (forall (p : nat) (l : p <= n) (l0 : ltree n),\n         P l0 -> forall l1 : ltree n, P l1 -> P (lnode n p l l0 l1))\n     -> forall l : ltree n, P l *)\n\nInductive sqrt_data (n : nat) : Set\n  := sqrt_intro : forall x : nat, x * x <= n -> n <  S x * S x -> sqrt_data n.\n\nCheck sqrt_data_ind.\n(* sqrt_data_ind : forall (n : nat) (P : sqrt_data n -> Prop),\n     (forall (x : nat) (l : x * x <= n) (l0 : n < S x * S x),\n             P (sqrt_intro n x l l0))\n     -> forall s : sqrt_data n, P s *)\n\n(* 6.5.2 Variably Dependent Inductive Types *)\nInductive htree (X : Type) : nat -> Type\n  := hleaf : X -> htree X 0\n   | hnode : forall h : nat, X -> htree X h -> htree X h -> htree X (S h).\n\nArguments hleaf {X} x.\nArguments hnode {X} h x t1 t2.\n\nCheck htree_ind.\n(* htree_ind : forall (A : Type) (P : forall n : nat, htree A n -> Prop),\n     (forall a : A, P 0 (hleaf A a))\n     -> (forall (n : nat) (a : A) (h : htree A n),\n          P n h -> forall h0 : htree A n,\n                     P n h0 -> P (S n) (hnode A n a h h0))\n     -> forall (n : nat) (h : htree A n), P n h *)\n\n(* repeat Z_btree definition *)\nOpen Scope Z_scope.\nInductive Z_btree : Set\n  := Z_leaf : Z_btree\n   | Z_bnode : Z -> Z_btree -> Z_btree -> Z_btree.\n\nFixpoint htree_to_btree (n : nat) (t : htree Z n) {struct t} : Z_btree\n  := match t with\n     | hleaf x => Z_bnode x Z_leaf Z_leaf\n     | hnode p v t1 t2\n       => Z_bnode v (htree_to_btree p t1) (htree_to_btree p t2)\n     end.\n\nFixpoint invert {A : Type} (n : nat) (t : htree A n) {struct t} : htree A n\n  := match t in htree _ x return htree A x with\n     | hleaf v => hleaf v\n     | hnode p v t1 t2 => hnode p v (invert p t2) (invert p t1)\n     end.\n\n(* Exercise 6.46 **\n   Prove one of the injection lemmas for the hnode construct: *)\nOpen Scope nat_scope.\nDefinition htree_left (X : Type) (n : nat) (t : htree X (S n)) : htree X n\n  := match t with\n     | hnode n v t1 t2 => t1\n     end.\n\nTheorem injection_left_htree (n : nat) (t1 t2 t3 t4 : htree nat n)\n   : hnode n O t1 t2 = hnode n O t3 t4 ->  t1 = t3.\nProof.\n  intro H. apply (f_equal (htree_left nat n)) in H. apply H.\nQed.\n\n(* authors' solution *)\nDefinition first_of_htree {A : Type} (n : nat)\n  : htree A n -> htree A (S n) -> htree A n.\n  intros v t. generalize v.\n  change (htree A (pred (S n)) -> htree A (pred (S n))).\n  case t.\n  - intros x v'. exact v'.\n  - intros p x t1 t2 v'. exact t1.\nDefined.\n\nPrint first_of_htree.\n(* first_of_htree : forall (A : Type) (n : nat),\n                           htree A n -> htree A (S n) -> htree A n\n   = fun (A : Type) (n : nat) (v : htree A n) (t : htree A (S n))\n     => (match t in (htree _ n0)\n             return (htree A (pred n0) -> htree A (pred n0))\n         with\n         | hleaf _ _ => fun (v' : htree A (pred 0)) => v'\n         | hnode _ p _ t1 _ => fun _ : htree A (pred (S p)) => t1\n         end) v *)\n\nCheck (first_of_htree 0 (hleaf 1)\n                      (hnode 0 2 (hleaf 3) (hleaf 4))).\n(* first_of_htree 0 (hleaf 1) (hnode 0 2 (hleaf 3) (hleaf 4))\n   : htree nat 0 *)\n\nCompute (first_of_htree 0 (hleaf 1)\n                        (hnode 0 2 (hleaf 3) (hleaf 4))).\n(* = hleaf 3 : htree nat 0 *)\n\nTheorem injection_first_htree (n : nat) (t1 t2 t3 t4 : htree nat n)\n  : hnode n O t1 t2 = hnode n O t3 t4 -> t1 = t3.\nProof.\n  intro H.\n  change\n    (first_of_htree n t1 (hnode n O t1 t2)\n     = first_of_htree n t1 (hnode n O t3 t4)).\n  now rewrite H.\nQed.\n\n(** Exercise 6.47\n   Define a function that takes a number n and builds\n   a fixedheight tree of height n containing\n   pairwise different -integer- natural values\n   (proofs with [nat] is slightly simpler). *)\n\n(* [pn_tree] is for \"perfect numbered tree\" *)\n\n(* Helper function for [pn_tree]\n   * h - height of tree\n   * n - value of root of tree\n   Nodes numbered like its arryay indexes in ahnentafel tree representaton.\n   See [Binary heap implementation](https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation)\n *)\nFixpoint pn_tree_aux (h n : nat) {struct h} : htree nat h\n  := match h with\n     | O => hleaf n\n     | S h' => hnode h' n\n                    (pn_tree_aux h' (2*n + 1))\n                    (pn_tree_aux h' (2*n + 2))\n     end.\n\nDefinition pn_tree (h : nat) : htree nat h := pn_tree_aux h 0.\n\nExample pn_tree_ex2\n  : pn_tree 2 = hnode 1 0\n                      (hnode 0 1 (hleaf 3) (hleaf 4))\n                      (hnode 0 2 (hleaf 5) (hleaf 6)).\nProof. reflexivity. Qed.\n\nExample pn_tree_ex3\n  : pn_tree 3\n    = hnode 2 0\n            (hnode 1 1\n                   (hnode 0 3 (hleaf 7) (hleaf 8))\n                   (hnode 0 4 (hleaf 9) (hleaf 10)))\n            (hnode 1 2\n                   (hnode 0 5 (hleaf 11) (hleaf 12))\n                   (hnode 0 6 (hleaf 13) (hleaf 14))).\nProof. reflexivity. Qed.\n\n(** authors' solution (with Z replaced by [nat])*)\nFixpoint make_htree_aux (h start : nat) : nat * htree nat h\n  := match h with\n     | 0 => (start + 1, hleaf start)\n     | S h' => let (start2, t1) := make_htree_aux h' (start + 1) in\n              let (next, t2) := make_htree_aux h' start2 in\n              (next, hnode h' start t1 t2)\n     end.\n\nDefinition make_htree (n : nat) : htree nat n := snd (make_htree_aux n 0).\n\nExample make_htree_ex3\n  : make_htree 3\n    = hnode 2 0\n            (hnode 1 1\n                   (hnode 0 2 (hleaf 3) (hleaf 4))\n                   (hnode 0 5 (hleaf 6) (hleaf 7)))\n            (hnode 1 8\n                   (hnode 0 9 (hleaf 10) (hleaf 11))\n                   (hnode 0 12 (hleaf 13) (hleaf 14))).\nProof. reflexivity. Qed.\n\n(** my proof of some properties *)\n\n(* get range of natural numbers\n   from n0 (inclusive) to n (exclusive) *)\nFixpoint range (n0 n : nat) : list nat\n  := match n with\n     | O => []\n     | S n' => n0 :: range (S n0) n'\n     end.\n\nExample range_ex1 : range 0 4 = [0; 1; 2; 3].\nProof. reflexivity. Qed.\n\n(* list htree elements DFS *)\nFixpoint flat_htree_dfs {X : Type} {h : nat} (t : htree X h)\n         {struct t} : list X\n  := match t with\n     | hleaf x => [x]\n     | hnode h' x t1 t2 => x :: (flat_htree_dfs t1) ++ (flat_htree_dfs t2)\n     end.\n\nCompute flat_htree_dfs (pn_tree 3).\n(* = [0; 1; 3; 7; 8; 4; 9; 10; 2; 5; 11; 12; 6; 13; 14] : list nat *)\nCompute flat_htree_dfs (make_htree 3).\n(* = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14] : list nat *)\nCompute range 0 15.\n(* = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14] : list nat *)\n\nExample flat_htree_dfs_ex3 : flat_htree_dfs (make_htree 3) = range 0 15.\nProof. simpl. reflexivity. Qed.\n\nDefinition htree_x {X : Type} {h : nat} (t : htree X h) : X\n  := match t with\n     | hleaf x => x\n     | hnode _ x _ _ => x\n     end.\n\nDefinition htree_t1 {X : Type} {h : nat} (t : htree X (S h)) : htree X h\n  := match t with hnode _ _ t1 _ => t1 end.\n\nDefinition htree_t2 {X : Type} {h : nat} (t : htree X (S h)) : htree X h\n  := match t with hnode _ _ _ t2 => t2 end.\n\n(** see \"convoy pattern\" in http://adam.chlipala.net/cpdt/html/MoreDep.html *)\n(** illustration on simple example: *)\n(*\nDefinition convoy_test_err (n : nat) (t : htree Z n) : htree Z (pred n)\n  := match n with\n     | O => t\n     | S n' => htree_t1 n' t\n     end t.\n*)\n\n(* Toplevel input, characters 131-132: *)\n(* > Definition convoy_test_err (n : nat) (t : htree Z n) : htree Z (pred n)   := match n with      | O => t      | S n' => htree_t1 n' t      end t. *)\n(* >                                                                                                                                    ^ *)\n(* Error: *)\n(* In environment *)\n(* n : nat *)\n(* t : htree Z n *)\n(* n' : nat *)\n(* The term \"t\" has type \"htree Z n\" while it is expected to have type *)\n(*  \"htree Z (S n')\" (cannot unify \"n\" and \"S n'\"). *)\n\nDefinition convoy_test_ok (n : nat) (t : htree Z n) : htree Z (pred n)\n  := match n return htree Z n -> htree Z (pred n) with\n     | O => fun t => t\n     | S n' => fun t => htree_t1 t\n     end t.\n\n(* It is bad example because \"convoy\" and even match \"in\" clause\n   is not nececarry *)\nDefinition convoy_test_no_convoy (n : nat) (t : htree Z n) : htree Z (pred n)\n  := match t with\n     | hleaf x => hleaf x\n     | hnode h x t1 t2 => t1\n     end.\n\n(** list htree elements BFS *)\nDefinition flat_htree_bfs_aux1 {X : Type}\n           (h : nat) (t : htree X (S h)) (acc : list (htree X h))\n  := (htree_t1 t) :: (htree_t2 t) :: acc.\n\nFixpoint flat_htree_bfs_aux {X : Type} {h : nat}\n         (q : list (htree X h)) {struct h}\n  : list X\n  := match h return list (htree X h) -> list X with\n     | O => fun Q => map htree_x Q\n     | S h' => fun Q => let q' := fold_right (flat_htree_bfs_aux1 h') [] Q in\n                    let cur_layer := map htree_x Q in\n                    let next_layers := (flat_htree_bfs_aux q') in\n                    cur_layer ++ next_layers\n     end q.\n\nPrint flat_htree_bfs_aux.\n\nDefinition flat_htree_bfs {X : Type} {h : nat} (t : htree X h) : list X\n  := @flat_htree_bfs_aux X h [t].\n\nCompute flat_htree_bfs (pn_tree 1).\n(* = [0; 1; 2] : list nat *)\n\nCompute pn_tree 2.\n(* = hnode 1 0 (hnode 0 1 (hleaf 3) (hleaf 4))\n               (hnode 0 2 (hleaf 5) (hleaf 6))\n   : htree nat 2 *)\n\nCompute flat_htree_bfs (pn_tree 2).\n(* = [0; 1; 2; 3; 4; 5; 6] : list nat *)\n\nCompute flat_htree_bfs (pn_tree 3).\n(* = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14] : list nat *)\n\nExample flat_htree_bfs_ex3 : flat_htree_bfs (pn_tree 3) = range 0 15.\nProof. reflexivity. Qed.\n\nFixpoint In_htree {X : Type} {h : nat} (y : X) (t : htree X h) {struct t} : Prop\n  := match t with\n     | hleaf x => x = y\n     | hnode h x t1 t2 => x = y \\/ In_htree y t1 \\/ In_htree y t2\n     end.\n\n(* htree is pairwise different *)\nFixpoint htree_is_pwdiff {X : Type} {h : nat} (t : htree X h) {struct t} : Prop\n  := match t with\n     | hleaf x => True\n     | hnode h' x t1 t2\n       => htree_is_pwdiff t1 /\\ htree_is_pwdiff t2\n         /\\ (forall y : X, In_htree y t1 -> y <> x)\n         /\\ (forall y : X, In_htree y t2 -> y <> x)\n         /\\ (forall y1 y2 : X, In_htree y1 t1 -> In_htree y2 t2 -> y1 <> y2)\n     end.\n\nTheorem not_in_tree_iff {X : Type} (x : X) (h : nat) (t : htree X h)\n  : (forall y : X, In_htree y t -> y <> x) <-> ~ In_htree x t.\nProof.\n  split; intro H.\n  - intro H1. apply H in H1. apply H1. reflexivity.\n  - intros y H1 eq. subst y. apply H, H1.\nQed.\n\nTheorem not_in_pn_tree_aux (h n k : nat)\n  : n < k -> ~ In_htree n (pn_tree_aux h k).\nProof.\n  generalize dependent k.\n  induction h as [| h1 IH]; simpl; try lia.\n  intros k k_gt [H | [H | H]]; try lia.\n  - apply (IH (k + (k + 0) + 1)); [lia | apply H].\n  - apply (IH (k + (k + 0) + 2)); [lia | apply H].\nQed.\n\nTheorem pn_tree_contains_left_branch (h n y : nat)\n  : In_htree y (pn_tree_aux h (2 * n + 1))\n    -> In_htree y (pn_tree_aux (S h) n).\nProof.\n  intro H. simpl. right. left. exact H.\nQed.\n\nTheorem pn_tree_contains_right_branch (h n y : nat)\n  : In_htree y (pn_tree_aux h (2 * n + 2))\n    -> In_htree y (pn_tree_aux (S h) n).\nProof.\n  intro H. simpl. right. right. exact H.\nQed.\n\nTheorem pn_tree_max (h n y : nat)\n  : In_htree y (pn_tree_aux h n) -> y <= 2^h * (n + 2) - 2.\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; intros n H.\n  - simpl in *. lia.\n  - destruct h1 as [| h2];\n      [|remember (S h2) as h1 eqn:eq_h1];\n      simpl in H;\n      replace (n + (n + 0)) with (2*n) in H by lia;\n      destruct H as [H | [H | H]];\n      try (subst y; simpl; lia).\n    + subst n. rewrite Nat.pow_succ_r'.\n      rewrite <- Nat.mul_assoc.\n      rewrite <- Nat.mul_pred_r.\n      rewrite <- Nat.double_twice. unfold Nat.double.\n      apply le_plus_trans, Nat.lt_le_pred.\n      rewrite <- (Nat.mul_1_l y) at 1.\n      apply Nat.mul_lt_mono; [|lia].\n      apply Nat.pow_gt_1; lia.\n    + apply IH in H. simpl in *. lia.\n    + apply IH in H. simpl in *. lia.\nQed.\n\nTheorem pn_tree_in_Sh' (h n y : nat)\n  : In_htree y (pn_tree_aux (S h) n)\n    -> In_htree y (pn_tree_aux h n)\n      \\/ (2^(S h) * (n + 1) - 1) <= y.\nProof.\n  generalize dependent n.\n  induction h as [| h' IH]; intros n H.\n  - simpl in *. lia.\n  - remember (S h') as h eqn:eq_h. simpl in H.\n    replace (n + (n + 0)) with (2*n) in H by lia.\n    destruct H as [H | [H | H]].\n    + left. subst h n. simpl. left. reflexivity.\n    + apply IH in H. destruct H as [H | H].\n      * left. subst h. apply pn_tree_contains_left_branch, H.\n      * subst h. right. simpl in *. lia.\n    + apply IH in H. destruct H as [H | H].\n      * left. subst h. apply pn_tree_contains_right_branch, H.\n      * subst h. right. simpl in *. lia.\nQed.\n\nTheorem pn_tree_in_Sh (h n y : nat)\n  : In_htree y (pn_tree_aux (S h) n)\n    -> In_htree y (pn_tree_aux h n)\n      \\/ (2^(S h) * (n + 1) - 1) <= y <= 2^(S h) * (n + 2) - 2.\nProof.\n  intro H. apply pn_tree_in_Sh' in H as H'.\n  destruct H' as [H' | H'].\n  - left. assumption.\n  - right. split.\n    + assumption.\n    + apply pn_tree_max in H. lia.\nQed.\n\nTheorem pow_ge_1 (n m : nat) : 1 <= n -> 1 <= n ^ m.\nProof. intro H. induction m as [| m' IH]; simpl; lia. Qed.\n\nLemma le_sub (a b c : nat) : b <= a -> c <= a -> a - b <= a - c -> c <= b.\nProof.\n  intros H1 H2 H.\n  apply (Nat.le_sub_le_add_r _ _ b) in H.\n  rewrite <- Nat.add_sub_swap in H; [|exact H2].\n  apply (plus_le_compat_r _ _ c) in H.\n  rewrite <- Nat.add_sub_swap in H; [|lia].\n  rewrite Nat.add_sub in H.\n  apply (Nat.add_le_mono_l c b a), H.\nQed.\n\nLemma le_sub2 (a b c d : nat)\n  : b <= a -> d <= c -> a - b <= c - d -> a + d <= c + b.\nProof.\n  intros H1 H2 H.\n  apply (Nat.le_sub_le_add_r _ _ b) in H.\n  rewrite <- Nat.add_sub_swap in H; [|exact H2].\n  apply (plus_le_compat_r _ _ d) in H.\n  rewrite <- Nat.add_sub_swap in H; [|lia].\n  rewrite Nat.add_sub in H. exact H.\nQed.\n\nTheorem pow_ge (a b c : nat) : 0 < a <= c -> a <= a ^ b * c.\nProof.\n  intros [a_gt a_lt]. rewrite <- (Nat.mul_1_l a) at 1.\n  apply Nat.mul_le_mono; [|lia].\n  apply pow_ge_1. lia.\nQed.\n\nTheorem pn_tree_last_layer (h n y : nat)\n  : (2^h * (n + 1) - 1) <= y <= 2^h * (n + 2) - 2\n    -> In_htree y (pn_tree_aux h n).\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; intros n [y_gt y_lt].\n  - simpl in *. lia.\n  - pose (IH (2*n + 1)) as H1.\n    pose (IH (2*n + 2)) as H2.\n    destruct (y <=? 2 ^ h1 * (2 * n + 1 + 2) - 2) eqn:neq.\n    + apply Nat.leb_le in neq.\n      apply pn_tree_contains_left_branch, H1.\n      simpl in y_gt. split; lia.\n    + apply Nat.leb_gt in neq. unfold lt in neq.\n      rewrite <- Nat.add_1_r in neq.\n      rewrite <- Nat.add_sub_swap in neq.\n      2:{ apply pow_ge. lia. }\n      apply pn_tree_contains_right_branch, H2.\n      simpl in y_lt. split; lia.\nQed.\n\nTheorem pn_tree_branches_is_diff (h n y : nat)\n  : In_htree y (pn_tree_aux h (2*n + 1))\n    -> ~ In_htree y (pn_tree_aux h (2*n + 2)).\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; [simpl; lia|].\n  intros n H1 H2.\n  apply pn_tree_in_Sh in H1.\n  apply pn_tree_in_Sh in H2.\n  destruct H1 as [H1 | H1]; destruct H2 as [H2 | H2].\n  - apply (IH n H1 H2).\n  - apply pn_tree_max in H1. destruct H2 as [y_gt y_lt].\n    pose (Nat.le_trans _ y _ y_gt H1) as H.\n    replace (2 * n + 2 + 1) with (2 * n + 1 + 2) in H by lia.\n    rewrite Nat.pow_succ_r' in H.\n    assert (2 <= 2 ^ h1 * (2 * n + 1 + 2)) as Hgt.\n    { apply pow_ge. lia. }\n    apply le_sub2 in H; lia.\n  - apply pn_tree_max in H2. destruct H1 as [y_gt y_lt].\n    pose (Nat.le_trans _ y _ y_gt H2) as H.\n    replace (2 * n + 1 + 1) with (2 * n + 2) in H by lia.\n    rewrite Nat.pow_succ_r' in H.\n    assert (2 <= 2 ^ h1 * (2 * n + 1 + 2)) as Hgt.\n    { apply pow_ge. lia. }\n    apply le_sub2 in H; lia.\n  - destruct H1 as [_ y_lt]. destruct H2 as [y_gt _].\n    pose (Nat.le_trans _ y _ y_gt y_lt) as H.\n    replace (2 * n + 2 + 1) with (2 * n + 1 + 2) in H by lia.\n    rewrite Nat.pow_succ_r' in H.\n    assert (2 <= 2 ^ h1 * (2 * n + 1 + 2)) as Hgt.\n    { apply pow_ge. lia. }\n    apply le_sub2 in H; lia.\nQed.\n\nTheorem pn_tree_aux_is_pwdiff (h n : nat) : htree_is_pwdiff (pn_tree_aux h n).\nProof.\n  generalize dependent n.\n  induction h as [| h' IH]; [reflexivity|].\n  intro n. simpl. repeat split; try apply IH.\n  - apply not_in_tree_iff, not_in_pn_tree_aux. lia.\n  - apply not_in_tree_iff, not_in_pn_tree_aux. lia.\n  - intros y1 y2 H1 H2. apply not_eq_sym.\n    generalize dependent H2.\n    generalize dependent y2.\n    rewrite (not_in_tree_iff y1).\n    apply pn_tree_branches_is_diff, H1.\nQed.\n\nTheorem pn_tree_is_pwdiff (h : nat) : htree_is_pwdiff (pn_tree h).\nProof. apply pn_tree_aux_is_pwdiff. Qed.\n\nTheorem make_htree_aux_fst_eq (h n : nat)\n  : fst (make_htree_aux h n) = (n + 2^(S h) - 1).\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; [simpl; lia|].\n  intro n. simpl make_htree_aux.\n  destruct (make_htree_aux h1 (n + 1)) as (start2, t1) eqn:eq1.\n  destruct (make_htree_aux h1 start2) as (next, t2) eqn:eq2.\n  simpl fst.\n  apply (f_equal fst) in eq1 as eq_start2. simpl in eq_start2.\n  apply (f_equal fst) in eq2 as eq_next. simpl in eq_next.\n  rewrite IH in eq_next, eq_start2.\n  rewrite <- eq_next, <- eq_start2.\n  remember (S h1) as h eqn:eq_h. rewrite Nat.pow_succ_r'.\n  replace (n + 1 + 2^h - 1 + 2^h - 1) with (n + (2 * 2^h + 1) - 2) by lia.\n  rewrite <- Nat.add_sub_assoc.\n  replace (2 * 2 ^ h + 1 - 2) with (2 * 2 ^ h - 1); try lia.\n  - rewrite Nat.add_sub_assoc; [lia|].\n    rewrite <- Nat.pow_succ_r'. apply pow_ge_1. lia.\n  - apply le_plus_trans. rewrite Nat.mul_comm. apply pow_ge. lia.\nQed.\n\nTheorem make_htree_start_lt_next (h n : nat)\n  : n < fst (make_htree_aux h n).\nProof.\n  rewrite make_htree_aux_fst_eq.\n  rewrite <- Nat.add_sub_assoc.\n  - rewrite plus_n_O at 1. apply plus_le_lt_compat; [lia|].\n    pose (Nat.pow_gt_1 2 (S h)) as neq. lia.\n  - apply pow_ge_1. lia.\nQed.\n\nTheorem make_htree_bounds (h n y : nat)\n  : In_htree y (snd (make_htree_aux h n))\n    <-> n <= y < fst (make_htree_aux h n).\nProof.\n  generalize dependent n.\n  generalize dependent y.\n  induction h as [| h1 IH]; [simpl; lia|]. simpl. intros y n.\n  destruct (make_htree_aux h1 (n + 1)) as (start2, t1) eqn:eq1.\n  destruct (make_htree_aux h1 start2) as (next, t2) eqn:eq2.\n  apply (f_equal fst) in eq1 as eq_start2. simpl in eq_start2.\n  apply (f_equal fst) in eq2 as eq_next. simpl in eq_next.\n  apply (f_equal snd) in eq1 as eq_t1. simpl in eq_t1.\n  apply (f_equal snd) in eq2 as eq_t2. simpl in eq_t2.\n  simpl. split; intro H.\n  - assert (n + 1 < start2) as neq1.\n    { subst start2. apply make_htree_start_lt_next. }\n    assert (start2 < next) as neq2.\n    { subst next. apply make_htree_start_lt_next. }\n    destruct H as [H | [H | H]].\n    + subst n. split; lia.\n    + rewrite <- eq_t1 in H. apply IH in H. rewrite eq_start2 in H. lia.\n    + rewrite <- eq_t2 in H. apply IH in H. rewrite eq_next in H. lia.\n  - destruct H as [y_ge_n y_lt_next].\n    apply le_lt_or_eq in y_ge_n. destruct y_ge_n as [y_gt_n | y_eq_n].\n    2:{ subst n. now left. }\n    right.\n    destruct (le_lt_dec start2 y) as [y_gt_s2 | y_lt_s2].\n    + right. rewrite <- eq_t2. apply IH. lia.\n    + left. rewrite <- eq_t1. apply IH. lia.\nQed.\n\nTheorem make_htree_aux_is_pwdiff (h n : nat)\n  : htree_is_pwdiff (snd (make_htree_aux h n)).\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; intro n; [reflexivity|].\n  simpl.\n  destruct (make_htree_aux h1 (n + 1)) as (start2, t1) eqn:eq1.\n  destruct (make_htree_aux h1 start2) as (next, t2) eqn:eq2.\n  apply (f_equal fst) in eq1 as eq_start2. simpl in eq_start2.\n  apply (f_equal fst) in eq2 as eq_next. simpl in eq_next.\n  apply (f_equal snd) in eq1 as eq_t1. simpl in eq_t1.\n  apply (f_equal snd) in eq2 as eq_t2. simpl in eq_t2.\n  simpl. repeat split.\n  - rewrite <- eq_t1. apply (IH (n + 1)).\n  - rewrite <- eq_t2. apply (IH start2).\n  - intros y H eq. subst y. rewrite <- eq_t1 in H.\n    apply make_htree_bounds in H. lia.\n  - intros y H eq. subst y. rewrite <- eq_t2 in H.\n    apply make_htree_bounds in H.\n    pose (make_htree_start_lt_next h1 (n + 1)) as neq. lia.\n  - intros y1 y2 H1 H2 eq.\n    rewrite <- eq_t1 in H1. rewrite <- eq_t2 in H2.\n    apply make_htree_bounds in H1, H2.\n    rewrite eq_start2 in H1. rewrite eq_next in H2. lia.\nQed.\n\nTheorem make_htree_is_pwdiff (h : nat) : htree_is_pwdiff (make_htree h).\nProof. apply make_htree_aux_is_pwdiff. Qed.\n\nTheorem range_cons (n m : nat) : n :: range (S n) m = range n (S m).\nProof. reflexivity. Qed.\n\nTheorem range_app (n1 n2 m1 m2 : nat)\n  : n2 = n1 + m1 -> range n1 m1 ++ range n2 m2 = range n1 (m1 + m2).\nProof.\n  generalize dependent n2.\n  generalize dependent n1.\n  induction m1 as [| m1' IH]; intros n1 n2 eq.\n  - simpl. subst n2. rewrite Nat.add_0_r. reflexivity.\n  - simpl. rewrite (IH (S n1) n2); [reflexivity | lia].\nQed.\n\nTheorem fold_double (n : nat) : n + (n + 0) = 2 * n.\nProof. reflexivity. Qed.\n\nTheorem flat_make_htree_aux_is_range (h n : nat)\n  : flat_htree_dfs (snd (make_htree_aux h n)) = range n (2^(S h) - 1).\nProof.\n  generalize dependent n.\n  induction h as [| h1 IH]; intro n; [reflexivity|].\n  simpl make_htree_aux. rewrite Nat.pow_succ_r'.\n  destruct (make_htree_aux h1 (n + 1)) as (start2, t1) eqn:eq1.\n  destruct (make_htree_aux h1 start2) as (next, t2) eqn:eq2.\n  apply (f_equal fst) in eq1 as eq_start2. simpl in eq_start2.\n  apply (f_equal fst) in eq2 as eq_next. simpl in eq_next.\n  apply (f_equal snd) in eq1 as eq_t1. simpl in eq_t1.\n  apply (f_equal snd) in eq2 as eq_t2. simpl in eq_t2.\n  simpl. rewrite <- eq_t1, <- eq_t2. rewrite !IH.\n  rewrite fold_double, Nat.add_1_r, range_app, range_cons.\n  - apply (f_equal (range n)). rewrite <- Nat.add_1_r.\n    rewrite fold_double.\n    replace (2^(S h1)) with (2 * 2^h1) by auto with arith.\n    replace (2 * 2^h1 + (2 * 2^h1 + 0)) with (4 * 2^h1) by lia.\n    replace (2 * 2^h1 - 1 + (2 * 2^h1 - 1)) with (4 * 2^h1 - 2) by lia.\n    rewrite <- Nat.add_sub_swap. lia.\n    rewrite Nat.mul_comm. apply pow_ge. lia.\n  - rewrite <- eq_start2, make_htree_aux_fst_eq.\n    rewrite Nat.add_sub_assoc; [| apply pow_ge_1]; lia.\nQed.\n\nTheorem flat_make_htree_is_range (h : nat)\n  : flat_htree_dfs (make_htree h) = range 0 (2^(S h) - 1).\nProof. apply flat_make_htree_aux_is_range. Qed.\n\nTheorem cons_eq {X : Type} (x1 x2 : X) (xs1 xs2 : list X)\n  : x1 = x2 -> xs1 = xs2 -> x1 :: xs1 = x2 :: xs2.\nProof. intros eq_x eq_xs. subst x2 xs2. reflexivity. Qed.\n\nTheorem flat_htree_bfs_aux_Sh {X : Type} (h : nat)\n        (ts : list (htree X (S h)))\n  : flat_htree_bfs_aux ts\n    = (map htree_x ts)\n        ++ flat_htree_bfs_aux (fold_right (flat_htree_bfs_aux1 h) [] ts).\nProof. reflexivity. Qed.\n\nTheorem flat_htree_bfs_aux_Sh_cons {X : Type} (h : nat)\n        (t : htree X (S h)) (ts : list (htree X (S h)))\n  : flat_htree_bfs_aux (t :: ts)\n    = (htree_x t)\n        :: (map htree_x ts)\n        ++ (flat_htree_bfs_aux\n              ((htree_t1 t)\n                 :: (htree_t2 t)\n                 :: (fold_right (flat_htree_bfs_aux1 h) [] ts))).\nProof. reflexivity. Qed.\n\nTheorem flat_htree_bfs_aux0 {X : Type} (ts : list (htree X 0))\n  : flat_htree_bfs_aux ts = map htree_x ts.\nProof. reflexivity. Qed.\n\nTheorem pn_trees_range_x (h n0 m : nat)\n  : map htree_x (map (pn_tree_aux h) (range n0 m))\n    = range n0 m.\nProof.\n  generalize dependent n0.\n  induction m as [| m' IH]; [reflexivity|].\n  intro n0. simpl. rewrite IH.\n  destruct h as [| h']; reflexivity.\nQed.\n\nTheorem pn_trees_range_second_layer (n0 m : nat)\n  : map htree_x\n        (fold_right (flat_htree_bfs_aux1 0) []\n                    (map (pn_tree_aux 1) (range n0 m)))\n    = range (2 * n0 + 1) (2 * m).\nProof.\n  generalize dependent n0.\n  induction m as [| m1 IH]; intro n0; [reflexivity|].\n  simpl. rewrite IH. simpl. apply cons_eq; [reflexivity|].\n  replace (m1 + S (m1 + 0)) with (S (2 * m1)) by lia. simpl.\n  apply cons_eq; [lia|]. f_equal. lia.\nQed.\n\nTheorem flat_htree_bfs_aux_nil (X : Type) (h : nat)\n  : @flat_htree_bfs_aux X h [] = [].\nProof.\n  induction h as [| h' IH]; [reflexivity|].\n  simpl. exact IH.\nQed.\n\nTheorem pn_trees_range_next_layers (h n0 m : nat)\n  : fold_right (flat_htree_bfs_aux1 h) []\n               (map (pn_tree_aux (S h)) (range n0 m))\n    = map (pn_tree_aux h) (range (2 * n0 + 1) (2 * m)).\nProof.\n  generalize dependent n0.\n  induction m as [| m' IH]; intro n0; [reflexivity|].\n  simpl in *. rewrite IH. unfold flat_htree_bfs_aux1. simpl.\n  apply cons_eq; [reflexivity|]. rewrite (Nat.add_succ_r m').\n  simpl. apply cons_eq.\n  - f_equal. lia.\n  - f_equal. f_equal. lia.\nQed.\n\nTheorem flat_htree_bfs_aux_pn_tree_Sh_head (h n0 m : nat)\n  : flat_htree_bfs_aux (map (pn_tree_aux (S h)) (range n0 m))\n    = (range n0 m)\n        ++ (flat_htree_bfs_aux (map (pn_tree_aux h)\n                                    (range (2 * n0 + 1) (2 * m)))).\nProof.\n  rewrite flat_htree_bfs_aux_Sh, pn_trees_range_x. apply app_inv_head_iff.\n  rewrite pn_trees_range_next_layers. reflexivity.\nQed.\n\nTheorem flat_htree_bfs_aux_pn_tree_Sh_last (h n0 m : nat)\n  : flat_htree_bfs_aux (map (pn_tree_aux (S h)) (range n0 m))\n    = (flat_htree_bfs_aux\n         (map (pn_tree_aux h) (range n0 m)))\n        ++ range (2^(S h) * (n0 + 1) - 1) (m * 2^(S h)).\nProof.\n  generalize dependent n0.\n  generalize dependent m.\n  induction h as [| h1 IH]; intros m n0.\n  - rewrite flat_htree_bfs_aux_Sh, !flat_htree_bfs_aux0, !pn_trees_range_x.\n    apply app_inv_head_iff. rewrite pn_trees_range_second_layer.\n    f_equal; simpl; lia.\n  - rewrite flat_htree_bfs_aux_pn_tree_Sh_head, IH.\n    rewrite flat_htree_bfs_aux_pn_tree_Sh_head.\n    rewrite <- app_assoc. repeat apply app_inv_head_iff.\n    f_equal; simpl; try lia.\nQed.\n\nCompute (flat_htree_bfs (pn_tree_aux 1 1)).\n(* = [1; 3; 4] : list nat *)\nCompute range (2^2 * (1 + 1) - 1) (2^2).\n(* = [7; 8; 9; 10] : list nat *)\nCompute (flat_htree_bfs (pn_tree_aux 2 1)).\n(* = [1; 3; 4; 7; 8; 9; 10] : list nat *)\n\nTheorem flat_pn_tree_Sh (h n : nat)\n  : flat_htree_bfs (pn_tree_aux (S h) n)\n    = (flat_htree_bfs (pn_tree_aux h n))\n        ++ range (2^(S h) * (n + 1) - 1) (2^(S h)).\nProof.\n  unfold flat_htree_bfs.\n  pose (flat_htree_bfs_aux_pn_tree_Sh_last h n 1) as H.\n  simpl in *. rewrite H. rewrite !fold_double.\n  apply app_inv_head_iff. f_equal. lia.\nQed.\n\nTheorem flat_pn_tree_is_range (h : nat)\n  : flat_htree_bfs (pn_tree h) = range 0 (2^(S h) - 1).\nProof.\n  unfold pn_tree. induction h as [| h' IH].\n  { unfold flat_htree_bfs. reflexivity. }\n  rewrite flat_pn_tree_Sh, IH. rewrite range_app; [|lia].\n  remember (S h') as h eqn:eq_h. rewrite Nat.pow_succ_r'.\n  f_equal. lia.\nQed.\n\n(* Exercise 6.48 * Define inductively the type [binary_word]\n   used in section 4.1.1.2 and define recursively\n   the function [binary_word_concat]. *)\nInductive binary_word : nat -> Set\n  := BW_empty : binary_word 0\n   | BW_cons : forall n : nat, bool -> binary_word n -> binary_word (S n).\n\nArguments BW_cons {n} _ _.\n\nFixpoint binary_word_concat {n1 n2 : nat}\n         (w1 : binary_word n1) (w2 : binary_word n2)\n  : binary_word (n1 + n2)\n  := match w1 in binary_word n return binary_word (n + n2) with\n     | BW_empty => w2\n     | BW_cons b w1' => BW_cons b (binary_word_concat w1' w2)\n     end.\n\nFixpoint bin_list_to_word (bs : list bool) : binary_word (length bs)\n  := match bs as x return binary_word (length x) with\n     | nil => BW_empty\n     | cons b bs' => BW_cons b (bin_list_to_word bs')\n     end.\n\nExample binary_word_concat_ex\n  : (binary_word_concat (bin_list_to_word [true; false; true])\n                        (bin_list_to_word [false; false]))\n    = (bin_list_to_word [true; false; true; false; false]).\nProof. reflexivity. Qed.\n\n(* Exercise 6.49 ** Define the function [binary_word_or]\n   that computes the bit-wise \"or\" operation of two words\n   of the same length (like the \"|\" operator in the C language). *)\n\nDefinition convert_bw_len (n1 n2 : nat) (H : S n2 = S n1)\n           (xs : binary_word n1) : binary_word n2.\napply eq_add_S in H. rewrite H. exact xs.\nDefined.\n\nPrint convert_bw_len.\n(* convert_bw_len =\n   fun (n1 n2 : nat) (H : S n2 = S n1) (xs : binary_word n1)\n   => let H0 : n2 = n1 := eq_add_S n2 n1 H\n      in eq_rec_r (fun n3 : nat => binary_word n3) xs H0\n   : forall n1 n2 : nat, S n2 = S n1 -> binary_word n1 -> binary_word n2\n *)\n\nFixpoint binary_word_or {n : nat} (xs ys : binary_word n) : binary_word n\n  := match xs in binary_word m1 return binary_word m1 -> binary_word m1 with\n     | BW_empty => fun _ => BW_empty\n     | @BW_cons n1 x xs'\n       => fun ys : binary_word (S n1)\n         => match ys in binary_word m2 return m2 = S n1 -> binary_word m2 with\n           | BW_empty => fun _ => BW_empty\n           | @BW_cons n2 y ys'\n             => fun H => BW_cons (x || y)\n                             (binary_word_or\n                                (convert_bw_len n1 n2 H xs') ys')\n           end (eq_refl (S n1))\n     end ys.\n\nTheorem binary_word_or_idempotent (n : nat) (xs : binary_word n)\n  : binary_word_or xs xs = xs.\nProof.\n  induction xs as [| n' b xs' IH]; [reflexivity|].\n  simpl. unfold convert_bw_len. simpl.\n  replace (b || b) with b.\n  2:{ destruct b; reflexivity. }\n  f_equal.\n  replace (eq_rec_r (fun n2 : nat => binary_word n2) xs' eq_refl) with xs'.\n  2:{ unfold eq_rec_r. reflexivity. }\n  apply IH.\nQed.\n\n(* Do the same exercises (last two), but considering vectors *)\nRequire Import Vector.\nDefinition bword := t bool.\nDefinition bw_concat := @append bool.\n\nFixpoint binary_word_to_bword {n : nat} (w : binary_word n)\n         {struct w} : bword n\n  := match w with\n     | BW_empty => nil bool\n     | @BW_cons n' b w' => cons bool b n' (binary_word_to_bword w')\n     end.\n\nFixpoint bword_to_binary_word {n : nat} (w : bword n)\n         {struct w} : binary_word n\n  := match w with\n     | nil _ => BW_empty\n     | cons _ b n' w' => @BW_cons n' b (bword_to_binary_word w')\n     end.\n\nTheorem binary_word_to_bword_inv (n : nat) (w : binary_word n)\n  : bword_to_binary_word (binary_word_to_bword w) = w.\nProof.\n  induction w as [| n' b w' IH]; [reflexivity|].\n  simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem bword_to_binary_word_inv (n : nat) (w : bword n)\n  : binary_word_to_bword (bword_to_binary_word w) = w.\nProof.\n  induction w as [| b n' w' IH]; [reflexivity|].\n  simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem bw_concat_correct (n1 n2 : nat) (w1 : bword n1) (w2 : bword n2)\n  : bw_concat n1 n2 w1 w2\n    = binary_word_to_bword\n        (binary_word_concat (bword_to_binary_word w1)\n                            (bword_to_binary_word w2)).\nProof.\n  induction w1 as [| b n1' w1' IH].\n  - simpl. rewrite bword_to_binary_word_inv. now unfold bw_concat.\n  - simpl. rewrite <- IH. unfold bw_concat. reflexivity.\nQed.\n\nDefinition bw_or {n : nat} (w1 w2 : bword n) : bword n\n  := map2 orb w1 w2.\n\nTheorem bw_or_correct {n : nat} (w1 w2 : bword n)\n  : bw_or w1 w2\n    = binary_word_to_bword\n        (binary_word_or (bword_to_binary_word w1)\n                        (bword_to_binary_word w2)).\nProof.\n  unfold bword in *.\n  generalize dependent w2.\n  generalize dependent w1.\n  generalize dependent n.\n  apply rect2; [reflexivity|].\n  intros n' w1' w2' IH x1 x2. simpl.\n  unfold convert_bw_len. simpl.\n  unfold eq_rec_r. simpl.\n  rewrite <- IH. reflexivity.\nQed.\n\nTheorem bw_or_idempotent (n : nat) (xs : bword n) : bw_or xs xs = xs.\nProof.\n  rewrite bw_or_correct, binary_word_or_idempotent.\n  now rewrite bword_to_binary_word_inv.\nQed.\n\n(* See also Consider the following definition,\n   very similar to Standard Library's definition: *)\nSection Vector_definitions.\n\n  Variable X : Type.\n\n  Inductive vector : nat -> Type\n    := vnil : vector 0\n     | vcons (x : X) (n : nat) (v : vector n) : vector (S n).\n\n  (* Define the functions that return respectively\n     the head and the tail of a non-empty vector,\n     as direct applications of the recursor vector_rect> *)\n\n  Definition vhd {n : nat} (v : vector (S n)) : X\n    := match v in vector m\n             return (match m with O => unit | S _ => X end)\n       with\n       | vnil => tt\n       | vcons x n' v' => x\n       end.\n\n  Definition vtl {n : nat} (v : vector (S n)) : vector n\n    := match v in vector m\n             return (match m with O => unit | S m' => vector m' end)\n       with\n       | vnil => tt\n       | vcons x n' v' => v'\n       end.\n\n  Definition v_Id (n : nat) : vector n -> vector n\n    := match n with\n       | 0 => fun v => vnil\n       | S p => fun v => vcons (vhd v) p (vtl v)\n       end.\n\n  Compute fun v : vector 0 => v_Id 0 v.\n  (*   = fun _ : vector 0 => vnil : vector 0 -> vector 0 *)\n\n  Lemma v_Id_eq (n : nat) (v : vector n) : v = v_Id n v.\n  Proof using.\n    pattern n, v. apply vector_rect.\n    - reflexivity.\n    - intros. reflexivity.\n  Qed.\n\n  Lemma vector0 (v : vector 0) : v = vnil.\n  Proof using.\n    change vnil with (v_Id 0 v).\n    apply v_Id_eq.\n  Qed.\n\n  Lemma vector_S (n : nat) (v : vector (S n)) : v = vcons (vhd v) n (vtl v).\n  Proof using.\n    change (vcons (vhd v) n (vtl v)) with (v_Id (S n) v).\n    apply v_Id_eq.\n  Qed.\nEnd Vector_definitions.\n\nArguments vnil {X}.\nArguments vcons {X}.\nArguments vhd {X} {n}.\nArguments vtl {X} {n}.\n\nExample vhd_ex : vhd (vcons 42 0 vnil) = 42.\nProof. reflexivity. Qed.\n\nExample vtl_ex : vtl (vcons 42 1 (vcons 22 0 vnil)) = vcons 22 0 vnil.\nProof. reflexivity. Qed.\n\n(* Exercise 6.50 ** Define a function with a dependent type\n   that returns [true] for natural numbers of the form [4*n + 1],\n   [false] for numbers of the form [4*n + 3],\n   and [n] for numbers of the form [2*n]. *)\n\nFixpoint dep_fn_type (n : nat) : Set\n  := match n with\n     | 0 => nat\n     | 1 => bool\n     | (S (S n')) => dep_fn_type n'\n     end.\n\nFixpoint dep_fn (n : nat) : dep_fn_type n\n  := match n with\n     | 0 => 0\n     | 1 => true\n     | 2 => 1\n     | 3 => false\n     | S (S (S (S n'))) => dep_fn n'\n     end.\n\nExample dep_fn_ex6 : dep_fn 6 = 1.\nProof. reflexivity. Qed.\n\nExample dep_fn_ex7 : dep_fn 7 = false.\nProof. reflexivity. Qed.\n\nExample dep_fn_ex9 : dep_fn 9 = true.\nProof. reflexivity. Qed.\n", "meta": {"author": "anton0xf", "repo": "coq-art", "sha": "eed9782f0b62b4aaa9b33c2270931230ebb09ae6", "save_path": "github-repos/coq/anton0xf-coq-art", "path": "github-repos/coq/anton0xf-coq-art/coq-art-eed9782f0b62b4aaa9b33c2270931230ebb09ae6/ch06/6.5_polimorphic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8085007522450346}}
{"text": "Require Import Relation.\nRequire Import Logic_utils.\n\nDefinition partial_ordering {A} (R : Relation A A) : Prop :=\nreflexive R /\\ antisymmetric R /\\ transitive R.\n\nDefinition strict_ordering {A} (R : Relation A A) : Prop :=\nasymmetric R /\\ transitive R.\n\nDefinition partial_to_strict {A} (R : Relation A A) : Relation A A :=\nfun p => match p with\n  | (a, b) => R(a, b) /\\ a <> b\nend.\n\nDefinition strict_to_partial {A} (S: Relation A A) : Relation A A :=\nfun p => match p with\n  | (a, b) => S(a, b) \\/ a = b\nend.\n\nTheorem partial_to_strict_returns_strict : \nforall (A: Type)(R: Relation A A), partial_ordering R -> strict_ordering (partial_to_strict R).\nProof.\nintros. set (S:=partial_to_strict R).\ndestruct H as [refl anti]. destruct anti as [anti trans].\napply conj.\n- intros a b Sab. intros Sba.\n  apply Sba in anti. contradiction. apply Sba. apply Sab.\n- intros a b c Sab Sbc. apply conj.\n  + apply trans with (b:=b). apply Sab. apply Sbc.\n  + intros ac. rewrite <- ac in Sbc.\n    apply Sab in anti. contradiction. apply Sab. apply Sbc.\nQed.\n\nTheorem strict_to_partial_returns_partial :\nforall (A:Type)(S: Relation A A), strict_ordering S -> partial_ordering (strict_to_partial S).\nProof.\nintros. set (R:=strict_to_partial S).\ndestruct H as [asymm trans].\napply conj.\n- unfold reflexive. intros. right. reflexivity.\n- apply conj.\n  + unfold antisymmetric. intros a b Rab Rba.\n    destruct Rab as [Sab|eq1]. destruct Rba as [Sba|eq2].\n    * apply asymm in Sba. contradiction.\n    * rewrite eq2. reflexivity.\n    * rewrite eq1. reflexivity.\n  + unfold transitive. intros a b c Rab Rbc.\n    destruct Rab as [Sab|eq1]. destruct Rbc as [Sbc|eq2].\n    * left. apply trans with (b:=b). apply Sab. apply Sbc.\n    * left. rewrite <- eq2. apply Sab.\n    * rewrite eq1. apply Rbc.\nQed.\n\nDefinition total_partial_ordering {A} (R : Relation A A) : Prop :=\n  partial_ordering R /\\ forall (a b : A), R(a, b) \\/ R(b, a).\n\nDefinition total_strict_ordering {A} (S : Relation A A) : Prop :=\n  strict_ordering S /\\ forall (a b : A), S(a, b) \\/ S(b, a) \\/ a = b.\n\nTheorem partial_to_strict_preserves_totality : \nforall (A: Type)(R : Relation A A), \ntotal_partial_ordering R -> total_strict_ordering (partial_to_strict R).\nProof.\nintros. set (S:=partial_to_strict R).\ndestruct H as [partialR totalR]. \napply conj. \n- apply partial_to_strict_returns_strict. apply partialR.\n- intros. \n  assert (eq : (a=b) \\/ (a <> b)).\n  { apply law_of_excluded_middle. }\n  destruct (totalR a b) as [Rab|Rba].\n  + destruct eq as [eq|neq].\n    * right. right. apply eq.\n    * left. apply conj. apply Rab. apply neq.\n  + destruct eq as [eq|neq].\n    * right. right. apply eq.\n    * right. left. apply conj. apply Rba. apply (neq_comm A). apply neq.\nQed.\n\nTheorem struct_to_partial_preserves_totality :\nforall (A: Type)(S : Relation A A),\ntotal_strict_ordering S -> total_partial_ordering (strict_to_partial S).\nProof.\nintros. set (R:=strict_to_partial S).\ndestruct H as [strictS totalS].\napply conj.\n- apply strict_to_partial_returns_partial. apply strictS.\n- intros. destruct (totalS a b) as [Sab|Rba].\n  + left. left. apply Sab.\n  + destruct Rba as [Sba|eq].\n    * right. left. apply Sba. \n    * left. right. apply eq.\nQed.\n\nTheorem strict_to_partial_to_strict_identity :\nforall (A: Type)(S : Relation A A),\nstrict_ordering S -> partial_to_strict (strict_to_partial S) = S.\nProof.\nintros. set (R:= strict_to_partial S). set (S':= partial_to_strict R).\napply Relation_eq. intros.\nunfold iff. apply conj.\n- intros S'ab. apply reduce_or_P_and_notP in S'ab. apply S'ab.\n- intros Sab. apply conj.\n  + left. apply Sab.\n  + destruct H as [asymm trans]. intros eq. destruct (asymm a b).\n    * apply Sab.\n    * rewrite eq. rewrite eq in Sab. apply Sab.\nQed.\n\nTheorem partial_to_strict_to_partial_identity :\nforall (A: Type)(R : Relation A A),\npartial_ordering R -> strict_to_partial (partial_to_strict R) = R.\nProof.\nintros. set (S:= partial_to_strict R). set (R':= strict_to_partial S).\napply Relation_eq. intros.\nunfold iff. apply conj.\n- intros R'ab. inversion R'ab.\n  + apply H0.\n  + destruct H as [refl _]. rewrite H0. apply refl.\n- intros Rab. \n  assert (eq: (a=b) \\/ (a<>b)).\n  { apply law_of_excluded_middle. }\n  destruct eq as [eq|neq].\n  + right. apply eq.\n  + left. split. apply Rab. apply neq.\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/Ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.8084703583479305}}
{"text": "Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat), \n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl.\nAbort.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\nTheorem snd_fst_is_swap : forall (p : natprod), \n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p.\n  destruct p as [n m]. simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p.\n  destruct p as [n m]. simpl. reflexivity. Qed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. 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.\n\n\n\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:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\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:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n match l1 with\n | nil => l2\n | h :: t => match l2 with\n             | nil => h :: t\n             | h2 :: t2 => h :: h2 :: alternate t t2\n             end\n end.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n\nDefinition bag := natlist.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n              | O => false\n              | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem beq_nat_same_eq : forall n : nat,\n  beq_nat n n = true.\nProof. \n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match beq_nat h v with\n              | true => 1 + count v t\n              | false => count v t\n              end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag := app.\n\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  match s with\n  | nil => [v]\n  | ht => v :: ht\n  end.\n\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\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  | nil => nil\n  | h :: t => match beq_nat h v with\n              | false => h :: remove_one v t\n              | true => t\n              end\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h :: t => match member h s2 with\n              | false => false\n              | true => subset t (remove_one h s2)\n              end\n  end.\n\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem add_increase_len : forall n : nat, forall b : bag,\n  length (add n b) = S (length b).\nProof.\n  intros n b.\n  induction b as [| b' IHl'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem add_bag_count_succ: \n  forall n : nat, forall b : bag,\n  count n (add n b) = S (count n b).\nProof.\n  intros n b.\n  induction b as [| b' IHn'].\n  - simpl. rewrite -> beq_nat_same_eq. reflexivity.\n  - simpl. rewrite -> beq_nat_same_eq. reflexivity.\nQed.\n\nTheorem add_bag_count_same_if_eq: \n  forall n m l: nat, forall b : bag,\n  n = m -> (count l (add n b) = count l (add m b)).\nProof.\n  intros n m l b IHn. rewrite <- IHn. reflexivity. Qed.\n\n\nTheorem app_assoc: forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl1'. reflexivity. Qed.\n\nFixpoint rev (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\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  - reflexivity.\n  - simpl. rewrite <- IHl'.\nAbort.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> app_length. rewrite -> plus_comm.\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nSearch natlist.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| l' c IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nSearch natlist.\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 [| l1' c IHn'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite <- app_assoc. reflexivity.\nQed.\n\nSearch rev.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| l' c IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. simpl. rewrite -> IHn'. 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 l1 l2 l3 l4.\n  rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\nQed.\n\nSearch \"++\".\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match h with\n              | 0 => nonzeros t\n              | _ => h :: nonzeros t\n              end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n\nProof. reflexivity. Qed.\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  simpl. induction l1 as [| l1' c IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. destruct l1'.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | nil => match l2 with\n           | nil => true\n           | h :: t => false\n           end\n  | h :: t => match l2 with\n              | h' :: t' => match beq_nat h h' with\n                            | true => beq_natlist t t'\n                            | false => false\n                            end\n              | nil => false\n              end\n  end.\n\nSearch beq_nat.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof. \n  intros l. induction l as [| l' c IHn'].\n  - reflexivity.\n  - simpl. rewrite -> beq_nat_same_eq. rewrite -> IHn'. 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\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. simpl. reflexivity. Qed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. induction s as [|s' c IHn'].\n  - reflexivity.\n  - destruct s'.\n    + simpl. rewrite -> ble_n_Sn. reflexivity.\n    + simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nSearch sum.\n\nTheorem bag_count_sum : forall (s1 s2: bag) (n :nat),\n  count n s1 = count n (sum s1 []).\nProof.\n  intros s1 s2 n.\n  unfold sum. rewrite app_nil_r. reflexivity.\nQed.\n\nSearch rev.\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 IHn. \n  rewrite <- rev_involutive. rewrite <- IHn. rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. 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\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.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default. destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n\nEnd NatList.\n\nModule PartialMap.\nExport NatList.\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nSearch beq_nat.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intros x. destruct x.\n  - simpl. rewrite -> beq_nat_same_eq. reflexivity.\nQed.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d : partial_map) (x : id) (value : nat)\n  : partial_map :=\nrecord 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 : forall (d : partial_map) (x : id) (v : nat),\n  find x (update d x v) = Some v.\nProof.\n  intros. simpl. rewrite <- beq_id_refl. reflexivity.\nQed.\n\nTheorem update_neq : forall (d : partial_map) (x y : id) (o : nat),\n  beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros. simpl. rewrite -> H. reflexivity.\nQed.\n\nEnd PartialMap.\n", "meta": {"author": "yanhick", "repo": "coq-exercises", "sha": "75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d", "save_path": "github-repos/coq/yanhick-coq-exercises", "path": "github-repos/coq/yanhick-coq-exercises/coq-exercises-75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d/LF/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8991213725394588, "lm_q1q2_score": 0.808419251671411}}
{"text": "(** definindo tipos indutivos *)\n\nInductive True1 : Prop :=\n| tt1 : True1.\n\nInductive False1 : Prop := .\n\nInductive conj1 (A B : Prop) : Prop :=\n| and1 : A -> B -> conj1 A B.\n\n(** exerc\u00edcio 13 \n    Defina o conectivo de disjun\u00e7\u00e3o *)\n\nInductive disj1 : Prop :=.\n\n(** booleanos *)\n\nInductive bool1 : Set :=\n| true1 : bool1\n| false1 : bool1.\n\nRequire Import Bool.\n\nDefinition not_bool (b : bool) : bool :=\n  match b with\n  | false => true\n  | true  => false\n  end.\n\nDefinition and_bool (b1 b2 : bool) : bool :=\n  match b1 , b2 with\n  | true  , b2 => b2\n  | false , b2 => false\n  end.\n\n(** exerc\u00edcio 14: Defina fun\u00e7\u00f5es para os conectivos de disjun\u00e7\u00e3o, \"ou\", e \n    exclusive-or, \"xor\" *)\n\nEval compute in not_bool false.\n\nLemma not_bool_inv : forall b : bool, not_bool (not_bool b) = b.\nProof.\n  intro b.\n  destruct b.\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    reflexivity.\nQed.\n\n(** exerc\u00edcio 15 *)\n\nLemma and_true_left : forall b, and_bool true b = b.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 16 *)\n\nLemma and_false_left : forall b, and_bool false b = false.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 17 *)\n\nLemma and_com : forall b b', and_bool b b' = and_bool b' b.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 18 *)\n\nLemma and_assocc : forall b1 b2 b3, and_bool b1 (and_bool b2 b3) = and_bool (and_bool b1 b2) b3.\nProof.\nAdmitted.\n\n(** N\u00fameros naturais *)\n\nLemma zero_identity_add_left : forall n, 0 + n = n.\nProof.\n    intro n.\n    simpl.\n    reflexivity.\nQed.\n\nLemma zero_identity_add_right : forall n, n + 0 = n.\nProof.\n   intro n.\n   simpl.\n   Restart.\n   intro n.\n   destruct n.\n   +\n     simpl.\n     reflexivity.\n   +\n     simpl.\n     (** reflexivity. *)\n     Restart.\n   intro n.\n   induction n as [ | n' IHn'].\n   +\n     simpl.\n     reflexivity.\n   +\n     simpl.\n     rewrite IHn'.\n     reflexivity.\nQed.     \n\nLemma add_inc : forall m n, S (m + n) = m + S n.\nProof.\n  intros m n.\n  induction m as [ | m' IHm'].\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    rewrite IHm'.\n    reflexivity.\nQed.\n\nLemma add_commut : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  +\n    simpl.\n    symmetry.\n    apply zero_identity_add_right.\n  +\n    simpl.\n    rewrite IHn'.\n    apply add_inc.\nQed.\n\n(** exerc\u00edcio 19 *)\n\nLemma add_associative : forall n m p, n + (m + p) = (n + m) + p.\nProof.\nAdmitted.\n\n(**\nExerc\u00edcio 20\n\nA seguir apresentamos uma defini\u00e7\u00e3o da opera\u00e7\u00e3o de multiplica\u00e7\u00e3o sobre n\u00fameros \nnaturais. \n\n\nA partir desta defini\u00e7\u00e3o, enuncie e prove os seguintes fatos sobre a multiplica\u00e7\u00e3o:\n        \n- O n\u00famero 1 \u00e9 identidade \u00e0 esquerda da multiplica\u00e7\u00e3o.\n- O n\u00famero 1 \u00e9 identidade \u00e0 direita da multiplica\u00e7\u00e3o.\n- A opera\u00e7\u00e3o de multiplica\u00e7\u00e3o \u00e9 associativa.\n- A opera\u00e7\u00e3o de multiplica\u00e7\u00e3o \u00e9 comutativa.\n **)\n\nFixpoint times (n m : nat) : nat :=\n  match n with\n  | 0    => 0\n  | S n' => m + (times n' m)\n  end.\n\n\n(**\nExerc\u00edcio 21\n\nDefina a fun\u00e7\u00e3o `even_bool : nat -> bool` que, a partir de um n\u00famero natural, retorne\nverdadeiro se este \u00e9 par.\n **)\n\nDefinition even_bool (n : nat) : bool.\nAdmitted.\n\n(** \nExerc\u00edcio 22 \n **)\n\nLemma even_add_n : forall n, even_bool (n + n) = true.\nProof.\nAdmitted.\n\n(** \nExerc\u00edcio 23\nDefina a fun\u00e7\u00e3o `odd_bool : nat -> bool` que, a partir de um n\u00famero natural, \nretorne verdadeirso se este \u00e9 \u00edmpar\n **)\n\nDefinition odd_bool (n : nat) : bool.\nAdmitted.\n\n\n(** Exerc\u00edcio 24 *)\n\nLemma odd_add_n_Sn : forall n, odd_bool (n + S n) = true.\nProof.\nAdmitted.\n\n(** Exerc\u00edcio 25 *)\n\nLemma even_SS : forall n, even_bool n = even_bool (S (S n)).\nProof.\nAdmitted.\n\n\n(** Exerc\u00edcio 26 *)\n\nLemma odd_SS : forall n, odd_bool n = odd_bool (S (S n)).\nProof.\nAdmitted.\n\n(** Exerc\u00edcio 27 *)\n\nLemma even_bool_S : forall n, even_bool n = not_bool (even_bool (S n)).\nProof.\nAdmitted.\n\n(** Listas *)\n\nRequire Import List.\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 list1 : list nat := 1 :: 2 :: 3 :: nil.\nDefinition list2 : list nat := [1 ; 2 ; 3].\n\nFixpoint repeat {A : Type}(n : nat)(x : A) : list A :=\n  match n with\n  | O => []\n  | S n' => x :: repeat n' x\n  end.\n\nFixpoint length {A : Type}(xs : list A) : nat :=\n  match xs with\n  | []        => O\n  | (x :: xs) => S (length xs)\n  end.\n\nLemma length_app\n  : forall {A : Type}(xs ys : list A), length (xs ++ ys) = length xs + length ys.\nProof.\n  intros A xs ys.\n  induction xs as [| z zs IHzs].\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    rewrite IHzs.\n    reflexivity.\nQed.\n\nFixpoint map {A B : Type}(f : A -> B)(xs : list A) : list B :=\n  match xs with\n  | []      => []\n  | y :: ys =>  f y :: map f ys\n  end.\n\nLemma map_length {A B : Type}{f : A -> B} : forall xs, length (map f xs) = length xs.\nProof.\n  intros xs.\n  induction xs as [ | y ys IHys].\n  +\n    reflexivity.\n  +\n    simpl.\n    rewrite IHys.\n    reflexivity.\nQed.\n\nFixpoint reverse {A : Type}(xs : list A) : list A :=\n  match xs with\n  | [] => []\n  | y :: ys => reverse ys ++ [ y ]\n  end.\n\nLemma reverse_length {A : Type}: forall (xs : list A), length xs = length (reverse xs).\nProof.\n  intros xs.\n  induction xs.\n  +\n    reflexivity.\n  +\n    simpl.\n    rewrite length_app, add_commut.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\n(** exerc\u00edcio 28 *)\n\nLemma repeat_length {A : Type} : forall (n : nat)(x : A), length (repeat n x) = n.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 29 *)\n\nLemma app_nil_right {A : Type} : forall (xs : list A), xs ++ [] = xs.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 30 *)\n\nLemma app_assoc {A : Type} : forall (xs ys zs : list A), xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 31 *)\n\nLemma map_app {A B : Type}{f : A -> B}\n  : forall xs ys, map f (xs ++ ys) = map f xs ++ map f ys.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 32 *)\n\nLemma reverse_app {A : Type}\n  : forall (xs ys : list A), reverse (xs ++ ys) = reverse ys ++ reverse xs.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 33 *)\n\nLemma reverse_inv {A : Type}\n  : forall (xs : list A), reverse (reverse xs) = xs.\nProof.\nAdmitted.\n\n(** Predicados indutivos *)\n\n\nInductive even : nat -> Prop :=\n| ev_zero : even 0\n| ev_ss   : forall n, even n -> even (S (S n)).\n\nExample eight_is_even : even 8.\nProof.\n  apply ev_ss.\n  apply ev_ss.\n  apply ev_ss.\n  apply ev_ss.\n  apply ev_zero.\nQed.\n\nExample teste : even 1 -> 1 = 2.\nProof.\n  intro H.\n  inversion H.\nQed.\nDefinition double (n : nat) := 2 * n.\n\n(** exerc\u00edcio 34 *)\n\nLemma double_even : forall n, even (double n).\nProof.\nAdmitted.\n\n(** Princ\u00edpio de invers\u00e3o *)\n\nLemma one_not_even : ~ even 1.\nProof.\n  intros Hone.\n  inversion Hone.\nQed.\n\nLemma even_2_inv : forall n, even (2 + n) -> even n.\nProof.\n  intros n H.\n  inversion H.\n  assumption.\nQed.\n\n(**\n   Inductive le (n : nat) : nat -> Prop :=\n   | le_n : n <= n \n   | le_S : forall m : nat, n <= m -> n <= S m\n *)\n\nExample teste_le : 3 <= 6.\nProof.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\nExample teste_le_false : 2 <= 1 -> 1 + 1 = 10.\nProof.\n  intros H.\n  inversion H.\n  inversion H1.\nQed.\n\nLemma le_0_n : forall n, 0 <= n.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  +\n    apply le_n.\n  +\n    apply le_S.\n    assumption.\nQed.\n\n(** exerc\u00edcio 35 *)\n\nLemma le_refl : forall n, n <= n.\nProof.\nAdmitted.\n\nLemma le_cong_S : forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m Hnm.\n  induction Hnm.\n  +\n    apply le_refl.\n  +\n    apply le_S.\n    assumption.\nQed.\n\nLemma le_S_cong : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m.\n  induction m as [| m' IHm'].\n  +\n    intros Hnm.\n    inversion Hnm.\n    -\n      apply le_refl.\n    -\n      inversion H0.\n   +\n     intros Hnm.\n     inversion Hnm.\n     -\n       subst.\n       apply le_refl.\n     -\n       subst.\n       apply le_S.\n       apply IHm'.\n       assumption.\nQed.\n\n(** exerc\u00edcio 36 *)\n\nLemma le_trans : forall n m p, n <= m -> m <= p -> n <= p.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 37 *)\n\nLtac inverts H := inversion H ; subst ; clear H.\n\nLemma le_antisym : forall n m, n <= m -> m <= n -> n = m.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 38 \n\nConsidere a tarefa de projetar um predicado indutivo\n`Sorted : list nat -> Prop` que constitui uma prova\nde que uma certa lista de n\u00fameros naturais est\u00e1 ordenada. \nSua defini\u00e7\u00e3o deve utilizar o predicado `<=` e conseguir\ndemonstrar os casos de teste abaixo.\n\n*)\n\nInductive Sorted : list nat -> Prop := .\n\nExample test_sorted1 : Sorted [].\nProof.\nAdmitted.\n\nExample test_sorted2 : Sorted [10].\nProof.\nAdmitted .\n\nExample test_sorted3 : Sorted [1 ; 3 ; 5 ].\nProof.\nAdmitted.\n\nReserved Notation \"x '<<=' y\" (at level 40, no associativity).\n\nInductive le_alt : nat -> nat -> Prop :=\n| le_alt_zero : forall n, 0 <<= n\n| le_alt_succ : forall n m, n <<= m -> S n <<= S m\nwhere \"x '<<=' y\" := (le_alt x y).\n\n(** exerc\u00edcio 39 *)\n\nLemma le_alt_refl : forall n, n <<= n.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 40 *)\n\nLemma le_alt_trans\n  : forall n m p, n <<= m -> m <<= p -> n <<= p.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 41 *)\n\nLemma le_alt_antisym : forall n m, n <<= m -> m <<= n -> n = m.\nProof.\nAdmitted.\n\n(** exerc\u00edcio 42 *)\n\nLemma le_alt_equiv_le : forall n m, n <<= m <-> n <= m.\nProof.\nAdmitted.\n", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/inductivetypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.9005297794439688, "lm_q1q2_score": 0.8084013335503206}}
{"text": "From Coq Require Import\n  Lia\n  List\n  ZArith.\nFrom FunProofs.Lib Require Import\n  Arith\n  Function\n  List\n  Tactics.\nFrom FunProofs.Lib Require Export\n  AltMap.\n\n#[local] Open Scope Z.\n\nSection Maximum.\n  Definition maximum min (xs : list Z) : Z :=\n    fold_right Z.max min xs.\n\n  Definition maximum0 (xs : list Z) : Z :=\n    maximum (hd 0 xs) xs.\n\n  Lemma maximum_case min xs (m := maximum min xs) :\n    Forall (fun x => x <= m) xs /\\\n    (In m xs \\/ (m = min /\\ Forall (fun x => x < min) xs)).\n  Proof.\n    induction xs as [| x xs]; cbn in *; auto;\n      destruct IHxs as (Hmax & Hin); fold (maximum min xs); split.\n    - constructor; auto using Z.le_max_l.\n      rewrite Forall_forall in *; intros * Hin'; apply Hmax in Hin'; lia.\n    - rewrite Z.max_comm; pattern (Z.max (maximum min xs) x);\n        apply Zmax_case_strong_lt; intros; intuition auto.\n      right; split; auto; constructor; auto; lia.\n  Qed.\n\n  Lemma maximum0_case xs (m := maximum0 xs) :\n    xs <> [] -> Forall (fun x => x <= m) xs /\\ In m xs.\n  Proof.\n    intros; pose proof (maximum_case (hd 0 xs) xs).\n    repeat intuition auto.\n    destruct xs as [| x xs]; cbn in *; [easy |].\n    prename (fun _ => _ < _) into Hfalse; inv Hfalse; lia.\n  Qed.\n\n  Lemma maximum_lower_bound min xs : min <= maximum min xs.\n  Proof. unfold maximum; induction xs as [| x xs]; cbn; intros; lia. Qed.\n\n  Lemma maximum_le_mono min min' xs : min <= min' -> maximum min xs <= maximum min' xs.\n  Proof. unfold maximum; induction xs as [| x xs]; cbn; intros; lia. Qed.\n\n  Lemma maximum_cons_le min xs x : maximum min xs <= maximum min (x :: xs).\n  Proof. unfold maximum; intros; cbn; lia. Qed.\n\n  Lemma maximum_in min xs (m := maximum min xs) : min < maximum min xs -> In m xs.\n  Proof.\n    induction xs as [| x xs]; cbn; intros; [lia |].\n    fold (maximum min xs) in *.\n    destruct (Z.lt_ge_cases x (maximum min xs));\n      rewrite ?Z.max_l in * by lia; rewrite ?Z.max_r in * by lia; auto.\n  Qed.\n\n  Lemma maximum_weaken_in min min' xs :\n    min <= min' -> In (maximum min' xs) xs -> maximum min xs = maximum min' xs.\n  Proof.\n    induction xs as [| x xs]; cbn; intros Hlt Hin; [easy |].\n    pose proof (maximum_le_mono min min' xs); unfold maximum in *.\n    destruct Hin as [Heq | Hin]; try lia.\n    pattern (Z.max x (fold_right Z.max min' xs)); apply Z.max_case_strong; intros;\n      try lia.\n    rewrite Z.max_r in Hin by auto; apply IHxs in Hin; auto; lia.\n  Qed.\n\n  Corollary maximum_weaken_lt min min' xs :\n    min <= min' < maximum min' xs -> maximum min xs = maximum min' xs.\n  Proof. intros; apply maximum_weaken_in, maximum_in; lia. Qed.\n\n  Lemma maximum0_unfold x xs : 0 <= x -> maximum0 (x :: xs) = Z.max x (maximum0 xs).\n  Proof.\n    intros; destruct xs as [| x' xs]; cbn; [lia |].\n    fold (maximum x xs); fold (maximum x' xs).\n    destruct (Z.lt_ge_cases x x').\n    - destruct (maximum_case x' xs) as (? & [? | (? & Hmax)]).\n      + rewrite (maximum_weaken_in x x' xs); auto; lia.\n      + destruct (maximum_case x xs) as (? & [Hin | (? & ?)]); try lia.\n        rewrite Forall_forall in Hmax; apply Hmax in Hin; lia.\n    - destruct (maximum_case x xs) as (? & [? | (? & Hmax)]).\n      + rewrite (maximum_weaken_in x' x xs); auto; lia.\n      + destruct (maximum_case x' xs) as (? & [Hin | (? & ?)]); try lia.\n        rewrite Forall_forall in Hmax; apply Hmax in Hin; lia.\n  Qed.\nEnd Maximum.\n\nSection Minimum.\n  Definition minimum max (xs : list Z) : Z :=\n    fold_right Z.min max xs.\n\n  Definition minimum0 (xs : list Z) : Z :=\n    minimum (hd 0 xs) xs.\n\n  Lemma minimum_case max xs (m := minimum max xs) :\n    Forall (fun x => m <= x) xs /\\\n    (In m xs \\/ (m = max /\\ Forall (fun x => max < x) xs)).\n  Proof.\n    induction xs as [| x xs]; cbn in *; auto;\n      destruct IHxs as (Hmin & Hin); fold (minimum max xs); split.\n    - constructor; auto using Z.le_min_l.\n      rewrite Forall_forall in *; intros * Hin'; apply Hmin in Hin'; lia.\n    - pattern (Z.min x (minimum max xs)); apply Zmin_case_strong_lt; intros;\n        intuition auto.\n      right; split; auto; constructor; auto; lia.\n  Qed.\n\n  Lemma minimum0_case xs (m := minimum0 xs) :\n    xs <> [] -> Forall (fun x => m <= x) xs /\\ In m xs.\n  Proof.\n    intros; pose proof (minimum_case (hd 0 xs) xs).\n    repeat intuition auto.\n    destruct xs as [| x xs]; cbn in *; [easy |].\n    prename (fun _ => _ < _) into Hfalse; inv Hfalse; lia.\n  Qed.\n\n  Lemma minimum_upper_bound max xs : minimum max xs <= max.\n  Proof. unfold minimum; induction xs as [| x xs]; cbn; intros; lia. Qed.\n\n  Lemma minimum_le_mono max max' xs : max <= max' -> minimum max xs <= minimum max' xs.\n  Proof. unfold minimum; induction xs as [| x xs]; cbn; intros; lia. Qed.\n\n  Lemma minimum_cons_le max xs x : minimum max (x :: xs) <= minimum max xs.\n  Proof. unfold minimum; intros; cbn; lia. Qed.\n\n  Lemma minimum_in max xs (m := minimum max xs) : minimum max xs < max -> In m xs.\n  Proof.\n    induction xs as [| x xs]; cbn; intros; [lia |].\n    fold (minimum max xs) in *.\n    destruct (Z.lt_ge_cases x (minimum max xs));\n      rewrite ?Z.min_l in * by lia; rewrite ?Z.min_r in * by lia; auto.\n  Qed.\n\n  Lemma minimum_weaken_in max max' xs :\n    max' <= max -> In (minimum max' xs) xs -> minimum max xs = minimum max' xs.\n  Proof.\n    induction xs as [| x xs]; cbn; intros Hlt Hin; [easy |].\n    pose proof (minimum_le_mono max' max xs); unfold minimum in *.\n    destruct Hin as [Heq | Hin]; try lia.\n    pattern (Z.min x (fold_right Z.min max' xs)); apply Z.min_case_strong; intros;\n      try lia.\n    rewrite Z.min_r in Hin by auto; apply IHxs in Hin; auto; lia.\n  Qed.\n\n  Corollary minimum_weaken_lt max max' xs :\n    minimum max' xs < max' <= max -> minimum max xs = minimum max' xs.\n  Proof. intros; apply minimum_weaken_in, minimum_in; lia. Qed.\nEnd Minimum.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Lib/Extrema.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8084006555937213}}
{"text": "(** Use some very basic facilities of mathcomp library *)\nFrom mathcomp Require Import ssreflect.\n\nModule My.\n(** We introduce these definitions inside a new module\n    to avoid name clashes with the standard library later *)\n\nInductive bool : Type :=\n| true\n| false.\n\nCheck true : bool.\nCheck true.\n\n(** Definitions (not part of Coq's type theory, by the way, it's\n    a meta-linguistic feature) *)\nDefinition idb := fun b : bool => b.\n\nCheck (fun b : bool => b).\nCheck idb.\n\n(** Pattern-matching *)\nDefinition negb (b : bool) :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nCompute idb true.\nCompute idb false.\n\nCompute negb true.\nCompute negb false.\n\nVariable c : bool.\n\nCompute idb c.\n\nCompute negb c.\n\nDefinition andb (b c : bool) : bool :=\n  match b with\n  | true => c\n  | false => false\n  end.\n\n(** Symbolic computations *)\nCompute andb c true.\nCompute andb c false.\nCompute andb false c.\n\n\n\n\n(** Peano numbers -- the first truly inductive type *)\nInductive nat : Type :=\n| S of nat\n| O.\nPrint nat.\n\nCheck O.\nCheck S.\nCheck (S O).\nCheck S (S O).\nCheck S (S (S O)).\n\n(** Incrementing function *)\nDefinition inc := S.\n(** [Definition inc (n : nat) := S n.] is the same definition,\n    only eta-expanded *)\n\n(**\neta-expansion is baked into Coq' notion of definitional equality, i.e\n(fun x => f x) and f are definitionally equal\nbut\nextensionally equal functions are not necessarily equal, i.e.\n(forall x, f x = g x -> f = g)\ndoes not have to hold.\n*)\nPrint inc.\n\nCompute inc (S (S O)).\n\n\nDefinition inc2 (n : nat) := S (S n).\nCompute inc2 (S (S O)).\n\n(** predecessor function *)\nDefinition pred (n : nat) : nat :=\n  match n with\n  | S n' => n'\n  | O => O   (* truncation! Coq's functions are total *)\n  end.\n\n(**\nSome options to go about implementing [pred] function:\n\n pred : nat -> nat  (* way to go *)\n pred : nat -> option nat\n pred : forall (n : nat), (n <> 0) -> nat\n\n*)\n\n(** Addition of natural numbers *)\n\n(** [{struct n}] means structural recursion on parameter [n].\n    Coq can infer the [struct] annotation in this case. *)\n\nFixpoint addn (n m : nat) {struct n} : nat :=\n  match n with\n  | S n' => S (addn n' m)\n  | O => m\n  end.\n\nCompute addn (S (S O)) (S (S O)).  (* 2 + 2 is 4 *)\n\n(** Alternative implementation by recursion on the second parameter *)\nFixpoint addn' (n m : nat) : nat :=\n  match m with\n  | S m' => S (addn' n m')\n  | O => n\n  end.\n\nPrint addn'.\n\nFixpoint muln (n m : nat) : nat :=\n  match n with\n  | S n' => addn m (muln n' m)\n  | O => O\n  end.\n\nCompute muln (S (S (S O))) (S (S O)).  (* 3 * 2 is 6 *)\nCompute muln (S (S O)) O.              (* 2 * 0 is 0 *)\n\nDefinition square (n : nat) : nat := muln n n.\n\nDefinition two := (S (S O)).\nDefinition apply2 (f : nat -> nat) (n : nat) :=\n  f (f n).\nEval hnf in (apply2 (apply2 square) two).\n(** Various reduction strategies:\n- Eval cbn in ...              call-by-name\n- Eval lazy in ...             call-by-need\n- Eval cbv in ...              call-by-value\n- Eval compute in ...          call-by-value (cbv's synonym)\n- Eval vm_compute in ...       call-by-value using a bytecode virtual machine\n                               [Compute] is synonym for [Eval vm_compute in]\n- Eval native_compute in ...   compile to OCaml and evaluate\n*)\n\nEnd My.\n\n(** After closing a module, the identifiers defined in it,\n    get prefixed with the module's name *)\nCheck My.apply2.\n\nFrom mathcomp Require Import ssrfun ssrbool ssrnat.\n\n(** Some interactive queries *)\nAbout nat.\nAbout S.\n\nLocate \".+1\".     (* Notation \"n .+1\" := (S n). *)\n\n\n(** Apply [n] times a function [f] on natural numbers to\n    an input [x] *)\nDefinition applyn (f : nat -> nat) :=\n  fix rec (n : nat) (x : nat) :=\n    if n is n'.+1 then rec n' (f x)\n    else x.\n\n(* a test *)\nCompute applyn S 5 42.\n\n(** An alternative implementation whose behavior is\n    different when we evaluate it symbolically *)\nDefinition applyn' :=\n  fix rec (f : nat -> nat) (n : nat) (x : nat) :=\n    if n is n'.+1 then rec f n' (f x)\n    else x.\n\n\nAxiom fun_ext :\n  forall (A B : Type) (f g : A -> B),\n    (forall x, f x = g x) -> f = g.\n\n(** A way of defining [applyn] using Coq's section mechanism *)\nSection Applyn.\n\nVariable f : nat -> nat.\n\nFixpoint applyn'' (n : nat) (x : nat) : nat :=\n  if n is n'.+1 then applyn'' n' (f x)\n  else x.\n\nVariable n : nat.\nCompute applyn'' (S n) 0.\n\nPrint applyn''.\n\nEnd Applyn.\n\nPrint applyn''.  (* compare the output to the one inside the above section *)\n\n(** A proposition which can never be constructed (in the empty context *)\nInductive False : Prop :=\n  .    (* no constructors! *)\n\nPrint False.\n\n(** Let's illustrate why \"in the empty context\" is important *)\nCheck (fun f : False => f (* here we construct a value of type\n                             [False], but the context is not empty,\n                             since the function parameter becomes\n                             part of context here *)\n      ).\n(** Since it's impossible to construct a value of an empty type,\n    it's impossible to call a function of type\n    False -> SomeType *)\n(** ... provided we are talking about empty contexts again: *)\nCheck (fun g : False =>\n         (fun f : False => f) g     (* call [fun f : False => f]\n                                       with [g] as the argument *)\n      ).\n\n(** This is why Coq does not allow non-terminating functions *)\nFail Fixpoint loop (n : nat) : False :=\n  loop n.\n(* loop : n -> False *)\n\n(** If this was allowed, we could construct a value of an empty type\n    in the empy context like so: *)\nFail Check (loop O : False).\n\n(** And this would preclude Coq from being a logic *)\n\n(** To be continued... *)\n", "meta": {"author": "kudryashovaia", "repo": "coq", "sha": "ff0e2139e4c23091edb6fba3947170c392a35ae4", "save_path": "github-repos/coq/kudryashovaia-coq", "path": "github-repos/coq/kudryashovaia-coq/coq-ff0e2139e4c23091edb6fba3947170c392a35ae4/code/lecture01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.916109614162018, "lm_q1q2_score": 0.8084006465982898}}
{"text": "\nRequire Import ZArith.\nRequire Import Omega.\nRequire Import Bool.\nFrom Coq Require Import ssreflect.\n\n\nOpen Scope Z_scope.\n\nGoal forall (x y : Z),\n    x + y = 2 -> 2 * x + y = 5 -> x = 3.  \nProof.\n  move=> x y H1 H2.\n  omega.\nQed.  \n\nDefinition Step (b : bool) := if b then 5 else 0.\n\nGoal forall b, b = true -> Step b = 5.\nProof.\n  move=> b Ht.\n  by rewrite /Step Ht.\nQed.\n\nDefinition OverThresholdLe (m x : Z) := m <=? x.\nDefinition OverThresholdLt (m x : Z) := m <? x.\nDefinition InnerRange (m1 m2 x : Z) := (m1 <=? x) && (x <=? m2).\n\nGoal forall x, 5 <= x -> OverThresholdLe 5 x = true.\nProof.\n  move=> x Ht.\n  rewrite /OverThresholdLe.\n    by apply/Z.leb_le.\nQed.\n\nGoal forall x, 5 <= x <-> OverThresholdLe 5 x = true.\nProof.\n  rewrite /OverThresholdLe.\n  split.\n  - move=> Hle.\n    move/Z.leb_le in Hle.\n      by [].\n  - move=> Hleb.      \n      by apply/Z.leb_le.\nQed.\n\nGoal forall x, x < 5 -> OverThresholdLe 5 x = false.\nProof.\n  move=> x Ht.\n  rewrite /OverThresholdLe.\n    by apply/Z.leb_gt.\nQed.\n\n\nGoal forall x, 5 < x -> OverThresholdLt 5 x = true.\nProof.\n  move=> x Ht.\n  rewrite /OverThresholdLt.\n    by apply/Z.ltb_lt.\nQed.\n\nGoal forall x, x <= 5 -> OverThresholdLt 5 x = false.\nProof.\n  move=> x Ht.\n  rewrite /OverThresholdLt.\n    by apply/Z.ltb_ge.\nQed.\n\n\nGoal forall x, 1 <= x <= 5 <-> InnerRange 1 5 x = true.\nProof.\n  rewrite /InnerRange.\n  split.\n  - case.\n    move=> H1 H5.\n    move/Z.leb_le in H1.\n    move/Z.leb_le in H5.\n      by rewrite H1 H5.\n  - move=> H15.\n    move/andb_true_iff in H15.\n    case: H15 => H1 H5.\n    move/Z.leb_le in H1.\n    move/Z.leb_le in H5.\n    split.\n    + done.\n    + done.\nQed.\n\nGoal forall x, x < 1 \\/ 5 < x <-> InnerRange 1 5 x = false.\nProof.\n  rewrite /InnerRange.\n  split.\n  - case => H1.\n    + apply/andb_false_iff.\n      left.\n        by apply/Z.leb_gt.\n    + apply/andb_false_iff.\n      right.\n        by apply/Z.leb_gt.\n  - move=> H15.\n    move/andb_false_iff in H15.\n    case: H15.\n    + move=> H1.\n      move/Z.leb_gt in H1.\n        by left.\n    + move=> H5.\n      move/Z.leb_gt in H5.\n        by right.\nQed.\n\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/ZComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8083856801932319}}
{"text": "Require Import Setoid.\nRequire Import Arith.\nRequire Import Bool.\nModule EvenAndOdd.\nInductive even:nat->Prop:=\n|even_0:even 0\n|even_SS:forall n,even n->even(S(S n)).\n\nInductive odd:nat->Prop:=\n|odd_1:odd 1\n|odd_SS:forall n,odd n->odd(S(S n)).\n\nTheorem even_add_SS:\nforall n,\neven(S(S n))->even n.\nProof.\nintros.\ngeneralize (refl_equal(S(S n))).\npattern(S(S n))at 2.\ncase H.\ndiscriminate.\nintros.\nrepeat apply eq_add_S in H1.\nrewrite H1.\nexact H0.\nQed.\n\nTheorem odd_add_SS:forall n,\nodd(S(S n))->odd n.\nintros.\ngeneralize (refl_equal(S(S n))).\npattern(S(S n))at 2.\ninfo case H.\ninfo discriminate.\nintros.\nrepeat apply eq_add_S in H1.\n\nrewrite H1.\nexact H0.\nQed.\nLemma even_S:\nforall n,\neven n->odd (S n).\nintros.\nelim H.\nexact odd_1.\nintros.\napply odd_SS.\nexact H1.\nQed.\nLemma odd_S:\nforall n,\nodd n->even (S n).\nintros.\nelim H.\nexact (even_SS 0 even_0).\nintros.\napply even_SS.\nexact H1.\nQed.\n\nLemma even_S_iff:\nforall n,\neven n<->odd(S n).\nintro.\nsplit.\napply even_S.\nintros.\napply even_add_SS.\napply odd_S.\nexact H.\nQed.\n\nLemma odd_S_iff:\nforall n,\nodd n<->even(S n).\nintro.\nsplit.\napply odd_S.\nintros.\napply odd_add_SS.\napply even_S.\nexact H.\nQed.\n\n\n\nLemma even_odd_dec:\nforall n,\n{even n}+{odd n}.\ninduction n.\nleft.\napply even_0.\ncase IHn.\nright.\nexact (even_S n e).\nleft.\nexact (odd_S n o).\nQed.\n\n\nLemma even_and_odd:\nforall n,\neven n->odd n->False.\ninduction n.\nintros.\ngeneralize (refl_equal 0).\npattern 0 at 2.\ncase H0;\ndiscriminate.\n\nintros.\nrewrite <-odd_S_iff in H.\nrewrite <-even_S_iff in H0.\nexact(IHn H0 H).\nQed.\n\n\nFixpoint beven(n:nat):bool:=\nmatch n with\n|0=>true\n|1=>false\n|S(S n')=>beven n'\nend.\n\nLemma beven_true:\nforall n:nat,\nbeven n=true->even n.\nfix IHn 1.\nintro.\ncase_eq n.\nintros.\nexact even_0.\nintro;case n0.\ndiscriminate.\nintros.\napply even_SS.\napply IHn.\nsimpl in H0.\nexact H0.\nQed.\nLemma beven_true_iff:\nforall n,\nbeven n=true<->even n.\nintros.\nsplit.\napply beven_true.\nintros.\nelim H.\nauto.\nintros.\nexact H1.\nQed.\nLemma beven_false:\nforall n,\nbeven n=false->odd n.\nintros.\nassert(~even n).\nrewrite <-beven_true_iff.\nrewrite H.\nSearchPattern(false<>true).\napply diff_false_true.\ncase (even_odd_dec n);auto.\nintros.\ncase H0.\nexact e.\nQed.\n\nLemma beven_false_iff:\nforall n,\nbeven n=false<->odd n.\nintro.\nsplit.\napply beven_false.\nintros.\napply not_true_is_false.\nintro.\napply beven_true in H0.\nexact (even_and_odd n H0 H).\nQed.\n\n\n\nTheorem even_is_mul_2:\nforall n,\neven n->exists x,n=2*x.\nsimpl.\n\nintros.\nelim H.\nexists 0.\nauto.\nintros.\ndestruct H1.\nexists (S x).\nrewrite H1.\nsimpl.\nrewrite (plus_comm x 0).\nsimpl.\nrewrite plus_n_Sm.\ninfo auto.\nQed.\nTheorem odd_is_S_mul_2:\nforall n,\nodd n->exists x,n=S(2*x).\nProof.\nintros.\nelim H.\nexists 0;auto.\nintros.\ndestruct H1.\nexists (S x).\nrewrite H1.\nsimpl.\nrewrite (plus_comm x 0).\nsimpl.\nrewrite plus_n_Sm.\ninfo auto.\nQed.\n\n\nTheorem even_plus_odd_is_odd:\nforall x y:nat,\neven x->odd y->\nodd(x+y).\nintros.\nelim H.\napply H0.\nintros.\nsimpl.\napply odd_SS.\napply H2.\nQed.\n\nEnd EvenAndOdd.\n\nSection OddIsNotEven.\nInductive even:nat->Prop:=\n|even_0:even 0\n|even_SS:forall n,even n->even(S(S n)).\nDefinition odd(n:nat):Prop:=\n~even n.\nTheorem even_add_SS:\nforall n,\neven(S(S n))->even n.\nProof.\nintros.\ngeneralize (refl_equal(S(S n))).\npattern(S(S n))at 2.\ncase H.\ndiscriminate.\nintros.\nrepeat apply eq_add_S in H1.\nrewrite H1.\nexact H0.\nQed.\n\nTheorem odd_add_SS:forall n,\nodd(S(S n))->odd n.\nintros.\nintro.\napply H.\napply even_SS.\nexact H0.\nQed.\nTheorem odd_SS:\nforall n,\nodd n->odd(S(S n)).\nintros n H H0.\napply H.\napply even_add_SS.\nexact H0.\nQed.\n\nLemma odd_1:odd 1.\nintro.\ngeneralize (refl_equal 1).\npattern 1 at 2.\ncase H;discriminate.\nQed.\n\n\n\n\nLemma even_S:\nforall n,\neven n->odd (S n).\nintros.\nelim H.\nexact odd_1.\nintros.\napply odd_SS.\nexact H1.\nQed.\nLemma odd_S:\nforall n,\nodd n->even (S n).\nfix IHn 1.\ninduction n.\nintros.\nelim H.\nexact even_0.\ncase_eq n.\nintros.\napply even_SS.\nexact even_0.\nintros.\napply even_SS.\napply odd_add_SS in H0.\napply IHn.\napply H0.\nQed.\n\nLemma even_S_iff:\nforall n,\neven n<->odd(S n).\nintro.\nsplit.\napply even_S.\nintros.\napply even_add_SS.\napply odd_S.\nexact H.\nQed.\n\nLemma odd_S_iff:\nforall n,\nodd n<->even(S n).\nintro.\nsplit.\napply odd_S.\nintros.\napply odd_add_SS.\napply even_S.\nexact H.\nQed.\n\n\n\nLemma even_odd_dec:\nforall n,\n{even n}+{odd n}.\ninduction n.\nleft.\napply even_0.\ncase IHn.\nright.\nexact (even_S n e).\nleft.\nexact (odd_S n o).\nQed.\n\n\nLemma even_and_odd:\nforall n,\neven n->odd n->False.\nauto.\nQed.\n\n\nFixpoint beven(n:nat):bool:=\nmatch n with\n|0=>true\n|1=>false\n|S(S n')=>beven n'\nend.\n\nLemma beven_true:\nforall n:nat,\nbeven n=true->even n.\nfix IHn 1.\nintro.\ncase_eq n.\nintros.\nexact even_0.\nintro;case n0.\ndiscriminate.\nintros.\napply even_SS.\napply IHn.\nsimpl in H0.\nexact H0.\nQed.\nLemma beven_true_iff:\nforall n,\nbeven n=true<->even n.\nintros.\nsplit.\napply beven_true.\nintros.\nelim H.\nauto.\nintros.\nexact H1.\nQed.\nLemma beven_false:\nforall n,\nbeven n=false->odd n.\nintros.\nunfold odd.\nrewrite <-beven_true_iff.\nrewrite H.\nSearchPattern(false<>true).\napply diff_false_true.\nQed.\n\nLemma beven_false_iff:\nforall n,\nbeven n=false<->odd n.\nintro.\nsplit.\napply beven_false.\nintros.\napply not_true_is_false.\nintro.\napply beven_true in H0.\nexact (even_and_odd n H0 H).\nQed.\n\n\n\nTheorem even_is_mul_2:\nforall n,\neven n->exists x,n=2*x.\nsimpl.\n\nintros.\nelim H.\nexists 0.\nauto.\nintros.\ndestruct H1.\nexists (S x).\nrewrite H1.\nsimpl.\nrewrite (plus_comm x 0).\nsimpl.\nrewrite plus_n_Sm.\ninfo auto.\nQed.\nTheorem odd_is_S_mul_2:\nforall n,\nodd n->exists x,n=S(2*x).\nProof.\nfix IHn 1.\nintro n.\ncase n.\n intros.\n absurd (even 0).\n exact H.\n exact even_0.\n\nintro n0.\ncase n0.\n intros.\n exists 0.\n auto.\nintros.\napply odd_add_SS in H.\ndestruct (IHn n1 H).\nexists (S x).\nsimpl in *.\nrewrite H0.\nrewrite plus_n_Sm.\nreflexivity.\nQed.\n\n\nTheorem even_plus_odd_is_odd:\nforall x y:nat,\neven x->odd y->\nodd(x+y).\nintros.\nelim H.\napply H0.\nintros.\nsimpl.\napply odd_SS.\napply H2.\nQed.\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/EvenOdd/EvenOdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.8083806139021137}}
{"text": "From Coq Require Import ZArith.\n\nOpen Scope Z.\n\nFixpoint sum (f : Z -> Z) (n : nat) : Z :=\n  match n with\n  | O => f 0\n  | S n => f (Z.of_nat (S n)) + (sum f n)\n  end.\n\nLemma sum_decomposition :\n  forall f n, sum f (S n) = sum f n + f (Z.of_nat (S n)).\nProof.\n  intros f n.\n  simpl.\n  rewrite Z.add_comm.\n  reflexivity.\nQed.\n\nAxiom square_plus :\n  forall a b,\n  Z.square (a + b) = Z.square a + 2 * a * b + Z.square b.\n\nLemma Z_of_nat_succ : forall n, Z.of_nat (S n) = Z.of_nat n + 1.\nProof.\n  intros n.\n  rewrite -> Nat2Z.inj_succ.\n  reflexivity.\nQed.\n\nTheorem thm_1_9_Z :\n  forall n,\n  sum (fun n => 2 * n + 1) n = Z.square (Z.of_nat n + 1).\nProof.\n  intros.\n  induction n.\n  + simpl.\n    reflexivity.\n  + rewrite sum_decomposition.\n    rewrite IHn.\n    rewrite square_plus.\n    rewrite square_plus.\n    rewrite Z_of_nat_succ.\n    rewrite square_plus.\n    rewrite Z.mul_1_r.\n    rewrite Z.add_assoc.\n    rewrite Z.mul_1_r.\n    reflexivity.\nQed.\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/web/coq/ibl-induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782973, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.8083774691526705}}
{"text": "\n(** Programming exercices in Coq *)\n\n(* Write a function addodd that sums the n first odd numbers.\n   Check on a few values that this function produces square numbers.\n   How do you state such a fact ? *)\n\n(* Same for the sum of the n first natural numbers, and the\n   formula n(n+1)/2. *)\n\nInductive comparison := Eq | Lt | Gt. (* equal / less-than / greater-than *)\n\n(* Write a compare function of type nat->nat->comparison. *)\n\n(* Write a compare_pos function of type positive->positive->comparison. *)\n\n(* Write a conversion function of type positive->nat.\n   State that your comparison functions are compatible with\n   this conversion, and test this fact on a few examples. *)\n\n(* Write a few usual functions on lists : append, map, rev... *)\n\n(* Write a function\n    tabulate : forall A, (nat -> A) -> nat -> list A\n   such that (tabulate f n = f 0 :: f 1 :: ... :: f (n-1)). *)\n\n(* Write a compose function of type :\n    forall A B C, (A->B)->(B->C)->(A->C) *)\n\n(* Write a function natiter : forall A, (A->A) -> n -> (A->A)\n   such that natiter f n = f^n.\n   How do you write the addition over nat via natiter ?\n   Same for the multiplication and exponentiation. *)\n\n(* Write a function syracuse : positive->positive such that\n    syracuse p = p/2 when p is even, and 3p+1 otherwise.\n   State the Syracuse conjecture : repetition of this process\n   ultimately reachs 1, regardless of the starting value.\n   How do you experimently verify this conjecture for a few values ? *)\n\n(* Define the inductive type of binary trees whose nodes contain\n   elements of a given type A.\n   Define a conversion function from trees to lists according\n   to your favorite traversal order.\n   Define a function checking whether a binary tree is perfect\n   or not. *)\n\n\n(* Small arithmetic expressions and stack machine. *)\n\nInductive expr :=\n| Num  : nat -> expr            (* Constant: n *)\n| Plus : expr -> expr -> expr   (* Sum:      e1 + e2 *)\n| Mult : expr -> expr -> expr.  (* Product:  e1 * e2 *)\n\n(* Define a function eval : expr -> nat. *)\n\nInductive instr :=\n| PUSH : nat -> instr (* Push a value on top of the stack *)\n| ADD : instr  (* remove the two topmost values on the stack\n                  and replace them by their sum. *)\n| MUL : instr.  (* same for multiplication *)\nDefinition prog := list instr.\nDefinition stack := list nat.\n\n(* Define a function exec_instr : instr -> stack -> stack.\n   Its behavior is unspecified if the stack hasn't enough elements. *)\n(* Same for exec_prog : prog -> stack -> stack. *)\n\n(* Provide a compile function of type expr -> prog. *)\n(* State its correctness, and test it on some examples *)", "meta": {"author": "yurug", "repo": "coqepit", "sha": "3a305c888d3e909b4525e18a16a6b5127f583e1b", "save_path": "github-repos/coq/yurug-coqepit", "path": "github-repos/coq/yurug-coqepit/coqepit-3a305c888d3e909b4525e18a16a6b5127f583e1b/support/day1/exos2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8962513731336204, "lm_q1q2_score": 0.8083476424344106}}
{"text": "From mathcomp Require Import all_ssreflect. \n\n\n(** *** Exercise 1:\n    - Let's define the subtype of odd and even natural numbers\n    - Intrument Coq to recognize odd/even number built out\n      of product and successor\n    - Inherit on [odd_nat] the [eqType] structure \n*)\n\nStructure odd_nat := Odd {\n  oval :> nat;\n  oprop : odd oval\n}.\n\n(* Prove the main property of [odd_nat] *)\nLemma oddP (n : odd_nat) : odd n.\nProof.\n(*D*)by case: n.\nQed.\n\nStructure even_nat := Even {\n  eval :> nat;\n  eprop : ~~ (odd eval)\n}.\n\n(* Prove the main property of [even_nat] *)\nLemma evenP (n : even_nat) : ~~ (odd n).\nProof.\n(*D*) by case: n.\nQed.\n\n(* The objective is to make it work: knowing that [n] is [odd]\n   Coq should infer that [n * 3] is also odd, and that [6] is even *)\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. Fail by rewrite oddP evenP. Abort.\n\n(* Let's start by telling Coq that 0 is even *)\nCanonical even_0 : even_nat := Even 0 isT.\n\nLemma oddS n : ~~ (odd n) -> odd n.+1.\nProof.\n(*D*)by rewrite /=; case: (odd n).\nQed.\n\nLemma evenS n : (odd n) -> ~~ (odd n.+1).\nProof.\n(*D*)by rewrite /=; case: (odd n).\nQed.\n\n(* Here we teach Coq that if [m] is even, then [m.+1] is odd *)\nCanonical odd_even (m : even_nat) : odd_nat :=\n  Odd m.+1 (oddS m (eprop m)).\n\n(* Implement the dual, teach coq that if [m] is odd then [m.+1] is even *)\nCanonical even_odd (m : odd_nat) : even_nat :=\n(*D*)Even m.+1 (evenS m (oprop m)).\n\n(* Now let's deal with multiplication *)\nLemma odd_mulP (n m : odd_nat) : odd (n * m).\nProof.\n(*D*)by rewrite odd_mul !oddP.\nQed.\n\n(* Teach Coq that [*] preserves being odd *)\nCanonical odd_mul (n m : odd_nat) : odd_nat :=\n(*D*)Odd (n * m) (odd_mulP n m).\n\n(* Enjoy! *)\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. by rewrite oddP evenP. Qed.\n\n(* We can't use [==] on odd natural numbers because \n   [odd_nat] is not an [eqType] *)\nFail Check forall n m : odd_nat, n == m.\n\n(* Use the subtype machinery (that we used for tuples) in order\n   to teach Coq that [odd_nat] is an [eqType] *)\nCanonical odd_subType :=\n(*D*)Eval hnf in [subType for oval].\nDefinition odd_eqMixin :=\n(*D*)Eval hnf in [eqMixin of odd_nat by <:].\nCanonical odd_eqType :=\n(*D*)Eval hnf in EqType odd_nat odd_eqMixin.\n\n(* Enjoy *)\nCheck forall n m : odd_nat, n == m.\n\n(* Now do the same for [even_nat] *)\nFail Check forall (n m : even_nat), m == n.\n\n(*D*)Canonical even_subType := Eval hnf in [subType for eval].\n(*D*)Definition even_eqMixin := Eval hnf in [eqMixin of even_nat by <:].\n(*D*)Canonical even_eqType := Eval hnf in EqType even_nat even_eqMixin.\n\nCheck forall (n m : even_nat), m == n.\n\n\n\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/exercise8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.808270171300187}}
{"text": "(* This file is part of the Linear Logic  formalization in Coq: https://github.com/brunofx86/LL *)\n\n(** ** Auxiliar Results\n\nSome arithmetic results needed in the proofs. \n*)\n\n\nRequire Import Arith.\n\nLemma GtZero : forall n, n >0 -> exists n', n = S n'.\nProof.\n  intros.\n  destruct n.\n  inversion H.\n  exists n;auto.\nQed.\n\n\nLemma plus_le_reg_r: forall n m q : nat, n + q <= m + q -> n <= m.\nProof.\n  intros.\n  assert (n+q = q + n) by (apply plus_comm).\n  assert (m+q = q + m) by (apply plus_comm).\n  rewrite H0 in H. rewrite H1 in H.\n  eapply plus_le_reg_l in H.\n  assumption.\nQed.\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/AuxResults.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.8082296929578701}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Setoid.\nRequire Import Coq.Classes.Equivalence.\nRequire Import List.\nRequire Import ListSet.\nRequire Import ListUtils.\nImport ListNotations.\n\nSection group_definitions.\n  Definition is_assoc (A: Set) (f: A -> A -> A) := forall a b c,\n    f (f a b) c = f a (f b c).\n\n  Definition is_commutative (A: Set) (f: A -> A -> A) := forall a b, f a b = f b a.\n\n  Definition is_inverse (A: Set) (f: A -> A -> A) (inv: A -> A) (z: A) :=\n    forall a,  f a (inv a) = z /\\ f (inv a) a = z.\n\n  Definition is_zero (A: Set) (f: A -> A -> A) (z: A) := forall a, f a z = a /\\ f z a = a.\n\n  Definition is_semigroup (A: Set) (op: A -> A -> A) (zero: A) := (is_assoc A op) /\\ (is_zero A op zero).\n\n  Definition is_group (A: Set) (op: A -> A -> A) (inv: A -> A) (zero: A) :=\n    is_semigroup A op zero /\\ is_inverse A op inv zero.\n\nEnd group_definitions.\n\nSection groups.\n  Structure Group : Type := makeGroup\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      eq_dec: forall (x y : A), {x = y} + {x <> y}\n    }.\n\n  Definition abelian_group (G: Group) := is_commutative (A G) (op G).\n\n  Arguments z {g}.\n  Arguments op {g} _ _.\n  Arguments inv {g} _.\n\n  Notation \"x <*> y\" := (op x y) (at level 50, left associativity).\n\n  Variable (G : Group).\n\n  Lemma inverse1 : forall (a : G), a <*> (inv a) = z.\n    apply op_inverse.\n  Qed.\n\n  Lemma inverse2 : forall (a: G), (inv a) <*> a = z.\n    apply op_inverse.\n  Qed.\n\n  Lemma inverse3 : forall (a b : G), inv a <*> (a <*> b) = b.\n    intros.\n    rewrite op_assoc, inverse2.\n    apply op_z.\n  Qed.\n\n  Lemma inverse4 : forall (a b : G), a <*> (inv a <*> b) = b.\n    intros.\n    rewrite op_assoc, inverse1.\n    apply op_z.\n  Qed.\n\n  Hint Rewrite inverse1.\n  Hint Rewrite inverse2.\n  Hint Rewrite inverse3.\n  Hint Rewrite inverse4.\n\n  Lemma inverse_commutes : forall (a: G), a <*> (inv a) = (inv a) <*> a.\n    intros; autorewrite with core; auto.\n  Qed.\n\n  Lemma group_add_l: forall (a b c : G), b = c -> a <*> b = a <*> c.\n    intros; rewrite H; auto.\n  Qed.\n\n  Lemma group_add_r: forall (a b c : G), b = c -> b <*> a = c <*> a.\n    intros; rewrite H; auto.\n  Qed.\n\n  Lemma group_z_r: forall (a : G), a <*> z = a.\n    apply op_z.\n  Qed.\n\n  Lemma group_z_l: forall (a : G), z <*> a = a.\n    apply op_z.\n  Qed.\n\n  Lemma group_assoc: forall (a b c : G), (a <*> b) <*> c = a <*> (b <*> c).\n    intros; rewrite op_assoc; reflexivity.\n  Qed.\n\n  Lemma group_cancel_l: forall (a b c : G), a <*> b = a <*> c -> b = c.\n    intros a b c OpABEqOpAC.\n    rewrite <- (group_z_l b), <- (group_z_l c).\n    rewrite <- (inverse2 a).\n    repeat rewrite group_assoc.\n    apply (group_add_l (inv a)).\n    assumption.\n  Qed.\n\n  Lemma group_cancel_r: forall (a b c :G), b <*> a = c <*> a -> b = c.\n    intros a b c OpABEqOpAC.\n    rewrite <- (group_z_r b), <- (group_z_r c).\n    rewrite <- (inverse1 a).\n    repeat rewrite <- group_assoc.\n    apply (group_add_r (inv a)).\n    assumption.\n  Qed.\n\n  Theorem id_is_unique: forall a : G, (forall b : G, a <*> b = b) -> a = z.\n    intros a ADef.\n    apply (group_cancel_r (inv a)).\n    rewrite group_z_l; apply ADef.\n  Qed.\n\n  Theorem op_z_commutes: forall (a b : G), a <*> b = z <-> b <*> a = z.\n    intros a b.\n    split.\n    intro OpABZ.\n    symmetry.\n    apply (group_cancel_l a _ _), (group_cancel_l b _ _).\n    rewrite <- group_assoc, <- (group_assoc a b a).\n    rewrite OpABZ, group_z_r, group_z_l.\n    reflexivity.\n    intro OpBAZ.\n    symmetry.\n    apply (group_cancel_l b _ _), (group_cancel_l a _ _).\n    rewrite <- group_assoc, <- (group_assoc b a b).\n    rewrite OpBAZ, group_z_r, group_z_l.\n    reflexivity.\n  Qed.\n\n  Theorem inverse_unique: forall (a b: G), a <*> b = z -> b = inv a.\n    intros a b.\n    intros OpABZ.\n    apply (group_cancel_l a _ _).\n    rewrite inverse1.\n    assumption.\n  Qed.\n\n  Theorem inverse_cancel: forall (a: G), inv (inv a) = a.\n    intros a.\n    (* show (inv a) * a = z *)\n    remember (inverse2 a) as H.\n    destruct HeqH.\n    apply inverse_unique in H.\n    symmetry; assumption.\n  Qed.\n\n  Hint Rewrite inverse_cancel.\n\n  Lemma inverse_cancel2: forall (a b: G), inv a = inv b -> a = b.\n  Proof.\n    intros b c inv_equal.\n    rewrite <- inverse_cancel, <- inv_equal.\n    autorewrite with core; reflexivity.\n  Qed.\n\n  Hint Rewrite inverse1.\n  Hint Rewrite inverse2.\n  Hint Rewrite inverse3.\n  Hint Rewrite inverse4.\n\n  Hint Rewrite group_z_r.\n  Hint Rewrite group_z_l.\n  Hint Rewrite group_assoc.\n\n  Hint Rewrite inverse_cancel.\n\n  Lemma inverse_apply: forall (a b : G), inv (a <*> b) = inv b <*> inv a.\n  Proof.\n    intros a b.\n    apply (group_cancel_l (a <*> b) _).\n    rewrite <- group_assoc, inverse1.\n    repeat rewrite group_assoc.\n    rewrite inverse4, inverse1.\n    reflexivity.\n  Qed.\n\n  Lemma inverse_swap: forall (a b c : G), a = (inv b) <*> c <-> b <*> a = c.\n  Proof.\n    intros a b c.\n    split.\n    intros a_eq.\n    apply (group_cancel_l (inv b)).\n    rewrite inverse3; assumption.\n    intros.\n    apply (group_cancel_l b).\n    rewrite inverse4; assumption.\n  Qed.\n\n  Lemma inverse_z: @inv G z = z.\n    apply (group_cancel_l z).\n    rewrite inverse1, group_z_l.\n    reflexivity.\n  Qed.\n\n  Hint Rewrite inverse_z.\n\n  Section group_examples.\n    Require Import Coq.ZArith.BinInt.\n    Require Import ZArithRing.\n    Require Import Znumtheory.\n    Require Import Zdiv.\n\n    Local Open Scope Z_scope.\n    Check Group.\n\n    Definition integer_group : Group.\n      remember (fun n => -n) as inv.\n      assert (forall a b c : Z, a + (b + c) = a + b + c) as Z_assoc.\n      intros; ring.\n      assert (forall a : Z, a + Z.zero = a /\\ Z.zero + a = a) as Z_zero.\n      intros; rewrite Z.add_0_r, Z.add_0_l; auto.\n      assert (forall a : Z, a + (fun n => -n) a = Z.zero /\\ (fun n => -n) a + a = Z.zero) as Z_inv.\n      intros; rewrite Z.add_opp_diag_r, Z.add_opp_diag_l. auto.\n      assert (forall a b : Z, {a = b} + {a <> b}) as eq_dec. apply Z.eq_dec.\n      exact (makeGroup Z Z.add (fun n => - n) Z.zero Z_assoc Z_zero Z_inv eq_dec).\n    Defined.\n\n    Inductive lt_n (n : Z): Set :=\n    | lt_n_intro (m : Z) : lt_n n.\n\n    Definition lt_n_add n (a b: lt_n n) : (lt_n n).\n      destruct a as [r]; induction b as [s].\n      apply (lt_n_intro n ((r + s) mod n)); auto.\n    Defined.\n\n    Notation \"m # n\" := (lt_n_intro n m) (at level 50, left associativity).\n    Check (4 # 3).\n\n    Axiom lt_n_intro_equality:\n      forall n a b, a mod n = b mod n -> a # n = b # n.\n\n    Require Import Omega.\n\n    Definition lt_n_inv n (a: lt_n n) : (lt_n n).\n      destruct a as [r].\n      apply (lt_n_intro n (-r)); auto.\n    Defined.\n\n    Definition lt_n_zero n := lt_n_intro n 0.\n\n    Lemma lt_n_add_rewrite n: forall r s,\n        lt_n_add n (r # n) (s # n) =\n        ((r + s) mod n) # n.\n    Proof.\n      intros r s.\n      simpl.\n      reflexivity.\n    Qed.\n\n    Lemma lt_n_add_comm n:\n      forall (a b : lt_n n), lt_n_add n a b = lt_n_add n b a.\n    Proof.\n      intros a b.\n      case a; case b; intros r s.\n      repeat rewrite lt_n_add_rewrite.\n      rewrite Zplus_comm.\n      reflexivity.\n    Defined.\n\n    Lemma lt_n_add_assoc n:\n      forall (a b c: lt_n n),\n        lt_n_add n (lt_n_add n a b) c = lt_n_add n a (lt_n_add n b c).\n    Proof.\n      intros a b c.\n      case a; case b; case c; intros r s t.\n      repeat rewrite lt_n_add_rewrite.\n      rewrite Zplus_mod_idemp_l.\n      rewrite <- Zplus_assoc.\n      rewrite Zplus_mod.\n      rewrite Zplus_mod_idemp_l.\n      reflexivity.\n    Qed.\n\n    Lemma lt_n_add_inverse n: forall a,\n        lt_n_add n a (lt_n_inv n a) =\n        lt_n_zero n.\n    Proof.\n      intros.\n      unfold lt_n_add.\n      destruct a; simpl; rewrite Z.add_opp_diag_r, Zmod_0_l; reflexivity.\n    Qed.\n\n    Lemma lt_n_add_zero n: forall a,\n        lt_n_add n a (lt_n_zero n) = a.\n    Proof.\n      intros; unfold lt_n_add.\n      simpl.\n      destruct a.\n      rewrite Z.add_0_r.\n      apply lt_n_intro_equality.\n      rewrite Zmod_mod.\n      reflexivity.\n    Qed.\n\n    Check integer_group.\n\n  End group_examples.\n\n  Section subgroups.\n\n    Definition set (A : Set) := A -> bool.\n\n    Definition is_mem (A: Set) (H: set A) (a : A) := H a = true.\n\n    Arguments is_mem {A} _ _.\n\n    Theorem is_mem_dec (A : Set) (H : set A) :\n      forall a, { is_mem H a } +  { ~(is_mem H a) }.\n      unfold is_mem. intros a.\n      apply (bool_dec (H a)).\n    Qed.\n\n    Theorem is_mem_contradict (A : Set) (H : set A) :\n      forall a, is_mem H a -> ~is_mem H a -> False.\n      intros a; auto.\n    Qed.\n\n    Theorem is_mem_not (A : Set) (H : set A):\n      forall a, ~is_mem H a <-> (H a) = false.\n      intros a.\n      unfold is_mem.\n      rewrite <- not_true_iff_false.\n      reflexivity.\n    Qed.\n\n    Structure subgroup (G : Group) : Type := makeSubgroup\n    {\n      subgroup_mem :> set G;\n      subgroup_z : is_mem subgroup_mem z;\n      subgroup_closed :\n        forall a b, is_mem subgroup_mem a /\\ is_mem subgroup_mem b -> is_mem subgroup_mem (a <*> b);\n      subgroup_inverse :\n        forall a, is_mem subgroup_mem a -> is_mem subgroup_mem (inv a)\n    }.\n\n    Lemma subgroup_mem_bool_rewrite (H: subgroup G):\n      forall a b, (is_mem H a) <-> (is_mem H b) -> subgroup_mem G H a = subgroup_mem G H b.\n    Proof.\n      intros a b.\n      unfold is_mem.\n      destruct (subgroup_mem G H a); destruct (subgroup_mem G H b); try tauto; symmetry; tauto.\n    Qed.\n\n    (* H is a subgroup *)\n    (* H is inductively defined, z is in it,\n       if a is in it, inv a is in it, if a b is in it, a op b is in it\n       z is a consequence of the other two\n     *)\n\n    Lemma subgroup_closed1: forall (H: subgroup G) (a b : G),\n        is_mem H a -> is_mem H b -> is_mem H (a <*> b).\n    Proof.\n      intros; apply subgroup_closed; auto.\n    Qed.\n\n    Lemma subgroup_closed2: forall (H : subgroup G) (a b : G),\n        is_mem H a -> is_mem H b -> is_mem H (b <*> a).\n    Proof.\n      intros; apply subgroup_closed; auto.\n    Qed.\n\n    Lemma subgroup_inverse1: forall (H: subgroup G) (a : G),\n        is_mem H a -> is_mem H (inv a).\n      intros; apply subgroup_inverse; auto.\n    Qed.\n\n    Lemma subgroup_inverse2: forall (H: subgroup G) (a : G),\n        is_mem H (inv a) -> is_mem H a.\n      intros H a.\n      intros.\n      rewrite <- (inverse_cancel a).\n      apply subgroup_inverse; assumption.\n    Qed.\n\n    Lemma subgroup_inverse3: forall (H: subgroup G) (a : G),\n        is_mem H (inv a) <-> is_mem H a.\n    Proof.\n      intros.\n      split; [apply subgroup_inverse2 | apply subgroup_inverse1].\n    Qed.\n\n    Lemma subgroup_op_non_member_right: forall (H: subgroup G) (a b : G),\n        is_mem H a -> ~is_mem H b -> ~is_mem H (a <*> b).\n      intros H a b Ha_mem Hb_not_mem.\n      (* Suppose ab were in the subgroup.  Then a^{-1} ab would be in the subgroup, so b is in the subgroup.\n         contradiction *)\n      destruct (is_mem_dec _ H (a <*> b)) as [Hab_mem | Hab_not_mem].\n      apply (subgroup_closed1 _ (inv a) _) in Hab_mem.\n      autorewrite with core in Hab_mem; auto.\n      apply subgroup_inverse; assumption.\n      assumption.\n    Qed.\n\n    Lemma subgroup_op_non_member_left: forall (H : subgroup G) (a b : G),\n        is_mem H b -> ~is_mem H a -> ~is_mem H (a <*> b).\n      intros H a b Hb_mem Ha_not_mem.\n      (* not sure if there is a clever way to use right, so we just duplicate the logic above (for now) *)\n      (* Suppose ab were in the subgroup.  Then a^{-1} ab would be in the subgroup, so b is in the subgroup.\n         contradiction *)\n      destruct (is_mem_dec _ H (a <*> b)) as [Hab_mem | Hab_not_mem].\n      apply (subgroup_closed1 _ _ (inv b)) in Hab_mem.\n      autorewrite with core in Hab_mem; auto.\n      apply subgroup_inverse; assumption.\n      assumption.\n    Qed.\n\n    Lemma subgroup_mem_l:\n      forall (H : subgroup G) a b,\n        is_mem H a -> is_mem H (a <*> b) <-> is_mem H b.\n      intros H a b Ha_mem.\n      (* want to reason like .... is_mem H b\n       If is_mem H a, then obviously since a is in the subgroup.\n       If H a = false, then...\n       *)\n      destruct (is_mem_dec _ H b) as [Hb_mem | Hb_not_mem].\n      remember (subgroup_closed1 _ _ _ Ha_mem Hb_mem).\n      split; [intros; assumption | intros; assumption].\n      (* a is member, b not member, so these are proofs by contradiction *)\n      remember (subgroup_op_non_member_right _ a b Ha_mem Hb_not_mem) as Hab_not_mem.\n      split.\n      intros Hab_mem.\n      contradict (is_mem_contradict _ _ _ Hab_mem Hab_not_mem).\n      intros Hb_mem.\n      contradict (is_mem_contradict _ _ _ Hb_mem Hb_not_mem).\n    Qed.\n\n    Lemma subgroup_mem_r: forall (H : subgroup G) a b,\n        is_mem H b -> is_mem H (a <*> b) <-> is_mem H a.\n      intros H a b Hb_mem.\n      (* want to reason like .... is_mem H b\n       If is_mem H a, then obviously since a is in the subgroup.\n       If H a = false, then...\n       *)\n      destruct (is_mem_dec _ H a) as [Ha_mem | Ha_not_mem].\n      remember (subgroup_closed1 _ _ _ Ha_mem Hb_mem).\n      split; [intros; assumption | intros; assumption].\n      (* a is member, b not member, so these are proofs by contradiction *)\n      remember (subgroup_op_non_member_left _ a b Hb_mem Ha_not_mem) as Hab_not_mem.\n      split.\n      intros Hab_mem.\n      contradict (is_mem_contradict _ _ _ Hab_mem Hab_not_mem).\n      intros Ha_mem.\n      contradict (is_mem_contradict _ _ _ Ha_mem Ha_not_mem).\n    Qed.\n\n    Lemma subgroup_inverse_non_member1: forall (H: subgroup G) a,\n        ~is_mem H a -> ~is_mem H (inv a).\n      intros H a.\n      destruct (is_mem_dec _ H (inv a)) as [Ha_inv_true | Ha_inv_false].\n      apply subgroup_inverse in Ha_inv_true.\n      rewrite inverse_cancel in Ha_inv_true.\n      intro Ha_false.\n      contradict (is_mem_contradict _ _ _ Ha_inv_true Ha_false).\n      intros; auto.\n    Qed.\n\n    Lemma subgroup_inverse_non_member2: forall (H: subgroup G) a,\n        ~is_mem H (inv a) -> ~is_mem H a.\n      intros H a.\n      intros Ha_inv_false.\n      apply (subgroup_inverse_non_member1 _ (inv a)) in Ha_inv_false.\n      rewrite <- (inverse_cancel a).\n      assumption.\n    Qed.\n\n  End subgroups.\n\n  Section cosets.\n\n    (* c \\in aH if b \\in H such that ab = c, b = a^{-1}c *)\n    Definition left_coset (G: Group) (a : G) (H: subgroup G) : set G :=\n      fun c => (subgroup_mem G H) ((inv a) <*> c).\n\n    (* c \\in Ha if b \\in H such that ba = c, b = c a^{-1} *)\n    Definition right_coset (G: Group) (H: subgroup G) (a: G) : set G :=\n      fun c => (subgroup_mem G H) (c <*> (inv a)).\n\n    Arguments is_mem {A} _ _.\n    Arguments right_coset {G} _.\n    Arguments left_coset {G} _.\n\n    Check right_coset.\n\n    Lemma right_coset_mem_bool_rewrite (H: subgroup G):\n      forall a b c, (is_mem (right_coset H a) c) <-> (is_mem (right_coset H b) c) ->\n                    right_coset H a c = right_coset H b c.\n    Proof.\n      intros a b c.\n      unfold is_mem.\n      destruct (right_coset H a c); destruct (right_coset H b c); try tauto; symmetry; tauto.\n    Qed.\n\n    Lemma coset_subgroup: forall a b  (H: subgroup G),\n        is_mem (right_coset H b) a <-> is_mem H (a <*> inv b).\n    Proof.\n      intros; unfold is_mem, right_coset.\n      reflexivity.\n    Qed.\n\n    Lemma coset_swap: forall a b (H: subgroup G),\n        is_mem (right_coset H b) a <-> is_mem (right_coset H a) b.\n    Proof.\n      intros; repeat rewrite coset_subgroup.\n      rewrite <- subgroup_inverse3, inverse_apply.\n      autorewrite with core.\n      reflexivity.\n    Qed.\n\n    Lemma coset_trans: forall a b c (H: subgroup G),\n        is_mem (right_coset H a) b -> is_mem (right_coset H b) c -> is_mem (right_coset H a) c.\n    Proof.\n      intros a b c H; repeat rewrite coset_subgroup.\n      intros H_a H_b.\n      replace (c <*> inv a) with ((c <*> inv b) <*> (b <*> inv a));\n        [apply subgroup_closed | autorewrite with core]; auto.\n    Qed.\n\n    (* a in Hb -> Ha = Hb *)\n    Lemma coset_intersection: forall a b d (H: subgroup G),\n        is_mem (right_coset H a) d ->\n        is_mem (right_coset H b) d ->\n        (forall c, is_mem (right_coset H a) c <-> is_mem (right_coset H b) c).\n    Proof.\n      intros a b d H Coset_ad Coset_bd.\n      assert (is_mem (right_coset H a) b) as Coset_ab.\n      rewrite coset_swap in Coset_bd.\n      apply (coset_trans _ d); auto.\n      repeat rewrite (coset_swap c).\n      split.\n      - intros Coset_ac.\n        rewrite coset_swap in Coset_ab; apply (coset_trans _ a); auto.\n      - intros Coset_bc.\n        apply (coset_trans _ b); auto.\n    Qed.\n\n    Lemma coset_reflexive: forall a (H: subgroup G),\n        is_mem (right_coset H a) a.\n    Proof.\n      intros a H.\n      rewrite coset_subgroup.\n      autorewrite with core; apply subgroup_z.\n    Qed.\n\n    Theorem coset_representative:\n      forall a b (H: subgroup G),\n        is_mem (right_coset H b) a ->\n        forall c, is_mem (right_coset H a) c <-> is_mem (right_coset H b) c.\n    Proof.\n      intros; split; apply coset_trans; [ | rewrite coset_swap ]; auto.\n    Qed.\n\n    Theorem coset_mult: forall a b (H: subgroup G),\n        is_mem H b -> is_mem (right_coset H a) (b <*> a).\n    Proof.\n      intros a b H H_mem.\n      rewrite coset_subgroup.\n      autorewrite with core; auto.\n    Qed.\n\n    Theorem coset_z: forall a (H: subgroup G),\n        is_mem H a ->\n        forall c, is_mem (right_coset H a) c <-> is_mem (right_coset H z) c.\n    Proof.\n      intros a H Ha_true.\n      intros c.\n      repeat rewrite coset_subgroup.\n      autorewrite with core.\n      apply subgroup_mem_r, subgroup_inverse; auto.\n    Qed.\n\n  End cosets.\n\n  Section normal_subgroups.\n\n    Arguments is_mem {A} _ _.\n    Arguments is_mem_dec {A} _ _.\n    Arguments right_coset {G} _.\n    Arguments left_coset {G} _.\n\n    Structure normal_subgroup (G : Group) := makeNormalSubgroup\n      {\n        normal_subgroup_mem :> subgroup G ;\n        normal_subgroup_conjugation: forall (a h : G), is_mem normal_subgroup_mem h -> is_mem normal_subgroup_mem (a <*> h <*> inv a)\n      }.\n\n    Arguments normal_subgroup_conjugation {G} _.\n\n    Lemma normal_subgroup_intro: forall a h (H : normal_subgroup G),\n        is_mem H h <-> is_mem H (a <*> h <*> inv a).\n    Proof.\n      intros a h H.\n      split.\n      intros h_Subgroup.\n      apply normal_subgroup_conjugation.\n      assumption.\n      intros h_conjugate.\n      apply (normal_subgroup_conjugation _ (inv a)) in h_conjugate.\n      autorewrite with core in h_conjugate.\n      assumption.\n    Qed.\n\n    Lemma normal_subgroup_conj_rewrite: forall a h (H : normal_subgroup G),\n        is_mem H h ->\n        is_mem H (a <*> h <*> inv a) <-> is_mem H ((inv a) <*> h <*> a).\n    Proof.\n      intros a h H h_Subgroup.\n      (* inv (a b) = inv b inv a *)\n      split.\n      intros.\n      rewrite <- (inverse_cancel a) at 2.\n      apply (normal_subgroup_conjugation _ (inv a)).\n      assumption.\n      intros; apply normal_subgroup_conjugation; assumption.\n    Qed.\n\n    Theorem normal_subgroup_membership_commutes : forall a b (H: normal_subgroup G),\n        is_mem H (a <*> b) <-> is_mem H (b <*> a).\n      intros; rewrite (normal_subgroup_intro (inv a) _).\n      autorewrite with core.\n      reflexivity.\n    Qed.\n\n    Theorem normal_subgroup_left_coset_iff_right_coset : forall a (H: normal_subgroup G),\n        forall c, is_mem (left_coset a H) c <-> is_mem (right_coset H a) c.\n    Proof.\n      intros; apply normal_subgroup_membership_commutes.\n    Qed.\n\n    Lemma coset_mem : forall a c (H: subgroup G),\n        is_mem (right_coset H a) c <-> is_mem H (c <*> inv a).\n    Proof.\n      intros a c H.\n      unfold right_coset, is_mem.\n      reflexivity.\n    Qed.\n\n    Theorem normal_subgroup_coset_op : forall a b c d (H: normal_subgroup G),\n        is_mem (right_coset H a) c ->\n        is_mem (right_coset H b) d ->\n        is_mem (right_coset H (a <*> b)) (c <*> d).\n    Proof.\n      intros a b c d H.\n      intros c_Coset d_Coset.\n      rewrite coset_mem in c_Coset, d_Coset.\n      rewrite normal_subgroup_membership_commutes in c_Coset.\n      apply coset_mem.\n      apply (subgroup_closed1 _ _ _ c_Coset) in d_Coset.\n      rewrite (normal_subgroup_intro a) in d_Coset.\n      autorewrite with core in d_Coset.\n      rewrite group_assoc, inverse_apply.\n      assumption.\n    Qed.\n  End normal_subgroups.\n\nEnd groups.\n\nHint Rewrite inverse1.\nHint Rewrite inverse2.\nHint Rewrite inverse3.\nHint Rewrite inverse4.\n\nHint Rewrite group_z_r.\nHint Rewrite group_z_l.\nHint Rewrite group_assoc.\n\nHint Rewrite inverse_cancel.\nHint Rewrite inverse_z.\nHint Rewrite inverse_apply.\n\nSection homomorphisms.\n\n  Structure homomorphism (G1 G2: Group) := makeHomomorphism\n    {\n      h :> G1 -> G2 ;\n      homomorphism_z : h (z G1) = (z G2) ;\n      homomorphism_apply : forall a b, h ((op G1) a b) = (op G2) (h a) (h b)\n    }.\n\n  Definition id_homomorphism : forall (G : Group), (homomorphism G G).\n    intros G.\n    apply (makeHomomorphism G G (fun a => a)).\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Lemma abelian_group_inv_homomorphism : forall (G : Group),\n    abelian_group G -> homomorphism G G.\n  Proof.\n    intros G.\n    unfold abelian_group, is_commutative.\n    intros IsCommutative.\n    apply (makeHomomorphism G G (fun a => inv _ a)).\n    apply inverse_z.\n    intros a b.\n    rewrite <- inverse_apply, (IsCommutative _ _).\n    reflexivity.\n  Qed.\n\n  Lemma homomorphism_inverse : forall (G1 G2: Group) (h: homomorphism G1 G2),\n      forall a, h (inv G1 a) = inv G2 (h a).\n  Proof.\n    intros G1 G2 h a.\n    apply (group_cancel_l G2 (h a)).\n    rewrite <- homomorphism_apply, (inverse1 G1), (inverse1 G2).\n    apply homomorphism_z.\n  Qed.\n\n  Lemma homomorphism_assoc : forall (G1 G2: Group) (h: homomorphism G1 G2),\n      forall a b c, op G2 (h (op G1 a b)) (h c) = op G2 (h a) (h (op G1 b c)).\n    intros G1 G2 h a b c.\n    rewrite homomorphism_apply, (group_assoc G2), homomorphism_apply.\n    reflexivity.\n  Qed.\n\n  (* NEXT: kernel of homomorphism is a normal subgroup, image of homomorphism is a subgroup *)\n  (* a \\in kern(f) if f(a) = z *)\n\n  Structure kernel G1 G2 (h: homomorphism G1 G2) :=\n    {\n      K :> set (A G1);\n      kernel_mem : forall a, is_mem _ K a <-> (h a) = (z G2)\n    }.\n\n  Structure image G1 G2 (h: homomorphism G1 G2) :=\n    {\n      I :> set (A G2);\n      image_mem : forall b, is_mem _ I b <-> exists a, (h a) = b\n    }.\n\n  Arguments kernel_mem {G1} {G2} _ _.\n  Arguments image_mem {G1} {G2} _ _.\n\n  Lemma kernel_subgroup : forall (G1 G2: Group) h (K : kernel G1 G2 h),\n      subgroup G1.\n  Proof.\n    intros G1 G2 h K.\n    apply (makeSubgroup _ K).\n    (* show z mapped to z *)\n    apply kernel_mem, homomorphism_z.\n    (* show kernel is closed under operation *)\n    intros a b.\n    rewrite (kernel_mem h K a), (kernel_mem h K b).\n    intros [Ha_z Hb_z].\n    apply kernel_mem.\n    rewrite homomorphism_apply, Ha_z, Hb_z.\n    autorewrite with core; reflexivity.\n    (* show kernel is closed under inverse *)\n    intros a.\n    rewrite (kernel_mem h K a), (kernel_mem h K (inv _ a)), homomorphism_inverse.\n    intros ha_z.\n    rewrite ha_z.\n    autorewrite with core.\n    reflexivity.\n  Defined.\n\n  Lemma kernel_normal_subgroup:\n    forall G1 G2 h (K : kernel G1 G2 h), normal_subgroup G1.\n  Proof.\n    intros G1 G2 h K.\n    apply (makeNormalSubgroup _ (kernel_subgroup _ _ _ K)).\n    intros a b b_kernel.\n    apply kernel_mem.\n    apply kernel_mem in b_kernel.\n    repeat rewrite homomorphism_apply.\n    rewrite b_kernel.\n    autorewrite with core.\n    rewrite homomorphism_inverse.\n    autorewrite with core.\n    reflexivity.\n  Defined.\n\n  Lemma image_subgroup : forall G1 G2 h (I: image G1 G2 h), subgroup G2.\n    intros G1 G2 h I.\n    apply (makeSubgroup _ I).\n    (* show z is in the image *)\n    apply (image_mem _ _ (z _)).\n    exists (z _).\n    apply homomorphism_z.\n    (* show closed under operation *)\n    intros a b.\n    rewrite (image_mem _ _ a), (image_mem _ _ b).\n    intros [[a' a'_def] [b' b'_def]].\n    apply image_mem.\n    exists (op G1 a' b').\n    rewrite homomorphism_apply, a'_def, b'_def; reflexivity.\n    (* show closed under inverse *)\n    intros a.\n    rewrite (image_mem _ _ a).\n    intros [a' a'_def].\n    apply image_mem.\n    exists (inv G1 a').\n    rewrite homomorphism_inverse, a'_def.\n    reflexivity.\n  Defined.\nEnd homomorphisms.\n\nSection quotient_groups.\n  (* represent coset equivalence how?\n     well, I can definitely prove equivalence relationship for\n     left_coset, right cosets, etc. *)\n\n  Arguments kernel_subgroup {G1} {G2} {h}.\n  Arguments kernel_normal_subgroup {G1} {G2} {h}.\n  Arguments image_subgroup {G1} {G2} {h}.\n\n  Arguments right_coset {G} _ _.\n\n  Structure coset (G: Group) (H: subgroup G) : Type := makeCoset\n    {\n      repr :> G ;\n    }.\n\n  Arguments is_mem {A}.\n\n  Definition quotient_mapping (G: Group) (H: subgroup G) (a: G) : coset G H.\n    apply (makeCoset _ _ a).\n  Defined.\n\n  Check quotient_mapping.\n\n  (* must define quotient z, quotient op, quotient inverse *)\n\n  Definition quotient_z G H : coset G H.\n    apply (makeCoset _ _ (z G)).\n  Defined.\n\n  Definition quotient_op 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 _ _ ((op G) a b)).\n  Defined.\n\n  Definition quotient_inv G H: coset G H -> coset G H.\n    intros a.\n    destruct a as [a].\n    exact (makeCoset _ _ ((inv G) a)).\n  Defined.\n\n  Definition quotient_eq_dec G H: forall a b : (coset G H), {a = b} + {a <> b}.\n  Proof.\n    intros a b.\n    destruct a as [a].\n    destruct b as [b].\n    destruct (eq_dec G a b).\n    left; rewrite e; auto.\n    right; contradict n; inversion n; auto.\n  Defined.\n\n  Arguments quotient_mapping {G} _.\n  Arguments quotient_inv {G} _.\n  Arguments quotient_op {G} _.\n  Arguments quotient_z {G} _.\n\n  Definition quotient_group (G: Group) (H: subgroup G) : Group.\n    apply (makeGroup (coset G H)\n                     (quotient_op H)\n                     (quotient_inv H)\n                     (quotient_z H)).\n    (* show quotient op associative *)\n    intros [a] [b] [c].\n    unfold quotient_op; autorewrite with core; reflexivity.\n    (* show quotient z *)\n    intros [a].\n    unfold quotient_op, quotient_z; autorewrite with core; auto.\n    intros [a].\n    unfold quotient_op, quotient_inv, quotient_z; autorewrite with core.\n    auto.\n    apply quotient_eq_dec.\n  Defined.\n\n  Theorem quotient_homomorphism :\n    forall (G : Group) (H: subgroup G),\n      homomorphism G (quotient_group G H).\n  Proof.\n    intros.\n    (* quotient_mapping is map from group to coset group *)\n    remember (quotient_mapping H) as h.\n    unfold quotient_mapping in Heqh.\n    (* must show it is a homomorphism *)\n    apply (makeHomomorphism _ (quotient_group G H) h).\n    rewrite Heqh; auto.\n    intros; rewrite Heqh; auto.\n  Qed.\n\n  (* Old definitions, require term rewriting.  I think in Coq terms per type\n     are unique - need to understand if there's some way to define a structure\n     that comes with a rewriting rule on it. *)\n\n  Definition is_injective' (A: Set) (B: Set) (h: A -> B) (H : set B) :=\n    forall a b, is_mem H (h a) /\\ is_mem H (h b) -> (h a) = (h b) <-> a = b.\n\n  Definition is_surjective' (A: Set) (B: Set) (h: A -> B) (H : set B) :=\n    forall (b : B), is_mem H b <-> exists (a : A), h a = b.\n\n  (* New definitions, I can prove things with these, but they lock in the\n     concept of mapping explicitly to cosets, so the statement of the first iso\n     theorem is less general *)\n  Check Equivalence.\n\n  Definition coset_with_repr G H (a : coset G H) : G.\n    destruct a as [a].\n    exact a.\n  Defined.\n\n  Arguments coset_with_repr {G} {H} _.\n\n  (* a and b are equivalent if there is some c that *)\n\n  Definition coset_equivalence (G: Group) (H: normal_subgroup G)\n             (a b: coset G H) :=\n    exists c,\n      is_mem (right_coset H c) (coset_with_repr a) /\\\n      is_mem (right_coset H c) (coset_with_repr b).\n\n  Instance Coset_Equivalence G H: Equivalence (coset_equivalence G H).\n  Proof.\n    unfold coset_equivalence, coset_with_repr.\n    split.\n    unfold Reflexive; intros x.\n    exists (coset_with_repr x).\n    split; [apply coset_reflexive | apply coset_reflexive].\n    unfold Symmetric; intros x y [c [x_c y_c]].\n    exists c.\n    split; [auto|auto].\n    unfold Transitive; intros x y z.\n    destruct x as [x].\n    destruct y as [y].\n    destruct z as [z].\n    intros [c1 [x_c1 y_c1]] [c2 [y_c2 z_c2]].\n    (* this is easy but annoying *)\n    (* there's some element such that x and y are in the same coset *)\n    (* there's some element such that y and z are in the same coset *)\n    (* so, some element witnesses x and z in the same coset through\n       coset_intersection *)\n    (*\n      x_c1 : is_mem (right_coset H c1) x\n      y_c1 : is_mem (right_coset H c1) y\n      y_c2 : is_mem (right_coset H c2) y\n      z_c2 : is_mem (right_coset H c2) z\n\n      coset_representative\n     : forall (G : Group) (a b : G) (H : subgroup G),\n       is_mem (right_coset H b) a ->\n       forall c : G, is_mem (right_coset H a) c <-> is_mem (right_coset H b) c\n\n     *)\n    auto.\n    exists c1.\n    split; [assumption | auto].\n    rewrite (coset_intersection G c1 c2 y); auto.\n  Qed.\n\n  Arguments coset_equivalence {G} {H}.\n\n  Check coset_equivalence.\n\n  Definition is_injective_equiv (G1 G2: Group) (h: G1 -> G2)\n             (equiv: G1 -> G1 -> Prop) :=\n      forall a b,\n        h a = h b -> (* a and b in same coset *)\n        equiv a b.\n\n  Definition is_surjective (G1 G2: Group) (h: G1 -> G2) H :=\n    forall b, is_mem H b <-> exists a, h a = b.\n\n  (* basically this is trivial because the definition of image / surjective are the same *)\n  Theorem quotient_mapping_is_surjective_to_image:\n    forall G H (I: image G _ (quotient_homomorphism G H)),\n      is_surjective _ _ (quotient_homomorphism G H) I.\n  Proof.\n    intros G H I b.\n    apply image_mem.\n  Qed.\n\n  Definition canonical_mapping G1 G2 h (K: kernel G1 G2 h)\n             (a : quotient_group G1 (kernel_subgroup K)) : G2.\n    destruct a as [a].\n    exact (h a).\n  Defined.\n\n  Definition canonical_isomorphism :\n    forall G1 G2 h (K : kernel G1 G2 h),\n      homomorphism (quotient_group G1 (kernel_subgroup K)) G2.\n  Proof.\n    intros G1 G2 h K.\n    apply (makeHomomorphism _ _ (canonical_mapping G1 G2 h K)).\n    simpl; apply homomorphism_z.\n    intros [a] [b].\n    apply homomorphism_apply.\n  Defined.\n\n\n  (* if canonical isomorphism maps two members to the same element of G2, they\n     are in the same coset of K *)\n\n  Lemma homomorphism_right_coset:\n    forall G1 G2 h (K: kernel G1 G2 h),\n      forall (a b: G1),\n      h a = h b -> is_mem (right_coset (kernel_subgroup K) a) b.\n    intros G1 G2 h K.\n    intros a b ha_eq_b.\n    unfold right_coset, is_mem; simpl.\n    apply kernel_mem.\n    rewrite homomorphism_apply, <- ha_eq_b.\n    rewrite <- homomorphism_apply.\n    autorewrite with core.\n    apply homomorphism_z.\n  Qed.\n\n  Lemma canonical_isomorphism_rewrite:\n    forall G1 G2 h (K: kernel G1 G2 h) a b,\n      (canonical_isomorphism G1 G2 h K) {| repr := a |} =\n      (canonical_isomorphism G1 G2 h K) {| repr := b |} ->\n      let K_Subgroup := kernel_subgroup K in\n      is_mem (right_coset K_Subgroup a) b.\n  Proof.\n    intros G1 G2 h K a b.\n    simpl.\n    apply homomorphism_right_coset.\n  Qed.\n\n  Lemma canonical_isomorphism_restricted :\n    forall G1 G2 h (K: kernel G1 G2 h),\n      let h' := (canonical_isomorphism G1 G2 h K) in\n      forall (a b : coset G1 (kernel_subgroup K)),\n      h' a = h' b <-> (@coset_equivalence G1 (kernel_normal_subgroup K)) a b.\n  Proof.\n    intros G1 G2 h K.\n    simpl.\n    intros a b.\n    unfold canonical_mapping.\n    destruct a as [a].\n    destruct b as [b].\n    unfold coset_equivalence.\n    split.\n    intros ha_eq_hb.\n    apply (homomorphism_right_coset _ _ _ K) in ha_eq_hb.\n    exists a.\n    split; [apply coset_reflexive | auto].\n    (* feels like all of this can be done by the rewriting system :| *)\n    intros [c [c_in_a c_in_b]].\n    unfold is_mem, right_coset in c_in_a, c_in_b.\n    simpl in c_in_a, c_in_b.\n    apply kernel_mem in c_in_a.\n    apply kernel_mem in c_in_b.\n    rewrite homomorphism_apply in c_in_a, c_in_b.\n    rewrite homomorphism_inverse in c_in_a.\n    rewrite homomorphism_inverse in c_in_b.\n    apply (group_add_r _ (h c)) in c_in_a.\n    apply (group_add_r _ (h c)) in c_in_b.\n    autorewrite with core in c_in_a.\n    autorewrite with core in c_in_b.\n    rewrite c_in_a, c_in_b.\n    reflexivity.\n  Qed.\n\n  Definition quotient_group_repr G K (a : quotient_group G K) : coset G K.\n    destruct a as [a].\n    exact (makeCoset _ _ a).\n  Defined.\n\n  Arguments quotient_group_repr {G} {K}.\n\n  Definition quotient_group_equivalence G (K: normal_subgroup G) (a b: quotient_group G K) : Prop.\n    exact (@coset_equivalence G K (quotient_group_repr a) (quotient_group_repr b)).\n  Defined.\n\n  Instance Quotient_Group_Equivalence G H: Equivalence (quotient_group_equivalence G H).\n  Proof.\n    unfold quotient_group_equivalence.\n    (* figure out how to do this later *)\n  Admitted.\n\n  Arguments quotient_group_equivalence {G} {K} _ _.\n\n  Lemma canonical_isomorphism_injectivity : forall G1 G2 h K,\n      let iso := canonical_isomorphism G1 G2 h K in\n      forall a b,\n        iso a = iso b ->\n        @quotient_group_equivalence G1 (kernel_normal_subgroup K) a b.\n  Proof.\n    intros G1 G2 h K.\n    intros iso a b.\n    destruct a as [a].\n    destruct b as [b].\n    intros H.\n    apply canonical_isomorphism_rewrite in H.\n    unfold quotient_group_equivalence, coset_equivalence.\n    simpl.\n    exists a.\n    split; [apply coset_reflexive | assumption].\n  Qed.\n\n  (* FIRST ISOMORPHISM THEOREM *)\n  Theorem quotient_of_homomorphism_is_isomorphic_to_image :\n    forall G1 G2 h (K: kernel G1 G2 h) (I: image G1 G2 h),\n      (* homomorphism, injective, and surjective *)\n      let h' := (canonical_isomorphism G1 G2 h K) in\n      let I_Subgroup := image_subgroup I in\n      let K_Subgroup := kernel_normal_subgroup K in\n      is_injective_equiv (quotient_group G1 K_Subgroup) G2 h'\n                         (@quotient_group_equivalence G1 K_Subgroup) /\\\n      is_surjective (quotient_group G1 K_Subgroup) G2 h' I.\n  Proof.\n    intros G1 G2 h K I.\n    split.\n    (* show injectivity *)\n    unfold is_injective_equiv.\n    apply canonical_isomorphism_injectivity.\n    (* show surjectivity *)\n    unfold is_surjective.\n    intros b.\n    split.\n    intros ImageB.\n    apply image_mem in ImageB.\n    destruct ImageB as [b' b'_def].\n    exists (makeCoset _ _ b').\n    simpl; assumption.\n    simpl.\n    intros Coset.\n    destruct Coset as [[a']].\n    apply image_mem.\n    exists a'; assumption.\n  Qed.\nEnd quotient_groups.\n\nSection klein_4_group.\n  Inductive klein :=\n    k_I | k_X | k_Y | k_Z.\n\n  Definition klein_op k1 k2 :=\n    match (k1, k2) with\n    | (k_I, _) => k2\n    | (_, k_I) => k1\n    | (k_X, k_X) => k_I\n    | (k_X, k_Y) => k_Z\n    | (k_X, k_Z) => k_Y\n    | (k_Y, k_X) => k_Z\n    | (k_Y, k_Y) => k_I\n    | (k_Y, k_Z) => k_X\n    | (k_Z, k_X) => k_Y\n    | (k_Z, k_Y) => k_X\n    | (k_Z, k_Z) => k_I\n    end.\n\n  Definition klein_inv (k1: klein) := k1.\n\n  Lemma klein_z : forall k, klein_op k_I k = k.\n    unfold klein_op.\n    auto.\n  Qed.\n\n  Lemma klein_z2 : forall k, klein_op k k_I = k.\n    intros.\n    unfold klein_op.\n    destruct k; [auto | auto | auto | auto].\n  Qed.\n\n  Lemma klein_abelian : forall x y, klein_op x y = klein_op y x.\n    intros x y.\n    destruct x.\n    rewrite klein_z, klein_z2; reflexivity.\n    destruct y; [auto | auto | auto | auto].\n    destruct y; [auto | auto | auto | auto].\n    destruct y; [auto | auto | auto | auto].\n  Qed.\n\n  Lemma klein_double : forall k, klein_op k k = k_I.\n    simple destruct k; [split; auto | auto | auto | auto].\n  Qed.\n\n  Hint Rewrite klein_double.\n  Hint Rewrite klein_z.\n  Hint Rewrite klein_z2.\n\n  Definition klein_group : Group.\n    apply (makeGroup klein klein_op klein_inv k_I).\n    (* associativity *)\n    - destruct a; destruct b; destruct c; compute; reflexivity.\n    (* identity *)\n    - destruct a; [split; auto | auto | auto | auto].\n    (* inverse *)\n    - intros; unfold klein_inv; rewrite klein_double; auto.\n    - simple destruct x; simple destruct y; auto; right; discriminate.\n  Defined.\n\nEnd klein_4_group.\n\nRequire Import Coq.Logic.FinFun.\n\nSection finite_groups.\n  Import ListNotations.\n\n  Arguments op {g} _ _.\n  Arguments inv {g} _.\n  Notation \"x <*> y\" := (op x y) (at level 50, left associativity).\n\n  Structure finite_group := makeFiniteGroup\n    {\n      G :> Group;\n      seq_g : list G;\n      seq_listing : Listing seq_g;\n    }.\n\n  Structure finite_subgroup (G: Group) := makeFiniteSubgroup\n    {\n      H :> subgroup G;\n      subgroup_seq : list G;\n      subgroup_seq_in : forall g, is_mem _ H g <-> In g subgroup_seq;\n      subgroup_seq_nodup : NoDup subgroup_seq;\n    }.\n\n  Definition cardinality (G: finite_group) :=\n    length (seq_g G).\n\n  Definition subgroup_filter (G: finite_group) (H: subgroup G) l : list G :=\n    filter (fun a => (subgroup_mem _ H a)) l.\n\n  Hint Immediate subgroup_filter.\n\n  Lemma subgroup_filter_NoDup (G: finite_group) H :\n    forall l, NoDup l -> NoDup (subgroup_filter G H l).\n  Proof.\n    unfold subgroup_filter; intros; apply filter_NoDup; assumption.\n  Qed.\n\n  Lemma subgroup_filter_contains (G: finite_group) H :\n    forall g, In g (subgroup_filter G H (seq_g G)) <-> is_mem _ H g.\n  Proof.\n    intros g.\n    split.\n    cut (forall l, In g (subgroup_filter G H l) -> is_mem G H g).\n    intros Cut; apply Cut.\n    (* prove cut *)\n    induction l; simpl; auto.\n    intros H1; contradict H1.\n    destruct (is_mem_dec G H a).\n    simpl.\n    unfold is_mem in i.\n    rewrite i.\n    intros H1.\n    apply in_inv in H1.\n    destruct H1 as [a_is_g | g_in_subgroup].\n    rewrite <- a_is_g; unfold is_mem; auto.\n    apply IHl; assumption.\n    unfold is_mem in n.\n    apply not_true_is_false in n.\n    rewrite n; apply IHl.\n    (* prove being in the subgroup means it is in the filter of the seq *)\n    cut (forall l, is_mem G H g -> In g l -> In g (subgroup_filter G H l)).\n    intros Cut H_mem.\n    remember (seq_listing G) as Q.\n    destruct Q as [NoDup Full].\n    apply (Cut (seq_g G) H_mem (Full g)).\n    (* prove cut *)\n    induction l; auto.\n    intros H_mem In_g.\n    simpl.\n    destruct In_g as [g_is_a | g_in_l].\n    unfold is_mem in H_mem.\n    rewrite g_is_a, H_mem.\n    apply in_eq.\n    destruct (true_dec (subgroup_mem _ H a)).\n    rewrite e; apply in_cons, IHl; assumption.\n    rewrite e; apply IHl; assumption.\n  Qed.\n\n  (* take a subgroup, take a finite group, create a finite subgroup *)\n  Definition subgroup_finite_group (G: finite_group) (H: subgroup G) : finite_subgroup G.\n  Proof.\n    apply (makeFiniteSubgroup _ H (subgroup_filter G H (seq_g G))).\n    (* forall g : G, is_mem G H g <-> In g (subgroup_filter G H (seq_g G)) *)\n    split; apply subgroup_filter_contains.\n    apply subgroup_filter_NoDup, seq_listing.\n  Qed.\n\n  Definition cardinality_subgroup (G: finite_group) (H: subgroup G) : nat :=\n    length (subgroup_filter G H (seq_g G)).\n\n  Theorem klein_group_finite : finite_group.\n    apply (makeFiniteGroup klein_group [k_I; k_X; k_Y; k_Z]).\n    split.\n    2: {\n      unfold Full.\n      destruct a; compute; auto.\n    }\n    apply NoDup_cons.\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply NoDup_cons.\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply NoDup_cons.\n    apply not_in_cons.\n    split ; [discriminate |auto].\n    apply NoDup_cons.\n    auto; auto.\n    apply NoDup_nil.\n  Defined.\n\n  Definition klein_eq_dec k1 k2 :=\n    match k1 with\n    | k_I => match k2 with k_I => true | _ => false end\n    | k_X => match k2 with k_X => true | _ => false end\n    | k_Y => match k2 with k_Y => true | _ => false end\n    | k_Z  => match k2 with k_Z => true | _ => false end\n    end.\n\n  Definition klein_subgroup (k: klein_group) : subgroup klein_group.\n    remember ((fun k' => match k' with\n                           | k_I => true\n                           | _ => klein_eq_dec k k'\n                        end) : set klein_group) as char.\n    apply (makeSubgroup _ char); auto.\n    rewrite Heqchar; cbv; auto.\n    (* closed under op *)\n    destruct k in Heqchar; simple destruct a; simple destruct b;\n      rewrite Heqchar; cbv; intros H; auto.\n    (* closed under op: impossible cases *)\n    0-36: destruct H; auto.\n  Defined.\n\n  Definition klein_subgroup_X := klein_subgroup k_X.\n  Definition klein_subgroup_Y := klein_subgroup k_Y.\n  Definition klein_subgroup_Z := klein_subgroup k_Z.\n\n  Require Import Arith BinNat Nat.\n\n  Lemma finite_subgroup_bounded (G: finite_group) (H : subgroup G):\n    cardinality_subgroup G H <= cardinality G.\n  Proof.\n    remember (seq_g G) as S.\n    unfold cardinality, cardinality_subgroup.\n    assert (forall l, length (subgroup_filter G H l) <= length l) as H0.\n    induction l; auto.\n    unfold subgroup_filter.\n    simpl.\n    destruct (subgroup_mem _ H a).\n    apply le_n_S; auto.\n    apply le_S; auto.\n    (* proved, so we can just apply this *)\n    apply H0.\n  Qed.\n\n  Lemma z_in_seq_G (G: finite_group) : In (z G) (seq_g G).\n  Proof.\n    apply seq_listing.\n  Qed.\n\n  Lemma in_subgroup_seq_is_mem (G: finite_group) (H: finite_subgroup G) :\n    forall c, In c (subgroup_seq _ H) <-> is_mem _ H c.\n  Proof.\n    intros c.\n    split; apply subgroup_seq_in.\n  Qed.\n\n  (* To show Lagrange's Theorem we will use the map from a to its cosets.\n     We will show it is surjective (so every coset shows up)\n     Then we will show every coset has n members *)\n\n  (* Must define a canonical coset map so we can say it's injective *)\n  Definition coset_repr (G: finite_group) (H: subgroup G) g :=\n    hd_error (filter (right_coset G H g) (seq_g G)).\n\n  Theorem coset_repr_always_some (G: finite_group) (H: subgroup G) :\n    forall g, coset_repr G H g <> None.\n  Proof.\n    intros g.\n    unfold not, coset_repr.\n    rewrite hd_error_nil.\n    destruct (seq_listing G) as [NoDup Full].\n    intros filter_def.\n    apply ((filter_empty _ _ _ filter_def g) (Full g)), coset_reflexive.\n  Qed.\n\n  Definition canonical_right_coset (G: finite_group) (H: subgroup G) g :=\n    match coset_repr G H g with\n    (* value should not matter because this branch will never be taken, just needs to check *)\n    | None => g\n    | Some a => a\n    end.\n\n  (* everything that is a member of the coset has the same canonical_right_coset value *)\n  Lemma coset_repr_mem (G: finite_group) (H: subgroup G) g :\n    coset_repr G H g = Some g ->\n    forall a, is_mem _ (right_coset G H g) a <-> coset_repr G H a = Some g.\n  Proof.\n    intros CosetReprG.\n    intros a.\n    split.\n    - rewrite coset_subgroup.\n      intros CosetMem.\n      unfold coset_repr.\n      apply hd_error_cons.\n      unfold coset_repr in CosetReprG.\n      apply hd_error_cons in CosetReprG.\n      destruct CosetReprG as [l2 l2_def].\n      exists l2.\n      rewrite <- l2_def.\n      apply filter_eq.\n      intros b.\n      unfold right_coset.\n      apply subgroup_mem_bool_rewrite.\n      split.\n      + intros; replace (b <*> inv g) with ((b <*> inv a) <*> (a <*> inv g));\n          [apply subgroup_closed; tauto | autorewrite with core; reflexivity].\n      + intros.\n        rewrite <- subgroup_inverse3, inverse_apply in CosetMem.\n        autorewrite with core in CosetMem.\n        replace (b <*> inv a) with ((b <*> inv g) <*> (g <*> inv a));\n          [apply subgroup_closed | autorewrite with core]; auto.\n    - intros CosetSame.\n      unfold coset_repr in CosetSame.\n      apply hd_error_cons in CosetSame.\n      destruct CosetSame as [l2 l2_def].\n      assert (In g (filter (right_coset G H a) (seq_g G))) as g_in_filter.\n      rewrite l2_def; simpl; auto.\n      rewrite filter_In in g_in_filter.\n      rewrite coset_swap; destruct g_in_filter; tauto.\n  Qed.\n\n  Lemma coset_repr_always_mem (G: finite_group) (H: subgroup G):\n    forall g d,\n      coset_repr G H g = Some d -> is_mem _ (right_coset G H d) g.\n  Proof.\n    intros g d.\n    unfold coset_repr.\n    rewrite hd_error_cons.\n    intros [l l_def].\n    apply filter_inv in l_def.\n    rewrite coset_swap; auto.\n  Qed.\n\n  Lemma canonical_right_coset_mem (G: finite_group) (H: subgroup G) g :\n    canonical_right_coset G H g = g ->\n    forall a, is_mem _ (right_coset G H g) a <-> canonical_right_coset G H a = g.\n  Proof.\n    intros CanonicalG a.\n    unfold canonical_right_coset.\n    remember (coset_repr G H a) as q.\n    remember (coset_repr_always_some G H a).\n    destruct q; [| contradict Heqq]; auto.\n    symmetry in Heqq.\n    rewrite coset_repr_mem, Heqq.\n    - split; [intros Q; inversion Q | intros Q; rewrite Q]; auto.\n    - unfold canonical_right_coset in CanonicalG.\n      remember (coset_repr G H g) as q.\n      remember (coset_repr_always_some G H g).\n      destruct q; [| contradict Heqq]; auto.\n      rewrite CanonicalG; reflexivity.\n  Qed.\n\n  Lemma canonical_right_coset_always_mem (G: finite_group) (H: subgroup G):\n    forall g, is_mem _ (right_coset G H (canonical_right_coset G H g)) g.\n  Proof.\n    intros g.\n    unfold canonical_right_coset.\n    remember (coset_repr G H g) as q.\n    destruct q.\n    apply coset_repr_always_mem; auto.\n    remember (coset_repr_always_some G H g) as Q.\n    contradict HeqQ; auto.\n  Qed.\n\n  Lemma coset_reprs_unique (G: finite_group) (H: subgroup G):\n    forall c d,\n      coset_repr G H d = Some c ->\n      coset_repr G H c = Some c.\n  Proof.\n    intros c d.\n    unfold coset_repr.\n    rewrite hd_error_cons.\n    intros [l l_def].\n    rewrite hd_error_cons.\n    exists l.\n    rewrite <- l_def.\n    apply filter_eq.\n    intros a.\n    apply filter_inv in l_def.\n    apply right_coset_mem_bool_rewrite.\n    fold (is_mem G (right_coset G H d) c) in l_def.\n    split; [ | rewrite coset_swap in l_def]; apply coset_trans; auto.\n  Qed.\n\n  (* proof is dumb *)\n  Lemma canonical_right_coset_unique (G: finite_group) (H: subgroup G):\n    forall c d,\n      canonical_right_coset G H d = c ->\n      canonical_right_coset G H c = c.\n  Proof.\n    intros c d.\n    unfold canonical_right_coset.\n    remember (coset_repr G H d) as q1.\n    remember (coset_repr G H c) as q2.\n    destruct q1; destruct q2; symmetry in Heqq1; symmetry in Heqq2.\n    apply coset_reprs_unique in Heqq1.\n    intros J; rewrite <- J, Heqq1 in Heqq2; inversion Heqq2; rewrite <- H1; auto.\n    apply coset_reprs_unique in Heqq1; intros; reflexivity.\n    remember (coset_repr_always_some G H d) as C; intros; contradict HeqC; auto.\n    remember (coset_repr_always_some G H d) as C; intros; contradict HeqC; auto.\n  Qed.\n\n  Compute (canonical_right_coset klein_group_finite klein_subgroup_X k_I).\n  Compute (canonical_right_coset klein_group_finite klein_subgroup_X k_X).\n  Compute (canonical_right_coset klein_group_finite klein_subgroup_X k_Y).\n  Compute (canonical_right_coset klein_group_finite klein_subgroup_X k_Z).\n\n  Definition finite_coset (G: finite_group) (H: subgroup G) g :=\n    (filter (right_coset G H g) (seq_g G)).\n\n  Lemma finite_coset_NoDup (G: finite_group) (H: subgroup G) g :\n    NoDup (finite_coset G H g).\n  Proof.\n    apply filter_NoDup, seq_listing.\n  Qed.\n\n  Lemma finite_coset_same_size_as_subgroup (G: finite_group) (H: finite_subgroup G):\n    forall g, length (finite_coset G H g) = cardinality_subgroup G H.\n  Proof.\n    intros g.\n    remember (fun c => c <*> (inv g)) as f.\n    (* h \\in H, take this to a coset of g *)\n    apply (listisomorphism_NoDup_same_length _ _ f);\n      [ | apply finite_coset_NoDup | apply subgroup_filter_NoDup; apply seq_listing].\n    (* show this is an isomorphism *)\n    split; try split.\n    - rewrite Heqf.\n      intros x y x_in y_in.\n      apply (group_cancel_r _ (inv g)).\n    - unfold ListSurjective.\n      rewrite Heqf.\n      intros c.\n      unfold subgroup_filter.\n      rewrite filter_In.\n      intros [_ c_subgroup].\n      exists (c <*> g).\n      unfold finite_coset.\n      rewrite filter_In.\n      unfold right_coset.\n      autorewrite with core.\n      repeat split; try apply seq_listing; auto.\n    - intros d.\n      unfold finite_coset, subgroup_filter, right_coset.\n      rewrite Heqf; repeat rewrite filter_In.\n      repeat split; try apply seq_listing; tauto.\n  Qed.\nEnd finite_groups.\n\nSection lagrange_theorem.\n\n  Compute (let G := klein_group_finite in\n          let H := klein_subgroup_X in\n          let f := finite_coset G H in\n          let f_inv := canonical_right_coset G H in\n          (expand_partition G f_inv (seq_g G), partition_reprs G f_inv (seq_g G) (eq_dec G))).\n\n  Definition unique_cosets (G: finite_group) (H: subgroup G) :=\n    fold_right\n      (set_add (eq_dec G))\n      (empty_set G)\n      (map (canonical_right_coset G H) (seq_g G)).\n\n  Compute (unique_cosets klein_group_finite (klein_subgroup_X)).\n\n    Check (let G := klein_group_finite in\n          let H := klein_subgroup_X in\n          let f := finite_coset G H in\n          let f_inv := canonical_right_coset G H in\n          expand_partition G f_inv (seq_g G)).\n\n  Compute (let G := klein_group_finite in\n          let H := klein_subgroup_X in\n          let f := finite_coset G H in\n          let f_inv := canonical_right_coset G H in\n          expand_partition G f_inv (seq_g G)).\n\n  Arguments op {g} _ _.\n  Arguments inv {g} _.\n  Notation \"x <*> y\" := (op x y) (at level 50, left associativity).\n\n  Theorem cosets_are_partition (G: finite_group) (H: finite_subgroup G):\n    fn_partition G\n                 (canonical_right_coset G H)\n                 (seq_g G)\n                 (eq_dec G)\n                 (cardinality_subgroup G H).\n  Proof.\n    apply fn_partition_intro.\n    - apply seq_listing.\n    - intros x.\n      rewrite in_map_iff.\n      intros [d [d_def _]].\n      apply canonical_right_coset_unique in d_def.\n      assumption.\n    - intros a coset_equiv.\n      rewrite <- (finite_coset_same_size_as_subgroup _ _ a).\n      apply filter_length_equiv.\n      intros b.\n      destruct ((eq_dec G) (canonical_right_coset G H b) a);\n        symmetry; [ | rewrite <- not_true_iff_false];\n        fold (is_mem _ (right_coset G H a) b).\n      apply canonical_right_coset_mem; auto.\n      intros Not.\n      apply canonical_right_coset_mem in Not; auto.\n  Qed.\n\n  Theorem lagrange_theorem : forall (G: finite_group) (H: finite_subgroup G),\n      length (unique_cosets G H) * cardinality_subgroup G H =\n      cardinality G.\n  Proof.\n    intros G H.\n    unfold cardinality.\n    remember (cosets_are_partition G H) as cosets_fn_partition.\n    rewrite <- (expand_partition_same_size\n                  _\n                  (canonical_right_coset G H)\n                  (seq_g G)\n                  (eq_dec G)\n                  (cardinality_subgroup G H)); auto.\n    rewrite (expand_partition_length\n                  _\n                  (canonical_right_coset G H)\n                  (seq_g G)\n                  (eq_dec G)\n                  (cardinality_subgroup G H)); auto.\n  Qed.\nEnd lagrange_theorem.\n\nSection element_powers.\n  Arguments z {g}.\n  Arguments op {g} _ _.\n  Arguments inv {g} _.\n  Arguments eq_dec {g} _ _.\n\n  Variable (G : Group).\n\n  Notation \"x ** y\" := (op x y) (at level 50, left associativity).\n\n  Fixpoint element_power (g: G) n : G :=\n    match n with\n    | 0 => z\n    | S m => (g ** (element_power g m))\n    end.\n\n  Notation \"g ^^ n\" := (element_power g n) (at level 51, right associativity).\n\n  Theorem element_power_0: forall g: G, g ^^ 0 = z.\n  Proof.\n    intros; simpl; autorewrite with core; auto.\n  Qed.\n\n  Theorem element_power_1: forall g: G, g ^^ 1 = g.\n  Proof.\n    intros; simpl; autorewrite with core; auto.\n  Qed.\n\n  Theorem element_power_z: forall n, z ^^ n = z.\n  Proof.\n    induction n; simpl; autorewrite with core; auto.\n  Qed.\n\n  Hint Rewrite element_power_0.\n  Hint Rewrite element_power_1.\n  Hint Rewrite element_power_z.\n\n  Theorem element_power_additive: forall (g : G) m n,\n      (g ^^ m) ** (g ^^ n) = g ^^ (m + n).\n  Proof.\n    intros g.\n    induction m; intros; simpl; autorewrite with core; auto.\n    rewrite IHm; auto.\n  Qed.\n\n  Theorem element_power_commutes: forall (g : G) m n,\n      (g ^^ m) ** (g ^^ n) = (g ^^ n) ** (g ^^ m).\n  Proof.\n    intros; repeat rewrite element_power_additive; rewrite plus_comm; auto.\n  Qed.\n\n  Theorem element_power_single_commutes: forall (g : G) m,\n      (g ^^m) ** g = g ** (g^^m).\n  Proof.\n    intros.\n    rewrite <- (element_power_1 g) at 2.\n    rewrite <- (element_power_1 g) at 3.\n    rewrite element_power_commutes.\n    autorewrite with core; auto.\n  Qed.\n\n  Lemma element_power_right  (g : G): forall n, (g ^^ n) ** g = g ^^ S n.\n  Proof.\n    induction n; simpl; autorewrite with core; auto.\n    rewrite IHn; simpl; auto.\n  Qed.\n\n  Lemma element_power_left  (g : G): forall n, g ** (g ^^ n) = g ^^ S n.\n  Proof.\n    induction n; simpl; autorewrite with core; auto.\n  Qed.\n\n  Lemma element_power_inverse_right: forall (g: G) n m,\n      n <= m -> (g ^^ m) ** ((inv g) ^^ n) = (g ^^ (m - n)).\n  Proof.\n    intros g.\n    induction n.\n    intros m; autorewrite with core; rewrite Nat.sub_0_r; auto.\n    simpl.\n    intros m H.\n    rewrite <- element_power_single_commutes.\n    rewrite op_assoc.\n    rewrite IHn; try omega.\n    apply (group_cancel_r _ g _ _).\n    autorewrite with core.\n    rewrite element_power_right.\n    assert (S (m - S n) = m - n) as Rewrite by omega.\n    rewrite Rewrite; auto.\n  Qed.\n\n  Lemma element_power_inverse_left: forall (g: G) n m,\n      n <= m -> ((inv g) ^^ n) ** (g ^^ m) = (g ^^ (m - n)).\n  Proof.\n    intros g.\n    induction n.\n    intros m; autorewrite with core; rewrite Nat.sub_0_r; auto.\n    simpl.\n    intros m H.\n    rewrite <- op_assoc.\n    rewrite IHn; try omega.\n    apply (group_cancel_l _ g _ _).\n    autorewrite with core.\n    rewrite element_power_left.\n    assert (S (m - S n) = m - n) as Rewrite by omega.\n    rewrite Rewrite; auto.\n  Qed.\n\n  Lemma element_power_inverse: forall (g: G) n,\n      inv (g^^n) = (inv g)^^n.\n  Proof.\n    intros g; induction n; simpl; autorewrite with core; auto.\n    rewrite IHn, element_power_right; auto.\n  Qed.\n\n  Hint Rewrite element_power_additive.\n  Hint Rewrite element_power_inverse_right.\n  Hint Rewrite element_power_inverse_left.\n  Hint Rewrite element_power_inverse.\nEnd element_powers.\n\nSection element_order.\n  Arguments z {g}.\n  Arguments op {g} _ _.\n  Arguments inv {g} _.\n  Arguments eq_dec {g} _ _.\n\n  Notation \"x ** y\" := (op x y) (at level 50, left associativity).\n  Arguments element_power {G} _ _.\n  Notation \"g ^^ n\" := (element_power g n) (at level 51, right associativity).\n\n  Hint Rewrite element_power_additive.\n  Hint Rewrite element_power_inverse_right.\n  Hint Rewrite element_power_inverse_left.\n  Hint Rewrite element_power_inverse.\n  Hint Rewrite element_power_1.\n  Hint Rewrite element_power_0.\n  Hint Rewrite element_power_z.\n\n  Definition iterated_powers (G: Group) (g : G) m : (list G) :=\n    map (fun n => g ^^ n)  (List.seq 0 m).\n\n  Theorem iterated_powers_works (G: Group) : forall g n m h,\n      nth_error (iterated_powers G g n) m = Some h -> g ^^ m = h.\n  Proof.\n    intros g n m h.\n    unfold iterated_powers.\n    intros H.\n    cut (m < n).\n    intros Cut.\n    assert ((nth_error (map (fun n => g ^^ n) (seq 0 n)) m) = Some (g ^^ m)).\n    apply map_nth_error, nth_error_seq; auto.\n    rewrite H in H0.\n    inversion H0; auto.\n    assert (nth_error (map (fun n : nat => g ^^ n) (seq 0 n)) m <> None) as H'.\n    contradict H.\n    rewrite H; discriminate.\n    apply nth_error_Some in H'.\n    rewrite map_length, seq_length in H'.\n    auto.\n  Qed.\n\n  Lemma iterated_powers_length (G: Group):\n    forall g n, length (iterated_powers G g n) = n.\n  Proof.\n    intros g n; unfold iterated_powers; rewrite map_length, seq_length; auto.\n  Qed.\n\n  Theorem iterated_powers_works2 (G: Group): forall g n m,\n      m < n -> nth_error (iterated_powers G g n) m = Some (g ^^ m).\n  Proof.\n    intros g n m m_lt_n.\n    rewrite <- (iterated_powers_length G g) in m_lt_n.\n    rewrite <- nth_error_Some in m_lt_n.\n    remember (nth_error (iterated_powers G g n) m) as h.\n    destruct h; [auto | contradict m_lt_n; auto].\n    symmetry in Heqh; apply iterated_powers_works in Heqh; rewrite Heqh; auto.\n  Qed.\n\n  Lemma finite_group_iterated_powers_repeats (G: finite_group):\n    forall g, ~ NoDup (iterated_powers G g (S (cardinality G))).\n  Proof.\n    intros g IteratedPowersNoDup.\n    remember (S (cardinality G)) as N.\n    assert (incl (iterated_powers G g N) (seq_g G)) as Powers_Subset.\n    unfold incl; intros a H; apply seq_listing.\n    apply (NoDup_incl_length IteratedPowersNoDup) in Powers_Subset.\n    rewrite iterated_powers_length in Powers_Subset.\n    rewrite HeqN in Powers_Subset.\n    unfold cardinality in Powers_Subset.\n    omega.\n  Qed.\n\n  Require Import Classical.\n\n  (* must show this to be able to show power cycle\n     approach requires classical logic - I imagine there is a way to do this\n     with a more direct \"find\" *)\n  Lemma not_nodup_means_different_elems: forall (A: Type) (l: list A),\n      ~NoDup l ->\n      (exists m i,\n          m < length l\n          /\\ (m + i) < length l\n          /\\ i > 0\n          /\\ nth_error l m = nth_error l (m + i)).\n  Proof.\n    intros A.\n    induction l; intros l_NoDup.\n    contradict l_NoDup; apply NoDup_nil.\n    rewrite NoDup_cons_iff in l_NoDup.\n    apply not_and_or in l_NoDup.\n    destruct l_NoDup as [In_a | Not_NoDup].\n    apply NNPP in In_a.\n    apply in_split in In_a.\n    destruct In_a as [l1 [l2 l_eq]].\n    exists 0; exists (S (length l1)).\n    repeat split; try simpl; try omega; rewrite l_eq.\n    rewrite app_length; simpl; try omega.\n    rewrite nth_error_app2; try omega.\n    rewrite Nat.sub_diag; simpl; auto.\n    (* induction step, must 'step forward' and add 1 to both m and n *)\n    apply IHl in Not_NoDup.\n    destruct Not_NoDup as [m [n [m_length [n_bounded [n_gt_0 list_eq]]]]].\n    exists (S m); exists n.\n    repeat split; try simpl; try omega; auto.\n  Qed.\n\n  Lemma power_cycle (G: Group) (g: G): forall m n,\n      n > m -> g ^^n = g^^m -> g ^^ (n - m) = z.\n  Proof.\n    induction m; intros n; autorewrite with core.\n    rewrite Nat.sub_0_r; auto.\n    intros n_gt_Sm.\n    simpl.\n    intros H.\n    (* would be nice to not do everything in H here *)\n    apply (group_add_r _ ((inv g)^^m)) in H.\n    rewrite <- op_assoc in H.\n    rewrite element_power_inverse_right in H; try omega.\n    rewrite element_power_inverse_right in H; try omega.\n    rewrite Nat.sub_diag in H.\n    simpl in H.\n    autorewrite with core in H.\n    apply (group_cancel_r _ g).\n    rewrite element_power_right.\n    replace (S (n - S m)) with (n -  m); try omega.\n    autorewrite with core; auto.\n  Qed.\n\n  Theorem every_finite_group_element_has_a_power_cycle (G: finite_group):\n    forall (g : G), exists m, 0 < m < S (cardinality G) /\\ g^^m = z.\n  Proof.\n    intros g.\n    remember (finite_group_iterated_powers_repeats G g) as RepeatedCycles.\n    destruct HeqRepeatedCycles.\n    remember (S (cardinality G)) as N.\n    apply not_nodup_means_different_elems in RepeatedCycles.\n    destruct RepeatedCycles as [m [i [m_lt_len [n_lt_len [i_gt_0 Cycle]]]]].\n    assert ((nth_error (iterated_powers G g N) m) = Some (g ^^ m)) as G_power_m.\n    apply iterated_powers_works2;\n      rewrite iterated_powers_length in m_lt_len; auto.\n    assert ((nth_error (iterated_powers G g N) (m + i)) = Some (g ^^ (m + i))) as G_power_n.\n    apply iterated_powers_works2;\n      rewrite iterated_powers_length in n_lt_len; auto.\n    rewrite iterated_powers_length in n_lt_len.\n    rewrite iterated_powers_length in m_lt_len.\n    rewrite G_power_m, G_power_n in Cycle.\n    exists i.\n    repeat split; try omega.\n    inversion Cycle as [A].\n    symmetry in A; apply power_cycle in A; replace (m + i - m) with i in A; try omega; auto.\n  Qed.\n\n  Lemma power_cycle_mult (G: Group):\n    forall (g: G) (k m: nat), g ^^m = z -> g ^^ k * m = z.\n  Proof.\n    intros g; induction k; intros m g_cycle; simpl; auto.\n    rewrite <- element_power_additive.\n    rewrite g_cycle.\n    autorewrite with core.\n    apply IHk; auto.\n  Qed.\n\n  Lemma power_cycle_mod (G: Group):\n    forall (g: G) (m n: nat), m > 0 -> (g ^^ m = z) -> (g ^^ n) = g ^^ (n mod m).\n  Proof.\n    intros g m n m_gt_0 m_power.\n    assert (g ^^ (m * (n / m)) = z).\n    rewrite Nat.mul_comm; apply power_cycle_mult; auto.\n    apply (group_cancel_r _ z).\n    rewrite <- H0 at 2.\n    autorewrite with core.\n    rewrite plus_comm.\n    rewrite <- (Nat.div_mod n m); auto; try omega.\n  Qed.\n\n  Lemma iterated_powers_contains_z (G: Group):\n    forall (g: G) n, n > 0 -> In z (iterated_powers G g n).\n  Proof.\n    intros g.\n    induction n; intros n_gt_0; try omega.\n    simpl; left; auto.\n  Qed.\n\n  (* what I really want to show is that the first m powers are unique\n     (no duplicates).  where this is challenging is that the k we get from the\n     power cycle lemma above is not guaranteed to be the first k *)\n\n  Definition powers_of_g (G: finite_group) (g: G) :=\n    let n := S (cardinality G) in\n    combine (seq 0 n) (iterated_powers G g n).\n\n  Theorem in_powers_of_g (G: finite_group) (g: G) : forall m h,\n      In (m, h) (powers_of_g G g) <-> 0 <= m < (S (cardinality G)) /\\ g^^m = h.\n  Proof.\n    intros m h.\n    unfold powers_of_g.\n    remember (S (cardinality G)) as N.\n    split.\n    - intro H_in_zip.\n      assert (0 <= m < N) as m_bound.\n      apply in_combine_l, in_seq in H_in_zip; omega.\n      destruct (combine_nth_error2 _ _ _ _ m h H_in_zip) as [n [nth_eq nth_power]].\n      assert (n < N) as n_bound.\n      apply nth_error_Some2 in nth_eq; rewrite seq_length in nth_eq; auto.\n      remember (nth_error_seq N 0 n).\n      replace m with (0 + m) in nth_eq by omega; apply (nth_error_seq N 0 _) in n_bound.\n      rewrite n_bound in nth_eq.\n      inversion nth_eq as [m_eq_n].\n      rewrite m_eq_n in nth_power.\n      split; [omega | apply (iterated_powers_works _ _ N _ _)]; auto.\n    - intros [m_bound m_eq].\n      assert (m < N) as m_lt_bound by omega.\n      assert (m < N) as m_lt_bound2 by omega.\n      apply (nth_error_seq _ 0 _) in m_lt_bound.\n      simpl in m_lt_bound.\n      apply (iterated_powers_works2 G g) in m_lt_bound2.\n      apply (nth_error_In _ m), combine_nth_error; rewrite <- m_eq; split; assumption.\n  Qed.\n\n  Definition nonzero_powers (G: finite_group) (g: G) := tail (powers_of_g G g).\n  Definition is_pair_zero (G: finite_group) :=\n    (fun (p: (nat * G)) => if eq_dec (snd p) z then true else false).\n\n  Definition order (G: finite_group) (g : G) :=\n    fst (hd (0, z) (filter (is_pair_zero G) (nonzero_powers G g))).\n\n  Lemma order_filter_nonempty (G: finite_group) (g : G):\n    exists p tl, (filter (is_pair_zero G) (nonzero_powers G g)) = p :: tl.\n  Proof.\n    destruct (every_finite_group_element_has_a_power_cycle G g) as\n        [h [h_bound g_to_h]].\n    assert (In (h, z) (powers_of_g G g)) as in_powers_of_g.\n    apply in_powers_of_g; split; try omega; auto.\n    assert (In (h, z) (nonzero_powers G g)) as in_nonzero_powers.\n    unfold powers_of_g, iterated_powers; unfold nonzero_powers; simpl.\n    apply (nth_error_In _ (h - 1)), combine_nth_error.\n    split; [ | rewrite <- g_to_h; apply map_nth_error]; replace h with (1 + (h - 1)) at 2 by omega; apply nth_error_seq; omega.\n    assert (In (h, z) (filter (is_pair_zero G) (nonzero_powers G g))) as in_filter.\n    apply filter_In; try split; auto; simpl; unfold is_pair_zero; simpl; destruct (@eq_dec G z z); auto.\n    assert (filter (is_pair_zero G) (nonzero_powers G g) <> []) as NonZeroFilter.\n    remember (filter (is_pair_zero G) (nonzero_powers G g)) as Q; destruct Q;\n      [contradict in_filter | discriminate].\n    remember (filter (is_pair_zero G) (nonzero_powers G g)) as Q; destruct Q;\n      [contradict NonZeroFilter | auto]; auto.\n    exists p; exists Q; auto.\n  Qed.\n\n  Lemma order_filter_cut (G: finite_group) (g: G): forall a b,\n      In (a, b) (filter (is_pair_zero G) (nonzero_powers G g)) -> a > 0.\n  Proof.\n    intros a b.\n    rewrite filter_In.\n    unfold nonzero_powers, powers_of_g.\n    simpl.\n    intros [H _].\n    apply in_combine_l in H.\n    rewrite in_seq in H; omega.\n  Qed.\n\n  Theorem order_always_positive (G: finite_group) (g : G):\n    order G g > 0.\n  Proof.\n    unfold order.\n    destruct (order_filter_nonempty G g) as [x [tl x_eq]].\n    rewrite x_eq.\n    simpl.\n    destruct x.\n    assert (In (n, a) (filter (is_pair_zero G) (nonzero_powers G g))).\n    (* dumb, but works *)\n    destruct (nonzero_powers G g);\n      [simpl in x_eq; contradict x_eq; discriminate | rewrite x_eq; simpl; tauto].\n    apply (order_filter_cut _ g n a); assumption.\n  Qed.\n\n  Lemma nth_error_empty: forall (A: Type) n, @nth_error A [] n = None.\n  Proof.\n    intros A; induction n; simpl; reflexivity.\n  Qed.\n\n  Lemma nth_error_empty2: forall (A: Type) n a, @nth_error A [] n <> Some a.\n  Proof.\n    intros A; induction n; simpl; discriminate.\n  Qed.\n\n  Lemma nth_error_map2: forall (A B: Type) (l: list A) (f: A -> B) (n: nat) (b: B),\n      nth_error (map f l) n = Some b -> exists a, nth_error l n = Some a /\\ f a = b.\n  Proof.\n    intros A B; induction l; intros f n b nth_error_eq.\n    simpl in nth_error_eq.\n    remember (nth_error_empty2 B n b) as Q.\n    contradict nth_error_eq; assumption.\n    destruct n; simpl in nth_error_eq.\n    inversion nth_error_eq.\n    exists a; simpl; tauto.\n    apply IHl in nth_error_eq.\n    destruct nth_error_eq as [c H].\n    exists c.\n    simpl; tauto.\n  Qed.\n\n  Theorem element_raised_to_order (G: finite_group) (g: G):\n    g ^^ (order G g) = z.\n  Proof.\n    unfold order.\n    unfold powers_of_g.\n    destruct (order_filter_nonempty G g) as [p [l H]].\n    rewrite H; simpl.\n    unfold nonzero_powers in H.\n    destruct p as [m h].\n    (* feels like we need this, but maybe we don't *)\n    assert (In (m, h) (filter (is_pair_zero G) (tl (powers_of_g G g)))) as H1.\n    rewrite H; simpl; left; tauto.\n    assert (h = z) as H2.\n    apply filter_In in H1; destruct H1 as [_ PairZero].\n    unfold is_pair_zero in PairZero.\n    simpl in PairZero; destruct (eq_dec h z);\n      [assumption | contradict PairZero; discriminate].\n    apply filter_In in H1.\n    destruct H1 as [H1 _].\n    unfold powers_of_g in H1.\n    (* must show g ^^ m = h *)\n    unfold iterated_powers in H1; simpl in H1.\n    apply combine_nth_error2 in H1.\n    destruct H1 as [i [i_value i_power]].\n    remember (nth_error_Some2 _ _ _ _ i_value) as i_bound.\n    destruct Heqi_bound.\n    rewrite seq_length in i_bound.\n    rewrite (nth_error_seq (cardinality G) _ i i_bound) in i_value.\n    inversion i_value as [m_eq_Si].\n    (* must finally show result through i_power *)\n    apply nth_error_map2 in i_power.\n    destruct i_power as [a [a_value a_equal]].\n    rewrite nth_error_seq, i_value in a_value by omega.\n    inversion a_value as [m_eq_a]. rewrite m_eq_Si, m_eq_a.\n    simpl; rewrite <- H2; assumption.\n  Qed.\n\n  Compute (order klein_group_finite k_Y).\n\n  Arguments order {G0} _.\n\n  Lemma order_bound (G: finite_group) (g: G) :\n    order g <= (cardinality G).\n  Proof.\n    unfold order.\n    unfold nonzero_powers.\n    remember (filter (is_pair_zero G) (tl (powers_of_g G g))) as q.\n    destruct q; simpl.\n    - omega.\n    - cut (In p (tl (powers_of_g G g))).\n      intros Cut.\n      simpl in Cut.\n      destruct p.\n      simpl.\n      apply in_combine_l, in_seq in Cut; omega.\n      cut (In p (filter (is_pair_zero G) (tl (powers_of_g G g)))).\n      rewrite filter_In; tauto.\n      rewrite <- Heqq; simpl; tauto.\n  Qed.\n\n  Definition smallest_power_cycle (G: Group) (g : G) (n : nat) :=\n    n > 0 /\\ g^^n = z /\\ (forall m, 0 < m < n -> g^^m <> z).\n\n  (* show order is smallest power cycle *)\n  Theorem order_is_smallest  (G: finite_group) (g : G) :\n    (smallest_power_cycle G g) (order g).\n  Proof.\n    unfold smallest_power_cycle.\n    remember (order_bound G g) as OrderBound.\n    destruct HeqOrderBound.\n    repeat split;\n      [apply order_always_positive | apply element_raised_to_order | auto].\n    intros m m_lt_g Not.\n    (* the approach here should be that order g was the first *)\n    remember (order g) as n.\n    assert (n = order g) as n_is_order_g by assumption.\n    unfold order in n_is_order_g.\n    destruct (order_filter_nonempty G g) as [p [l p_rest]].\n    rewrite p_rest in n_is_order_g; simpl in n_is_order_g.\n    apply filter_split in p_rest.\n    destruct p_rest as [l2 [l3 [l2_l3_eq no_z_smaller]]].\n    assert (In (m, z) (powers_of_g G g)) as InMz.\n    apply in_powers_of_g; split; [omega | auto].\n    assert (In (m, z) l2) as Contradiction.\n    unfold nonzero_powers in l2_l3_eq.\n    simpl in l2_l3_eq.\n    apply (nth_error_In l2 (m - 1)).\n    rewrite <- (nth_error_app1 _ (p :: l3)), <- l2_l3_eq, <- combine_nth_error.\n    replace m with (1 + (m - 1)) at 2 by omega.\n    split; [ |\n            rewrite <- Not; apply map_nth_error;\n            replace m with (1 + (m - 1)) at 2 by omega]; apply nth_error_seq; omega.\n    (* show m - 1 < length l2, which it should be *)\n    apply combine_seq_length in l2_l3_eq; auto; omega.\n    (* once we have the bound on m it is straightforward *)\n    apply no_z_smaller in Contradiction.\n    unfold is_pair_zero in Contradiction.\n    simpl in Contradiction; destruct (eq_dec z z) as [always | impossible];\n      contradict Contradiction.\n    discriminate.\n    contradict impossible; reflexivity.\n  Qed.\n\n  Lemma powers_of_g_nth_error (G: finite_group) (g: G) :\n    forall n m a, nth_error (powers_of_g G g) n = Some (m, a) -> m = n /\\ g ^^ m = a.\n  Proof.\n    intros n m a Hma.\n    assert (n < S (cardinality G)) as n_bound.\n    apply nth_error_Some2 in Hma; unfold powers_of_g in Hma;\n      rewrite combine_length, seq_length, iterated_powers_length in Hma;\n      rewrite Nat.min_id in Hma; assumption.\n    assert (In (m, a) (powers_of_g G g)) as ma_in_powers.\n    apply nth_error_In in Hma; assumption.\n    rewrite in_powers_of_g in ma_in_powers.\n    unfold powers_of_g in Hma.\n    rewrite <- combine_nth_error in Hma.\n    destruct Hma as [Hm Hn].\n    apply iterated_powers_works in Hn.\n    rewrite nth_error_seq in Hm; [ simpl in Hm; inversion Hm; tauto | assumption ].\n  Qed.\n\n\n  (* show the element powers are a subgroup *)\n\n  Definition element_subgroup_mem (G: finite_group) (g : G) : (set G) :=\n    let power_list := iterated_powers G g (S (cardinality G)) in\n    (fun h => match count_occ eq_dec power_list h with\n                                      0 => false\n                                    | _ => true\n                                    end).\n\n  Lemma iterated_powers_in (G : Group) (g: G): forall a n,\n      In a (iterated_powers G g n) <-> exists m, m < n /\\ g ^^ m = a.\n  Proof.\n    intros a n; unfold iterated_powers; rewrite in_map_iff.\n    split; simpl.\n    intros [x [g_to_x x_in_seq]].\n    exists x.\n    apply in_seq in x_in_seq; split; auto; omega.\n    intros [m [m_lt_n g_to_m]].\n    exists m.\n    split; auto; apply in_seq; omega.\n  Qed.\n\n  Lemma element_subgroup_mem_exists_n (G: finite_group) (g : G) :\n    forall a,\n      is_mem G (element_subgroup_mem G g) a <->\n      (exists n,\n          n < S (cardinality G) /\\\n          g ^^ n = a).\n  Proof.\n    intros a.\n    unfold element_subgroup_mem, is_mem.\n    remember (count_occ eq_dec _ a) as Q.\n    split.\n    destruct Q; intros H.\n    contradict H; auto.\n    assert (count_occ eq_dec\n                      (iterated_powers G g (S (cardinality G))) a > 0) as H1\n      by omega.\n    apply count_occ_In in H1.\n    apply (iterated_powers_in _ _ _ (S (cardinality G))); auto.\n    intros [n [n_bounded g_to_n]].\n    apply (iterated_powers_works2 G g (S (cardinality G))) in n_bounded.\n    apply nth_error_In in n_bounded.\n    rewrite g_to_n in n_bounded.\n    apply (count_occ_In eq_dec) in n_bounded.\n    destruct Q; try omega; auto.\n  Qed.\n\n  Lemma element_subgroup_mem_z (G: finite_group) (g: G) :\n    is_mem G (element_subgroup_mem G g) z.\n  Proof.\n    assert (S (cardinality G) > 0) as Gt by omega.\n    remember (iterated_powers_contains_z G g (S (cardinality G)) Gt) as Q.\n    destruct HeqQ.\n    unfold is_mem, element_subgroup_mem.\n    rewrite (count_occ_In eq_dec _ _) in Q.\n    destruct (count_occ eq_dec _ z); try omega; auto.\n  Qed.\n\n  Lemma element_subgroup_mem_closed (G: finite_group) (g : G) :\n    forall a b,\n      is_mem G (element_subgroup_mem G g) a /\\\n      is_mem G (element_subgroup_mem G g) b ->\n      is_mem G (element_subgroup_mem G g) (a ** b).\n  Proof.\n    intros a b [a_mem b_mem].\n    remember (order_always_positive G g) as order_positive.\n    remember (order_bound G g) as order_bounded.\n    apply element_subgroup_mem_exists_n in a_mem.\n    apply element_subgroup_mem_exists_n in b_mem.\n    destruct a_mem as [h [h_bound g_to_h]].\n    destruct b_mem as [i [g_bound g_to_i]].\n    rewrite <- g_to_h, <- g_to_i.\n    rewrite element_power_additive.\n    (* h + i % group order *)\n    assert (g ^^ (h + i) = g ^^ ((h + i) mod (order g))) as ThingWeCanProve.\n    apply power_cycle_mod; [apply order_always_positive | apply element_raised_to_order].\n    rewrite ThingWeCanProve.\n    assert (((h + i) mod (order g)) < (order g)).\n    apply Nat.mod_upper_bound; omega.\n    assert (((h + i) mod (order g)) < (S (cardinality G))) by omega.\n    apply element_subgroup_mem_exists_n.\n    exists ((h + i) mod (order g)); auto.\n  Qed.\n\n  Lemma element_subgroup_mem_inverse (G: finite_group) (g : G) :\n    forall a,\n      is_mem G (element_subgroup_mem G g) a ->\n      is_mem G (element_subgroup_mem G g) (inv a).\n  Proof.\n    intros a a_mem.\n    apply element_subgroup_mem_exists_n in a_mem.\n    destruct a_mem as [h [h_bound g_to_h]].\n    remember (order_always_positive G g) as order_positive.\n    remember (order_bound G g) as order_bounded.\n    apply element_subgroup_mem_exists_n.\n    destruct (lt_eq_lt_dec h (order g)) as [[h_lt_k | h_eq_k] | h_gt_k].\n    exists ((order g) - h).\n    split; try omega.\n    rewrite <- g_to_h.\n    rewrite element_power_inverse.\n    apply (group_cancel_r _ (g ^^ h)).\n    autorewrite with core; try omega.\n    replace ((order g) - h + h) with (order g) by omega.\n    rewrite Nat.sub_diag.\n    autorewrite with core; apply element_raised_to_order.\n    (* option 2, h = k *)\n    exists (order g).\n    rewrite h_eq_k, element_raised_to_order in g_to_h.\n    rewrite <- g_to_h; rewrite element_raised_to_order; split;\n      [omega | autorewrite with core; reflexivity].\n    (* option 3, h > k *)\n    (* cycle is at k = 5, we are given h = 12 *)\n    (* actual inverse is at 3 *)\n    (* we first replace with the case *)\n    exists ((order g) - (h mod (order g))).\n    split; try omega.\n    assert (g ^^ h = g ^^ h mod (order g)) as replace_mod.\n    apply power_cycle_mod; [omega | apply element_raised_to_order].\n    rewrite replace_mod in g_to_h.\n    rewrite <- g_to_h.\n    apply (group_cancel_r _ (g ^^ (h mod (order g)))).\n    autorewrite with core; auto.\n    assert (h mod (order g) < (order g)) as h_mod_k_bound.\n    apply Nat.mod_upper_bound; omega.\n    replace ((order g) - h mod (order g) + h mod (order g)) with (order g) by omega.\n    rewrite Nat.sub_diag.\n    autorewrite with core; apply element_raised_to_order; reflexivity.\n  Qed.\n\n  Definition element_subgroup (G: finite_group):\n    forall (g: G), subgroup G.\n  Proof.\n    intros g.\n    remember (iterated_powers G g (S (cardinality G))) as power_list.\n    apply (makeSubgroup G (element_subgroup_mem G g)).\n    apply (element_subgroup_mem_z G g).\n    apply (element_subgroup_mem_closed G g).\n    apply (element_subgroup_mem_inverse G g).\n  Defined.\n\n  Definition element_subgroup_finite (G: finite_group):\n    forall (g: G), finite_subgroup G.\n  Proof.\n    intros g.\n    apply (makeFiniteSubgroup G (element_subgroup G g)\n                              (fold_right (set_add eq_dec) (empty_set G)\n                                          (iterated_powers G g (S (cardinality G))))).\n    intros h.\n    rewrite fold_set_add_in, (element_subgroup_mem_exists_n G g h), iterated_powers_in; tauto.\n    apply fold_set_NoDup; reflexivity.\n  Defined.\n\n  Lemma mod_squeeze: forall a b c, c <> 0 -> a >= b -> a < c -> b < c -> (a - b) mod c = 0 <-> a = b.\n  Proof.\n    intros a b c c_eq_0 a_lt_c b_lt_c.\n    split; [ | intros H; rewrite H; rewrite Nat.sub_diag, Nat.mod_0_l; auto].\n    intros ModSqueeze.\n    destruct (lt_eq_lt_dec a b) as [[a_lt_b | a_eq_b] | a_gt_b]; try omega.\n    rewrite Nat.mod_divide in ModSqueeze; [|assumption]; try omega; apply Nat.divide_pos_le in ModSqueeze; omega.\n  Qed.\n\n  Theorem power_isomorphism (G: finite_group) (g: G):\n    ListIsomorphism (fun n => g^^n)\n                    (seq 0 (order g))\n                    (filter (fun a : G => element_subgroup_mem G g a) (seq_g G)).\n  Proof.\n    remember (order_always_positive G g) as OrderPositive.\n    remember (order_bound G g) as OrderBound.\n    assert (order g <> 0) as OrderNeq0 by omega.\n    repeat split.\n    - (* injectivity: must use order g is minimum here *)\n      remember (order_is_smallest G g) as SmallestPowerCycle.\n      unfold smallest_power_cycle in SmallestPowerCycle.\n      destruct SmallestPowerCycle as [OrderGt0 [OrderPowerCycle BoundRaiseToZ]].\n      intros m n m_bound n_bound gm_eq_gn.\n      rewrite in_seq in m_bound.\n      rewrite in_seq in n_bound.\n      destruct (lt_eq_lt_dec m n) as [[m_lt_n | m_eq_n] | m_gt_n];\n        [ remember ((n - m) mod (order g)) as Value; symmetry in gm_eq_gn |\n          assumption |\n          remember ((m - n) mod (order g)) as Value];\n        apply power_cycle in gm_eq_gn; [|omega | |omega];\n          rewrite (power_cycle_mod _ _ (order g)) in gm_eq_gn; try assumption;\n          assert (Value < (order g)) as nm_bound.\n        1, 3: rewrite HeqValue; apply Nat.mod_upper_bound; omega.\n        1, 2: remember (BoundRaiseToZ Value).\n        1, 2: assert (~(Value > 0)) as ValueNeqGt0.\n        1, 3: intros Not; apply n0; [split; omega | rewrite HeqValue; assumption].\n        1, 2: apply not_gt, le_n_0_eq in ValueNeqGt0;\n          destruct m_bound as [_ m_bound];\n          destruct n_bound as [_ n_bound];\n          simpl in m_bound;\n          simpl in n_bound.\n        1: symmetry; apply (mod_squeeze n m (order g)); try omega.\n        1: apply (mod_squeeze m n (order g)); try omega.\n        (* ugh *)\n    - (* surjectivity: *)\n      unfold ListSurjective.\n      intros h; rewrite filter_In.\n      intros [_ h_is_sugroup_mem].\n      unfold element_subgroup_mem in h_is_sugroup_mem.\n      remember (count_occ eq_dec (iterated_powers G g (S (cardinality G))) h) as q.\n      assert (count_occ eq_dec (iterated_powers G g (S (cardinality G))) h > 0)\n        as CountGt0.\n      destruct q; [contradict h_is_sugroup_mem; discriminate | omega].\n      rewrite <- count_occ_In in CountGt0.\n      rewrite iterated_powers_in in CountGt0.\n      destruct CountGt0 as [m [m_bound g_raised_to_m]].\n      exists (m mod (order g)).\n      split.\n      * apply in_seq; split; [apply Nat.le_0_l | apply Nat.mod_upper_bound]; omega.\n      * rewrite <- power_cycle_mod;\n          [assumption | omega | apply element_raised_to_order].\n    - (* mapping *)\n      intros m m_in_order.\n      apply filter_In; split; [apply seq_listing | auto].\n      assert (In (g^^m) (iterated_powers G g (S (cardinality G)))) as g_m_in_iterated_powers.\n      rewrite iterated_powers_in.\n      exists m.\n      rewrite in_seq in m_in_order.\n      split; [omega  |reflexivity].\n      rewrite (count_occ_In eq_dec) in g_m_in_iterated_powers.\n      unfold element_subgroup_mem.\n      remember (count_occ eq_dec _ _) as q.\n      destruct q; [omega | reflexivity].\n  Qed.\n\n  Theorem order_is_cardinality_subgroup (G: finite_group):\n    forall (g: G), cardinality_subgroup G (element_subgroup_finite G g) = (order g).\n  Proof.\n    intros g; symmetry.\n    unfold cardinality_subgroup, element_subgroup, subgroup_filter; simpl.\n    replace (order g) with (length (seq 0 (order g)));\n      [| rewrite seq_length; reflexivity].\n    apply (listisomorphism_NoDup_same_length _ _ (fun n => g ^^n));\n      [apply power_isomorphism | apply seq_NoDup | apply filter_NoDup, seq_listing].\n  Qed.\n\n  Lemma order_divides_group (G: finite_group) : forall g,\n      exists k, k * (@order G g) = (cardinality G).\n  Proof.\n    intros g.\n    rewrite <- order_is_cardinality_subgroup.\n    exists (length (unique_cosets G (element_subgroup G g))).\n    apply (lagrange_theorem G (element_subgroup_finite G g)).\n  Qed.\nEnd element_order.\n\nCompute (iterated_powers klein_group k_Y 4).\nCompute (@element_power klein_group k_Y 1).\nCompute (nth_error (iterated_powers klein_group_finite k_Y 4) 1).\n", "meta": {"author": "tildedave", "repo": "coq-playground", "sha": "860f5e68b6c0caed8a038f128ee298b504607c85", "save_path": "github-repos/coq/tildedave-coq-playground", "path": "github-repos/coq/tildedave-coq-playground/coq-playground-860f5e68b6c0caed8a038f128ee298b504607c85/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8079715739444212}}
{"text": "Require Import List Omega.\nSet Implicit Arguments.\n\n(* Part 1: introduction to proof search *)\n\nPrint plus.\n\nExample four_plus_three : 4 + 3 = 7.\n  reflexivity.\nQed.\n\nPrint four_plus_three.\n\nInductive plusR : \n      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\nHint Constructors plusR.\n\n\n\nTheorem plus_plusR : forall n m,\n  plusR n m (n + m).\n  induction n. \n  auto. simpl. auto.\nQed.\n\nTheorem plusR_plus : forall n m r,\n  plusR n m r\n  -> r = n + m.\n  induction 1.\n  auto. simpl. auto. \nQed.\n\nExample four_plus_three' : plusR 4 3 7.\n  apply PlusS.\n  apply PlusS.\n  apply PlusS.\n  apply PlusS.\n  apply PlusO.\n  (* manual search *)\n\nRestart.\n  info_auto.\n\n\nQed.\n\n\nPrint four_plus_three'.\n\nExample five_plus_three : plusR 5 3 8.\n  auto 6.\n\nRestart.\n  info_auto 6.\n\nQed.\n\n(* Backtracking and Unification *)\n\nExample seven_minus_three : \n    exists x, x + 3 = 7.\n  exists 0.\n  Restart.\n  exists 4.\n  reflexivity.\nQed.  \n\nExample seven_minus_three' : \n   exists x, plusR x 3 7.\n eexists.\n  apply PlusS.\n  apply PlusS.\n  apply PlusS.\n  apply PlusS.\n  apply PlusO.\nQed.\n\nNotation \"[ x ]\" := \n  (ex_intro _ x _).\n\nPrint seven_minus_three'.\n\nExample seven_minus_three'' : \n   exists x, plusR x 3 7.\n  info_eauto 6.\nQed.\nPrint seven_minus_three''.\n\n\nExample seven_minus_four' : exists x, plusR 4 x 7.\n  eauto 6.\nQed.\n\nPrint seven_minus_four'.\n\n(* Unification for functional definitions *)\n\nSearchRewrite (O + _).\n\nHint Immediate plus_O_n.\n\nLemma plusS : forall n m r,\n  n + m = r\n  -> S n + m = S r.\n  \n  intros. simpl. auto.\nQed.  \n\nHint Resolve plusS.\n\nExample seven_minus_three''' : \n       exists x, x + 3 = 7.\n  info_eauto 6.\nQed.\n\nPrint seven_minus_three'''.\n\nExample seven_minus_four : exists x, 4 + x = 7.\n  eauto 6.\nQed.\n\nExample seven_minus_four_zero : \n       exists x, 4 + x + 0 = 7.\n  eauto 6.\nAbort.\n\nLemma plusO : forall n m,\n  n = m\n  -> n + 0 = m.\n  intros.  omega.\nQed. \n\nPrint plusO.\n\nHint Resolve plusO.\n\nExample seven_minus_four_zero : exists x, 4 + x + 0 = 7.\n  eauto 6.\nQed.\n\n(* Path 2: Synthesizing Expressions *)\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : exp\n| Plus : exp -> exp -> 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 : \n  forall var, eval var \n   (Plus Var (Plus (Const 8) Var)) \n   (var + (8 + var)).\n  info_auto.\nQed.\n\nExample eval1' : forall var, \n  eval var (Plus Var (Plus (Const 8) Var)) \n            (2 * var + 8).\n  auto.\nAbort.\n\nTheorem EvalPlus' : \n   forall var e1 e2 n1 n2 n, eval var e1 n1\n  -> eval var e2 n2\n  -> n1 + n2 = n\n  -> eval var (Plus e1 e2) n.\n  intros.\n  rewrite <- H1.\n  auto.\nQed.\n\nHint Resolve EvalPlus'.\n\nHint Extern 1 (_ = _) => abstract omega.\n\nExample eval1' : forall var, \n   eval var (Plus Var (Plus (Const 8) Var)) \n   (2 * var + 8).\n  info_eauto.\nQed.\n\nPrint eval1'.\n\nExample synthesize1 : exists e, \n   forall var, eval var e (var + 7).\n  eauto.\nQed.\n\nPrint synthesize1.\n\nExample synthesize2 : exists e, \n   forall var, eval var e (2 * var + 8).\n  eauto.\nQed.\n\nPrint synthesize2.\n\nExample synthesize3 : exists e, \n     forall var, eval var e (30 * var + 42).\n  eauto 32.\nQed.\n\nPrint synthesize3.\n\nTheorem EvalConst' : forall var n m, n = m\n  -> eval var (Const n) m.\n  intros. rewrite H. auto.\nQed.\n\n\nHint Resolve EvalConst'.\n\nTheorem zero_times : forall n m r,\n  r = m\n  -> r = 0 * n + m.\n  simpl. auto.\nQed.\n\n\nHint Resolve zero_times.\n\nTheorem EvalVar' : forall var n,\n  var = n\n  -> eval var Var n.\n  intros. rewrite <- H. auto.\nQed.\n\n\nHint Resolve EvalVar'.\n\nTheorem plus_0 : forall n r,\n  r = n\n  -> r = n + 0.\n  auto.\nQed.\n\nTheorem times_1 : forall n, n = 1 * n.\n  auto.\nQed.\n\nHint Resolve plus_0 times_1.\n\nRequire Import Arith Ring.\n\nTheorem combine : forall x k1 k2 n1 n2,\n  (k1 * x + n1) + (k2 * x + n2) = (k1 + k2) * x + (n1 + n2).\n  intros; ring.\nQed.\n\nHint Resolve combine.\n\nTheorem linear : forall e, exists k, exists n,\n  forall var, eval var e (k * var + n).\n  intros.\n  induction e; eauto.\n  destruct IHe1 as [k1 [n1 H1]].\n  destruct IHe2 as [k2 [n2 H2]].\n  eauto. \nQed.\n\n\n", "meta": {"author": "ulysses4ever", "repo": "certif-sw-2014", "sha": "846fb4dc34af70a0ab1ca153311b8bfff2a13827", "save_path": "github-repos/coq/ulysses4ever-certif-sw-2014", "path": "github-repos/coq/ulysses4ever-certif-sw-2014/certif-sw-2014-846fb4dc34af70a0ab1ca153311b8bfff2a13827/lecture-11-examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.8079715703083021}}
{"text": "\n(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2020/03/05.                                             *)\n(* Due: 2020/03/09, 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(*      Myself                                                       *)\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, 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, 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\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 (\u5076\u6570); if yes, [0] will be assigned into [Y].\nDo they express equivalent meaning? 1: Yes. 2: No.\n*)\n\nDefinition my_choice: Z := 1.\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\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\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 := 2.\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 _ _ _ _ _ (triple1 x y)).\n  apply (hoare_seq _ _ _ _ _ (triple2 x y)).\n  apply (triple3 x y).\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 a c e).\n  - apply (R_trans _ _ _ H H0).\n  - apply (R_trans _ _ _ H1 H2).\nQed.\n(** [] *)\n\nEnd PreOrder.\n\n\n\n(* Thu Mar 5 01:20:37 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/Assignment1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.9073122125886485, "lm_q1q2_score": 0.8077748267986861}}
{"text": "(*\n  Exercises for <Software Foundations> CH6.\n  Author : Brethland, Late 2019.\n*)\n\nFrom Coq Require Import Peano.\nFrom Coq Require Import Nat.\nFrom Coq Require Import Arith.\nFrom Coq Require Import List.\n\nModule Logic.\n\nLemma and_intro : forall (A B : Prop),\n  A -> B -> and A B.\nProof.\n  intros.\n  split.\n  apply H.\n  apply H0.\nQed.\n\nExample and_exercise : forall (n m : nat),\n  n + m = 0 -> and (n = 0) (m = 0).\nProof.\n  intros.\n  apply and_intro.\n  - induction n.\n    + auto.\n    + inversion H.\n  - induction m.\n    + auto.\n    + rewrite plus_comm in H.\n      inversion H.\nQed.\n\nLemma proj1 : forall (P Q : Prop),\n  P /\\ Q -> P.\nProof.\n  intros.\n  destruct H.\n  auto.\nQed.\n\nLemma proj2 : forall (P Q : Prop),\n  P /\\ Q -> Q.\nProof.\n  intros.\n  destruct H.\n  auto.\nQed.\n\nLemma and_commut : forall (P Q : Prop),\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros.\n  destruct H.\n  split.\n  auto.\n  auto.\nQed.\n\nLemma 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  trivial. trivial. trivial.\nQed.\n\n(* ex falso quodlibet *)\n\nFact not_implies_our_not : forall (P : Prop),\n  ~ P -> (forall (Q :Prop), P -> Q).\nProof.\n  intros.\n  destruct H.\n  auto.\nQed.\n\nTheorem not_False :   ~ False. \nProof.   \n  unfold not. \n  intros H. \n  destruct H. \nQed.\n\nLemma contradiction_implies_everything : forall (P Q : Prop),\n  (P /\\ ~ P) -> Q.\nProof.\n  intros P Q [HA HNA].\n  unfold not in HNA.\n  apply HNA in HA.\n  inversion HA.\nQed.\n\nLemma double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H0.\n  auto.\nQed.\n\nLemma contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros P Q H.\n  unfold not.\n  intros.\n  apply H in H1.\n  apply H0 in H1.\n  inversion H1.\nQed.\n\nFact not_both_true_false : forall P : Prop,\n  ~ (P /\\ ~ P).\nProof.\n  intros.\n  unfold not.\n  intros [HA HNA].\n  apply HNA in HA.\n  inversion HA.\nQed.\n\nTheorem not_true_is_false : forall b : bool,   \n  b <> true -> b = false. \nProof. \n  intros [] H.\n  - unfold not in H.\n    exfalso.\n    apply H.\n    auto.\n  - auto.\nQed.\n\nLemma True_is_true : True.\nProof.\n  apply I.\nQed.\n\nLemma iff_sym : forall (P Q : Prop),\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  auto.\n  auto.\nQed.\n\nLemma not_true_iff_false : forall b : bool,\n  b <> true <-> b = false.\nProof.\n  intros b.\n  split.\n  apply not_true_is_false.\n  intros.\n  rewrite H.\n  intros H'.\n  inversion H'.\nQed.\n\nLemma or_distriutes_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 [HR | [HQ HR]].\n    + auto.\n    + auto.\n  - intros [[HP | HQ] [HP' | HR]].\n    + auto.\n    + auto.\n    + auto.\n    + auto.\nQed.\n\nRequire Import Coq.Setoids.Setoid.\n\nLemma mult_0 : forall (n m : nat),\n  n * m = 0 <-> n = 0 \\/ m = 0.\nAdmitted.\n\nLemma mult_0_3 : forall (n m p : nat),\n  n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros.\n  rewrite 2 mult_0.\n  rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2.\n  auto.\nQed.\n\nLemma exists_example : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  auto.\nQed.\n\nLemma dist_not_exists : forall (X : Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H0 as [x E].\n  apply E in H.\n  inversion H.\nQed.\n\nLemma dist_exists_or : forall (X : Prop) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros.\n  split.\n  - intros [x0 [HP | HQ]].\n    left. exists x0. auto.\n    right. exists x0. auto.\n  - intros [[x1 E1] | [x2 E2]].\n    exists x1. left. auto.\n    exists x2. right. auto.\nQed.\n\n(* Fixpoint In {X : Type} (x : X) (l : list X) :=\n  match l with\n  | nil => False\n  | cons e es => x = e \\/ In x es\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\nExample In_example :  forall n, In n [2;4] -> exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. auto.\n  - exists 2. auto.\nQed.\n\nLemma In_map : forall (X Y : Type) (f : X -> Y) (l : list X) (x : X),\n  In x l -> In (f x) (map f l).\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    destruct H.\n    + rewrite <- H. left. auto.\n    + apply IHl in H.\n      right. apply H.\nQed.\n\nLemma In_map_iff : forall (X Y : Type) (f : X -> Y) (l : list X) (y : Y),\n  In y (map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n  intros. split.\n  induction l.\n  - simpl. intros. inversion H.\n  - simpl. intros [HA | HB].\n    + exists a. split. auto. left. auto.\n    + apply IHl in HB. destruct HB. exists x.\n      split. destruct H. auto. right. destruct H. auto.\n  - intros [x [HA HB]].\n    rewrite <- HA. apply In_map. auto.\nQed.\n\nLemma In_app_iff : forall X l1 l2 (x : X),\n  In x (l1 ++ l2) <-> In x l1 \\/ In x l2.\nProof.\n  intros.\n  split.\n  induction l1.\n  - intros. simpl in H. right. auto.\n  - simpl. intros [HA | HB].\n    + left. left. auto.\n    + apply IHl1 in HB. (* or_assoc *)\n      destruct HB.\n      ++ left. right. auto.\n      ++ right. auto.\n  - apply in_or_app.\nQed.\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) :=\n  match l with\n  | [] => True\n  | e :: es => P e /\\ All P es\n  end.\n\nLemma or_forall : forall {X : Type} (P1 P2 : Prop),\n  (forall x : X, P1) \\/ (forall x : X, P2) -> (forall x : X, P1 \\/ P2).\nProof.\n  intros.\n  destruct H.\n  auto. auto.\nQed.\n\nLemma All_In : forall T (P : T -> Prop) (l : list T),\n  (forall x : T, In x l -> P x) <-> All P l.\nProof.\n  intros. split.\n  - induction l.\n    + intros.\n      unfold All. auto.\n    + intros. simpl. split. \n      ++ apply H. simpl. left. auto.\n      ++ apply IHl. simpl in H.\n         intros. apply H.\n         right. auto.\n  - induction l.\n    + intros. inversion H0.\n    + intros.\n      destruct H.\n      destruct H0 as [HA | HB].\n      ++ rewrite <- HA. auto.\n      ++ apply IHl. auto. auto.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) :=\n  fun n => if odd n then Podd n else Peven n.\n\nRequire Import Unicode.Utf8.\n\nTheorem combine_odd_even_intro :   \u2200 (Podd Peven : nat \u2192 Prop) (n : nat),\n  (odd n = true \u2192 Podd n) \u2192\n  (odd n = false \u2192 Peven n) \u2192\n  combine_odd_even Podd Peven n.\nProof.\n  intros.\n  unfold combine_odd_even.\n  destruct (odd n).\n  - apply H. auto.\n  - apply H0. auto.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n   \u2200 (Podd Peven : nat \u2192 Prop) (n : nat),\n  combine_odd_even Podd Peven n \u2192\n  odd n = true \u2192 \n  Podd n.\nProof.\n  intros.\n  unfold combine_odd_even in H.\n  rewrite H0 in H. auto.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  \u2200 (Podd Peven : nat \u2192 Prop) (n : nat),\n  combine_odd_even Podd Peven n \u2192\n  odd n = false \u2192\n  Peven n. \nProof.\n(*   Too trivial.*)\nAdmitted.\n\nAxiom functional_extensionality : \u2200 {X Y: Type} {f g : X \u2192 Y}, \n  (\u2200 (x:X), f x = g x) \u2192 f = g.\n\nExample function_equality_ex2 :   (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 All_In.\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=   \n  match l1 with   \n  | [] => l2   \n  | x :: l1' => rev_append l1' (x :: l2)   \n  end. \n\nDefinition tr_rev {X} (l : list X) : list X :=   \n  rev_append l [].\n\nLemma rev_append_app: forall {X : Type} (l l1 l2: list X),\n    rev_append l (l1 ++ l2) = rev_append l l1 ++ l2.\n  intros.\n  generalize dependent l2.\n  generalize dependent l1.\n  induction l as [| h t IH].\n  - auto.\n  - intros. simpl.\n    apply (IH (h::l1)).\nQed.\n\nLemma tr_rev_app : forall {X : Type} (l l1 : list X),\n  rev_append l l1 = tr_rev l ++ l1.\nProof.\n  intros. generalize dependent l1. unfold tr_rev.\n  induction l.\n  - auto.\n  - simpl. intros.\n    rewrite <- (@rev_append_app X l [a] l1).\n    auto.\nQed.\n\nTheorem app_silly : forall X (l1 l2 l : list X),\n  l1 = l2 -> l1 ++ l = l2 ++ l.\nProof.\n  intros.\n  rewrite H.\n  auto.\nQed.\n\nCheck functional_extensionality.\n\nCheck f_equal.\n\nLemma tr_rev_correct : \u2200 X, @tr_rev X = @rev X. \nProof.\n  intros.\n  apply functional_extensionality.\n  intros. \n  induction x.\n  - auto.\n  - simpl. unfold tr_rev. simpl.\n    rewrite tr_rev_app.\n    apply (@app_silly X (tr_rev x) (rev x) [a]).\n    auto.\nQed.\n\nFixpoint evenb (n : nat) :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S n') => evenb n'\n  end.\n\nLemma neg_id : forall b : bool, negb (negb b) = b.\nProof.\n  intros [].\n  - auto.\n  - auto.\nQed.\n\nLemma evenb_S: forall n : nat, evenb (S n) = negb (evenb n).\nProof.\n  intros n.\n  induction n.\n  - auto.\n  - rewrite -> IHn.\n    rewrite -> neg_id.\n    auto.\nQed.\n\n\nTheorem evenb_double_conv : \u2200 n, \u2203 k, n = if evenb n then double k else S (double k). \nProof.\n  intros.\n  induction n.\n  - exists 0. auto.\n  - destruct IHn.\n    destruct (evenb n) eqn:HA.\n    + rewrite evenb_S. rewrite HA. simpl.\n      exists x. auto.\n    + rewrite evenb_S. rewrite HA. simpl.\n      exists (S x). rewrite H. unfold double. simpl.\n      rewrite plus_n_Sm. auto.\nQed.\n\nLemma andb_true_iff : \u2200 b1 b2:bool, andb b1 b2 = true \u2194 b1 = true \u2227 b2 = true.\nProof. \n  intros. split.\n  - intros.\n    destruct b1. \n    + simpl in H. auto.\n    + inversion H.\n  - intros [HA HB].\n    rewrite HA. rewrite HB. auto.\nQed.\n\nLemma orb_true_iff : \u2200 b1 b2,  (b1 || b2)%bool = true \u2194 b1 = true \u2228 b2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    destruct b1.\n    + left. auto.\n    + simpl in H. right. auto.\n  - intros [HA | HB].\n    + rewrite HA. auto.\n    + rewrite HB.\n      destruct b1. auto. auto.\nQed. \n\nTheorem beq_nat_true_iff : \u2200 n1 n2 : nat,   beq_nat n1 n2 = true \u2194 n1 = n2. \nProof.   \n  intros n1 n2. split.   \n  - apply beq_nat_true.   \n  - intros H. rewrite H. rewrite <- beq_nat_refl. \n    reflexivity. \nQed. \n\nTheorem beq_nat_false_iff : \u2200 x y : nat,   beq_nat x y = false \u2194 x \u2260 y. \nProof.\n  intros. split.\n  - intros.\n    unfold not. intros. apply beq_nat_true_iff in H0.\n    rewrite H0 in H. inversion H.\n  - generalize (beq_nat_true_iff x y).\n    destruct beq_nat.\n    + intros. destruct H0. apply H. auto.\n    + intros. auto.\nQed.\n\nFixpoint beq_list {A : Type} (beq : A -> A -> bool) (l1 l2 : list A) :=\n  match l1,l2 with\n  | [] , y :: et => false\n  | x :: es , [] => false\n  | []      , [] => true\n  | x :: es , y :: et => andb (beq x y) (beq_list beq es et)\n  end.\n\n\nLemma beq_list_true_iff :   \u2200 A (beq : A \u2192 A \u2192 bool),     \n  (\u2200 a1 a2, beq a1 a2 = true \u2194 a1 = a2) \u2192     \n  \u2200 l1 l2, beq_list beq l1 l2 = true \u2194 l1 = l2. \nProof.\n  intros.\n  split.\n  - intros.\n    generalize dependent l2.\n    induction l1.\n    + intros. destruct l2. auto. inversion H0.\n    + intros. destruct l2.\n      ++ inversion H0.\n      ++ simpl in H0. apply andb_true_iff in H0. destruct H0.\n         apply H in H0. rewrite H0. apply IHl1 in H1. rewrite H1. auto.\n  - intros. generalize dependent l2. induction l1.\n    + intros. destruct l2. auto. inversion H0.\n    + intros. destruct l2.\n      ++ inversion H0.\n      ++ simpl. apply andb_true_iff. split.\n         inversion H0. apply H. auto.\n         apply IHl1. inversion H0. auto.\nQed.\n\nTheorem forallb_true_iff : \u2200 X test (l : list X),    forallb test l = true \u2194 All (fun x => test x = true) l.\nProof.\n  intros. split.\n  - intros. induction l.\n    + simpl. auto.\n    + simpl. split.\n      simpl in H. apply andb_true_iff in H. destruct H. auto.\n      apply IHl. simpl in H. apply andb_true_iff in H. destruct H. auto.\n  - intros. induction l.\n    + simpl. auto.\n    + simpl. apply andb_true_iff. split.\n      simpl in H. destruct H. auto.\n      simpl in H. destruct H. apply IHl in H0. auto.\nQed.\n\nTheorem excluded_middle_irrefutable: \u2200 (P:Prop),   \u00ac \u00ac (P \u2228 \u00ac P). \nProof.\n  intros.\n  unfold not. intros. apply H.\n  right. intros. apply H. left. auto.\nQed.\n\nTheorem not_exists_dist :\n  (forall (P : Prop), P \\/ (~ P)) ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros.\n  destruct (H (P x)).\n  + auto.\n  + exfalso. apply H0. exists x. auto.\nQed.\n\nDefinition peirce := \u2200 P Q: Prop,   ((P\u2192Q)\u2192P)\u2192P. \nDefinition double_negation_elimination := \u2200 P:Prop,   ~~P \u2192 P. \nDefinition de_morgan_not_and_not := \u2200 P Q:Prop,   ~(~P \u2227 \u00acQ) \u2192 P\u2228Q. \nDefinition implies_to_or := \u2200 P Q:Prop,   (P\u2192Q) \u2192 (\u00acP\u2228Q).\nDefinition excluded_middle := forall (P : Prop), P \\/ (~ P).\n\nLemma double_negation_excluded_middle_iff : \n  excluded_middle <-> double_negation_elimination.\nProof.\n  split.\n  - intros. unfold excluded_middle in H.\n    unfold double_negation_elimination.\n    unfold not. intros.\n    specialize (H P). destruct H. auto.\n    unfold not in H. elim H0. intros.\n    apply H0. auto.\n  - intros. unfold excluded_middle.\n    unfold double_negation_elimination in H.\n    intros. apply H. unfold not in *. auto.\nQed.", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Coq11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8077713323491124}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 1 *)\n\nRequire Import Frap Pset1Sig.\n\n(* The first part of this assignment involves the [bool] datatype,\n * which has the following definition.\n * <<\n     Inductive bool :=\n     | true\n     | false.\n   >>\n * We will define logical negation and conjunction of Boolean values,\n * and prove some properties of these definitions.\n *)\n\n(* Define [Neg] so that it implements Boolean negation, which flips\n * the truth value of a Boolean value.\n *)\nDefinition Neg (b : bool) : bool := \n  match b with\n    | true => false\n    | false => true\n  end.\n\n(* For instance, the negation of [true] should be [false].\n * This proof should follow from reducing both sides of the equation\n * and observing that they are identical.\n *)\nTheorem Neg_true : Neg true = false.\nProof.\nsimplify.\nequality.\nQed.\n(* Negation should be involutive, meaning that if we negate\n * any Boolean value twice, we should get the original value back.\n\n * To prove a fact like this that holds for all Booleans, it suffices\n * to prove the fact for both [true] and [false] by using the\n * [cases] tactic.\n *)\nTheorem Neg_involutive : forall b : bool, Neg (Neg b) = b.\nProof.\n  simplify.\n  cases b; try (simplify; equality).\nQed.\n\n(* Define [And] so that it implements Boolean conjunction. That is,\n * the result value should be [true] exactly when both inputs\n * are [true].\n *)\nDefinition And (x y : bool) : bool := \n  match x,y with\n    | true, true => true\n    | _, _ => false\n  end.\n\n(* Here are a couple of examples of how [And] should act on\n * concrete inputs.\n *)\nTheorem And_true_true : And true true = true.\nProof.\nsimplify.\nequality.\nQed.\n\nTheorem And_false_true : And false true = false.\nProof.\nsimplify.\nequality.\nQed.\n\n(* Prove that [And] is commutative, meaning that switching the order\n * of its arguments doesn't affect the result.\n *)\nTheorem And_comm : forall x y : bool, And x y = And y x.\nProof.\nsimplify.\ncases x; (cases y; simplify; equality).\nQed.\n(* Prove that the conjunction of a Boolean value with [true]\n * doesn't change that value.\n *)\nTheorem And_true_r : forall x : bool, And x true = x.\nProof.\nsimplify.\ncases x; simplify; equality.\nQed.\n\n(* In the second part of this assignment, we will work with a simple language\n * of imperative arithmetic programs that sequentially apply operations\n * to a natural-number-valued state.\n\n * The [Prog] datatype defines abstract syntax trees for this language.\n *)\n\nPrint Prog.\n\n\n(* Define [run] such that [run p n] gives the final state\n * that running the program [p] should result in, when the\n * initial state is [n].\n *)\nFixpoint run (p : Prog) (initState : nat) : nat :=\n  match p with\n    | Done => initState\n    | AddThen e1 p1 => run p1 (initState + e1)\n    | MulThen e2 p2 => run p2 (initState * e2)\n    | DivThen e3 p3 => run p3 (initState / e3)\n    | VidThen e4 p4 => run p4 (e4 / initState)\n    | SetToThen e5 p5 => run p5 e5\nend.\n\nPrint Prog.\nExample test := (MulThen 5 (AddThen 2 Done)).\nCompute run test 2.\nTheorem run_Example1 : run Done 0 = 0.\nProof.\nsimplify.\nequality.\nQed.\n\nTheorem run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7.\nProof.\n  simplify.\n  equality.\nQed.\n\n\nTheorem run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6.\nProof.\nsimplify.\nequality.\nQed.\n(* Define [numInstructions] to compute the number of instructions\n * in a program, not counting [Done] as an instruction.\n *)\nFixpoint numInstructions (p : Prog) : nat :=\n  match p with \n    | Done => 0\n    | AddThen e1 p1   => 1 + numInstructions (p1)\n    | MulThen e1 p1   => 1 + numInstructions (p1)\n    | DivThen e1 p1   => 1 + numInstructions (p1)\n    | VidThen e1 p1   => 1 + numInstructions (p1)\n    | SetToThen e1 p1 => 1 + numInstructions (p1)\n  end.\n\nTheorem numInstructions_Example :\n  numInstructions (MulThen 5 (AddThen 2 Done)) = 2.\nProof.\n  simplify.\n  equality.\nQed.\n\n(* Define [concatProg] such that [concatProg p1 p2] is the program\n * that first runs [p1] and then runs [p2].\n *)\nFixpoint concatProg (p1 p2 : Prog) : Prog := \n  match p1 with\n    | Done => p2\n    | AddThen e1 res => AddThen e1 (concatProg res p2)\n    | MulThen e1 res => MulThen e1 ( concatProg res p2)\n    | DivThen e1 res => DivThen e1 ( concatProg res p2)\n    | VidThen e1 res => VidThen e1 ( concatProg res p2)\n    | SetToThen e1 res => SetToThen e1 (concatProg res p2)\n  end.\n\nExample a := concatProg (AddThen 1 Done) (MulThen 2 Done). \nCompute a.\n\nTheorem concatProg_Example :\n     concatProg (AddThen 1 Done) (MulThen 2 Done)\n     = AddThen 1 (MulThen 2 Done).\nProof.\nsimplify.\nequality.\nQed.\n\nTheorem concat_base\n  : forall (p1: Prog), concatProg p1 Done = p1.\nProof.\n  simplify.\n  induct p1; simplify; equality.\nQed.\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 *)\nTheorem concatProg_numInstructions\n  : forall (p1 p2 : Prog), numInstructions (concatProg p1 p2)\n                      = numInstructions p1 + numInstructions p2.\nProof.\nsimplify.\ninduction p1; simplify; equality; simplify; rewrite IHp1; equality.\nQed.\n(* Prove that running the concatenation of [p1] with [p2] is\n   equivalent to running [p1] and then running [p2] on the\n   result. *)\nTheorem concatProg_run\n  : forall (p1 p2 : Prog) (initState : nat),\n    run (concatProg p1 p2) initState =\n    run p2 (run p1 initState).\nProof.\ninduct p1; simplify; equality.\nQed.\n(* Read this definition and understand how division by zero is handled. *)\nFixpoint runPortable (p : Prog) (state : nat) : bool * nat :=\n  match p with\n  | Done => (true, state)\n  | AddThen n p => runPortable p (n+state)\n  | MulThen n p => runPortable p (n*state)\n  | DivThen n p =>\n      if n ==n 0 then (false, state) else\n      runPortable p (state/n)\n  | VidThen n p =>\n      if state ==n 0 then (false, 0) else\n      runPortable p (n/state)\n  | SetToThen n p =>\n      runPortable p n\n  end.\nArguments Nat.div : simpl never. (* you don't need to understand this line *)\n\n\n\n\n\nLemma run_portable_helper: forall (p: Prog) (n: nat),\n  runPortable (DivThen 0 p) n = (false, n).\nProof.\n  simplify.\n  cases (n);simplify; equality.\nQed.\n\nLemma run_portable_helper_vid: forall (p: Prog) (n: nat),\n  runPortable (VidThen n p) 0 = (false, 0).\nProof.\n  simplify.\n  cases (n);simplify; equality.\nQed.\n\n\nLemma run_portable_helper2: forall (p: Prog) (n n2: nat),\n  n <> 0 -> runPortable (DivThen n p) n2 = runPortable p (n2 / n).\nProof.\n  simplify.\n  cases (n ==n 0).\n  contradiction.\n  equality.\nQed.\n\n\nLemma run_portable_helper_vid2: forall (p: Prog) (n n2: nat),\n  n2 <> 0 -> runPortable (VidThen n p) n2 = runPortable p (n / n2).\nProof.\n  simplify.\n  cases (n2 ==n 0).\n  contradiction.\n  equality.\nQed.\n\n\nLemma run_portable_helper3: forall(p: Prog) (n s0 s1: nat),  \n   (runPortable (DivThen n p) s0 = (true, s1)) -> n <> 0.\nProof.\nintros.\ncases n.\nassert(H2: runPortable (DivThen 0 p) s0 = (false, s0)).\napply run_portable_helper.\nrewrite H in H2.\nequality.\nlinear_arithmetic.\nQed.\n\nLemma run_portable_helper_vid3: forall(p: Prog) (n s0 s1: nat),  \n   (runPortable (VidThen n p) s0 = (true, s1)) -> s0 <> 0.\nProof.\nintros.\ncases s0.\nassert(H2: runPortable (VidThen n p) 0 = (false, 0)).\napply run_portable_helper_vid.\nrewrite H in H2.\nequality.\nlinear_arithmetic.\nQed.\n\n\n(* Prove that running the concatenation [p] using [runPortable]\n   coincides with using [run], as long as [runPortable] returns\n   [true] to confirm that no divison by zero occurred. *)\n   \nLemma runPortable_run : forall p s0 s1,\n  runPortable p s0 = (true, s1) -> run p s0 = s1.\nProof.\nintros.\ninduct p; try(simplify; equality); try(apply IHp in H; simplify; try(rewrite plus_comm); try(rewrite mult_comm); try apply H).\n\napply IHp.\nrewrite <- H.\nrewrite run_portable_helper2.\nequality.\nassert(H2: runPortable (DivThen n p) s0 = (true, s1) -> n <> 0).\napply run_portable_helper3.\napply H2.\napply H.\n\napply IHp.\nrewrite <- H.\nrewrite run_portable_helper_vid2.\nequality.\nassert(H2: runPortable (VidThen n p) s0 = (true, s1) -> s0 <> 0).\napply run_portable_helper_vid3.\napply H2.\napply H.\n\nQed.\n\nFixpoint validate_helper p (b : bool) :=\n    match p with\n    | Done => true\n    | AddThen n p => if n ==n 0 then validate_helper p b else validate_helper p true\n    | MulThen n p => if n ==n 0 then validate_helper p false else validate_helper p b\n    | DivThen n p => if n ==n 0 then false else (if b then validate_helper p (Nat.eqb n 1) else validate_helper p false)\n    | VidThen n p => if b then validate_helper p false else false\n    | SetToThen n p => if n ==n 0 then validate_helper p false else validate_helper p true\n    end. \n\n\nDefinition validate (p : Prog) : bool :=\n  validate_helper p false.\n\n\n(*Lemma validate_sound_helper: forall (p: Prog), validate p = true -> forall s, fst(runPortable p s) = true -> fst(runPortable p 0) = true.\ninduct p; simplify; try(apply IHp); try(equality).\nunfold validate in IHp.\napply IHp.\nQed.*)\n\n\n(*Lemma b : forall (p: Prog)(n: nat), fst (runPortable p (n)) = true <-> (runPortable p n = (true, run p n)).\nProof.\n  induct p; simplify; try (apply IHp in H); try(rewrite <- plus_comm); try(rewrite <- mult_comm);\n  try(equality); try(rewrite plus_comm in H); try(rewrite mult_comm in H); try(assumption);\n  try(cases(n ==n 0); cases (n0 ==n 0));simplify; try(equality); try(rewrite IHp); try(equality).\nQed.\n\nLemma concat_portable : forall p1 p2 n, runPortable (concatProg p1 p2) n\n        = (let (x, answer) := runPortable p1 n in if x then runPortable p2 answer else (x,answer)).\nProof.\n  induct p1; try equality; simplify; try apply IHp1; try equality; try( cases (n ==n 0); cases (n0 ==n 0);\n  try equality;\n  simplify;\n  apply IHp1).\nQed.\n*)\n  (* If a clear plan hasn't emerged in 10 minutes (or if you get stuck later),\n * take a look at the hints for this pset on the course web site.\n * It is not expected that this pset is doable for everyone without the hints,\n * but some planning is required for successful proof.\n * In particular, repeatedly trying out different combinations of tactics\n * and ideas from hints until something sticks can go on for arbitrarily long\n * with little insight and no success; just guessing a solution is unlikely.\n * Thus, we encourage you to take your time thinking, look at the hints when\n * necessary, and only jump into coding when you have some idea why it should\n * succeed. Some may call Coq a video game, but it is not a grinding contest. *)\n\n(* The final goal of this pset is to implement [validate : Prog -> bool]\n   such that if this function returns [true], the program would not trigger\n   division by zero regardless of what state it starts out in.  [validate] is\n   allowed to return [false] for some perfectly good programs that never cause\n   division by zero, but it must recognize as good the examples given below.  In\n   jargon, [validate] is required to be sound but not complete, but \"complete\n   enough\" for the use cases defined by the examples given here: *)\n\nDefinition goodProgram1 := AddThen 1 (VidThen 10 Done).\nExample runPortable_good : forall n,\n  runPortable goodProgram1 n = (true, 10/(1+n)).\nProof. simplify. equality. Qed.\n\nDefinition badProgram1 := AddThen 0 (VidThen 10 Done).\nExample runPortable_bad : let n := 0 in\n  runPortable badProgram1 n = (false, 0).\nProof. simplify. equality. Qed.\n\n\nDefinition badProgram2 := AddThen 1 (DivThen 0 Done).\nExample runPortable_bad2 : forall n,\n  runPortable badProgram2 n = (false, 1+n).\nProof. simplify. equality. Qed.\n\nDefinition goodProgram2 := AddThen 0 (MulThen 10 (AddThen 0 (DivThen 1 Done))).\nDefinition goodProgram3 := AddThen 1 (MulThen 10 (AddThen 0 (VidThen 1 Done))).\nDefinition goodProgram4 := Done.\nDefinition goodProgram5 := SetToThen 0 (DivThen 1 Done).\nDefinition goodProgram6 := SetToThen 1 (VidThen 1 Done).\nDefinition goodProgram7 := AddThen 1 (DivThen 1 (DivThen 1 (VidThen 1 Done))).\n\n(* If you already see a way to build [validate] that meets the\n * requirements above, _and have a plan for how to prove it correct_,\n * feel free to just code away. Our solution uses one intermediate definition\n * and one intermediate lemma in the soundness proof -- both of which are more\n * sophisticated than the top-level versions given here. *)\nExample validate1 : validate goodProgram1 = true. Proof. equality. Qed.\nExample validate2 : validate goodProgram2 = true. Proof. equality. Qed.\nExample validate3 : validate goodProgram3 = true. Proof. equality. Qed.  \nExample validate4 : validate goodProgram4 = true. Proof. equality. Qed.\nExample validate5 : validate goodProgram5 = true. Proof. equality. Qed.\nExample validate6 : validate goodProgram6 = true. Proof. equality. Qed.\nExample validate7 : validate goodProgram7 = true. Proof. equality. Qed.\nExample validate8 : validate badProgram1 = false. Proof. equality. Qed.\nExample validate9 : validate badProgram2 = false. Proof. equality. Qed.\n\n\nLemma validate_sound_helper: forall p b, validate_helper p b = true ->\n     forall s : nat, (b = true -> s <> 0) ->\n     runPortable p s = (true, run p s).\ninduct p; try(simplify); try(equality).\nrewrite plus_comm.\nsimplify.\ncases (n ==n 0).\napply IHp with (b:=b).\nassumption.\nrewrite e.\nsimplify.\napply H0 in H1.\nlinear_arithmetic.\napply IHp with (b:=true).\nassumption.\nsimplify.\nlinear_arithmetic.\n\n\n\nrewrite mult_comm.\nsimplify.\ncases (n ==n 0).\napply IHp with (b:=false).\nassumption.\npropositional.\nequality.\napply IHp with (b:=b).\nassumption.\n\nsimplify.\napply H0 in H1.\nsimplify.\napply Nat.neq_mul_0.\npropositional.\n\ncases (n ==n 0).\nequality.\ncases b.\napply IHp with (b:= Nat.eqb n 1).\nassumption.\ncases(Nat.eqb n 1). \nintros.\napply Nat.eqb_eq in Heq.\nrewrite Heq.\napply H0 in H1.\nrewrite Nat.div_1_r.\nassumption.\npropositional.\nequality.\napply IHp with (b := false) (s := s/n).\nassumption.\npropositional.\nequality.\n\ncases (s ==n 0).\ncases b.\npropositional.\nequality.\ncases b.\napply IHp with (b := false) (s := n/s).\nassumption.\npropositional.\nequality.\nequality.\n\ncases (n ==n 0).\napply IHp with (b := false) (s := n).\nassumption.\npropositional.\nequality.\n\napply IHp with (b := true) (s := n).\nassumption.\npropositional.\nQed.\n\nHint Rewrite Nat.add_0_r.\nLemma validate_sound : forall p, validate p = true ->\n  forall s, runPortable p s = (true, run p s).\nProof.\ninduct p; try(simplify); try(equality); try(rewrite plus_comm).\nunfold validate in IHp.\n\napply validate_sound_helper with (s:=s) in H.\nsimplify.\nassert(ejre: n + s = s + n).\nlinear_arithmetic.\nrewrite <- ejre.\nrewrite <- ejre in H.\ntrivial.\npropositional.\nequality.\n\n\napply validate_sound_helper with (s:=s) in H.\nsimplify.\nassumption.\npropositional.\nequality.\n\ncases (n ==n 0).\napply validate_sound_helper with (s:=s) in H.\nsimplify.\nrewrite e in H.\nsimplify.\nrewrite e.\napply H.\npropositional.\nequality.\n\napply validate_sound_helper with (s:=s) in H.\nsimplify.\ncases (n ==n 0).\nequality.\napply H.\n\npropositional.\nequality.\n\napply validate_sound_helper with (s:= s) in H.\nsimplify.\napply H.\n\npropositional.\nequality.\n\napply validate_sound_helper with (s:= s) in H.\nsimplify.\napply H.\n\npropositional.\nequality.\nQed.\n(* Here is the complete list of commands used in one possible solution:\n  - Search, for example Search (_ + 0).\n  - induct, for example induct x\n  - simplify\n  - propositional\n  - equality\n  - linear_arithmetic\n  - cases, for example cases (X ==n Y)\n  - apply, for example apply H\n  - apply in, for example apply H1 in H2 or apply somelemma in H1\n  - apply with, for example apply H1 with (x:=2)\n  - apply in with, for example apply H1 with (x:=2) in H2\n  - rewrite, for example rewrite H\n  - rewrite in, for example rewrite H1 in H2 or rewrite somelemma in H1\n  - ;, for example simplify; propositional *)\n", "meta": {"author": "nicolas3355", "repo": "FormalReasoningAboutProgramsSpring2020", "sha": "85a908b07ea5b95212979ce224f902ad23497208", "save_path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020", "path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020/FormalReasoningAboutProgramsSpring2020-85a908b07ea5b95212979ce224f902ad23497208/pset01_ProgramAnalysis/Pset1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.8076268219683496}}
{"text": "\n(**\n    Written by Mitchell Buckley. Started on 25/11/2013 while a\n    PhD student at Macquarie University.\n\n    This file contains some basic lemmas concerning natural\n    numbers that I could not find in the standard library,\n    and were required for a formalisation of the theory\n    of Parity Complexes.\n  **)\n\nRequire Import Utf8_core.\nRequire Import Arith.\n\n(* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *)\n(* Independent Lemmas concerning nat                    *)\n(* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *)\n\n  (* Strong mathematical induction *)\n  Lemma strong_induction :\n    forall P : nat -> Prop,\n    P O ->\n    (forall n : nat, (forall m, m <= n -> P m) -> P (S n)) ->\n    forall n : nat, P n.\n  Proof with intuition.\n    intros P.\n    set (Q := fun n => (forall m, m <= n -> P m)).\n\n    intros.\n    assert (Q 0) as A.\n      unfold Q... inversion H1...\n    assert (forall l, Q l -> Q (S l)) as B.\n      unfold Q...\n      inversion H2...\n    assert (Q n) as C.\n      apply (nat_ind Q)...\n    apply (C n).\n    left.\n  Qed.\n\n  (* Less-than-or-equal-to is a total relation *)\n  Lemma le_total : forall n m, (n <= m) \\/ (m <= n).\n  Proof with intuition.\n    apply NPeano.Nat.le_ge_cases.\n  Qed.\n\n  (* A four case comparison of two natural numbers *)\n  Lemma lt_eq_eq_lt_dec: forall k m, {k < m} + {k = m} + {k = S m} + {S m < k}.\n  Proof with intuition.\n    intros.\n    pose (lt_eq_lt_dec k m)...\n    unfold lt in b.\n    apply le_lt_eq_dec in b...\n  Qed.\n\n  (* Three basic contradictions on less-than *)\n  Lemma lt_Sn : forall n, (S n < n) -> False.\n  Proof with intuition.\n    intros n.\n    induction n...\n    apply (lt_n_0) in H...\n  Qed.\n\n  Lemma lt_SSn : \u2200 n : nat, S (S n) < n -> False.\n  Proof with intuition.\n    intros n.\n    induction n...\n      inversion H...\n  Qed.\n\n  Lemma lt_SSSn : \u2200 n : nat, S (S (S n)) < n -> False.\n  Proof with intuition.\n    intros n.\n    induction n...\n      inversion H...\n  Qed.\n\n  (* Two basic contradictions on less-than-or-equal-to *)\n  Lemma le_SSn : \u2200 n : nat, S (S n) <= n -> False.\n  Proof with intuition.\n    intros n.\n    induction n...\n      inversion H...\n  Qed.\n\n  Lemma le_SSSn : \u2200 n : nat, S (S (S n)) <= n -> False.\n  Proof with intuition.\n      intros n.\n    induction n...\n      inversion H...\n  Qed.\n\n  (* A basic contradictions on equality *)\n  Lemma SSn_n : forall n, S (S n) = n -> False.\n  Proof with intuition.\n    intros...\n    induction n...\n    inversion H...\n  Qed.\n\n  (* A basic property of the successor function *)\n  Lemma Sn_minus_1 : forall n, (S n - 1 = n).\n  Proof with intuition.\n    simpl...\n  Qed.\n\n  Hint Resolve SSn_n le_SSn.\n", "meta": {"author": "MitchellBuckley", "repo": "Parity-Complexes", "sha": "fe563124a9e25aa39ff9e235a783d5051bd19ac6", "save_path": "github-repos/coq/MitchellBuckley-Parity-Complexes", "path": "github-repos/coq/MitchellBuckley-Parity-Complexes/Parity-Complexes-fe563124a9e25aa39ff9e235a783d5051bd19ac6/basic_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705932, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.807611308906264}}
{"text": "Require Import List Omega.\nSet Implicit Arguments.\n\n(* Part 1: introduction to proof search *)\n\nPrint plus.\n\nExample four_plus_three : 4 + 3 = 7.\n  reflexivity.\nQed.\n\nPrint four_plus_three.\n\nInductive plusR : \n      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\nHint Constructors plusR.\n\nLtac crush' := intros; simpl; \n  match goal with\n  | [ H : ex _ |- _] => destruct H\n  | [ H : _ |- _ ] => try (rewrite <- H || rewrite H)\n  | _ => idtac\n  end; try omega; eauto.\n\nLtac crush := repeat crush'.\n\nTheorem plus_plusR : forall n m,\n  plusR n m (n + m).\n  induction n; crush.\nQed.\n\nTheorem plusR_plus : forall n m r,\n  plusR n m r\n  -> r = n + m.\n  induction 1; crush.\nQed.\n\nHint Immediate plus_O_n.\n\nLemma plusS : forall n m r,\n  n + m = r\n  -> S n + m = S r.\n  crush.  \nQed.  \n\nHint Resolve plusS.\n\nLemma plusO : forall n m,\n  n = m\n  -> n + 0 = m.\n  crush.\nQed. \n\nPrint plusO.\n\nHint Resolve plusO.\n\n\n(* Path 2: Synthesizing Expressions *)\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : exp\n| Plus : exp -> exp -> 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\nTheorem EvalPlus' : \n   forall var e1 e2 n1 n2 n, eval var e1 n1\n  -> eval var e2 n2\n  -> n1 + n2 = n\n  -> eval var (Plus e1 e2) n.\n  crush.\nQed.\n\nHint Resolve EvalPlus'.\n\nHint Extern 1 (_ = _) => abstract omega.\n\nTheorem EvalConst' : forall var n m, n = m\n  -> eval var (Const n) m.\n  crush.\nQed.\n\nHint Resolve EvalConst'.\n\nTheorem zero_times : forall n m r,\n  r = m\n  -> r = 0 * n + m.\n  crush.\nQed.\n\n\nHint Resolve zero_times.\n\nTheorem EvalVar' : forall var n,\n  var = n\n  -> eval var Var n.\n  crush.\nQed.\n\n\nHint Resolve EvalVar'.\n\nTheorem plus_0 : forall n r,\n  r = n\n  -> r = n + 0.\n  auto.\nQed.\n\nTheorem times_1 : forall n, n = 1 * n.\n  auto.\nQed.\n\nHint Resolve plus_0 times_1.\n\nRequire Import Arith Ring.\n\nTheorem combine : forall x k1 k2 n1 n2,\n  (k1 * x + n1) + (k2 * x + n2) = (k1 + k2) * x + (n1 + n2).\n  intros; ring.\nQed.\n\nHint Resolve combine.\n\nTheorem linear : forall e, exists k, exists n,\n  forall var, eval var e (k * var + n).\n  induction e; crush. \nQed.\n\n\n", "meta": {"author": "ulysses4ever", "repo": "certif-sw-2014", "sha": "846fb4dc34af70a0ab1ca153311b8bfff2a13827", "save_path": "github-repos/coq/ulysses4ever-certif-sw-2014", "path": "github-repos/coq/ulysses4ever-certif-sw-2014/certif-sw-2014-846fb4dc34af70a0ab1ca153311b8bfff2a13827/lecture-11-examples-with-ltac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8074429132835068}}
{"text": "(* Exercise 5.15 *)\n\nDefinition my_True : Prop := forall P : Prop, P -> P.\nDefinition my_False : Prop := forall P : Prop, P.\n\nDefinition my_I : my_True := fun P p => p.\nDefinition my_False_ind := forall P : Prop, my_False -> P.\n\nDefinition my_not (P : Prop) : Prop := P -> my_False.\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\nTheorem theorem1 : forall P Q : Prop, my_and P Q -> P.\nProof.\n  unfold my_and.\n  intros P Q H.\n  apply H; intros; assumption.\nQed.\n\nTheorem theorem2 : forall P Q : Prop, my_and P Q -> Q.\nProof.\n  unfold my_and.\n  intros P Q H.\n  apply H; intros; assumption.\nQed.\n\nTheorem theorem3 : forall P Q R : Prop, (P -> Q -> R) -> my_and P Q -> R.\nProof.\n  unfold my_and.\n  intros P Q R H H0.\n  apply H0; assumption.\nQed.\n\nTheorem theorem4 : forall P Q : Prop, P -> my_or P Q.\nProof.\n  unfold my_or.\n  intros P Q p R Hleft Hright.\n  apply Hleft; assumption.\nQed.\n\nTheorem theorem5 : forall P Q : Prop, Q -> my_or P Q.\nProof.\n  unfold my_or.\n  intros P Q p R Hleft Hright.\n  apply Hright; assumption.\nQed.\n\nTheorem theorem6 : forall P Q R : Prop, (P -> R) -> (Q -> R) -> my_or P Q -> R.\nProof.\n  unfold my_or.\n  intros P Q R H H0 H1.\n  apply H1; assumption.\nQed.\n\nTheorem theorem7 : forall P : Prop, my_or P my_False -> P.\nProof.\n  unfold my_or, my_False.\n  intros P H.\n  apply H.\n  apply id.\n  intro H0.\n  apply H0.\nQed.\n\nTheorem theorem8 : forall P Q : Prop, my_or P Q -> my_or Q P.\nProof.\n  unfold my_or.\n  intros P Q H R H0 H1.\n  apply H; assumption.\nQed.\n\nTheorem theorem9 : forall (A : Set) (P : A -> Prop) (a : A), P a -> my_ex A P.\nProof.\n  unfold my_ex.\n  intros A P a H R H0.\n  apply H0 with a; assumption.\nQed.\n\nTheorem theorem10 : forall (A : Set) (P : A -> Prop), my_not (my_ex A P) -> forall a : A, my_not (P a).\nProof.\n  unfold my_not, my_ex, my_False.\n  intros A P H a H0 Q.\n  apply H.\n  intros R H1.\n  apply H1 with a; assumption.\nQed.\n", "meta": {"author": "aymanosman", "repo": "coq-art-exercises", "sha": "ff7e2aba35a5094d366be5b9f55dfdd13d38cd48", "save_path": "github-repos/coq/aymanosman-coq-art-exercises", "path": "github-repos/coq/aymanosman-coq-art-exercises/coq-art-exercises-ff7e2aba35a5094d366be5b9f55dfdd13d38cd48/05_everyday_logic/exercise_15.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.8074428989100023}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives.\n\n*)\n\n(* ########################################################### *)\n(** * Propositions *)\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions\n    ([forall x, P]).\n*)\n\n\n(** In Coq, the type of things that can (potentially)\n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated\n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P].\n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on\nequality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat\n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that\ntakes evidence for [P] as input and produces evidence for [Q] as its\noutput.\n*)\n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?\n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other\n      datatype.\n\n    - Sometimes a proposition is declared to be true without\n      substantiating evidence.  Such propositions are called _axioms_.\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q].\n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** ** \"Introducing\" conjunctions *)\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [destruct] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  destruct H as [_ HQ].\n  apply HQ.\nQed.\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  destruct H as [HP HQ].\n  split.\n    Case \"left\". apply HQ.\n    Case \"right\". apply HP.  Qed.\n\n\n(** **** Exercise: 2 stars (and_assoc)  *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [destruct] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  destruct H as [HP [HQ HR]].\n  split.\n  Case \"P /\\ Q\".\n    split. apply HP. apply HQ.\n  Case \"R\".\n    apply HR.\nQed.\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  destruct H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  destruct H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P.\n  split.\n    intros H. apply H.\n    intros H. apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R HPQ HQR.\n  split.\n    Case \"P->R\".\n      destruct HPQ as [HPQ' _].\n      destruct HQR as [HQR' _].\n      intros HP.\n      apply HQR'.\n      apply HPQ'.\n      apply HP.\n    Case \"R->P\".\n      destruct HPQ as [_ HQP'].\n      destruct HQR as [_ HRQ'].\n      intros HR.\n      apply HQP'.\n      apply HRQ'.\n      apply HR.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [destruct] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\n\n\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. destruct H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2)  *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H.\n  inversion H0.\n    left. apply H2.\n    inversion H1.\n      left. apply H3.\n      right. split.  apply H2.  apply H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct H.\n  rewrite H. rewrite H0. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (andb_false)  *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    simpl in H.\n    right. apply H.\n  Case \"b = false\".\n    left. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false)  *)\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    left. reflexivity.\n  Case \"b = false\".\n    simpl in H.\n    right.\n    apply H.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false_elim)  *)\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    simpl in H.\n    inversion H.\n  Case \"b = false\".\n    simpl in H.\n    split.\n      reflexivity.\n      apply H.\nQed.\n(** [] *)\n\n\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := .\n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** *** *)\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, advanced (True)  *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop :=\n| truth : True.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to\n    higher-order [Prop]s. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. destruct H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not.\n  intros P Q HPQ HQ HP.\n  apply HQ.\n  apply HPQ.\n  apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  unfold not.\n  intros P H.\n  inversion H.\n  apply H1.\n  apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H.\n  (* But now what? There is no way to \"invent\" evidence for [~P]\n     from evidence for [P]. *)\n  Abort.\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := forall P:Prop,\n  P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n(* FIXME *)\n(** [] *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \\/ ~ P).\nProof.\n  unfold not.\n  intros P H.\n  apply H.\n  right.\n  intros HP.\n  apply H.\n  left.\n  apply HP.\nQed.\n\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** **** Exercise: 2 stars (false_beq_nat)  *)\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      apply ex_falso_quodlibet.\n      unfold not in H.\n      apply H.\n      reflexivity.\n    SCase \"m = S m'\".\n      reflexivity.\n  Case \"n = S n'\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      reflexivity.\n    SCase \"m = S m'\".\n      simpl.\n      apply IHn'.\n      unfold not.\n      intros eq.\n      apply H.\n      rewrite -> eq.\n      reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_false)  *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      inversion H.\n    SCase \"m = S m'\".\n      unfold not.\n      intros contra.\n      inversion contra.\n  Case \"n = S n'\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      unfold not.\n      intros contra.\n      inversion contra.\n    SCase \"m = S m'\".\n      unfold not.\n      intros eq.\n      inversion eq.\n      rewrite -> H1 in H.\n      rewrite <- beq_nat_refl in H.\n      inversion H.\nQed.\n(** [] *)\n\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "ftiasch", "repo": "sf", "sha": "63ed39b75232f93f18f302099dc6c7637dea02ad", "save_path": "github-repos/coq/ftiasch-sf", "path": "github-repos/coq/ftiasch-sf/sf-63ed39b75232f93f18f302099dc6c7637dea02ad/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.9219218402181233, "lm_q1q2_score": 0.8074071549791692}}
{"text": "Module Ex03_1.\n\n(* Problem 11 *)\nRequire Import Arith.\n\nFixpoint sum_odd(n:nat) : nat :=\n  match n with\n  | O => O\n  | S m => 1 + m + m + sum_odd m\n  end.\n\nGoal forall n, sum_odd n = n * n.\nProof.\n  intro.\n  induction n.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite -> IHn.\n    SearchAbout (_ * S _).\n    rewrite mult_succ_r.\n    rewrite (plus_comm (n * n) n).\n    rewrite (plus_assoc).\n    reflexivity.\nQed.\n\nEnd Ex03_1.\n\n", "meta": {"author": "katayamak", "repo": "Coq2014", "sha": "bc953683fbe977c69b35311661eedbdaae4d1d61", "save_path": "github-repos/coq/katayamak-Coq2014", "path": "github-repos/coq/katayamak-Coq2014/Coq2014-bc953683fbe977c69b35311661eedbdaae4d1d61/ex03_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.8073650941258511}}
{"text": "\n(* Proof by Induction *)\n\nFrom LF Require Export Volume1_Ch1_Basics.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n    n = n + 0.\nProof.\n  intros n.\n  simpl.\nAbort.\n\n\nTheorem plus_n_O_secondtry : forall n:nat,\n    n = n + 0.\nProof.\n  intros n. destruct n as [|n'] eqn:E.\n  - reflexivity. \n  - simpl.\nAbort.\n\n\nTheorem plus_n_O : forall n:nat,\n    n = n + 0.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity. Qed.\n\n\nTheorem minus_n_n : forall n,\n    minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\n(* Exercise *)\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\n\nTheorem plus_n_Sm : forall n m : nat,\n    S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n.\n  induction m.\n  simpl. reflexivity.\n  simpl. reflexivity.\n  simpl. rewrite <- IHn.\n  reflexivity.\nQed.\n\n\n\nTheorem plus_comm : forall n m : nat,\n    n + m = m + n.\nProof.\n  intros.\n  induction n.\n  induction m.\n  reflexivity.\n  simpl.\n  rewrite <- IHm.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- plus_n_Sm.\n  rewrite <- IHn.\n  reflexivity.\nQed.\n\n \nTheorem plus_assoc : forall n m p : nat,\n    n + (m + p) = (n + m) + p.\nProof.\n  intros.\n  induction n.\n  induction m.\n  induction p.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n,\n    double n = n + n.\nProof.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  rewrite -> IHn'.\n  rewrite -> plus_n_Sm.\n  reflexivity.\nQed.\n\nFixpoint evenb (n:nat) : bool := \nmatch n with\n| O => true\n| S O => false\n| S (S n') => evenb n'\nend.\n\nLemma neg_id : forall n,\n    n = negb (negb n).\nProof.\n  intros.\n  induction n.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem evenb_S : forall n:nat,\n    evenb (S n) = negb (evenb n).\nProof.\n  intros.\n  induction n.\n  reflexivity.\n  rewrite -> IHn.\n  rewrite <- neg_id.\n  reflexivity.\nQed.\n\n(* Proofs Within Proofs *)\n\nTheorem mult_0_plus' : forall n m : nat,\n    (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n  { reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n    (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm.\n    reflexivity. }\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\n(* Formal vs. Informal Proof *)\n\nTheorem plus_assoc' : forall n m p : nat,\n    n + (m + p) = (n + m) + p.\nProof. intros. induction n as [| n' IHn']. reflexivity.\n       simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\nTheorem plus_assoc'' : forall n m p : nat,\n    n + (m + p) = (n + m) + p.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n\n(* More Exercises *)\n\n\nTheorem plus_swap : forall n m p : nat,\n    n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite plus_assoc.\n  assert (H: m + n = n + m).\n  { rewrite plus_comm.\n    reflexivity. }\n  rewrite <- H.\n  rewrite plus_assoc.   \n  reflexivity.\nQed.\n\n\nTheorem mult_comm : forall m n : nat,\n    m * n = n * m.\nProof.\nAdmitted.\n\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n    true = (n <=? n).\nProof.\nAdmitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n    0 =? (S n) = false.\nProof.\nAdmitted.\n\n\nTheorem andb_false_r : forall b:bool,\n    andb b false = false.\nProof.\nAdmitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n    n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\nAdmitted.\n\nTheorem S_nbeq_o : forall n:nat,\n    (S n) =? 0 = false.\nProof.\nAdmitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\nAdmitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n    (n + m) * p = (n * p) + (m * p).\nProof.\nAdmitted.\n\nTheorem mult_assoc : forall n m p : nat,\n    n * (m * p) = (n * m ) * p.\nProof.\nAdmitted.\n\n\nTheorem eqb_refl : forall n:nat,\n    true = (n =? n).\nProof.\nAdmitted.\n\nTheorem plus_swap' : forall n m p : nat,\n    n + (m + p) = m + (n + p).\nProof.\nAdmitted.\n\n\nFixpoint nat_to_bin (n:nat) : bin\n. Admitted.\n\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\nAdmitted.\n\n", "meta": {"author": "leechanwoo", "repo": "coq", "sha": "0ac863e4686c608d29ffb9c361d98180e45a727d", "save_path": "github-repos/coq/leechanwoo-coq", "path": "github-repos/coq/leechanwoo-coq/coq-0ac863e4686c608d29ffb9c361d98180e45a727d/Volume1_Ch2_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.8073599479146288}}
{"text": "Require Import ZArith.\nRequire Import Ensembles.\nRequire List.\n\nSet Implicit Arguments.\n\nSection Class.\n\nLemma contraposee : forall (A B:Prop),\n  (A -> B) -> (~B -> ~A).\nProof.\nintros A B Himpl Hnot_b.\nunfold not; unfold not in Hnot_b; intro HA; apply Hnot_b.\napply (Himpl HA).\nQed.\n\nEnd Class.\n\nGlobal Hint Resolve contraposee : util.\n\nSection EmptySet.\nDefinition set := Ensemble.\nLemma empty_set_is_empty : forall (A:Set) (s:set A),\n  ~(exists e, In _ s e) <-> Same_set _ (Empty_set _) s.\nProof.\nintros A s.\nsplit.\n(*->*)\nintros Hnon; unfold Same_set.\nunfold not in Hnon; unfold In in Hnon;\nunfold Included.\nsplit; intros x Hin_empty.\nelim Hnon; exists x; inversion Hin_empty.\ndestruct Hnon; exists x; apply Hin_empty.\n(*<-*)\nintros Hsame; unfold not; unfold In.\nintros Hexists.\nunfold Same_set in Hsame.\nunfold Included in Hsame.\ndestruct Hsame as [Hemp_s Hs_emp].\ndestruct Hexists as [e Hse].\nassert (In _ (Empty_set _) e).\napply (Hs_emp e Hse).\ninversion H.\nQed.\n\nLemma empty_set_is_empty_dir : forall (A:Set) (s:set A),\n  ~(exists e, In _ s e) -> Same_set _ s (Empty_set _).\nProof.\nintros A s Hnot.\nunfold not in Hnot.\nunfold Same_set; unfold Included; split.\n(*->*)\nintros x Hsx.\nassert (exists x, In A s x) as Hx.\nexists x; exact Hsx.\nassert (False) as Habs. \napply (Hnot Hx).\ncontradiction.\n(*<-*)\nintros x.\nintros Hempx.\ninversion Hempx.\nQed.\n\nLemma empty_set_is_empty_back : forall (A:Set) (s:set A),\n  Same_set _ s (Empty_set _) ->  ~(exists e, In _ s e).\nProof.\nunfold not; unfold Same_set; unfold Included.\nintros A s Hemp He.\ndestruct Hemp as [Hsemp Hemps].\ndestruct He as [e Hse].\nassert (In A (Empty_set A) e) as Hemp.\napply (Hsemp e Hse).\ninversion Hemp.\nQed.\n\nLemma non_empty_set_is_non_empty_dir : forall (A:Set) (s:set A),\n  (exists e, In _ s e) -> ~(Same_set _ s (Empty_set _)).\nProof.\nunfold not; unfold Same_set; unfold Included.\nintros A s Hexists Hsame.\ndestruct Hsame as [Hemps Hsemp].\ndestruct Hexists as [e Hse].\nassert (In A (Empty_set A) e) as Habs.\napply (Hemps e Hse).\ninversion Habs.\nQed.\n\nLemma incl_is_enough_for_empty : forall (A:Set) (s:set A),\n  Included _ s (Empty_set _) -> Same_set _ s (Empty_set _).\nProof.\nunfold Same_set; unfold Included; unfold In.\nintros A s Hemp.\nsplit; [exact Hemp|].\nintros x Habs.\ninversion Habs.\nQed.\n\nLemma incl_is_enough_for_empty_back : forall (A:Set) (s:set A),\n  Same_set _ s (Empty_set _) -> Included _ s (Empty_set _).\nProof.\nunfold Same_set; unfold Included; unfold In.\nintros A s Hemp.\ndestruct Hemp as [Hemp].\nexact Hemp.\nQed.\n\nEnd EmptySet.\n\nSection Inclusion.\n\nLemma incl_union : forall (A:Set) (s1 s2 s:set A),\n  Included _ s1 s -> Included _ s2 s -> Included _ (Union _ s1 s2) s.\nProof.\nintros A s1 s2 s H1 H2.\nintros x Hu.\n  inversion Hu as [? Hi1 | ? Hi2].\n    apply H1; auto.\n    apply H2; auto.\nQed.\n\nLemma incl_union_in : forall (A:Set) (s1 s2 s:set A),\n  Included _ s1 s -> Included _ s2 s -> \n  (forall x, In _ (Union _ s1 s2) x -> In _ s x).\nProof.\napply incl_union.\nQed.\n\nLemma incl_union_left_in : forall (A:Set) (s1 s2 : set A),\n  forall x, In _ s1 x -> In _ (Union _ s1 s2) x.\nProof.\nunfold In; intros.\napply Union_introl.\nexact H.\nQed.\n\nLemma incl_union_right_in : forall (A:Set) (s1 s2 : set A),\n  forall x, In _ s2 x -> In _ (Union _ s1 s2) x.\nProof.\nunfold In; intros.\napply Union_intror.\nexact H.\nQed.\n\nLemma incl_union_back : forall (A:Set) (s1 s2 s: set A),\n  Included _ (Union _ s1 s2) s -> Included _ s1 s /\\ Included _ s2 s.\nProof.\nunfold Included; intros.\nsplit.\nintros.\napply (H x).\napply incl_union_left_in; exact H0.\nintros.\napply (H x).\napply incl_union_right_in; exact H0.\nQed.\n\nLemma incl_union_back_in : forall (A:Set) (s1 s2 s: set A),\n  Included _ (Union _ s1 s2) s -> \n  (forall x, In _ (Union _ s1 s2) x -> In _ s x).\nProof.\nunfold Included; intros.\napply H.\nexact H0.\nQed.\n\nLemma incl_trans : forall (A:Set) (s1 s2 s3:set A),\n  Included _ s1 s2 -> Included _ s2 s3 -> Included _ s1 s3.\nProof.\nunfold Included; unfold In; intros.\napply (H0 x (H x H1)).\nQed.\n\nEnd Inclusion.\n\nSection SameSet.\n\nLemma same_trans : forall (A:Set) (s1 s2 s3:set A),\n  Same_set _ s1 s2 -> Same_set _ s2 s3 -> Same_set _ s1 s3.\nProof.\nunfold Same_set; unfold Included; unfold In.\nintros A s1 s2 s3 H12 H23.\ndestruct H12 as [H12 H21];\ndestruct H23 as [H23 H32].\nsplit; intros x; [intro H1 | intro H3].\napply H23; apply H12; exact H1.\napply H21; apply H32; exact H3.\nQed.\n\nLemma same_refl : forall (A:Set) (s1 s2:set A),\n  Same_set _ s1 s2 -> Same_set _ s2 s1.\nProof.\nunfold Same_set; unfold Included; unfold In.\nintros A s1 s2 H12.\ndestruct H12 as [H12 H21].\nsplit; [exact H21 | exact H12].\nQed.\n\nLemma not_same_refl : forall (A:Set) (s1 s2:set A),\n  ~(Same_set _ s1 s2) -> ~(Same_set _ s2 s1).\nProof.\nunfold not; intros A s1 s2 H12 H21.\napply H12.\napply same_refl; exact H21.\nQed.\n\nLemma not_same_trans : forall (A:Set) (s1 s2 s3:set A),\n  Same_set _ s1 s2 -> ~(Same_set _ s1 s3) -> ~(Same_set _ s2 s3).\nProof.\nunfold not; intros A s1 s2 s3 H12 Hnot13 H23.\nassert (Same_set A s1 s3) as H13.\neapply same_trans; [apply H12 | apply H23].\napply (Hnot13 H13).\nQed.\n\nLemma same_impl_incl : forall (A:Set) (s1 s2:set A),\n  Same_set _ s1 s2 -> Included _ s1 s2.\nProof.\nunfold Same_set; unfold Included; unfold In.\nintros A s1 s2 Hsame.\ndestruct Hsame as [H12 H21].\nexact H12.\nQed.\n\nEnd SameSet.\n\nSection LinOrder. (*w. set*)\n\nDefinition domain (A B:Set) (e:set (A*B)) : set B :=\n  fun y => exists x, In _ e (x,y).\n\nDefinition range (A B:Set) (e:set (A*B)) : set A :=\n  fun x => exists y, In _ e (x,y).\n\nLemma range_is_range : forall (A B:Set) (e:set (A*B)) (x:A),\n  (exists y, In _ e (x,y)) -> In _ (range e) x.\nProof.\nunfold range; unfold In; trivial.\nQed.\n\nLemma domain_is_domain : forall (A B:Set) (e:set (A*B)) (y:B),\n  (exists x, In _ e (x,y)) -> In _ (domain e) y.\nProof.\nunfold domain; unfold In; trivial.\nQed.\n\nDefinition linear_order (A:Set) (r:set (A*A)) (xs:set A) : Prop :=\n  Included _ (Union _ (domain r) (range r)) xs /\\\n  (*transitivity*)\n  (forall x1 x2 x3, (In _ r (x1,x2)) /\\ (In _ r (x2,x3)) -> (In _ r (x1,x3))) /\\\n  (*antisymetry*)\n  (forall x1 x2, (In _ r (x1,x2)) /\\ (In _ r (x2,x1)) -> x1=x2) /\\\n  (*linear on xs*)\n  (forall x1 x2, (In _ xs x1) -> (In _ xs x2) -> ((In _ r (x1,x2)) \\/ (In _ r (x2,x1)))).\n\nLemma linear_prop_cart : forall (A:Set) (so:set (A*A)) (s:set A) (x:A),\n  (linear_order so s) -> In _ s x -> In _ s x -> In _ so (x,x).\nProof.\nunfold linear_order; unfold In; intros. \ndestruct H as [Hincl H].\ndestruct H as [Htrans H].\ndestruct H as [Hrefl Hlin].\nassert (so (x,x) \\/ so (x,x)).\napply (Hlin x x H0 H1).\ninversion H.\nexact H2.\nexact H2.\nQed.\n\nLemma linear_order_trans : forall (A:Set) (so:set (A*A)) (x1 x2 x3:A),\n  (exists s, (linear_order so s)) ->\n  In _ so (x1,x2) -> In _ so (x2,x3) -> In _ so (x1,x3).\nProof.\nintros A so x1 x2 x3 Hexists H12 H23.\nunfold linear_order in Hexists.\ndestruct Hexists as [s He].\ndestruct He as [Hincl He].\ndestruct He as [Htrans He].\neapply Htrans.\nsplit; [apply H12 | apply H23].\nQed.\n\nLemma incl_lin_order_range : forall (A:Set) (so: set (A*A)) (s:set A) (x1 x2:A),\n  linear_order so s -> In _ so (x1,x2) -> In _ s x1.\nProof.\nunfold linear_order; unfold In; intros.\nassert (In _ (range so) x1).\napply range_is_range.\nexists x2; apply H0.\nassert (In _ (Union A (domain so) (range so)) x1).\napply incl_union_right_in; exact H1.\nrepeat (destruct H).\nunfold Included in H; apply H; exact H2.\nQed.\n\nLemma incl_lin_order_domain : forall (A:Set) (so: set (A*A)) (s:set A) (x1 x2:A),\n  linear_order so s -> In _ so (x1,x2) -> In _ s x2.\nProof.\nunfold linear_order; unfold In; intros.\nassert (In _ (domain so) x2).\napply domain_is_domain.\nexists x1; apply H0.\nassert (In _ (Union A (domain so) (range so)) x2).\napply incl_union_left_in; exact H1.\nrepeat (destruct H).\nunfold Included in H; apply H; exact H2.\nQed.\n\nLemma incl_dom_ran : forall (A:Set) (so sor:set (A*A)),\n  Included (A * A) sor so ->\n  Included A (Union A (domain sor) (range sor))\n  (Union A (domain so) (range so)).\nProof.\nunfold Included;\nintros A so sor Hincl x Hsor.\ninversion Hsor as [y Hdom | y Hran].\n(*dom*)\nunfold In in Hdom; unfold domain in Hdom.\napply incl_union_left_in; unfold In; unfold domain.\ndestruct Hdom as [x0 Hin]; exists x0; apply (Hincl (x0,x) Hin).\n(*ran*)\nunfold In in Hran; unfold range in Hran.\napply incl_union_right_in; unfold In; unfold range.\ndestruct Hran as [x0 Hin]; exists x0; apply (Hincl (x,x0) Hin).\nQed.\n\nEnd LinOrder.\n\n(*Section LinStrictOrder.*)\n\nDefinition Rln (A:Type) := A -> A -> Prop.\n\nDefinition dom (A:Type) (r:Rln A) : set A :=\n  fun x => exists y, r x y.\nDefinition ran (A:Type) (r:Rln A) : set A :=\n  fun y => exists x, r x y.\n\nDefinition udr (A:Type) (so: Rln A) : set A :=\n  Union _ (dom so) (ran so).\n\nDefinition rel_incl (A:Type) (r1 r2 : Rln A) : Prop :=\n  forall x y, r1 x y -> r2 x y.\n\n(** Linear and linear strict orders *)\nDefinition partial_order (A:Type) (r:Rln A) (xs:set A) : Prop :=\n  Included _(Union _ (dom r) (ran r)) xs /\\\n  (*transitivity*)\n  (forall x1 x2 x3, (r x1 x2) /\\ (r x2 x3) -> (r x1 x3)) /\\\n  (*irreflexivity*)\n  (forall x, ~(r x x)).\n\nDefinition linear_strict_order (A:Type) (r:Rln A) (xs:set A) : Prop :=\n  Included _(Union _ (dom r) (ran r)) xs /\\\n  (*transitivity*)\n  (forall x1 x2 x3, (r x1 x2) /\\ (r x2 x3) -> (r x1 x3)) /\\\n  (*irreflexivity*)\n  (forall x, ~(r x x)) /\\\n  (*linear on xs*)\n  (forall x1 x2, (x1 <> x2) -> (In _ xs x1) -> (In _ xs x2) -> \n    (r x1 x2) \\/ (r x2 x1)).\nLtac destruct_lin H :=\n  destruct H as [Hdr [Htrans [Hac Htot]]].\n\nModule Type OrdExt.\nParameter Elt : Type.\nParameter LE : Rln Elt -> Rln Elt.\nHypothesis OE : forall (s S:set Elt) (r:Rln Elt),\n  Included _ s S ->\n  partial_order r s -> \n  rel_incl r (LE r) /\\\n  linear_strict_order (LE r) S.\nHypothesis le_lso : forall (s:set Elt) (r:Rln Elt),\n  linear_strict_order r s -> LE r = r.\nEnd OrdExt.\n\nLemma linear_strict_order_trans : forall (A:Set) (so:Rln A) (x1 x2 x3:A),\n  (exists s, (linear_strict_order so s)) ->\n  so x1 x2 -> so x2 x3 -> so x1 x3.\nProof.\nunfold linear_strict_order; unfold In; intros. \ndestruct H as [s [Hdr [Htrans [Hac Htot]]]].\napply (Htrans x1 x2 x3).\nsplit. \nexact H0.\nexact H1.\nQed.\n\nLemma linear_strict_order_lin : forall (A:Set) (s:set A) (so:Rln A) (x1 x2:A),\n  (linear_strict_order so s) ->\n  (x1 <> x2) -> (In _ s x1) -> (In _ s x2) ->\n  so x1 x2 \\/ so x2 x1.\nProof.\nintros A s so x1 x2 Hlin Hdiff H1 H2.\ndestruct Hlin as [Hdom [Htrans [Hacycl Hlin]]].\napply (Hlin x1 x2 Hdiff H1 H2).\nQed.\n\nLemma incl_lin_strict_order_dom : forall (A:Set) (so: Rln A) (s:set A) (x1 x2:A),\n  linear_strict_order so s -> so x1 x2 -> In _ s x1.\nProof.\nunfold linear_strict_order; unfold In; intros.\nassert (In _ (dom so) x1).\nexists x2; apply H0.\nassert (In _ (Union A (dom so) (ran so)) x1).\napply incl_union_left_in; exact H1.\ndestruct H as [Hdr [Htrans [Hac Htot]]].\n unfold Included in Hdr; apply Hdr. \nexact H2.\nQed.\n\nLemma incl_lin_strict_order_ran : forall (A:Set) (so: Rln A) (s:set A) (x1 x2:A),\n  linear_strict_order so s -> so x1 x2 -> In _ s x2.\nProof.\nunfold linear_strict_order; unfold In; intros.\nassert (In _ (ran so) x2).\nexists x1; apply H0.\nassert (In _ (Union A (dom so) (ran so)) x2).\napply incl_union_right_in; exact H1.\ndestruct H as [Hdr [Htrans [Hac Htot]]].\nunfold Included in Hdr; apply Hdr; exact H2.\nQed.\n\n(*End LinStrictOrder.*)\n\nSection RRestrict.\n\nDefinition rrestrict (A:Set) (r:Rln A) (s:set A) : Rln A := \n    fun x => fun y =>\n    r x y /\\ In _ s x /\\ In _ s y.\n\nEnd RRestrict.\n\nSection TransClos.\n\n(** Transitive closure *)\nInductive transitive_closure (A:Type) (e:set (A*A)) : set (A*A) :=\n    | t_step : forall x y, In _ e (x,y) -> In _ (transitive_closure e) (x,y)\n    | t_trans : forall x y z, In _ (transitive_closure e) (x,y) -> \n                     In _ (transitive_closure e) (y,z) -> \n                     In _ (transitive_closure e) (x,z).\n\nInductive tc (A : Type)(r : A -> A -> Prop) : A -> A -> Prop :=\n   |trc_step : forall x, forall y : A, r x y -> (tc r) x y\n   |trc_ind : forall x y z : A,\n      (tc r) x z ->\n      (tc  r) z y -> (tc r) x y.\n\nInductive rc (A : Type)(r : A -> A -> Prop) : A -> A -> Prop :=\n   |rc_step : forall x, forall y : A, tc r x y -> (rc r) x y\n   |rc_eq : forall x y : A, x = y -> (rc r) x y.\n\n(** Strict transitive closure *)\n\nDefinition strict (A:Set) (r:Rln A) : Rln A := \n  fun e1 => fun e2 =>\n    r e1 e2 /\\ e1 <> e2.\n\nDefinition stc (A:Set) (r: Rln A) : Rln A := strict (tc r).\n\nEnd TransClos.\n\nSection Acyclicity.\n\n(** Acyclicity *)\nDefinition acyclic (A:Type) (r: Rln A) : Prop :=\n  forall x, ~((tc r) x x).\nDefinition irrefl (A:Type) (r: Rln A) : Prop :=\n  forall x, ~(r x x).\nEnd Acyclicity.\n\nSection BasicSet.\n\n(** Union *)\n\nLemma union_refl : forall (A:Set) (r1 r2: set (A*A)),\n  (Union _ r1 r2) = (Union _ r2 r1).\nProof.\nintros A r1 r2.\napply (Extensionality_Ensembles _ (Union _ r1 r2) (Union _ r2 r1)).\nunfold Same_set; unfold Included; split; intros c Hin.\ninversion Hin as [c' H1 | c' H2].\n  apply incl_union_right_in; exact H1.\n  apply incl_union_left_in; exact H2.\ninversion Hin as [c' H2 | c' H1].\n  apply incl_union_right_in; exact H2.\n  apply incl_union_left_in; exact H1.\nQed.\n\n(** Cartesian product of two sets *)\nDefinition cartesian (A B:Set) (sa:set A) (sb:set B) : set (A*B) :=\n  fun c => match c with (a,b) =>\n  In _ sa a /\\ In _ sb b end.\n\n(** Topo *)\n\nLemma dom_tc_in_dom :\n  forall (A:Set) (r: Rln A) (x:A),\n  In _ (dom (tc r)) x ->\n  In _ (dom r) x.\nProof.\nintros A r x Hd.\ndestruct Hd as [y Hd].\ninduction Hd as [ x y Hs |x y Hi].\n  exists y; apply Hs.\n  exact IHHd1.\nQed.\n\nLemma ran_tc_in_ran :\n  forall (A:Set) (r: Rln A) (x:A),\n  In _ (ran (tc r)) x ->\n  In _ (ran r) x.\nProof.\nintros A r x Hr.\ndestruct Hr as [y Hr].\ninduction Hr as [ x y Hs |x y Hi].\n  exists x; apply Hs.\n  exact IHHr2.\nQed.\n\nLemma dom_ran_tc : \n  forall (A:Set) (r:Rln A),\n  Union _ (dom r) (ran r) = Union _ (dom (tc r)) (ran (tc r)).\nProof.\nintros A r.\napply (Extensionality_Ensembles _ \n  (Union _ (dom r) (ran r)) (Union _ (dom (tc r)) (ran (tc r))));\nsplit; unfold Included; intros x Hx.\n(*r -> stc r*)\ninversion Hx as [e Hd | e Hr].\n  apply incl_union_left_in; unfold In; unfold domain; \n    unfold In in Hd; unfold domain in Hd; destruct Hd as [y Hd].\n   exists y; apply trc_step; apply Hd.\n    apply incl_union_right_in; unfold In; unfold range; \n    unfold In in Hr; unfold range in Hr; destruct Hr as [y Hr].\n exists y; apply trc_step; apply Hr.\n(*stc r -> r*)\ninduction Hx as [e Hd | e Hr].\n  apply incl_union_left_in; apply dom_tc_in_dom; apply Hd.\n  apply incl_union_right_in; apply ran_tc_in_ran; apply Hr.\nQed.\n\nDefinition rel_union (A:Type) (r1 r2 : Rln A) : Rln A :=\n  fun x => fun y => r1 x y \\/ r2 x y.\n\n(** Maximal elements *)\nDefinition maximal_elements (A:Set) (xs:set A) (r:set (A*A)) : set A :=\n  fun x => In _ xs x /\\ forall x', In _ xs x'/\\ In _ r (x, x') -> (x = x').\n\nLemma maximal_preserves_incl : forall (A:Set) (xs:set A) (r:set (A*A)) (e:A),\n  In _ (maximal_elements xs r) e ->\n  In _ xs e.\nProof.\nunfold maximal_elements; unfold In.\nintros A xs r e Hmax.\ndestruct Hmax as [Hxs].\nexact Hxs.\nQed.\n\n(** Mirror *)\nDefinition inv (A:Set) (r:set (A*A)) :=\n  fun c => match c with (y,x) =>\n  In _ r (x,y) end.\n\n(** Singleton *)\n\nDefinition is_singleton (A:Set) (s:set A) :=\n  exists e, In _ s e /\\\n  ~(exists e', e <> e' /\\ In _ s e').\n\nDefinition is_empty (A:Set) (s:set A) := \n  Same_set _ s (Empty_set _).\n\nEnd BasicSet.\n\nSection BasicRel.\n\nDefinition emp_rel (A:Set) : Rln A :=\n  fun x => fun y => False. \n\nDefinition same_rel (A:Set) (r1 r2 : Rln A) : Prop :=\n  rel_incl r1 r2 /\\ rel_incl r2 r1.\nAxiom ext_rel : forall (A:Type) (r1 r2 : Rln A),  \n  (forall x y, r1 x y <-> r2 x y) -> r1 = r2.\n\nLemma incl_path :\n  forall (A:Set) (r1 r2 : Rln A) (x y : A),\n  rel_incl r1 r2 ->\n  tc r1 x y ->\n  tc r2 x y.\nProof.\nintros A r1 r2 x y H12 H1.\ninduction H1.\n  apply trc_step; apply H12; apply H.\n  apply trc_ind with z; auto.\nQed.\n\nLemma incl_ac : \n  forall (A:Set) (r1 r2 : Rln A),\n  rel_incl r1 r2 ->\n  acyclic r2 ->\n  acyclic r1.\nProof.\nunfold acyclic; unfold not;\nintros A r1 r2 H12 H2 x H1; apply (H2 x).\neapply incl_path; [apply H12 | apply H1].\nQed.\n\nLemma lso_is_tc :\n  forall A (so:Rln A) (s: set A), \n  linear_strict_order so s -> tc so = so.\nProof.\nintros A so s Hlin.\ndestruct Hlin as [Hdr [Htrans [Hac Htot]]].\nassert (forall x y, (tc so) x y <-> so x y) as Hext.\n  intros x y; split; intro Hxy.\n    induction Hxy.\n      apply H.\n      apply (Htrans x z y); split; [apply IHHxy1 | apply IHHxy2].\n    apply trc_step; apply Hxy.\napply (ext_rel (tc so) (so) Hext).\nQed.\n\nLemma po_is_tc :\n  forall A (so:Rln A) (s: set A), \n  partial_order so s -> tc so = so.\nProof.\nintros A so s Hp.\ndestruct Hp as [Hdr [Htrans Hac]].\nassert (forall x y, (tc so) x y <-> so x y) as Hext.\n  intros x y; split; intro Hxy.\n    induction Hxy.\n      apply H.\n      apply (Htrans x z y); split; [apply IHHxy1 | apply IHHxy2].\n    apply trc_step; apply Hxy.\napply (ext_rel (tc so) (so) Hext).\nQed.\n\nLemma lin_strict_ac :\n  forall (A:Set) (s:set A) (r : Rln A),\n  linear_strict_order r s -> \n  acyclic r.\nProof.\nintros A s r Hlin.\ngeneralize (lso_is_tc Hlin); intro Heq.\nunfold acyclic; rewrite Heq.\ndestruct Hlin as [Hdr [Htrans [Hac Htot]]];\n  apply Hac.\nQed.\n\nLemma union_triv : (*util*)\n  forall (A:Type) (r1 r2 : Rln A),\n  rel_union r1 r2 = rel_union r2 r1.\nProof.\nintros A r1 r2.\napply ext_rel;\nunfold rel_union; split; intro Hx; \ninversion Hx as [H1 | H2].\n  right; apply H1.\n  left; apply H2.\n  right; apply H1.\n  left; apply H2.\nQed.\n\nLemma tc_incl : forall  (E : Type)  (r1 r2 : Rln E),\n  rel_incl r1 r2 -> rel_incl (tc r1) (tc r2).\nProof.\nunfold rel_incl.\nintros E r1 r2 ir12 x y tcr1xy.\ninduction tcr1xy.\n  apply trc_step.\n  apply ir12; trivial.\napply trc_ind with z; trivial.\nQed.\n\nLemma ac_incl : forall (E : Set)  (r1 r2 : Rln E),\n  acyclic r2 ->  rel_incl r1 r2 -> acyclic r1.\nProof.\nintros E r1 r2; unfold acyclic. intros ar2 ; unfold Included. \nintros ir12 x ixx.\nassert (nar2 : tc r2 x x).\n  apply (tc_incl ir12); trivial.\nassert (h := ar2 x).\ncontradiction.\nQed.\n\nLemma incl_implies_union_eq :\n  forall A (r1 r2: Rln A),\n  rel_incl r1 r2 -> \n  rel_union r1 r2 = r2.\nProof.\nunfold rel_incl; \nintros A r1 r2 Hincl.\napply ext_rel; intros x y; split; intro Hxy.\n  inversion Hxy as [H1 | H2].\n    apply Hincl; apply H1.\n    apply H2.\n  unfold rel_union; right; apply Hxy.\nQed.\n\nLemma incl_implies_ac_union :\n  forall A (r1 r2: Rln A),\n  rel_incl r1 r2 -> \n  acyclic r2 ->\n  acyclic (rel_union r1 r2).\nProof.\nintros A r1 r2 Hincl Hac;\ngeneralize (incl_implies_union_eq Hincl);\nintro Heq; rewrite Heq; apply Hac.\nQed.\n\nLemma rel_union_refl :\n  forall A (r1 r2: Rln A),\n  rel_union r1 r2 = rel_union r2 r1.\nProof.\nintros A r1 r2.\napply ext_rel; intros x y; split; intro Hxy;\ninversion Hxy as [H1 | H2].\n  right; apply H1.\n  left; apply H2.\n  right; apply H1.\n  left; apply H2.\nQed.\n\nLemma rel_incl_right :\n  forall A (r1 r2 r3: Rln A),\n  rel_incl r1 r2 ->\n  rel_incl (rel_union r1 r3) (rel_union r2 r3).\nProof.\nunfold rel_incl;\nintros A r1 r2 r3 H12 x y H13.\ninversion H13 as [H1 | H3].\n  left; apply H12; apply H1.\n  right; apply H3.\nQed.\n\nLemma rel_incl_left :\n  forall A (r1 r2 r3: Rln A),\n  rel_incl r1 r2 ->\n  rel_incl (rel_union r3 r1) (rel_union r3 r2).\nProof.\nunfold rel_incl;\nintros A r1 r2 r3 H12 x y H31.\ninversion H31 as [H3 | H1].\n  left; apply H3.\n  right; apply H12; apply H1.\nQed. \n\nLemma rel_incl_trans : forall (A:Set) (r1 r2 r3 : Rln A),\n  rel_incl r1 r2 -> rel_incl r2 r3 -> rel_incl r1 r3.\nProof.\nunfold rel_incl;\nintros A r1 r2 r3 H12 H23 x y H1.\napply H23; apply H12; apply H1.\nQed.\n\nDefinition rel_seq (A:Type) (r1 r2 : Rln A) : Rln A :=\n  fun x => fun y => exists z, r1 x z /\\ r2 z y.\n\nDefinition maybe (A:Type) (r:Rln A) : Rln A :=\n  fun e1 => fun e2 => r e1 e2 \\/ e1 = e2.\n\nDefinition phx (A:Type) (r1 r2 :Rln A) : Rln A :=\n  fun e1 => fun e2 => (tc (rel_seq r1 r2)) e1 e2 \\/ e1 = e2.\n\nDefinition hx (A:Type) (r1 r2:Rln A) : Rln A :=\n  fun e1 => fun e2 => \n    rel_seq (maybe r2) (rel_seq (phx r1 r2) (maybe r1)) e1 e2. \n\nDefinition phx' (A:Type) (r1 r2 :Rln A) : Rln A :=\n  fun e1 => fun e2 => (tc (rel_seq r1 (tc r2))) e1 e2 \\/ e1 = e2.\n\nDefinition hx' (A:Type) (r1 r2:Rln A) : Rln A :=\n  fun e1 => fun e2 => \n    rel_seq (maybe (tc r2)) (rel_seq (phx r1 (tc r2)) (maybe r1)) e1 e2. \n\nDefinition trans (A:Type) (r:Rln A) : Prop :=\n  forall x y z, r x y -> r y z -> r x z.\n\nLemma test : forall (A:Set) (r1 r2: Rln A) x y, (phx r1 r2 x y) = (maybe (tc (rel_seq r1 r2)) x y).\nintros.\nunfold phx, maybe. trivial.\nQed.\n\n(* si r1 trans et  x r1 y (r1r2)+ z \n   alors x (r1r2)+ z *)\nLemma glue_front : forall (A:Type) (r1 r2: Rln A) (Tr1: trans r1) x y z, \n   r1 x y -> tc (rel_seq r1 r2) y z -> tc (rel_seq r1 r2) x z.\nintros.\nremember (rel_seq r1 r2) as r. induction H0; subst.\n(* x r1 x0 r1 z r2 y donc x r1 z r2 y (par trans) donc x r1r2 y\n   donc x (r1r2)+ y *)\ndestruct H0 as [z [? ?]].\napply trc_step. exists z; split; trivial.\napply Tr1 with x0; trivial.\n(*  cas trc_ind; trivial *)\napply trc_ind with z; trivial.\napply IHtc1; trivial.\nQed.\n\n(* si r2 trans et x (r1r2)+ y r2 z\n   alors x (r1r2)+ z *)\nLemma glue_back : forall (A:Type) (r1 r2: Rln A) (Tr2: trans r2) x y z, \n   tc (rel_seq r1 r2) x y -> r2 y z ->  tc (rel_seq r1 r2) x z.\nintros.\nremember (rel_seq r1 r2) as r. induction H; subst.\n(* x r1 a r2 y r2 z donc x r1 a r2 z (par trans) donc x r1r2 z\n   donc x (r1r2)+ z *)\ndestruct H as [a [? ?]].\napply trc_step. exists a; split; trivial.\napply Tr2 with y; trivial.\n(*  cas trc_ind; trivial *)\napply trc_ind with z0; trivial.\napply IHtc2; trivial.\nQed.\n\nLemma hx_trans : (*2*)\n  forall (A:Type) (r1 r2:Rln A),\n  trans r1 -> trans r2 ->\n  trans (hx r1 r2).\nProof.\nintros.\nunfold trans in *; intros.\nunfold hx in *.\ndestruct H1 as [z1 [? ?]].\ndestruct H2 as [z2 [? ?]].\ndestruct H3 as [z11 [? ?]].\ndestruct H4 as [z21 [? ?]].\ndestruct H3; destruct H4.\n\n  exists z1; split; trivial; clear x H1.\n  exists z21; split; trivial; clear z H6.\n  destruct H5; destruct H2; left.\n    apply trc_ind with z11; trivial; clear z1 H3.\n    apply trc_ind with z2; trivial; clear z21 H4.\n    apply trc_step. exists y; split; trivial.\n\n    apply trc_ind with z11; trivial; clear z1 H3.\n    apply glue_front with y; subst; trivial.\n\n    apply trc_ind with z2; trivial; clear z21 H4.\n    apply glue_back with y; subst; trivial. \n\n    apply trc_ind with z11; subst; trivial.\n\n  subst. exists z1; split; trivial; clear x H1.\n  destruct H2.\n    exists z21; split; trivial. clear z H6. left.\n    destruct H5.\n      apply trc_ind with z11; trivial; clear z1 H3.\n      apply trc_step. exists y; split; trivial.\n\n      subst. apply glue_back with y; trivial.\n\n    subst. exists z11; split. left; trivial.\n    destruct H5; destruct H6; subst.\n    left; apply H with z21; trivial.\n    left; trivial. left; trivial. right; trivial.\n\n  subst. destruct H5.\n    exists z11; split; trivial. clear x H1.\n    exists z21; split; trivial. clear z H6.\n    left. destruct H2; subst.\n      apply trc_ind with z2; trivial.\n      apply trc_step. exists y; split; trivial.\n\n      apply glue_front with z2; trivial.\n\n    subst. exists z2; split.\n      destruct H1; destruct H2; subst.\n      left; apply H0 with y; trivial. left; trivial. \n      left; trivial. right; trivial.\n\n      clear H1 H2. exists z21; split; trivial. left; trivial.\n\n  subst. destruct H1; destruct H5; destruct H2; destruct H6; subst.\n    exists z11; split. left; trivial.\n    exists z21; split. left. apply trc_step. exists y; split; trivial.\n    left; trivial.\n\n    exists z11; split. left; trivial.\n    exists z; split. left. apply trc_step. exists y; split; trivial.\n    right; trivial.\n\n    exists z11; split. left; trivial.\n    exists z11; split. right; trivial.\n    left; apply H with z21; trivial.\n\n    exists z11; split. left; trivial.\n    exists z11; split. right; trivial. left; trivial.\n\n    exists z21; split. left; apply H0 with y; trivial. \n    exists z21; split. right; trivial. left; trivial. \n\n    exists z; split. left; apply H0 with y; trivial. exists z; split; right; trivial.\n\n    exists z21; split. left; apply H1.\n    exists z21; split. right; trivial. left; apply H4.\n\n    exists z; split. left; apply H1.\n    exists z; split; right; trivial.\n\n    exists z11; split. right; trivial.\n    exists z21; split.\n      left; apply trc_step; exists y; split; [apply H3 | apply H2].\n      left; apply H4.\n\n   exists z11; split. right; trivial.\n     exists z; split; [| right; trivial].\n     left; apply trc_step; exists y; split; [apply H3 | apply H2].\n\n  exists z11; split. right; trivial.\n  exists z11; split. right; trivial.\n  left; apply H with z21. apply H3. apply H4.\n\n  exists z11; split. right; trivial.\n  exists z11; split. right; trivial.\n  left; apply H3.\n\n  exists z21; split. left; apply H2.\n  exists z21; split. right; trivial.\n    left; apply H4.\n\n  exists z; split. left; apply H2.\n  exists z; split; right; trivial.\n\n  exists z21; split; [right; trivial |].\n  exists z21; split; [right; trivial |].\n  left; apply H4.\n\n  exists z; split; [right; trivial |].  \n  exists z; split; right; trivial.  \nQed.\n\nLemma hx'_trans : (*2*)\n  forall (A:Type) (r1 r2:Rln A),\n  trans r1 ->\n  trans (hx (tc r2) r1).\nProof.\nintros.\nunfold trans in *; intros.\nunfold hx' in *.\ndestruct H0 as [z1 [? ?]].\ndestruct H1 as [z2 [? ?]].\ndestruct H2 as [z11 [? ?]].\ndestruct H3 as [z21 [? ?]].\ndestruct H2; destruct H3.\n\n  exists z1; split; trivial; clear x H0.\n  exists z21; split; trivial; clear z H5.\n  destruct H4; destruct H1; left.\n    apply trc_ind with z11; trivial; clear z1 H2.\n    apply trc_ind with z2; trivial; clear z21 H3.\n    apply trc_step. exists y; split; trivial.\n\n    apply trc_ind with z11; trivial; clear z1 H2.\n    apply glue_front with y; subst; trivial.\n    intros e1 e2 e3 H12 H23.\n      apply trc_ind with e2; auto. \n\n    apply trc_ind with z2; trivial; clear z21 H3.\n    apply glue_back with y; subst; trivial.\n\n    apply trc_ind with z11; subst; trivial.\n\n  subst. exists z1; split; trivial; clear x H0.\n  destruct H1.\n    exists z21; split; trivial. clear z H5. left.\n    destruct H4.\n      apply trc_ind with z11; trivial; clear z1 H2.\n      apply trc_step. exists y; split; trivial.\n\n      subst. apply glue_back with y; trivial.\n    subst. exists z11; split. left; trivial.\n    destruct H4; destruct H5; subst.\n    left; apply trc_ind with z21; auto.\n    left; trivial. left; trivial. right; trivial.\n   \n  subst. destruct H4.\n    exists z11; split; trivial. clear x H0.\n    exists z21; split; trivial. clear z H5.\n    left. destruct H1; subst.\n      apply trc_ind with z2; trivial.\n      apply trc_step. exists y; split; trivial.\n\n      apply glue_front with z2; trivial.\n\n    subst. \n    intros e1 e2 e3 H12 H23.\n      apply trc_ind with e2; auto. \n  exists z2; split.\n      destruct H0; destruct H1; subst.\n      left; apply H with y; trivial. left; trivial. \n      left; trivial. right; trivial.\n\n      clear H0 H1. exists z21; split; trivial. left; trivial.\n\n  subst. destruct H0; destruct H4; destruct H1; destruct H5; subst.\n    exists z11; split. left; trivial.\n    exists z21; split. left. apply trc_step. exists y; split; trivial.\n    left; trivial.\n\n    exists z11; split. left; trivial.\n    exists z; split. left. apply trc_step. exists y; split; trivial.\n    right; trivial.\n\n    exists z11; split. left; trivial.\n    exists z11; split. right; trivial.\n    left; apply trc_ind with z21; trivial.\n\n    exists z11; split. left; trivial.\n    exists z11; split. right; trivial. left; trivial.\n\n    exists z21; split. left; apply H with y; trivial. \n    exists z21; split. right; trivial. left; trivial. \n\n    exists z; split. left; apply H with y; trivial. exists z; split; right; trivial.\n\n    exists z21; split. left; apply H0.\n    exists z21; split. right; trivial. left; apply H3.\n\n    exists z; split. left; apply H0.\n    exists z; split; right; trivial.\n\n    exists z11; split. right; trivial.\n    exists z21; split.\n      left; apply trc_step; exists y; split; [apply H2 | apply H1].\n      left; apply H3.\n\n   exists z11; split. right; trivial.\n     exists z; split; [| right; trivial].\n     left; apply trc_step; exists y; split; [apply H2 | apply H1].\n\n  exists z11; split. right; trivial.\n  exists z11; split. right; trivial.\n  left; apply trc_ind with z21. apply H2. apply H3.\n\n  exists z11; split. right; trivial.\n  exists z11; split. right; trivial.\n  left; apply H2.\n\n  exists z21; split. left; apply H1.\n  exists z21; split. right; trivial.\n    left; apply H3.\n\n  exists z; split. left; apply H1.\n  exists z; split; right; trivial.\n\n  exists z21; split; [right; trivial |].\n  exists z21; split; [right; trivial |].\n  left; apply H3.\n\n  exists z; split; [right; trivial |].  \n  exists z; split; right; trivial.  \nQed. \n\nLemma tc_dec : forall (A:Type) (r:Rln A) (x y:A),  \n  tc r x y -> \n  exists z,  (r x z /\\ (tc r z y \\/ z = y)).\nintros.\ninduction H.\nexists y; split;trivial. right; trivial.\ndestruct IHtc1 as [z1 ?]. destruct H1. destruct H2.\ndestruct IHtc2 as [z2 ?]. destruct H3. destruct H4.\nexists z1; intuition. left.\neapply trc_ind. apply H2. eapply trc_ind. apply trc_step. apply H3.\ntrivial.\nexists z1; intuition. left.\neapply trc_ind. apply H2. apply trc_step.  rewrite <- H4. trivial.\ndestruct IHtc2 as [z2 ?]. destruct H3. destruct H4.\nexists z1; intuition. left.\nrewrite H2. eapply trc_ind. apply trc_step. apply H3. trivial.\nexists z1; intuition. left.\nrewrite H2. rewrite <- H4. constructor; trivial.\nQed.\n\nLemma tc_dec2 : forall (A:Set) (r:Rln A) (x y:A),  \n  tc r x y -> \n  exists z,  ((tc r x z \\/ z = x) /\\ r z y).\nintros.\ninduction H.\nexists x; split;trivial. right; trivial.\ndestruct IHtc1 as [z1 ?]. destruct H1.\ndestruct IHtc2 as [z2 ?]. destruct H3. \nexists z2; intuition. left.\neapply trc_ind. apply H5. eapply trc_ind. apply trc_step. apply H2.\ntrivial.\nleft. apply trc_ind with z1; auto.\n  rewrite H1; apply trc_step; auto.\nleft; eapply trc_ind. subst; apply trc_step. apply H2. auto.\nsubst; left. apply trc_step; auto.\nQed.\n\nLemma union_implies_hexa_path : (*1*)\n  forall A (r1 r2 r: Rln A) (x y:A),\n  trans r2 ->\n  trans r ->\n  rel_incl r1 r2 ->\n  (tc (rel_union r1 r) x y)->\n  (hx r2 r) x y.\nProof.\nintros A r1 r2 r x y Ht2 Htr Hincl Hin.\ninduction Hin as [x y Hs |].\n  (*step case*)\n  inversion Hs as [Hhb | Hpo].\n     (*hb*)\n    unfold hx; unfold rel_seq. exists x; split;\n      [right; trivial| exists x; split; [right; trivial| left; apply Hincl; apply Hhb]].\n     (*po*)\n    unfold hx; unfold rel_seq; exists y; split;\n      [left; apply Hpo | exists y; split; [right; trivial|right; trivial]].\n  (*ind case*)\n  apply (hx_trans Ht2 Htr IHHin1 IHHin2).\nQed.\n\nLemma r2_left :\n  forall A (r r2:Rln A) (x y z : A),\n  trans r2 ->\n  r2 x z ->\n  tc (rel_seq r2 r) z y ->\n  tc (rel_seq r2 r) x y.\nProof.\nintros A r r2 x y z Ht2 Hhb_xz Htc_zy.\ninduction Htc_zy.\n  destruct H as [z [Hhb_x0z Hpo_zy]].\n  apply trc_step; exists z; split; [|apply Hpo_zy].\n  eapply Ht2; [apply Hhb_xz | apply Hhb_x0z].\n  apply trc_ind with z; [|apply Htc_zy2].\n    apply IHHtc_zy1; apply Hhb_xz.\nQed.\n\nLemma r1_left :\n  forall A (r r1 r2:Rln A) (x y z : A),\n  trans r2 ->\n  rel_incl r1 r2 ->\n  r1 x z ->\n  tc (rel_seq r2 r) z y ->\n  tc (rel_seq r2 r) x y.\nProof.\nintros A r r1 r2 x y z Ht2 Hincl Hhb_xz Htc_zy.\ninduction Htc_zy.\n  destruct H as [z [Hhb_x0z Hpo_zy]].\n  apply trc_step; exists z; split; [|apply Hpo_zy].\n  eapply Ht2; [apply Hincl; apply Hhb_xz | apply Hhb_x0z].\n  apply trc_ind with z; [|apply Htc_zy2].\n    apply IHHtc_zy1; apply Hhb_xz.\nQed.\n\nLemma r1_hexa :\n  forall A (r r1 r2:Rln A) (x z : A),\n  ~(exists x, r2 x x) ->\n  rel_incl r1 r2 ->\n  trans r2 ->\n  trans r ->\n  r1 x z ->\n  (hx r2 r) z x ->\n  exists y, tc (rel_seq r2 r) y y.\nProof.\nintros A r r1 r2 x z Hac2 Hincl Ht2 Htr Hhb_xz Hhx_zx.\n  destruct Hhx_zx as [y [Hor_zy [y' [Hor_yy' Hor_y'x]]]].\n  inversion Hor_zy as [Hpo_zy | Heq_zy];\n  inversion Hor_yy' as [Htc_yy' | Heq_yy'];\n  inversion Hor_y'x as [Hhb'_y'x | Heq_y'x].\n    (* x -hb-> z -po-> y -tc-> y' -hb'-> x *)\n    exists y; apply trc_ind with y'; [apply Htc_yy'|].\n      apply trc_step; exists z; split; [| apply Hpo_zy].\n       eapply Ht2; [apply Hhb'_y'x | apply Hincl; apply Hhb_xz].\n    (* x -hb-> z -po-> y -tc-> y' = x *)    \n   exists y; rewrite Heq_y'x in Htc_yy';\n      apply trc_ind with x; [apply Htc_yy' |\n        apply trc_step; exists z; split; \n          [apply Hincl; apply Hhb_xz|apply Hpo_zy]].\n    (* x -hb-> z -po-> y = y' -hb'-> x *)\n    exists y; apply trc_step; exists z; split; [| apply Hpo_zy].\n    subst; \n      eapply Ht2; [apply Hhb'_y'x | apply Hincl; apply Hhb_xz].\n    (* x -hb-> z -po-> y = y' = x *)\n    exists y; subst; apply trc_step; exists z; split;\n      [apply Hincl; apply Hhb_xz|apply Hpo_zy].\n    (* x -hb-> z = y -tc-> y' -hb'-> x *)\n    exists y'; eapply r2_left; [apply Ht2 | apply Hhb'_y'x |].\n      eapply r1_left; [apply Ht2 | apply Hincl | apply Hhb_xz | subst; apply Htc_yy'].\n    (* x -hb-> z = y -tc-> y' = x *)\n    exists y'; subst.\n      eapply r1_left; [apply Ht2 | apply Hincl | apply Hhb_xz | apply Htc_yy'].\n    (* x -hb-> z = y = y' -hb'-> x *)  (*contrad hb' x x*)\n      subst; assert (r2 x x) as Hhb'_xx.\n        eapply Ht2; [ | apply Hhb'_y'x].\n          apply Hincl; apply Hhb_xz.\n      assert (exists x, r2 x x) as Hcy.\n        exists x; auto.\n      generalize (Hac2 Hcy); intro Htriv; \n      inversion Htriv.\n    (* x -hb-> z = y = y' = x *)    \n      assert (exists x, r2 x x) as Hc.\n        subst; exists x; auto.\n      contradiction.\nQed.\n\nLemma r_right :\n  forall A (r r2 : Rln A) (x y z : A),\n  trans r ->\n  tc (rel_seq r2 r) x z ->\n  r z y ->\n  tc (rel_seq r2 r) x y.\nProof.\nintros A r r2 x y z Htr Htc_xz Hpo_zy.\ninduction Htc_xz.\n  destruct H as [z [Hhb'_xz Hpo_zy0]].\n    apply trc_step; exists z; split; [apply Hhb'_xz | \n      eapply Htr; [apply Hpo_zy0 | apply Hpo_zy]].\napply trc_ind with z; [apply Htc_xz1 |].\n  apply IHHtc_xz2; apply Hpo_zy.\nQed.\n\nLemma hexa_r :\n  forall A (r r2 : Rln A) (x z : A),\n  ~(exists x, r x x) ->\n  trans r ->\n  hx r2 r x z ->\n  r z x ->\n  exists y, tc (rel_seq r2 r) y y.\nProof.\nintros A r r2 x z Hac Htr Hhx_xz Hpo_zx.\n  destruct Hhx_xz as [y [Hor_xy [y' [Hor_yy' Hor_y'z]]]].\n  inversion Hor_xy as [Hpo_xy | Heq_xy];\n  inversion Hor_yy' as [Htc_yy' | Heq_yy'];\n  inversion Hor_y'z as [Hhb'_y'z | Heq_y'z].\n  (* z -po-> x -po-> y -tc-> y' -hb'-> z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; apply trc_ind with y'; [apply Htc_yy' | apply trc_step].\n    exists z; split; [apply Hhb'_y'z |apply Hpo_zy].\n  (* z -po-> x -po-> y -tc-> y' = z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; eapply r_right; [apply Htr | apply Htc_yy' | subst; apply Hpo_zy].\n  (* z -po-> x -po-> y = y' -hb'-> z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; apply trc_step; exists z; split; [subst; apply Hhb'_y'z | apply Hpo_zy].\n  (* z -po-> x -po-> y = y' = z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy; subst.\n  (* contrad: po z z *)\n    assert (exists z, r z z) as Hcy.\n      exists z; auto.\n    generalize (Hac Hcy); intro Hc; contradiction.\n  (* z -po-> x = y -tc-> y' -hb'-> z *)\n  exists y; apply trc_ind with y'; [apply Htc_yy' |].\n    apply trc_step; exists z; split; [apply Hhb'_y'z | subst; apply Hpo_zx].\n  (* z -po-> x = y -tc-> y' = z *)\n  exists y; subst; eapply r_right; [apply Htr | apply Htc_yy' | apply Hpo_zx].\n  (* z -po-> x = y = y' -hb'-> z *)\n  exists y; subst; apply trc_step; exists z; split;\n    [apply Hhb'_y'z | apply Hpo_zx].\n  (* z -po-> x = y = y' = z *)\n(* contrad: po z z *)\n    assert (exists z, r z z) as Hcy.\n      subst; exists z; auto.\n  subst; generalize (Hac Hcy); intro Htriv; inversion Htriv.\nQed.\n\nLemma trans_tc :\n  forall A (r:Rln A),\n  trans r -> tc r = r.\nProof.\nintros A r Ht.\ngeneralize (ext_rel (tc r) r); intro Hext.\napply Hext; split; intro Hxy.\ninduction Hxy; auto.\n  apply Ht with z; auto.\napply trc_step; auto.\nQed.\n\nLemma trans_maybe :\n  forall A (r: Rln A),\n  trans r -> trans (maybe r).\nProof.\nintros A r Ht x y z Hxy Hyz.\ninversion Hxy; inversion Hyz.\n  left; apply Ht with y; auto.\n  left; rewrite H0 in H; auto.\n  left; rewrite <- H in H0; auto.\n  right; subst; auto.\nQed.\n\nLemma hexa'_r :\n  forall A (r r2 : Rln A) (x z : A),\n  ~(exists x, r x x) ->\n  trans r ->\n  hx (tc r2) r x z ->\n  r z x ->\n  exists y, tc (rel_seq (tc r2) (maybe r)) y y.\nProof.\nintros A r r2 x z Hac Htr Hhx_xz Hpo_zx.\n  destruct Hhx_xz as [y [Hor_xy [y' [Hor_yy' Hor_y'z]]]].\n  inversion Hor_xy as [Hpo_xy | Heq_xy];\n  inversion Hor_yy' as [Htc_yy' | Heq_yy'];\n  inversion Hor_y'z as [Hhb'_y'z | Heq_y'z].\n  (* z -po-> x -po-> y -tc-> y' -hb'-> z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; apply trc_ind with y'; [ | apply trc_step].\n  assert (rel_incl (rel_seq (tc r2) r) (rel_seq (tc r2) (maybe r))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split; auto. left; auto.\n  apply (tc_incl Hi Htc_yy').\n    exists z; split; [apply Hhb'_y'z |left; apply Hpo_zy].\n  (* z -po-> x -po-> y -tc-> y' = z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; eapply r_right; [apply trans_maybe; auto | | subst; left; apply Hpo_zy].\n  assert (rel_incl (rel_seq (tc r2) r) (rel_seq (tc r2) (maybe r))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split; auto. left; auto.\n  subst; apply (tc_incl Hi Htc_yy').\n  (* z -po-> x -po-> y = y' -hb'-> z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy.\n  exists y; apply trc_step; exists z; split; [subst; apply Hhb'_y'z | left; apply Hpo_zy].\n  (* z -po-> x -po-> y = y' = z *)\n    generalize (Htr z x y Hpo_zx Hpo_xy); intro Hpo_zy; subst.\n  (* contrad: po z z *)\n    assert (exists z, r z z) as Hcy.\n      exists z; auto.\n    generalize (Hac Hcy); intro Hc; contradiction.\n  (* z -po-> x = y -tc-> y' -hb'-> z *)\n  exists y; apply trc_ind with y'; [ |].\n  assert (rel_incl (rel_seq (tc r2) r) (rel_seq (tc r2) (maybe r))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split; auto. left; auto.\n  apply (tc_incl Hi Htc_yy').\n    apply trc_step; exists z; split; [apply Hhb'_y'z | subst; left; apply Hpo_zx].\n  (* z -po-> x = y -tc-> y' = z *)\n  exists y; subst; eapply r_right; [apply trans_maybe; auto | | left; apply Hpo_zx].\n  assert (rel_incl (rel_seq (tc r2) r) (rel_seq (tc r2) (maybe r))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split; auto. left; auto.\n  apply (tc_incl Hi Htc_yy').\n  (* z -po-> x = y = y' -hb'-> z *)\n  exists y; subst; apply trc_step; exists z; split;\n    [apply Hhb'_y'z | left; apply Hpo_zx].\n  (* z -po-> x = y = y' = z *)\n(* contrad: po z z *)\n    assert (exists z, r z z) as Hcy.\n      subst; exists z; auto.\n  subst; generalize (Hac Hcy); intro Htriv; inversion Htriv.\nQed.\n\nLemma union_cycle_implies_seq_cycle : \n  forall A (r1 r2 r : Rln A) (x:A),\n  ~(exists x, rel_union r1 r x x) ->\n  ~(exists x, r x x) ->\n  ~(exists x, r2 x x) ->\n  trans r2 ->\n  trans r ->\n  rel_incl r1 r2 ->\n  (tc (rel_union r1 r)) x x ->\n  (exists y, (tc (rel_seq r2 r)) y y).\nProof.\nintros A r1 r2 r x ac_u Hacr Hac2 Ht2 Htr Hincl Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      generalize (union_implies_hexa_path Ht2 Htr Hincl Htc_zx); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        eapply (r1_hexa); auto; [apply Hincl | apply Hhb_xz | apply Hp_zx].\n        apply (hexa_r Hacr Htr Hp_zx Hpo_xz).\n     generalize (ac_u); intro Hco.\n     assert (exists x, rel_union r1 r x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma union_implies_hx_path : \n  forall A (r1 r2: Rln A) (x y:A),\n  trans r1 -> trans r2 ->\n  (tc (rel_union r1 r2) x y)->\n  hx r2 r1 x y.\nProof.\nintros A r1 r2 x y Htr1 Htr2 Hin.\ninduction Hin.\n  inversion H as [H1 | H2];\n    unfold hx; unfold rel_seq; unfold maybe.\n      exists y; split; [left; auto |exists y; split; right;auto].\n      exists x; split; [right; auto | exists x; split; [right; auto | left; auto]].\n  apply (hx_trans Htr2 Htr1 IHHin1 IHHin2).\nQed.\n\nLemma union_implies_hx'_path : \n  forall A (r1 r2: Rln A) (x y:A),\n  trans r1 ->\n  (tc (rel_union r1 r2) x y)->\n  hx (tc r2) r1 x y.\nProof.\nintros A r1 r2 x y Htr1 Hin.\ninduction Hin.\n  inversion H as [H1 | H2];\n    unfold hx; unfold rel_seq; unfold maybe.\n      exists y; split; [left; auto |exists y; split; right;auto]. \n      exists x; split; [right; auto | exists x; split; [right; auto | left; auto]].\n      apply trc_step; auto.\n  apply (hx'_trans Htr1 IHHin1 IHHin2).\nQed.\n\nLemma seq_path_implies_union_path :\n  forall A (r1 r2: Rln A) (x y:A),\n  tc (rel_seq r2 r1) x y ->\n  (tc (rel_union r1 r2) x y).\nProof.\nintros A r1 r2 x y Hxy.\ninduction Hxy.\n  destruct H as [z [Hxz Hzy]].\n  apply trc_ind with z; apply trc_step; [right; auto | left; auto].\n  apply trc_ind with z; auto.\nQed.\n\nLemma hx_implies_union_path : \n  forall A (r1 r2: Rln A) (x y:A),\n  hx r2 r1 x y ->\n  (tc (rel_union r1 r2) x y) \\/ x = y.\nProof.\nintros A r1 r2 x y Hin.\ndestruct Hin as [x0 [Hxx0 [y0 [Hx0y0 Hy0y]]]].\ninversion Hxx0; [left|].\n  inversion Hx0y0.\n    inversion Hy0y.\n      apply trc_ind with x0. \n        apply trc_step; left; auto.\n        apply trc_ind with y0.\n          apply seq_path_implies_union_path; auto.\n          apply trc_step; right; auto.\n          subst; apply trc_ind with x0.\n            apply trc_step; left; auto.\n            apply seq_path_implies_union_path; auto.\n      subst; inversion Hy0y.\n      apply trc_ind with y0; apply trc_step; [left; auto | right; auto].\n      subst; apply trc_step; left; auto.\n\n  inversion Hx0y0.\n    inversion Hy0y.\n      left; subst; apply trc_ind with y0.\n          apply seq_path_implies_union_path; auto.\n          apply trc_step; right; auto.\n          subst; left; apply seq_path_implies_union_path; auto.\n      subst; inversion Hy0y.\n      left; apply trc_step; right; auto.\n      right; auto.\nQed.\n\nLemma r2_hexa :\n  forall A (r1 r2:Rln A) (x z : A),\n  ~(exists x, r2 x x) ->\n  trans r2 ->\n (*trans r1 ->*)\n  r2 x z ->\n  (hx r2 r1) z x ->\n  exists y, tc (rel_seq r2 r1) y y.\nProof.\nintros A r1 r2 x z Hac2 Ht2 (*Ht1*) Hhb_xz Hhx_zx.\n  destruct Hhx_zx as [y [Hor_zy [y' [Hor_yy' Hor_y'x]]]].\n  inversion Hor_zy as [Hpo_zy | Heq_zy];\n  inversion Hor_yy' as [Htc_yy' | Heq_yy'];\n  inversion Hor_y'x as [Hhb'_y'x | Heq_y'x].\n    (* x -hb-> z -po-> y -tc-> y' -hb'-> x *)\n    exists y; apply trc_ind with y'; [apply Htc_yy'|].\n      apply trc_step; exists z; split; [| apply Hpo_zy].\n       eapply Ht2; [apply Hhb'_y'x | apply Hhb_xz].\n    (* x -hb-> z -po-> y -tc-> y' = x *)    \n   exists y; rewrite Heq_y'x in Htc_yy';\n      apply trc_ind with x; [apply Htc_yy' |\n        apply trc_step; exists z; split; \n          [apply Hhb_xz|apply Hpo_zy]].\n    (* x -hb-> z -po-> y = y' -hb'-> x *)\n    exists y; apply trc_step; exists z; split; [| apply Hpo_zy].\n    subst; \n      eapply Ht2; [apply Hhb'_y'x | apply Hhb_xz].\n    (* x -hb-> z -po-> y = y' = x *)\n    exists y; subst; apply trc_step; exists z; split;\n      [apply Hhb_xz|apply Hpo_zy].\n    (* x -hb-> z = y -tc-> y' -hb'-> x *)\n    subst; exists y'; eapply r2_left; [apply Ht2 | apply Hhb'_y'x |].\n      eapply r2_left; [apply Ht2 | apply Hhb_xz | subst; apply Htc_yy'].\n    (* x -hb-> z = y -tc-> y' = x *)\n    exists y'; subst.\n      eapply r2_left; [apply Ht2 | apply Hhb_xz | apply Htc_yy'].\n    (* x -hb-> z = y = y' -hb'-> x *)  (*contrad hb' x x*)\n      subst; assert (r2 x x) as Hhb'_xx.\n        eapply Ht2; [ | apply Hhb'_y'x].\n          apply Hhb_xz.\n      assert (exists x, r2 x x) as Hcy.\n        exists x; auto.\n      generalize (Hac2 Hcy); intro Htriv; \n      inversion Htriv.\n    (* x -hb-> z = y = y' = x *)    \n      assert (exists x, r2 x x) as Hc.\n        subst; exists x; auto.\n      contradiction.\nQed.\n\nLemma r2_hexa' :\n  forall A (r1 r2:Rln A) (x z : A),\n  ~(exists x, r2 x x) ->\n  trans r1 ->\n  r2 x z ->\n  (hx (tc r2) r1) z x ->\n  exists y, tc (rel_seq (tc r2) (maybe r1)) y y.\nProof.\nintros A r1 r2 x z Hac2 Ht1 Hhb_xz Hhx_zx.\n  destruct Hhx_zx as [y [Hor_zy [y' [Hor_yy' Hor_y'x]]]].\n  inversion Hor_zy as [Hpo_zy | Heq_zy];\n  inversion Hor_yy' as [Htc_yy' | Heq_yy'];\n  inversion Hor_y'x as [Hhb'_y'x | Heq_y'x].\n    (* x -hb-> z -po-> y -tc-> y' -hb'-> x *)\n    exists y; apply trc_ind with y'; [|].\n  assert (rel_incl (rel_seq (tc r2) r1) (rel_seq (tc r2) (maybe r1))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split.\n      auto. left; auto.\n  apply (tc_incl Hi Htc_yy').  \n      apply trc_step; exists z; split; [| left; apply Hpo_zy].\n       eapply trc_ind; [apply Hhb'_y'x | left; apply Hhb_xz].\n    (* x -hb-> z -po-> y -tc-> y' = x *)    \n   exists y; rewrite Heq_y'x in Htc_yy';\n      apply trc_ind with x; [ |\n        apply trc_step; exists z; split; \n          [left; apply Hhb_xz|left; apply Hpo_zy]].\n  assert (rel_incl (rel_seq (tc r2) r1) (rel_seq (tc r2) (maybe r1))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split.\n      auto. left; auto.\n  apply (tc_incl Hi Htc_yy').  \n    (* x -hb-> z -po-> y = y' -hb'-> x *)\n    exists y; apply trc_step; exists z; split; [|left; apply Hpo_zy].\n    subst; \n      eapply trc_ind; [apply Hhb'_y'x | left; apply Hhb_xz].\n    (* x -hb-> z -po-> y = y' = x *)\n    exists y; subst; apply trc_step; exists z; split;\n      [left; apply Hhb_xz| left; apply Hpo_zy].\n    (* x -hb-> z = y -tc-> y' -hb'-> x *)\n    subst; exists y'; eapply r2_left; [ | apply Hhb'_y'x |].\n    intros e1 e2 e3 H12 H23; apply trc_ind with e2; auto.\n      eapply r2_left; [ | left; apply Hhb_xz | subst].\n    intros e1 e2 e3 H12 H23; apply trc_ind with e2; auto.\n  assert (rel_incl (rel_seq (tc r2) r1) (rel_seq (tc r2) (maybe r1))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split.\n      auto. left; auto.\n  apply (tc_incl Hi Htc_yy').\n    (* x -hb-> z = y -tc-> y' = x *)\n    exists y'; subst.\n      eapply r2_left; [ | left; apply Hhb_xz | ].\n    intros e1 e2 e3 H12 H23; apply trc_ind with e2; auto.\n  assert (rel_incl (rel_seq (tc r2) r1) (rel_seq (tc r2) (maybe r1))) as Hi.\n    intros e1 e2 [e [H1e He2]]; exists e; split.\n        auto. left; auto.\n  apply (tc_incl Hi Htc_yy').\n    (* x -hb-> z = y = y' -hb'-> x *)  (*contrad hb' x x*)\n   exists y'; apply trc_step.\n   exists z; split; [|subst]; auto.\n   apply trc_ind with x; auto; apply trc_step; auto.\n    (* x -hb-> z = y = y' = x *)    \n      assert (exists x, r2 x x) as Hc.\n        subst; exists x; auto.\n      contradiction.\nQed.\n\nLemma union_cycle_implies_seq_cycle2 : \n  forall A (r1 r2 : Rln A) (x:A),\n  ~(exists x, r1 x x) ->\n  ~(exists x, r2 x x) ->\n  ~(exists y, (rel_union r1 r2) y y) ->\n  trans r2 ->\n  trans r1 ->\n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq r2 r1)) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Hu Ht2 Ht1 Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      generalize (union_implies_hx_path Ht1 Ht2 Htc_zx); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        apply (hexa_r Hac1 Ht1 Hp_zx Hhb_xz).\n        eapply (r2_hexa); auto; [apply Hpo_xz | apply Hp_zx].\n     assert (exists x, rel_union r1 r2 x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma union_cycle_implies_seq_cycle3 : \n  forall A (r1 r2 : Rln A) (x:A),\n  ~(exists x, r1 x x) ->\n  ~(exists x, r2 x x) ->\n  ~(exists y, (rel_union r1 r2) y y) ->\n  trans r1 ->\n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq (tc r2) (maybe r1))) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Hu Ht1 Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      generalize (union_implies_hx'_path Ht1 Htc_zx); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        apply (hexa'_r Hac1 Ht1 Hp_zx Hhb_xz).\n        eapply (r2_hexa'); auto; [apply Hpo_xz | apply Hp_zx].\n     assert (exists x, rel_union r1 r2 x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma union_cycle_implies_seq_cycle4 : \n  forall A (r1 r2 : Rln A) (x:A),\n  ~(exists x, r1 x x) ->\n  ~(exists x, r2 x x) ->\n  ~(exists y, (rel_union r1 r2) y y) ->\n  trans r2 ->\n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq (tc r1) (maybe r2))) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Hu Ht2 Hc.\nrewrite union_triv in Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      generalize (union_implies_hx'_path Ht2 Htc_zx); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        apply (hexa'_r Hac2 Ht2 Hp_zx Hhb_xz).\n        eapply (r2_hexa'); auto; [apply Hpo_xz | apply Hp_zx].\n     assert (exists x, rel_union r1 r2 x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; rewrite union_triv in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma union_cycle_implies_seq_cycle_fin : \n  forall A (r1 r2 : Rln A) (x:A),\n  ~(exists x, tc r1 x x) ->\n  ~(exists x, tc r2 x x) ->\n  ~(exists y, (rel_union r1 r2) y y) ->\n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq (tc r2) (tc r1))) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Hu Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      assert (trans (tc r1)) as Ht1.\n        intros e1 e2 e3 H12 H23; apply trc_ind with e2; auto.\n      assert (trans (tc r2)) as Ht2.\n        intros e1 e2 e3 H12 H23; apply trc_ind with e2; auto.\n      assert (tc (rel_union (tc r1) (tc r2)) z x) as Htc_zx'.\n        generalize Htc_zx; apply tc_incl; intros e1 e2 H12;\n        inversion H12; [left | right]; apply trc_step; auto.\n      generalize (union_implies_hx_path Ht1 Ht2 Htc_zx'); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        assert (tc r1 x z) as Hhb_xz'.\n          apply trc_step; auto.\n        apply (hexa_r Hac1 Ht1 Hp_zx Hhb_xz').\n        eapply (r2_hexa); auto.\n        apply trc_step; apply Hpo_xz. apply Hp_zx.\n     assert (exists x, rel_union r1 r2 x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma seq_path_implies_inv_seq_path :\n  forall A (r1 r2 : Rln A) (x y:A),\n  (tc (rel_seq r1 r2)) x y ->\n  (exists e1, exists e2, r1 x e1 /\\ (maybe (tc (rel_seq r2 r1))) e1 e2 /\\ r2 e2 y).\nProof.\nintros A r1 r2 x y Hxy.\ninduction Hxy.\n  destruct H as [e [Hxe Hey]]; exists e; exists e; split; auto; split; auto.\n    right; auto.\n  destruct IHHxy1 as [e [e' [Hxe [Hee' He'z]]]];\n  destruct IHHxy2 as [e1 [e2 [Hz1 [H12 H2y]]]].\n    exists e; exists e2; split; auto; split; auto.\n    inversion Hee'.\n    left; apply trc_ind with e'; auto.\n      inversion H12.\n        apply trc_ind with e1; auto.\n          apply trc_step; exists z; auto.\n        apply trc_step; exists z; split; auto; subst; auto.\n    subst.\n      inversion H12.\n        left; apply trc_ind with e1; auto.\n          apply trc_step; exists z; auto.\n        left; apply trc_step; exists z; split; auto; subst; auto.\nQed.\n\nLemma seq_cycle_implies_inv_seq_cycle :\n  forall A (r1 r2 : Rln A) (x:A),\n  (tc (rel_seq r1 r2)) x x ->\n  (exists y, (tc (rel_seq r2 r1)) y y).\nProof.\nintros A r1 r2 x Hx.\ngeneralize (seq_path_implies_inv_seq_path Hx); intros [e [e' [Hxe [Hee' He'y]]]].\n  inversion Hee'.\n    exists e'; apply trc_ind with e; auto.\n      apply trc_step; exists x; split; auto.\n    subst; exists e'; apply trc_step; exists x; split; auto.\nQed.\n\nLemma union_cycle_implies_seq_cycle5 : \n  forall A (r1 r2 : Rln A) (x:A),\n  ~(exists x, r1 x x) ->\n  ~(exists x, r2 x x) ->\n  ~(exists y, (rel_union r1 r2) y y) ->\n  trans r2 ->\n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq (maybe r2) (tc r1))) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Hu Ht2 Hc.\ngeneralize (union_cycle_implies_seq_cycle4 Hac1 Hac2 Hu Ht2 Hc); intros [y Hy].\napply (seq_cycle_implies_inv_seq_cycle Hy).\nQed.\n\nLemma union_cycle_implies_seq_cycle6 : \n  forall A (r1 r2 r : Rln A) (x:A),\n  ~(exists x, rel_union r1 r x x) ->\n  ~(exists x, r x x) ->\n  ~(exists x, r2 x x) ->\n  trans r2 ->\n  rel_incl r1 r2 ->\n  (tc (rel_union r1 r)) x x ->\n  (exists y, (tc (rel_seq (tc r) (maybe r2) )) y y).\nProof.\nintros A r1 r2 r x ac_u Hacr Hac2 Ht2 Hincl Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      assert (tc (rel_union r2 r) z x) as Hzx'.\n        apply tc_incl with (rel_union r1 r); auto.\n          intros e1 e2 H12; inversion H12; auto.\n            left; apply Hincl; auto. right; auto.\n            \n      generalize (union_implies_hx'_path Ht2 Hzx'); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        assert (r2 x z) as Hxz'.\n          apply Hincl; auto.\n        apply (hexa'_r Hac2 Ht2 Hp_zx Hxz').\n        eapply (r2_hexa'); auto; [apply Hpo_xz | apply Hp_zx].\n     generalize (ac_u); intro Hco.\n     assert (exists x, rel_union r1 r x x) as Hcon.\n       exists x; rewrite Heq_zx in Hr_xz; apply Hr_xz.\n     contradiction.\nQed.\n\nLemma union_cycle_implies_seq_cycle' : \n  forall A (r1 r2 r : Rln A) (x:A),\n  ~(exists x, rel_union r1 r x x) ->\n  ~(exists x, r x x) ->\n  ~(exists x, r2 x x) ->\n  trans r2 ->\n  rel_incl r1 r2 ->\n  (tc (rel_union r1 r)) x x ->\n  (exists y, (tc (rel_seq (maybe r2) (tc r))) y y).\nProof.\nintros A r1 r2 r x Hacu Hacr Hac2 Ht2 Hincl Hc.\ngeneralize (union_cycle_implies_seq_cycle6 Hacu Hacr Hac2 Ht2 Hincl Hc); intros [y Hy].\napply (seq_cycle_implies_inv_seq_cycle Hy).\nQed.\n\nLemma seq_in_maybe_sure_maybe :\n  forall A (r1 r2: Rln A) (x y:A),\n  tc (rel_seq r2 r1) x y ->\n  tc (rel_seq (maybe r2) (rel_seq r1 (maybe r2))) x y.\nProof.\nintros A r1 r2 x y Hxy.\ninduction Hxy.\n  destruct H as [z [Hxz Hzy]]; apply trc_step.\n  exists z; split; [left; auto | exists y; split; [auto | right; auto]].\n  apply trc_ind with z; auto.\nQed.\n\nLemma union_cycle_implies_seq_seq_cycle : \n  forall A (r1 r2: Rln A) (x:A),\n  ~(exists x, r1 x x) ->\n  ~(exists x, r2 x x) ->\n  trans r2 ->\n  trans r1 -> \n  (tc (rel_union r1 r2)) x x ->\n  (exists y, (tc (rel_seq (maybe r2) (rel_seq r1 (maybe r2)))) y y).\nProof.\nintros A r1 r2 x Hac1 Hac2 Ht2 Ht1 Hc.\ngeneralize (tc_dec Hc); intro Hstep.\ndestruct Hstep as [z Hsl].\n  destruct Hsl as [Hr_xz Hor_zx].\n    inversion Hor_zx as [Htc_zx | Heq_zx].\n      generalize (union_implies_hx_path Ht1 Ht2 Htc_zx); intro Hp_zx.\n      inversion Hr_xz as [Hhb_xz | Hpo_xz].\n        generalize (hexa_r Hac1 Ht1 Hp_zx Hhb_xz); intros [y Hy].\n        exists y; apply seq_in_maybe_sure_maybe; auto.\n        generalize (r2_hexa Hac2 Ht2 Hpo_xz Hp_zx); intros [y Hy].\n        exists y; apply seq_in_maybe_sure_maybe; auto.\n  rewrite Heq_zx in Hr_xz; inversion Hr_xz.\n  assert (exists x, r1 x x) as H1.\n    exists x; auto.\n  contradiction.\n  assert (exists x, r2 x x) as H2.\n    exists x; auto.\n  contradiction.\nQed.\n\nLemma union_union_implies_union_hx_path : \n  forall A (r1 r2 r : Rln A) (x y:A),\n  (tc (rel_union r (rel_union r1 r2)) x y)->\n  tc (rel_union r (hx r2 r1)) x y.\nProof.\nintros A r1 r2 r x y Hin.\ninduction Hin.\n  inversion H as [Hr | H12]; apply trc_step.\n    left; auto.\n    inversion H12 as [H1 | H2];\n    unfold hx; unfold rel_seq; unfold maybe; right.\n      exists y; split; [left; auto |exists y; split; right;auto].\n      exists x; split; [right; auto | exists x; split; [right; auto | left; auto]].\n  apply trc_ind with z; auto.\nQed.\n\nDefinition rel_sub (A:Set) (r1 r2 : Rln A) :=\n  fun e1 e2 => r2 e1 e2 /\\ not (r1 e1 e2).\nDefinition mrel (A:Set) (b:bool) (r:Rln A) :=\n  if b then r else (fun e1 => fun e2 => False).\n\nLemma irr_trans_ac :\n  forall A (r : Rln A),\n  trans r ->\n  ~ (exists x, r x x) ->\n  acyclic r.\nProof.\nunfold acyclic;\nintros A r Ht Hc y Hy.\nrewrite (trans_tc Ht) in Hy.\nassert (exists x, r x x) as Hco.\n  exists y; auto.\ncontradiction.\nQed.\n\nLemma lin_implies_part :\n  forall A (r:Rln A) (s:set A),\n  linear_strict_order r s ->\n  partial_order r s.\nProof.\nintros A r s Hlin.\ndestruct_lin Hlin; split; auto.\nQed.\n\nLemma convoluted_u :\n  forall A (r1 r2 : Rln A),\n  rel_incl (rel_union (rel_union (rel_seq r1 r2) (rel_seq r2 r1)) \n    (rel_union r1 r2)) \n      (tc (rel_union r1 r2)).\nProof.\nintros A r1 r2 x y Hxy.\n  inversion Hxy as [Hs | Hu].\n    inversion Hs as [H12 | H21].\n      destruct H12 as [z [H1 H2]]; apply trc_ind with z; \n      apply trc_step; [left | right]; auto.\n      destruct H21 as [z [H2 H1]]; apply trc_ind with z; \n      apply trc_step; [right | left]; auto.\n    apply trc_step; auto.\nQed.\n\nLemma irrefl_equiv :\n  forall A (r1 r2 : Rln A),\n  (~exists x, rel_seq r1 r2 x x) <-> \n  (~exists x, rel_seq r2 r1 x x).\nProof.\nintros A r1 r2; split; intros Hn [x [e [H1 H2]]]; apply Hn;\n  exists e; exists x; split; auto.\nQed.\n\nEnd BasicRel.\n\nUnset Implicit Arguments.\n\nSet Implicit Arguments.\n\nLtac decide_equality := decide equality; auto with equality arith.\n\nDefinition Word := nat.\n\nDefinition Address := Word.\n\nDefinition Value := Word.\nHypothesis eqValue_dec : forall (x y: Value), {x=y} + {x <> y}.\nGlobal Hint Resolve eqValue_dec : equality.\n\nDefinition Proc := nat.\nHypothesis eqProc_dec : forall (x y: Proc), {x=y} + {x <> y}.\nGlobal Hint Resolve eqProc_dec : equality.\n\nDefinition program_order_index := nat.\nLemma eqPoi_dec : forall (x y: program_order_index), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined. \nGlobal Hint Resolve eqPoi_dec : equality.\n\nRecord Iiid  : Set := mkiiid {\n  proc : Proc;\n  poi: program_order_index }.\nLemma eqIiid_dec : forall (x y: Iiid), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined. \nGlobal Hint Resolve eqIiid_dec : equality.\n\nDefinition Eiid := nat.\nLemma eqEiid_dec : forall (x y: Eiid), {x=y} + {x<>y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqEiid_dec : equality.\n\nInductive Dirn : Set :=\n  | R : Dirn\n  | W : Dirn.\nLemma eqDirn_dec : forall (x y: Dirn), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqDirn_dec.\n\nDefinition Location := Address.\n\nLemma eqLoc_dec : forall (x y: Location), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqLoc_dec : equality.\n\nInductive Action : Set :=\n  | Access : Dirn -> Location -> Value -> Action.\nLemma eqAction_dec : forall (x y: Action), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqAction_dec : equality.\n\nRecord Event := mkev {\n  eiid : Eiid; \n  iiid : Iiid;\n  action : Action}.\nLemma eqEv_dec : forall (x y: Event), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqEv_dec : equality.\n\nLemma eqEvc_dec : forall (x y: Event*Event), {x=y} + {x <> y}.\nProof.\ndecide_equality.\nDefined.\nGlobal Hint Resolve eqEvc_dec : equality.\n\n(*Module OEEvt.\nParameter LE : Rln Event -> Rln Event.\nHypothesis OE : forall (s S:set Event) (r:Rln Event),\n  Included _ s S ->\n  partial_order r s -> \n  rel_incl r (LE r) /\\\n  linear_strict_order (LE r) S.\nHypothesis le_lso : forall (s:set Event) (r:Rln Event),\n  linear_strict_order r s -> LE r = r.\nEnd OEEvt.\nImport OEEvt.*)\n\nRecord Event_struct : Type := mkes {\n  events : set Event;\n  iico : Rln Event}. \n\nDefinition po (es: Event_struct) : set (Event*Event) :=\n  fun c => match c with (e1,e2) =>\n   (* both events have same processor *)\n  (e1.(iiid).(proc) = e2.(iiid).(proc)) /\\\n  (* the program order index of e1 is less than the program order index of e2 *)\n  (le e1.(iiid).(poi) e2.(iiid).(poi)) /\\\n  (* both e1 and e2 are in the events of e *)\n  (In _ es.(events) e1) /\\\n  (In _ es.(events) e2)\n  end.\n\nDefinition po_strict (es: Event_struct) : Rln Event :=\n  fun e1 => fun e2 =>\n   (* both events have same processor *)\n  (e1.(iiid).(proc) = e2.(iiid).(proc)) /\\\n  (* the program order index of e1 is less than the program order index of e2 *)\n  (lt e1.(iiid).(poi) e2.(iiid).(poi)) /\\\n  (* both e1 and e2 are in the events of e *)\n  (In _ es.(events) e1) /\\\n  (In _ es.(events) e2).\n\nDefinition po_iico (E:Event_struct) : Rln Event :=\n  fun e1 => fun e2 =>\n    (po_strict E) e1 e2 \\/ (iico E) e1 e2.\n\nDefinition loc (e:Event) : (*option*) Location :=\nmatch e.(action) with\n  | Access _ l _ => (*Some*) l\nend. \n\nDefinition value_of (e:Event) : (*option*) Value :=\n  match e.(action) with\n  | Access _ _ v => (*Some*) v\n  end.\n\nDefinition proc_of (e:Event) : Proc := e.(iiid).(proc). \n\nDefinition procs (es: Event_struct) : set Proc := \n   fun p => exists e, \n     In _ es.(events) e /\\ \n     p = proc_of e. \n\nDefinition to_shared (s:set Event) : set (Event) :=\n  fun e => In _ s e /\\ exists l, exists a, l = a /\\ loc e = (*Some*) l.\n\nDefinition reads (es:Event_struct) : set Event :=\n  fun e => (In _ es.(events) e) /\\ (exists l, exists v, e.(action) = Access R l v). \n\nDefinition writes (es:Event_struct) : set Event :=\n  fun e => (In _ es.(events) e) /\\ (exists l, exists v, e.(action) = Access W l v).\n\nDefinition po_loc (E:Event_struct) : Rln Event :=\n  fun e1 => fun e2 => loc e1 = loc e2 /\\ po_iico E e1 e2.\nDefinition po_loc_llh (E:Event_struct) : Rln Event :=\n  fun e1 => fun e2 => loc e1 = loc e2 /\\ po_iico E e1 e2 /\\\n    ~(reads E e1 /\\ reads E e2).\n\nDefinition well_formed_event_structure (E:Event_struct) : Prop :=\n  (forall x y, po_iico E x y -> proc_of x = proc_of y) /\\\n  (forall e1 e2, In _ E.(events) e1 -> In _ E.(events) e2 ->\n   (e1.(eiid) = e2.(eiid)) /\\ (e1.(iiid) = e2.(iiid)) -> (e1 = e2)) /\\\n   Included _ (dom (iico E)) E.(events) /\\\n   Included _ (ran (iico E)) E.(events) /\\\n   acyclic (iico E) /\\ (forall x y, events E x /\\ events E y /\\ poi (iiid x) = poi (iiid y) /\\ proc_of x = proc_of y -> x <> y -> iico E x y) /\\\n    (forall e1 e2, (iico E) e1 e2 -> (e1.(iiid) = e2.(iiid))) /\\\n   trans (iico E).\n\nDefinition Coherence := Rln Event.\n\nDefinition write_to (e:Event) (l:Location) : Prop :=\n  exists v, action e = Access W l v.\n\nDefinition writes_to_same_loc_l (s:set Event) (l:Location) : set Event :=\n  fun e => In _ s e /\\ write_to e l.\n\nDefinition coherence_well_formed (s:set Event) (co:Coherence) : Prop :=\n  (forall l, linear_strict_order \n     (rrestrict co (writes_to_same_loc_l s l)) (writes_to_same_loc_l s l)) (*Hws_tot*) /\\\n  (forall x e, co x e ->\n   (exists l : Location,\n    In _ (writes_to_same_loc_l s l) x /\\\n    In _ (writes_to_same_loc_l s l) e)) (*Hws_cands*).\nDefinition write_serialization_well_formed (s:set Event) (co:Coherence) := \n  coherence_well_formed s co.\n\nLtac destruct_ws H :=\n  destruct H as [Hws_tot Hws_cands].\n\nDefinition Rfmap := Rln Event.\n\nDefinition read_from (e:Event) (l:Location) : Prop :=\n  exists v, action e = Access R l v.\n\nDefinition rfmaps (s:set Event) : Rln Event :=\n  fun e1 => fun e2 =>\n  In _ s e1 /\\ In _ s e2 /\\\n  exists l, write_to e1 l /\\ read_from e2 l /\\ \n    value_of e1 = value_of e2.\n\nDefinition no_intervening_write (e1 e2:Event) (s:Rln Event): Prop :=\n  s e1 e2 /\\\n  forall l, write_to e1 l ->\n    ~(exists e3, write_to e3 l /\\ s e1 e3 /\\ s e3 e2).\n\nDefinition ls (E:Event_struct) : Rln Event :=\n  fun e1 => fun e2 =>\n    In _ (reads E) e1 /\\ In _ (writes E) e2 /\\ (po_iico E) e1 e2.\n\nDefinition rfmaps_well_formed (E:Event_struct) (s:set Event) (rf:Rfmap) : Prop :=\n  (forall er, In _ (reads E) er -> exists ew, \n     ((In _ s ew) /\\ rf ew er)) /\\ (*Hrf_init*) \n  (forall e1 e2, rf e1 e2 -> (rfmaps s) e1 e2) /\\ (*Hrf_cands*) \n   (forall x w1 w2, rf w1 x -> rf w2 x ->\n    w1 = w2).  (*Hrf_uni*)\n\nLtac destruct_rf H :=\n  destruct H as [Hrf_init [Hrf_cands Hrf_uni]].\n\nDefinition Frmap := Rln Event.\n\nDefinition frmaps (s:set Event) (rf:Rfmap) (co:Coherence) : Frmap :=\n  fun er => fun ew => In _ s er /\\ In _ s ew /\\\n    exists wr, rf wr er /\\ co wr ew.\n\nDefinition AB := Rln Event. \n\nDefinition ab_well_formed (s:set Event) (abc : AB) :=\n  (forall x y, abc x y -> In _ s x /\\ In _ s y /\\ x<>y).\n\nRecord Execution_witness : Type := mkew {\n  co : Coherence;\n  rf : Rfmap}.\nDefinition ws X := co X.\n\nDefinition fr (E:Event_struct) (X:Execution_witness) : Frmap :=\n  frmaps (events E) (rf X) (co X).\nDefinition rfi (X:Execution_witness) : Rfmap :=\n  fun ew => fun er => (rf X) ew er /\\ proc_of ew = proc_of er.\nDefinition rfe (X:Execution_witness) : Rfmap :=\n  fun ew => fun er => (rf X) ew er /\\ proc_of ew <> proc_of er.\n\nDefinition com (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  rel_union (rel_union (rf X) (fr E X)) (co X).\n\nModule Type Dp.\nParameter dp : Event_struct -> Rln Event.\nHypothesis dp_valid : forall (E:Event_struct),\n  rel_incl (dp E) (po_iico E) /\\ trans (dp E) /\\\n  forall x y, dp E x y -> reads E x.\n(*Hypothesis dp_fun :\n  forall E s x y,\n  dp E x y /\\ s x /\\ s y <->\n  dp (mkes (Intersection Event (events E) s) (rrestrict (iico E) s)) x y.*)\nEnd Dp.\n\nSet Implicit Arguments.\nDefinition rfc (A:Type) (rfe:Rln A) (r:Rln A) :=\n  rel_union r (rel_union (rel_seq rfe r) (rel_union (rel_seq r rfe) (rel_seq rfe (rel_seq r rfe)))).\nUnset Implicit Arguments.\n\nModule Type Archi.\nParameter llh : bool.\nParameter ppo : Event_struct -> Rln Event.\nHypothesis ppo_valid : forall (E:Event_struct),\n  rel_incl (ppo E) (po_iico E).\nParameter fences : Event_struct -> Rln Event.\nHypothesis fences_valid : forall (E:Event_struct),\n  rel_incl (fences E) (po_iico E).\nParameter prop : Event_struct -> Execution_witness -> Rln Event.\nHypothesis prop_valid : forall E X, ~(exists x, (prop E X) x x).\nHypothesis prop_trans : forall E X, trans (prop E X).\nHypothesis wit_incl :\n  forall E X X' e1 e2,\n  ((rf X) e1 e2 -> (rf X') e1 e2) ->\n  prop E X e1 e2 ->\n  prop E X' e1 e2.\nEnd Archi.\n\nModule Wmm (A : Archi) (dp : Dp).\nImport A.\nImport dp.\n\nDefinition hb (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  rel_union (rfe X) (tc (rel_union (A.ppo E) (A.fences E))).\n\nDefinition com' (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  fun e1 => fun e2 => (rel_union (rel_union (com E X) (rel_seq (ws X) (rf X))) (rel_seq (fr E X) (rf X))) e1 e2.\n\nDefinition com_vs_po E X (r:Rln Event) :=\n  (forall e1 e2, r e1 e2 -> ~(com' E X e2 e1)).\n\nDefinition uniproc E X :=\n  (*if llh then*) com_vs_po E X (po_loc_llh E)\n  (*else com_vs_po E X (po_loc E)*).\n\nDefinition valid_execution (E:Event_struct) (X:Execution_witness) : Prop :=\n  coherence_well_formed (events E) (co X) /\\\n  rfmaps_well_formed E (events E) (rf X) /\\\n  uniproc E X /\\\n  acyclic (hb E X) /\\ (*<<< would need irrefl(hb) for C++ as of today*)\n  irrefl (rel_seq (fr E X) (rel_seq (prop E X) (hb E X))) /\\\n  acyclic (rel_union (co X) (prop E X)).\n\nLtac destruct_valid H :=\n  destruct H as [[Hws_tot Hws_cands] [[Hrf_init [Hrf_cands Hrf_uni]] [Huni [Hth [Hlc Hvalid]]]]]; \n  unfold coherence_well_formed in Hws_tot(*; unfold uniproc in Hsp*).\n\n(*Goal forall E X, valid_execution E X -> True.\nintros E X Hvalid.\ndestruct_valid Hvalid. *)\n\nEnd Wmm.", "meta": {"author": "0Ccipher", "repo": "proofs", "sha": "e645989767bc4e4f6c0f20a908c18da6cad01306", "save_path": "github-repos/coq/0Ccipher-proofs", "path": "github-repos/coq/0Ccipher-proofs/proofs-e645989767bc4e4f6c0f20a908c18da6cad01306/ref/wmm-1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8073341016784555}}
{"text": "Require Import ZArith.\nAdd LoadPath \".\".\nRequire Import groups.\nInstance semigroupZ : Semigroup Z :=\n{\n  mult := Z.add;\n  assoc := Z.add_assoc;\n}.\n\nInstance monoidZ : Monoid Z :=\n{\n  e := 0;\n  left_id := Z.add_0_l;\n}.\n\nInstance groupZ : Group Z :=\n{\n  inv := Z.opp;\n  left_inv := Z.add_opp_diag_l;\n}.\n\nOpen Scope group_scope.\nSection Z_Groups.\n  Variable G: Type.\n  Context `{Hgr: Group G}.\n\n  Definition pow_z (a: G) (z: Z) : G :=\n    match z with\n    | Z0 => e\n    | Zpos x => pow G a (Pos.to_nat x)\n    | Zneg x => inv (pow G a (Pos.to_nat x))\n    end.\n\n  Notation \"a ** b\" := (pow_z a b) (at level 35, right associativity).\n\n  Lemma pow_a_n_plus_1_Z : forall (a: G) (n: Z), (pow_z a (Z.succ n)) = a * pow_z a n.\n  Proof.\n    intros a n. unfold Z.succ. unfold Z.add.\n    destruct n.\n    - simpl. reflexivity.\n    - simpl. rewrite (Pos2Nat.inj_add p 1). rewrite Nat.add_comm. rewrite <- a_pow_m_n. simpl. rewrite (right_id G). reflexivity.\n    - rewrite <- Pos2Z.add_pos_neg. induction p using Pos.peano_ind.\n      + simpl. rewrite (right_id G). rewrite right_inv. reflexivity.\n      + rewrite <- Pos.add_1_l. rewrite <- Pos2Z.add_neg_neg. rewrite Z.add_assoc. rewrite Z.add_opp_diag_r. rewrite Z.add_0_l. rewrite Pos2Z.add_neg_neg. unfold pow_z. rewrite Pos.add_comm. rewrite Pos2Nat.inj_add. simpl. rewrite <- a_pow_m_n. rewrite inv_prod. simpl. rewrite (right_id G). rewrite assoc. rewrite right_inv. rewrite left_id. reflexivity.\n  Qed.\n\n  Lemma pow_a_n_minus_1_Z : forall (a: G) (n: Z), (pow_z a (Z.pred n)) = inv(a) * pow_z a n.\n  Proof.\n    intros a n. unfold Z.pred. unfold Z.add.\n    destruct n.\n    - simpl. repeat rewrite (right_id G). reflexivity.\n    - rewrite <- Pos2Z.add_pos_neg. induction p using Pos.peano_ind.\n      + simpl. rewrite (right_id G). rewrite left_inv. reflexivity.\n      + rewrite Pplus_one_succ_l. rewrite Pos.add_1_l. rewrite Pos2Z.inj_succ. rewrite pow_a_n_plus_1_Z. rewrite assoc. rewrite left_inv. rewrite left_id. rewrite <- Z.add_1_r. rewrite <- Z.add_assoc. rewrite Pos2Z.add_pos_neg. simpl (Z.pos_sub 1 1). rewrite Z.add_0_r. reflexivity.\n    - simpl. rewrite (Pos2Nat.inj_add p 1). rewrite <- a_pow_m_n. rewrite inv_prod. simpl (pow G a (Pos.to_nat 1)). rewrite (right_id G). reflexivity.\n  Qed.\n\n  Proposition a_pow_m_n_Z : forall (a: G) (n m: Z), (pow_z a n)*(pow_z a m) = pow_z a (n + m).\n  Proof.\n    intros. induction n using Z.peano_ind.\n    - simpl. apply left_id.\n    - rewrite pow_a_n_plus_1_Z. rewrite <- assoc. rewrite IHn. rewrite <- pow_a_n_plus_1_Z. rewrite Z.add_succ_l. reflexivity.\n    - rewrite pow_a_n_minus_1_Z. rewrite <- assoc. rewrite IHn.\n      rewrite Z.add_pred_l. rewrite pow_a_n_minus_1_Z. reflexivity.\n  Qed.\n\n  Definition order (a: G) (n: nat) :=\n    pow G a n = e /\\ (forall k, 0 < k < n -> pow G a k <> e).\n\nEnd Z_Groups.\nClose Scope group_scope.\n", "meta": {"author": "usr345", "repo": "groups", "sha": "bb841f040cf663c7ceec080f355583e8ce470a76", "save_path": "github-repos/coq/usr345-groups", "path": "github-repos/coq/usr345-groups/groups-bb841f040cf663c7ceec080f355583e8ce470a76/groups_Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.8071239468808004}}
{"text": "(*|\n##################################################################\nProving ``even + even = even`` with mutual induction using tactics\n##################################################################\n\n:Link: https://stackoverflow.com/q/43560581\n|*)\n\n(*|\nQuestion\n********\n\nI was trying out mutual induction in Coq, the first type I defined was\n|*)\n\nInductive IsEven : nat -> Prop :=\n| EvenO : IsEven O\n| EvenS n : IsOdd n -> IsEven (S n)\nwith IsOdd : nat -> Prop :=\n| OddS n : IsEven n -> IsOdd (S n).\n\n(*|\nI now wanted to prove that the sum of even numbers is even. I was able\nto do this using a ``Fixpoint`` and pattern matching:\n|*)\n\nFixpoint even_plus_even (n m : nat) (evenn : IsEven n) (evenm : IsEven m) :\n  IsEven (n + m) :=\n  match evenn with\n  | EvenO => evenm\n  | EvenS n' oddn' => EvenS (n' + m) (odd_plus_even n' m oddn' evenm)\n  end\nwith odd_plus_even (n m : nat) (oddn : IsOdd n) (evenm : IsEven m) :\n  IsOdd (n + m) :=\n  match oddn with\n  | OddS n' evenn' => OddS (n' + m) (even_plus_even n' m evenn' evenm)\n  end.\n\n(*|\nThis defines both ``even_plus_even`` and ``odd_plus_even``. I would\nnow like to prove this using tactics in a more terse way (preferably\nwithout using many predefined lemmas to keep the code as\nself-contained as possible) but I haven't gotten very far.\n\nSpecifically, is it possible to prove both ``even_plus_even`` and\n``odd_plus_even`` using only one Lemma like we can with the\n``Fixpoint``?\n\n**Edit:** Thank you very much for your answers, the ``Lemma ... with\n...`` syntax was exactly what I was looking for. In fact\n|*)\n\nLemma even_plus_even2 (n m : nat) (evenn : IsEven n) (evenm : IsEven m) :\n  IsEven (n + m)\nwith odd_plus_even2 (n m : nat) (oddn : IsOdd n) (evenm : IsEven m) :\n  IsOdd  (n + m).\nProof.\n  induction evenn; simpl.\n  - assumption.\n  - constructor. auto.\n  - induction oddn; simpl. constructor. auto.\nDefined.\n\n(*|\ngenerates exactly the same proof term as the ``Fixpoint`` in my\noriginial question.\n|*)\n\n(*|\nAnswer (Vinz)\n*************\n\nThere is support for mutual induction in Coq. I know of two ways, but\nI only recall how to use one:\n\n1. Combined Schemes\n\n   Here is how it works:\n|*)\n\nScheme IsEven_ind2 := Induction for IsEven Sort Prop\n    with IsOdd_ind2 := Induction for IsOdd Sort Prop.\n\nCombined Scheme IsEvenOdd_ind from IsEven_ind2, IsOdd_ind2.\n\nLemma foo : (forall (n : nat) (evenn : IsEven n), forall m (evenm : IsEven m),\n                IsEven (n + m)) /\\\n              (forall (n : nat) (oddn : IsOdd n), forall m (evenm : IsEven m),\n                  IsOdd (n + m)).\nProof.\n  apply IsEvenOdd_ind.\n  - now intros m hm.\n  - intros h hn hi m hm. rewrite plus_Sn_m. apply EvenS. now apply hi.\n  - intros h hn hi m hm. rewrite plus_Sn_m. apply OddS. now apply hi.\nQed.\n\n(*|\n1. ``Lemma with``\n\n   On this one I just don't know how to finish it but that's a syntax\n   issue iirc:\n|*)\n\nReset foo. (* .none *)\nLemma foo : forall (n m : nat) (evenn : IsEven n) (evenm : IsEven m),\n    IsEven (n + m)\nwith bar : forall (n m : nat) (oddn : IsOdd n) (evenm : IsEven m),\n    IsOdd (n + m).\nProof.\n  - intros n m hn. revert m.\n    induction hn as [| p hp]; intros m hm; simpl in *.\n    + exact hm.\n    + now apply EvenS; apply bar.\n  - intros n m hn hm. revert n hn.\n    induction hm as [| p hp]; intros n hn; simpl in *.\n    + now apply bar; [exact hn | apply EvenO].\n    + apply bar; [exact hn |]. now apply EvenS.\nFail Qed. (* .fails .unfold *)\nAbort. (* .none *)\n\n(*|\n**Edit:** Here is a valid syntax for the ``Lemma with`` solution.\n|*)\n\nLemma foo (n : nat) (evenn : IsEven n) :\n  forall (m : nat) (evenm : IsEven m), IsEven (n + m)\nwith bar (n : nat) (oddn : IsOdd n) :\n  forall (m : nat) (evenm : IsEven m), IsOdd (n + m).\nProof.\n  - induction evenn as [| p hp]; intros m hm; simpl in *.\n    + exact hm.\n    + now apply EvenS; apply bar.\n  - induction oddn as [p hp]. intros n hn. simpl in *.\n    apply OddS. now apply foo.\nQed.\n\n(*|\nAnswer (larsr)\n**************\n\nYou can for instance prove both lemmas at the same time by \"anding\"\nthem together into one lemma, and then extract the left or right part\nof the clause using ``proj1`` and ``proj2``.\n|*)\n\nReset even_plus_even. (* .none *)\nLemma even_or_odd_plus_even: forall (n m : nat),\n    (forall (evenn : IsEven n) (evenm : IsEven m), IsEven (n + m)) /\\\n      (forall (oddn : IsOdd n) (evenm : IsEven m), IsOdd (n + m)).\nProof.\n  induction n; split; intros.\n  - auto.\n  - inversion oddn.\n  - destruct (IHn m) as [He Ho]. inversion evenn.\n    constructor. auto.\n  - destruct (IHn m) as [He Ho]. inversion oddn.\n    constructor. auto.\nQed.\n\nDefinition even_plus_even n m := proj1 (even_or_odd_plus_even n m).\nDefinition odd_plus_even n m := proj2 (even_or_odd_plus_even n m).\n\n(*| gives you |*)\n\nCheck even_plus_even. (* .unfold .messages *)\nCheck odd_plus_even. (* .unfold .messages *)\n\n(*|\nNotice that the two clauses share share the ``n`` and ``m``, which you\nneed if the clauses can't be proved separately because they need to\ndepend on each other. (In this particular case they don't, though. You\n*could* prove the statements separately, as Anton showed.)\n\nEDIT: just saw Vinz solution. I didn't know Lemma had the ``with``\nsyntax (thanks for showing!), but that makes sense and is I think a\nneater way to do this mutually dependent definition.\n|*)\n\nReset even_plus_even. (* .none *)\nLemma even_plus_even : forall n m, IsEven n -> IsEven m -> IsEven (n + m)\nwith odd_plus_even: forall n m, IsOdd n -> IsEven m -> IsOdd (n + m).\nProof.\n  - induction 1; simpl; auto using EvenS.\n  - induction 1; simpl; auto using OddS.\nQed.\n\n(*|\n----\n\n**A:** Actually, both ``Lemma`` and ``Fixpoint`` are just aliases for\n``Theorem``, see `here\n<https://coq.inria.fr/distrib/current/refman/Reference-Manual003.html#hevea_command20>`__,\nwhich means that you can also define ``Fixpoint`` definitions with\nproof tactics, without giving the explicit proof term upfront. By the\nway, the ``refine`` tactic is useful if you want to give parts of the\nproof term explicitly, while leaving holes to fill in by tactics.\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-even-even-even-with-mutual-induction-using-tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.9252299612154571, "lm_q1q2_score": 0.807121939922205}}
{"text": "(** \u5e30\u7d0d\u578b\u306e\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb **)\n(** A Tutorial on [Co-]Inductive Types in Coq **)\n\n\n(* 2 Introducing Inductive Types *)\n\n\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\n\nPrint nat.\nCheck nat.\nCheck O.\nCheck S.\nCheck (S (S (S O))).                        (* S (S (S O)) *)\n\n\nReset nat.\nPrint nat.\nCheck nat.\nCheck O.\nCheck S.\nCheck (S (S (S O))).                        (* 3 *)\n\n\n\n\n(* 2.1 Lists *)\nRequire Import List.\nPrint list.                                 (* nil, cons *)\n\n\n(*\nInductive list (A : Type) : Type :=\n    nil : list A | cons : A -> list A -> list A\n*)\n\n\nCheck list.                                 (* Type -> Type *)\nCheck (list nat).                           (* Set *)\nCheck (nil (A:= nat)).                      (* list nat *)\nCheck (nil (A:= nat -> nat)).               (* list (nat -> nat) *)\nCheck (fun A: Set => (cons (A:=A))).\nCheck (cons 3 (cons 2 nil)).\n\n\n\n\n(* 2.2 Vectors. *)\n\n\nRequire Import Bvector.\nPrint vector.                               (* Vnil, Vcons *)\n\n\nCheck (Vnil nat).                           (* vector nat 0 *)\nCheck (fun (A:Set)(a:A) => Vcons _ a _ (Vnil _)).\nCheck (Vcons _ 5 _ (Vcons _ 3 _ (Vnil _))).\n\n\nCheck (Vcons _ 3 _ (Vnil _)).\n\n\nCheck (Vcons _   1  _ (Vcons _   2  _ (Vcons _   3 _ (Vnil _  )))). (* vector nat 3 *)\nCheck (Vcons nat 1  2 (Vcons nat 2  1 (Vcons nat 3 0 (Vnil nat)))). (* vector nat 3 *)\nCheck (vector nat 3).                       (* nat\u306e3\u500b\u306e\u8981\u7d20\u304b\u3089\u306a\u308b\u30d9\u30af\u30bf\u30fc *)\n\n\n\n\n(* 2.3 The contradictory proposition. *)\n\n\nPrint False.                                (* Inductive False : Prop := *)\n(* Notice that no constructor is given in this definition. *)\n\n\n\n\n(* 2.4 The tautological proposition. *)\n\n\nPrint True.                                 (* Inductive True : Prop := I : True *)\n(* only one element I. *)\n\n\n\n\n(* 2.5 Relations as inductive types. *)\n\n\nPrint le.                                   (* le_n, le_S *)\n(*\n  Inductive le (n : nat) : nat -> Prop :=   (* (le n) : (nat -> Prop) *)\n  | le_n : n <= n\n  | le_S : forall m : nat, n <= m -> n <= S m.\n*)\n\n\nTheorem zero_leq_three: 0 <= 3.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  Restart.\n\n\n  constructor 2.                            (* constructor \u3060\u3051\u3067\u3082\u3088\u3044 *)\n  constructor 2.                            (* constructor \u3060\u3051\u3067\u3082\u3088\u3044 *)\n  constructor 2.                            (* constructor \u3060\u3051\u3067\u3082\u3088\u3044 *)\n  constructor 1.                            (* constructor \u3060\u3051\u3067\u3082\u3088\u3044 *)\n  Restart.\n\n\n  repeat constructor.\nQed.\n\n\nPrint zero_leq_three.\n(*\n  zero_leq_three = le_S 0 2 (le_S 0 1 (le_S 0 0 (le_n 0)))\n*)\n\n\nPrint lt.\n\n\nLemma zero_lt_three : 0 < 3.\n\n\n  (* Goal : 0 < 3 *)\n  unfold lt.\n  (* Goal : 1 <= 3 *)\n\n\n  repeat constructor.\nQed.\n\n\n\n\n(* 2.6 The propositional equality type. *)\n\n\nPrint eq.                                   (* refl_equal *)\n\n\n(* The type system of Coq allows us to consider equality\n  between various kinds of terms:\n  elements of a set, proofs, propositions, types, and so on.\n*)\n\n\nLemma eq_3_3 : 2 + 1 = 3.\n  apply refl_equal.\n  Restart.\n\n\n  reflexivity.\nQed.\n\n\nLemma eq_3_3' : 1 + 2 = 3.\n  apply eq_3_3.\nQed.\n\n\nLemma eq_3x4_3x4 : (2*6) = (3*4).\n  reflexivity.\nQed.\nPrint eq_3x4_3x4.                           (* refl_equal (3 * 4) *)\n\n\nLemma eq_proof_proof : refl_equal (2*6) = refl_equal (3*4).\n  reflexivity.\nQed.\nPrint eq_proof_proof.                       (* refl_equal (refl_equal (3 * 4)) *)\n\n\nLemma eq_lt_le : (2 < 4) = (3 <= 4).\n  reflexivity.\nQed.\nPrint eq_lt_le.\n\n\nLemma eq_nat_nat : nat = nat.\n  reflexivity.\nQed.\nPrint eq_nat_nat.                           (* refl_equal nat *)\n\n\nLemma eq_Set_Set : Set = Set.\n  reflexivity.\nQed.\nPrint eq_Set_Set.                           (* refl_equal Set *)\n\n\n(* 2.7 Logical connectives. *)\n\n\n(* conjunction\u3001\u8ad6\u7406\u7a4d *)\nPrint and.\n(*\n  Inductive and (A B : Prop) : Prop :=\n  | conj : A -> B -> A /\\ B.\n*)\n\n\n(* disjunction\u3001\u8ad6\u7406\u548c *)\nPrint or.\n(*\n  Inductive or (A B : Prop) : Prop :=\n  | or_introl : A -> A \\/ B\n  | or_intror : B -> A \\/ B.\n*)\n\n\n(* the type sumbool is a disjunction but with computational contents. *)\nPrint sumbool.\n(*\n  Inductive sumbool (A B : Prop) : Set :=\n  | left : A -> {A} + {B}\n  | right : B -> {A} + {B}.\n*)\n\n\nRequire Import Compare_dec.\nCheck le_lt_dec.                            (* forall n m : nat, {n <= m} + {m < n} *)\n\n\nDefinition max (n p :nat) :=\n  match le_lt_dec n p with\n  | left _ => p\n  | right _ => n\n  end.\n\n\n\n\nTheorem le_max : forall n p, n <= p -> max n p = p.\n  intros.\n  unfold max.\n  case (le_lt_dec n p).\n  \n  (* Goal : n <= p -> p = p *)\n  reflexivity.                              (* \u300c->\u300d\u304c\u524d\u306b\u3064\u3044\u3066\u3044\u3066\u3082\u3001\u554f\u984c\u306a\u3044 *)\n\n\n  (* Goal : p < n -> n = p *)\n  intros.\n  absurd (p < p).\n  eauto with arith.\n  eauto with arith.\nQed.\nExtraction max.\n\n\n\n\n(* 2.8 The existential quantifier. *)\n\n\nPrint ex.\n(*\n  Inductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> ex P.\n*)\n\n\n(* 2.9 Mutually Dependent Definitions *)\n\n\nInductive tree(A:Set) : Set :=\n  node : A -> forest A -> tree A\n    with forest (A: Set) : Set :=\n    | nochild : forest A\n    | addchild : tree A -> forest A -> forest A.\n\n\nInductive\n  even : nat -> Prop :=\n  | evenO : even O\n  | evenS : forall n, odd n -> even (S n)\nwith\n  odd : nat -> Prop :=\n    oddS : forall n, even n -> odd (S n).\n\n\nLemma odd_3 : odd 3.\n  simpl.\n  apply oddS.\n  apply evenS.\n  apply oddS.\n  apply evenO.\nQed.\nPrint odd_3.\n\n\nLemma odd_49 : odd (7 * 7).\n  simpl; repeat constructor.\nQed.\nPrint odd_49.\n\n\n\n\n(* 3 Case Analysis and Pattern-matching *)\n\n\n(* 3.1 Non-dependent Case Analysis *)\n\n\n(* In most of the cases, Coq is able to infer the type B of the object defined,\n  so the \u201creturn B\u201d part can be omitted. *)\n\n\nDefinition Is_Zero (n:nat) :=\n  match n return Prop with                  (* return Prop \u306f\u7701\u7565\u3067\u304d\u308b\u3002 *)\n  | O => True\n  | S p => False\n  end.\n\n\n(* 3.1.1 Example: the predecessor function. *)\n\n\nDefinition pred (n:nat) :=\n  match n return nat with                   (* return nat \u306f\u7701\u7565\u3067\u304d\u308b\u3002 *)\n  | O => O\n  | S m => m\n  end.\n\n\nEval simpl in pred 56.                      (* 55 *)\nEval simpl in pred 0.                       (* 0 *)\nEval simpl in fun p => pred (S p).          (* fun p : nat => p *)\n\n\nDefinition xorb (b1 b2:bool) :=\n  match b1, b2 with\n  | false, true => true\n  | true, false => true\n  | _ , _ => false\nend.\nPrint xorb.\n\n\n\n\n(* 3.2 Dependent Case Analysis *)\n\n\n(* 3.2.1 Example: strong specification of the predecessor function. *)\n\n\nDefinition pred_spec (n:nat) :=\n  {m:nat | n = 0 /\\ m = 0 \\/ n = S m}.\n\n\nDefinition predecessor : forall n:nat, pred_spec n.\n  intros.\n  case n.\n\n\n  (* Goal : pred_spec 0 *)\n  unfold pred_spec.\n  exists 0.\n  auto.\n\n\n  (* Gaol : pred_spec (S n0) *)\n  intros.\n  unfold pred_spec.\n  exists n0.\n  auto.\nQed.\nPrint predecessor.\nExtraction predecessor.\n\n\n(* Exercise 3.1 *)\nTheorem nat_expand :\n  forall n:nat,\n  n = match n return nat with                   (* return nat \u306f\u7701\u7565\u3067\u304d\u308b\u3002 *)\n      | 0 => 0\n      | S p => S p\n      end.\n\n\n  intros.\n  case n.\n\n\n  (* Goal : 0 = 0 *)\n  reflexivity.\n\n\n  (* forall n0 : nat, S n0 = S n0 *)    \n  intros.\n  reflexivity.\nQed.\nPrint nat_expand.\nExtraction nat_expand.\n\n\n\n\n(* 3.3 Some Examples of Case Analysis *)\n\n\n(* 3.3.1 The Empty Type *)\n\n\nTheorem fromFalse : False -> 0=1.\n  intros.\n  contradiction.\nQed.\nPrint fromFalse.\nExtraction fromFalse.\n\n\nPrint not.                                  (* fun A : Prop => A -> False *)\nLocate \"~ _\".                               (* ~ x := not x *)\n\n\nFact Nosense : 0 <> 0 -> 2 = 3.\n  intro H.\n  case H.\n  reflexivity.\nQed.\n\n\n\n\n(* 3.3.2 The Equality Type *)\n\n\nTheorem trans : forall n m p : nat, n = m -> m = p -> n = p.\n  intros n m p H H0.\n  case H0.\n  apply H.\nQed.\n\n\n(* Exercise 3.2 Prove the symmetry property of equality. *)\n\n\nTheorem trans' : forall n m p : nat, n = m -> m = p -> n = p.\n  intros n m p H H0.\n  (* H : n = m *)\n  rewrite -> H.                             (* \u5de6\u8fba\u3092 -> \u53f3\u8fba\u3067\u7f6e\u304d\u63db\u3048\u308b\u3002->\u306f\u7701\u3051\u308b\u3002*)\n  apply H0.\nQed.\n\n\nPrint trans.\nPrint trans'.\n\n\nLemma Rw : forall x y: nat, y = y * x -> y * x * x = y.\n  intros x y e.\n  rewrite <- e. rewrite <- e.               (* do 2 rewrite <- e. \u3068\u3057\u3066\u3082\u3088\u3044\u3002 *)\n  reflexivity.\nQed.\n\n\nRequire Import Arith.\nPrint mult_1_l.                             (* _\uff11_L *) (* forall n : nat, 1 * n = n *)\nPrint mult_plus_distr_r.\n                                  (* forall n m p : nat, (n + m) * p = n * p + m * p *)\n\n\nLemma mult_distr_S : forall n p : nat, n * p + p = (S n) * p.\n  intros n p.\n  simpl.\n  apply plus_comm.                          (* Library Coq.Arith.Plus *)\nQed.\n\n\nLemma four_n : forall n : nat, n + n + n + n = 4 * n.\n  intro n.\n  rewrite <- (mult_1_l n).\n  Restart.\n\n\n  intro n.\n  pattern n at 1.\n  rewrite <- mult_1_l.\n  rewrite mult_distr_S.\n  rewrite mult_distr_S.\n  rewrite mult_distr_S.\n  reflexivity.\nQed.\n\n\n\n\n(* 3.3.3 The Predicate n <= m *)\n\n\nLemma predecessor_of_positive :\n  forall n, 1 <= n -> exists p : nat, n = S p.\n  intros n H.\n  case H.                           (* apply nat_ind with (n := n) in H. *)\n  \n  (* exists p : nat, 1 = S p *)\n  exists 0.\n  reflexivity.\n\n\n  (* forall m : nat, 1 <= m -> exists p : nat, S m = S p *)\n  intros m H0.\n  exists m.\n  reflexivity.\nQed.\n\n\n\n\n(* 3.3.4 Vectors *)\n\n\n(* For instance, let us define a function for computing the tail of any vector. *)\n\n\nDefinition Vtail_total (A : Set) (n : nat) (v : vector A n) : vector A (pred n) :=\n  match v in (vector _ n0) return (vector A (pred n0)) with\n  | Vnil => Vnil A\n  | Vcons _ n0 v0 => v0\n  end.\n\n\n\n\n(* 3.4 Case Analysis and Logical Paradoxes *)\n\n\n(* 3.4.1 The Positivity Condition *)\n\n\nSection Paradox.\nVariable Lambda : Set.\nVariable lambda : (Lambda -> False) -> Lambda.\n\n\nVariable matchL : Lambda ->\n  forall Q : Prop, ((Lambda -> False) -> Q) -> Q.\n\n\nDefinition application (f x : Lambda) : False :=\n  matchL f False (fun h => h x).\n\n\nDefinition Delta : Lambda :=\n  lambda (fun x : Lambda => application x x).\n\n\nDefinition loop : False := application Delta Delta.\n\n\nTheorem two_is_three : 2 = 3.\n  elim loop.\nQed.\nEnd Paradox.\n\n\nRequire Import ZArith.\nInductive itree : Set :=\n  | ileaf : itree\n  | inode : Z -> (nat -> itree) -> itree.\n\n\nDefinition isingle l := inode l (fun i => ileaf).\n\n\nDefinition t1 := inode 0 (fun n => isingle (Z_of_nat n)).\n\n\nDefinition t2 :=\n  inode 0\n    (fun n : nat =>\n      inode (Z_of_nat n)\n        (fun p => isingle (Z_of_nat (n*p)))).\n\n\nInductive itree_le : itree -> itree -> Prop :=\n  | le_leaf : forall t, itree_le ileaf t\n  | le_node : forall l l' s s',\n                Zle l l' ->\n                  (forall i, exists j:nat, itree_le (s i) (s' j)) ->\n                    itree_le (inode l s) (inode l' s').\n\n\nInductive itree_le' : itree -> itree -> Prop :=\n  | le_leaf' : forall t, itree_le' ileaf t\n  | le_node' : forall l l' s s' g,\n              Zle l l' ->\n                (forall i, itree_le' (s i) (s' (g i))) ->\n                  itree_le' (inode l s) (inode l' s').\n\n\nRequire Import List.\nInductive ltree (A:Set) : Set :=\n  lnode : A -> list (ltree A) -> ltree A.\n\n\n\n\n(* 3.4.2 Impredicative Inductive Types *)\n\n\nInductive prop : Prop :=\n  prop_intro : Prop -> prop.\n\n\nLemma prop_inject: prop.\n  Proof prop_intro prop.\n\n\nInductive ex_Prop (P : Prop -> Prop) : Prop :=\n  exP_intro : forall X : Prop, P X -> ex_Prop P.\n\n\nInductive ex_Set (P : Set -> Prop) : Type :=\n  exS_intro : forall X : Set, P X -> ex_Set P.\n\n\nInductive typ : Type :=\n  typ_intro : Type -> typ.\n\n\nDefinition typ_inject: typ.\n  split; exact typ.                         (* Proof completed. *)\n(* Defined.                                    Error: Universe inconsistency. *)\nAbort.\n\n\n(*\nCheck (fun (P:Prop ->Prop)(p: ex_Prop P) =>\n  match p with exP_intro X HX => X end).\n*)\n\n\n(* 3.4.3 Extraction Constraints *)\n\n\n(* 3.4.4 Strong Case Analysis on Proofs *)\n\n\nDefinition comes_from_the_left_sumbool (P Q:Prop) (x:{P} + {Q}) : Prop :=\n  match x with\n    | left p => True\n    | right q => False\n  end.\n\n\n(* \u7d9a\u304f *)", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_rectutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.8071219365883934}}
{"text": "(* (c) P. Casteran *)\n\nRequire Import Arith.\nFixpoint sum_n (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S p + sum_n p\n  end.\n\nRequire Import ArithRing.\n\nTheorem sum_closed_form : forall n:nat, 2 * sum_n n = n * S n.\nProof.\n induction n. \n simpl; trivial.\n simpl (sum_n (S n)).\n simpl (S n * S (S n)).\n ring_simplify.\n   ring_simplify. (* for V81gamma *)\n rewrite IHn.\n ring.\nQed.\n\nTheorem sum_n_le_n : forall n:nat, n <= sum_n n.\nProof.\n simple induction n.\n auto with arith.\n intros n0 Hn0; simpl.\n auto with arith.\nQed.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/structinduct/SRC/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771663, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.8071219294384521}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export Tactics.\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions ([forall\n    x, P]).  In this chapter, we will see how Coq can be used to carry\n    out other familiar forms of logical reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** Note that all well-formed propositions have type [Prop] in Coq,\n    regardless of whether they are true or not. Simply _being_ a\n    proposition is one thing; being _provable_ is something else! *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** Indeed, propositions don't just have types: they are _first-class\n    objects_ that can be manipulated in the same ways as the other\n    entities in Coq's world.  So far, we've seen one primary place\n    that propositions can appear: in [Theorem] (and [Lemma] and\n    [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** We can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments.  For instance, here's a\n    polymorphic property defining the familiar notion of an _injective\n    function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** The equality operator [=] that we have been using so far is also\n    just a function that returns a [Prop]. The expression [n = m] is\n    just syntactic sugar for [eq n m], defined using Coq's [Notation]\n    mechanism. Because [=] can be used with elements of any type, it\n    is also polymorphic: *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type argument [A]\n    to [eq] is declared as implicit, so we need to turn off implicit\n    arguments to see the full type of [eq].) *)\n\n\n\n\n\n(* #################################################################### *)\n(** * Logical Connectives *)\n\n(** ** Conjunction *)\n\n(** The _conjunction_ or _logical and_ of propositions [A] and [B] is\n    written [A /\\ B], denoting the claim that both [A] and [B] are\n    true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  Its effect is to\n    generate two subgoals, one for each part of the statement: *)\n\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** More generally, the following principle works for any two\n    propositions [A] and [B]: *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** A logical statement with multiple arrows is just a theorem with\n    has several hypotheses.  Here, [and_intro] says that, for any\n    propositions [A] and [B], if we assume that [A] is true and we\n    assume that [B] is true, then [A /\\ B] is also true.\n\n    Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can, apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** So much for proving conjunctive statements.  To go in the other\n    direction -- i.e., to _use_ a conjunctive hypothesis to prove\n    something else -- we employ the [destruct] tactic.\n\n    If the proof context contains a hypothesis [H] of the form [A /\\\n    B], writing [destruct H as [HA HB]] will remove [H] from the\n    context and add two new hypotheses: [HA], stating that [A] is\n    true, and [HB], stating that [B] is true.  For instance: *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] when we introduce it instead of\n    introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** In this case, there is not much difference between the two\n    theorems.  But it is often necessary to explicitly decompose\n    conjunctions that arise from intermediate steps in proofs,\n    especially in bigger developments.  Here's a simplified\n    example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know [A /\\\n    B] but in some context we need just [A] (or just [B]).  The\n    following lemmas are useful in such cases: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of conjuncts in multi-way conjunctions.  The\n    following commutativity and associativity theorems come in handy\n    in such cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n  \n(** **** Exercise: 2 stars (and_assoc)  *)\n(** (In the following proof of associativity, notice how the _nested_\n    intro pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (Alternatively, we can write [or A B], where [or : Prop ->\n    Prop -> Prop].)\n\n    To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis, which, as for [nat] or other data types, can be done\n    with [destruct] or [intros].  Here is an example: *)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     [n = 0 \\/ m = 0] *)\n  intros n m [Hn | Hm].\n  - (* Here, [n = 0] *)\n    rewrite Hn. reflexivity.\n  - (* Here, [m = 0] *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n(** We can see in this example that, when we perform case analysis on\n    a disjunction [A \\/ B], we must satisfy two proof obligations,\n    each showing that the conclusion holds under a different\n    assumption -- [A] in the first subgoal and [B] in the second.\n    Note that the case analysis pattern ([Hn | Hm]) allows us to name\n    the hypothesis that is generated in each subgoal.\n\n    Conversely, to show that a disjunction holds, we need to show that\n    one of its sides does. This is done via two tactics, [left] and\n    [right].  As their names imply, the first one requires proving the\n    left side of the disjunction, while the second requires proving\n    its right side.  Here is a trivial use... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and a slightly more interesting example requiring the use of\n    both [left] and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** ** Falsehood and Negation *)\n\n(** So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    _negative_ results, showing that certain propositions are _not_\n    true. In Coq, such negative statements are expressed with the\n    negation operator [~].\n\n    To see how negation works, recall the discussion of the _principle\n    of explosion_ from the [Tactics] chapter; it asserts that, if we\n    assume a contradiction, then any other proposition can be derived.\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].  Coq actually makes a slightly different\n    choice, defining [~ P] as [P -> False], where [False] is a\n    _particular_ contradictory proposition defined in the standard\n    library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can [destruct] it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\n(** Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** This is how we use [not] to state that [0] and [1] are different\n    elements of [nat]: *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** Such inequality statements are frequent enough to warrant a\n    special notation, [x <> y]: *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    get things into the right configuration so that Coq can understand\n    it!  Here are proofs of a few familiar facts to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** Similarly, since inequality involves a negation, it requires a\n    little practice to be able to work with it fluently.  Here is one\n    useful trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n\n\n\n\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see some examples such uses of [True] later on. *)\n\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB.  Qed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we need\n    to import a special Coq library that allows rewriting with other\n    formulas besides equality: *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences: *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\n(** We can now use these facts with [rewrite] and [reflexivity] to\n    give smooth proofs of statements involving equivalences.  Here is\n    a ternary version of the previous [mult_0] result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which side of\n    the equivalence to use. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n(* ############################################################ *)\n(** ** Existential Quantification *)\n\n(** Another important logical connective is _existential\n    quantification_.  To say that there is some [x] of type [T] such\n    that some property [P] holds of [x], we write [exists x : T,\n    P]. As with [forall], the type annotation [: T] can be omitted if\n    Coq is able to infer from the context what the type of [x] should\n    be.\n\n    To prove a statement of the form [exists x, P], we must show that\n    [P] holds for some specific choice of value for [x], known as the\n    _witness_ of the existential.  This is done in two steps: First,\n    we explicitly tell Coq which witness [t] we have in mind by\n    invoking the tactic [exists t]; then we prove that [P] holds after\n    all occurrences of [x] are replaced by [t].  Here is an example: *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n    the context, we can destruct it to obtain a witness [x] and a\n    hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.  Qed.\n\n(** **** Exercise: 1 star (dist_not_exists)  *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* #################################################################### *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure:\n\n    - If [l] is the empty list, then [x] cannot occur on it, so the\n      property \"[x] appears in [l]\" is simply false.\n\n    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n      occurs in [l] if either it is equal to [x'] or it occurs in\n      [l']. *)\n\n(** We can translate this directly into a straightforward Coq\n    function, [In].  (It can also be found in the Coq standard\n    library.) *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested conjunctions. *)\n\nExample In_example_1 : In 4 [3; 4; 5].\nProof.\n  simpl. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions, though convenient in some\n    cases, also has some drawbacks.  In particular, it is subject to\n    Coq's usual restrictions regarding the definition of recursive\n    functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n  (* FILL IN HERE *) admit.\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (* FILL IN HERE *) admit.\n\n(** To test your definition, prove the following facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* #################################################################### *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from many other proof\n    assistants is that it treats _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it in detail in order to use Coq.  This\n    section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use the [Check] command to ask Coq to\n    print the type of an expression.  We can also use [Check] to ask\n    what theorem a particular identifier refers to. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** Coq prints the _statement_ of the [plus_comm] theorem in the same\n    way that it prints the _type_ of any term that we ask it to\n    [Check].  Why?\n\n    The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_ -- a data structure that represents a logical\n    derivation establishing of the truth of the statement [forall n m\n    : nat, n + m = m + n].  The type of this object _is_ the statement\n    of the theorem that it is a proof of.\n\n    Intuitively, this makes sense because the statement of a theorem\n    tells us what we can use that theorem for, just as the type of a\n    computational object tells us what we can do with that object --\n    e.g., if we have a term of type [nat -> nat -> nat], we can give\n    it two [nat]s as arguments and get a [nat] back.  Similarly, if we\n    have an object of type [n = m -> n + n = m + m] and we provide it\n    an \"argument\" of type [n = m], we can derive [n + n = m + m].\n\n    Operationally, this analogy goes even further: by applying a\n    theorem, as if it were a function, to hypotheses with matching\n    types, we can specialize its result without having to resort to\n    intermediate assertions.  For example, suppose we wanted to prove\n    the following result: *)\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\n\n(** One simple way of fixing this problem, using only tools that we\n    already know, is to use [assert] to derive a specialized version\n    of [plus_comm] that can be used to rewrite exactly where we\n    want. *)\n\n  rewrite plus_comm.\n  assert (H : m + p = p + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n(** A more elegant alternative is to apply [plus_comm] directly to the\n    arguments we want to instantiate it with, in much the same way as\n    we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take2 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples of the idioms from this section in\n    later chapters. *)\n\n(* #################################################################### *)\n(** * Coq vs. Set Theory *)\n\n(** Coq's logical core, the _Calculus of Inductive Constructions_,\n    differs in some important ways from other formal systems that are\n    used by mathematicians for writing down precise and rigorous\n    proofs.  For example, in the most popular foundation for\n    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set\n    Theory (ZFC), a mathematical object can potentially be a member of\n    many different sets; a term in Coq's logic, on the other hand, is\n    a member of at most one type.  This difference often leads to\n    slightly different ways of capturing informal mathematical\n    concepts, though these are by and large quite natural and easy to\n    work with.  For example, instead of saying that a natural number\n    [n] belongs to the set of even numbers, we would say in Coq that\n    [ev n] holds, where [ev : nat -> Prop] is a property describing\n    even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be either cumbersome or\n    sometimes even impossible, unless we enrich the core logic with\n    additional axioms.  We conclude this chapter with a brief\n    discussion of some of the most significant differences between the\n    two worlds. *)\n\n(** ** Functional Extensionality\n\n    The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But\n    since Coq's equality operator is polymorphic, these are not the\n    only possibilities -- in particular, we can write propositions\n    claiming that two _functions_ are equal to each other: *)\n\nExample function_equality_ex : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same outputs:\n    (forall x, f x = g x) -> f = g\n    This is known as the principle of _functional extensionality_.\n\n    Informally speaking, an \"extensional property\" is one that\n    pertains to an object's observable behavior.  Thus, functional\n    extensionality simply means that a function's identity is\n    completely determined by what we can observe from it -- i.e., in\n    Coq terms, the results we obtain after applying it.\n\n    Functional extensionality is not part of Coq's basic axioms: the\n    only way to show that two functions are equal is by\n    simplification (as we did in the proof of [function_equality_ex]).\n    But we can add it to Coq's core logic using the [Axiom]\n    command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Using [Axiom] has the same effect as stating a theorem and\n    skipping its proof using [Admitted], but it alerts the reader that\n    this isn't just something we're going to come back and fill in\n    later!\n\n    We can now invoke functional extensionality in proofs: *)\n\nLemma plus_comm_ext : plus = fun n m => m + n.\nProof.\n  apply functional_extensionality. intros n.\n  apply functional_extensionality. intros m.\n  apply plus_comm.\nQed.\n\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as they may render it inconsistent -- that is, it may\n    become possible to prove every proposition, including [False]!\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe: hard work is generally required to establish the\n    consistency of any particular combination of axioms.  Fortunately,\n    it is known that adding functional extensionality, in particular,\n    _is_ consistent.\n\n    Note that it is possible to check whether a particular proof\n    relies on any additional axioms, using the [Print Assumptions]\n    command. For instance, if we run it on [plus_comm_ext], we see\n    that it uses [functional_extensionality]: *)\n\nPrint Assumptions plus_comm_ext.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 5 stars (tr_rev)  *)\n(** One problem with the definition of the list-reversing function\n    [rev] that we have is that it performs a call to [app] on each\n    step; running [app] takes time asymptotically linear in the size\n    of the list, which means that [rev] has quadratic running time.\n    We can improve this with the following definition: *)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(** This version is said to be _tail-recursive_, because the recursive\n    call to the function is the last operation that needs to be\n    performed (i.e., we don't have to execute [++] after the recursive\n    call); a decent compiler will generate very efficient code in this\n    case.  Prove that both definitions are indeed equivalent. *)\n\n(* FILL IN HERE *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** ** Propositions and Booleans *)\n\n(**  AAA: I'm anticipating some of the discussion on evenness from\n   the next chapter here. We can remove/adapt some of the material in\n   IndProp.v soon. \n *)\n(** We've seen that Coq has two different ways of encoding logical\n    facts: with _booleans_ (of type [bool]), and with\n    _propositions_ (of type [Prop]). For instance, to claim that a\n    number [n] is even, we can say either (1) that [evenb n] returns\n    [true] or (2) that there exists some [k] such that [n = double k].\n    Indeed, these two notions of evenness are equivalent, as can\n    easily be shown with a couple of auxiliary lemmas (one of which is\n    left as an exercise).\n\n    We often say that the boolean [evenb n] _reflects_ the proposition\n    [exists k, n = double k].  *)\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(** **** Exercise: 3 stars (evenb_double_conv)  *)\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either (1) that [beq_nat n m] returns [true] or (2) that [n =\n    m].  These two notions are equivalent. *)\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** However, while the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, we have\n    also seen that they need not be equivalent _operationally_.\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little help in the middle of a proof\n    involving [n] and [m]; however, if we convert the statement to the\n    equivalent form [n = m], we can rewrite with it.\n\n    The case of even numbers is also interesting.  Recall that, when\n    proving the backwards direction of\n    [even_bool_prop] ([evenb_double], going from the propositional to\n    the boolean claim), we used a simple induction on [k]).  On the\n    other hand, the converse (the [evenb_double_conv] exercise)\n    required a clever generalization, since we can't directly prove\n    [(exists k, n = double k) -> evenb n = true].\n\n    For these examples, the propositional claims were more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects an\n    elements of [bool] (or some other inductive type with two\n    elements).  The reason for this error message has to do with the\n    _computational_ nature of Coq's core language, which is designed\n    so that every function that it can express is computable and\n    total.  One reason for this is to allow the extraction of\n    executable programs from Coq developments.  As a consequence,\n    [Prop] in Coq does _not_ have a universal case analysis operation\n    telling whether any given proposition is true or false, since such\n    an operation would allow us to write non-computable functions.\n\n    Although general non-computable properties cannot be phrased as\n    boolean computations, it is worth noting that even many\n    _computable_ properties are easier to express using [Prop] than\n    [bool], since recursive function definitions are subject to\n    significant restrictions in Coq.  For instance, the next chapter\n    shows how to define the property that a regular expression matches\n    a given string using [Prop].  Doing the same with [bool] would\n    amount to writing a regular expression matcher, which would be\n    more complicated, harder to understand, and harder to reason\n    about.\n\n    Conversely, an important side benefit of stating facts using\n    booleans is enabling some proof automation through computation\n    with Coq terms, a technique known as _proof by\n    reflection_. Consider the following statement: *)\n\nExample even_1000 : exists k, 1000 = double k.\n\n(** The most direct proof of this fact is to give the value of [k]\n    explicitly. *)\n\n Proof. exists 500. reflexivity. Qed.\n\n(** On the other hand, the proof of the corresponding boolean\n    statement is even simpler: *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** What is interesting is that, since the two notions are equivalent,\n    we can use the boolean formulation to prove the other one without\n    mentioning 500 explicitly: *)\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** Although we haven't gained much in terms of proof size in this\n    case, larger proofs can often be made considerably simpler by the\n    use of reflection.  As an extreme example, the Coq proof of the\n    famous _4-color theorem_ uses reflection to reduce the analysis of\n    hundreds of different cases to a boolean computation.  We won't\n    cover reflection in great detail, but it serves as a good example\n    showing the complementary strengths of booleans and general\n    propositions. *)\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  (* FILL IN HERE *) admit.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** ** Classical vs. Constructive Logic *)\n\n(** We have seen that it is not possible to test whether or not a\n    proposition [P] holds while defining a Coq function.  You may be\n    surprised to learn that a similar restriction applies to _proofs_!\n    In other words, the following intuitive reasoning principle is not\n    derivable in Coq: *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\n(** To understand operationally why this is the case, recall that, to\n    prove a statement of the form [P \\/ Q], we use the [left] and\n    [right] tactics, which effectively require knowing which side of\n    the disjunction holds.  However, the universally quantified [P] in\n    [excluded_middle] is an _arbitrary_ proposition, which we know\n    nothing about.  We don't have enough information to choose which\n    of [left] or [right] to apply, just as Coq doesn't have enough\n    information to mechanically decide whether [P] holds or not inside\n    a function.  On the other hand, if we happen to know that [P] is\n    reflected in some boolean term [b], then knowing whether it holds\n    or not is trivial: we just have to check the value of [b].  This\n    leads to the following theorem: *)\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m].\n\n    You may find it strange that the general excluded middle is not\n    available by default in Coq; after all, any given claim must be\n    either true or false.  Nonetheless, there is an advantage in not\n    assuming the excluded middle: statements in Coq can make stronger\n    claims than the analogous statements in standard mathematics.\n    Notably, if there is a Coq proof of [exists x, P x], it is\n    possible to explicitly exhibit a value of [x] for which we can\n    prove [P x] -- in other words, every proof of existence is\n    necessarily _constructive_.  Because of this, logics like Coq's,\n    which do not assume the excluded middle, are referred to as\n    _constructive logics_.  More conventional logical systems such as\n    ZFC, in which the excluded middle does hold for arbitrary\n    propositions, are referred to as _classical_.\n\n    The following example illustrates why assuming the excluded middle\n    may lead to non-constructive proofs: *)\n\n(** _Claim_: There exist irrational numbers [a] and [b] such that [a ^\n    b] is rational.\n\n    _Proof_: It is not difficult to show that [sqrt 2] is irrational.\n    If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =\n    sqrt 2] and we are done.  Otherwise, [sqrt 2 ^ sqrt 2] is\n    irrational.  In this case, we can take [a = sqrt 2 ^ sqrt 2] and\n    [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^\n    2 = 2].  []\n\n    Do you see what happened here?  We used the excluded middle to\n    consider separately the cases where [sqrt 2 ^ sqrt 2] is rational\n    and where it is not, without knowing which one actually holds!\n    Because of that, we wind up knowing that such [a] and [b] exist\n    but we cannot determine what their actual values are (at least,\n    using this line of argument).\n\n    As useful as constructive logic is, it does have its limitations:\n    There are many statements that can easily be proven in classical\n    logic but that have much more complicated constructive proofs, and\n    there are some that are known to have no constructive proof at\n    all!  Fortunately, like functional extensionality, the excluded\n    middle is known to be compatible with Coq's logic, allowing us to\n    add it safely as an axiom.  However, we will not need to do so in\n    this book: the results that we cover can be developed entirely\n    within constructive logic at negligible extra cost.\n\n    It takes some practice to understand which proof techniques must\n    be avoided in constructive reasoning, but arguments by\n    contradiction, in particular, are infamous for leading to\n    non-constructive proofs.  Here's a typical example: suppose that\n    we want to show that there exists [x] with some property [P],\n    i.e., such that [P x].  We start by assuming that our conclusion\n    is false; that is, [~ exists x, P x]. From this premise, it is not\n    hard to derive [forall x, ~ P x].  If we manage to show that this\n    intermediate fact results in a contradiction, we arrive at an\n    existence proof without ever exhibiting a value of [x] for which\n    [P x] holds!\n\n    The technical flaw here, from a constructive standpoint, is that\n    we claimed to prove [exists x, P x] using a proof of [~ ~ exists\n    x, P x]. However, allowing ourselves to remove double negations\n    from arbitrary statements is equivalent to assuming the excluded\n    middle, as shown in one of the exercises below.  Thus, this line\n    of reasoning cannot be encoded in Coq without assuming additional\n    axioms. *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** The consistency of Coq with the general excluded middle axiom\n    requires complicated reasoning that cannot be carried out within\n    Coq itself.  However, the following theorem implies that it is\n    always safe to assume a decidability axiom (i.e., an instance of\n    excluded middle) for any _particular_ Prop [P].  Why? Because we\n    cannot prove the negation of such an axiom; if we could, we would\n    have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist)  *)\n(** It is a theorem of classical logic that the following two\n    assertions are equivalent:\n    ~ (exists x, ~ P x)\n    forall x, P x\n    The [dist_not_exists] theorem above proves one side of this\n    equivalence. Interestingly, the other direction cannot be proved\n    in constructive logic. Your job is to show that it is implied by\n    the excluded middle.\n*)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\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\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/hw5/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8962513648201266, "lm_q1q2_score": 0.8071010498693382}}
{"text": "Require Import ZArith.\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nOpen Scope Z_scope.\n\nDefinition manhattan_dist (p1 p2 : plane) : Z :=\n (Zabs (abscissa p1 - abscissa p2)) +\n (Zabs (ordinate p1 - ordinate p2)).\n\n\n(** Test \n \nCompute (manhattan_dist (point 2 5) (point 7 (-9))).\n\n*)\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch6_inductive_data/SRC/manhattan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8070004112718178}}
{"text": "Theorem plus_n_O : forall n : nat, n = n + O.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n    (* 0 = 0 *)\n    reflexivity.\n    (* n = S n' *)\n    simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat, n - n = 0.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n    (* 0 - 0 = 0*)\n    reflexivity.\n    (* S n' - S n' = 0 *)\n    simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n    (* 0 * 0 = 0 *)\n    reflexivity.\n    (* S n' * 0 = 0 *)\n    simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nFixpoint double (n : nat) :=\n  match n with\n  | O => O\n  | S n' => S( S(double n') )\n  end.\n\n(* Lemma double_plus : forall n, double n = n + n.\nProof.\n  intros.\n  induction n as [|n' IHn'].\n    (* 0 = 0 *)\n    reflexivity.\n    (* double Sn' = Sn' + Sn' *)\n    simpl.\n    rewrite -> IHn'.\n    Admitted. *)\n\nTheorem mult_0_plus' : forall m n : nat, (0 + n) * m  = n * m.\nProof.\n  intros.\n  assert (H: 0 + n = n). { reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem plus_comm : forall m n : nat, n + m = m + n.\nProof.\n  intros.\n  induction n as [|n' IHn'].\n  induction m as [|m' IHm'].\n  (* 0 + 0 = 0 + 0 *)\n  reflexivity.\n  (* 0 + Sm' = Sm' + 0 *)\n  simpl.\n  rewrite <- IHm'.\n  simpl.\n  reflexivity.\n  (* Sn' + m = m + Sn' *)\n  simpl.\n  rewrite <- IHn'.\n  \n\nTheorem plus_rearrange : forall n m p q, (n+m) + (p+q) = (m+n) + (p+q).\nProof.\n  intros.\n  assert (H: n + m = m + n).\n  { rewrite plus_comm. reflexivity. }\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/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.8069794389917636}}
{"text": "Require Import Nat Arith Plus Minus.\n\nFixpoint mult (n m : nat) : nat :=\n  match m with\n  | S m' => n + mult n m'\n  | 0 => 0\n  end.\n\nLemma mult_0 : forall (x : nat), mult 0 x = 0.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. assumption.\nQed.\n\nLemma le_mult : forall (x y : nat), y <= mult (S x) y.\nProof.\n  intros.\n  induction y.\n  - reflexivity.\n  - simpl. apply le_n_S. rewrite plus_comm. apply le_plus_trans. assumption.\nQed.\n\nTheorem theorem0 : forall (x : nat) (y : nat), eq (minus (mult x y) y) (mult (minus x 1) y).\nProof.\n  intros.\n  destruct x.\n  - simpl. rewrite mult_0. reflexivity.\n  - simpl. rewrite <- minus_n_O. induction y.\n    + reflexivity.\n    + simpl. rewrite <- IHy. symmetry. apply (plus_minus (x + mult (S x) y) y (x + (mult (S x) y - y))). rewrite plus_assoc. rewrite (plus_comm y x). rewrite <- plus_assoc. rewrite le_plus_minus_r.\n      * reflexivity.\n      * apply le_mult.\nQed.\n\nLemma mult_s : forall (n m : nat), mult (S n) m = m + mult n m.\nProof.\n  intros.\n  induction m.\n  - reflexivity.\n  - simpl. rewrite IHm. rewrite plus_assoc. rewrite (plus_comm n m). rewrite plus_assoc. reflexivity.\nQed.\n\nTheorem theorem1 : forall (n : nat) (m : nat), eq (mult n m) (mult m n).\nProof.\n  intros.\n  induction m.\n  - simpl. rewrite mult_0. reflexivity.\n  - simpl. rewrite mult_s. rewrite IHm. 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/mult_int.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8069430415231781}}
{"text": "\nInductive Nat :=\n | Zero: Nat\n | Succ: Nat-> Nat.\n\nFixpoint add (n m: Nat) :=\n  match n with\n  | Zero => m\n  | Succ n => Succ (add n m)\n  end.\n\n\nTheorem Ex_13_2 : forall (n m: Nat), add n (Succ m) = Succ (add n m).\nProof.\n  intros n m.\n  induction n.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\n\nLemma add_n_z_eq_n : forall n: Nat, add n Zero = n.\nProof.\n  induction n.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\nTheorem Ex_13_3 : forall (n m: Nat), add n m = add m n.\nProof.\n  intros n m.\n  induction n.\n    simpl.\n    rewrite add_n_z_eq_n.\n    reflexivity.\n    \n    simpl.\n    rewrite Ex_13_2.\n    rewrite IHn.\n    reflexivity.\nQed.\n\n\nInductive List (A: Type) :=\n | Nil: List A\n | Cons: A -> List A -> List A.\nImplicit Arguments Nil [A].\nImplicit Arguments Cons [A].\n\nFixpoint all {A} (p: A -> Prop) (list: List A): Prop :=\n  match list with\n  | Nil => True\n  | Cons x xs => (p x) /\\ (all p xs)\n  end.\n\nFixpoint replicate {A} (n: nat) (x: A): List A :=\n  match n with\n  | O => Nil\n  | S n => Cons x (replicate n x)\n  end.\n\nTheorem Ex_13_4 : forall (A: Type) (n: nat) (x: A),\n  all (fun a => a = x) (replicate n x).\nProof.\n  intros A n x.\n  induction n.\n    unfold replicate.\n    unfold all.\n    exact I.\n    \n    simpl.\n    split.\n      reflexivity.\n      \n      exact IHn.\nQed.\n\n\nFixpoint append {A} (xs ys: List A): List A :=\n  match xs with\n  | Nil => ys\n  | Cons x xs => Cons x (append xs ys)\n  end.\n\nTheorem Ex_13_5_1 : forall (A: Type) (xs: List A), append xs Nil = xs.\nProof.\n  intros A xs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nTheorem Ex_13_5_2 : forall (A: Type) (xs ys zs: List A),\n  append xs (append ys zs) = append (append xs ys) zs.\nProof.\n  intros A xs ys zs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\n\nFixpoint reverse {A} (xs: List A): List A :=\n  match xs with\n  | Nil => Nil\n  | Cons x xs => append (reverse xs) (Cons x Nil)\n  end.\n\n(* proof of section 13.5 *)\nLemma reverse_assoc : forall (A: Type) (xs ys: List A),\n  reverse (append xs ys) = append (reverse ys) (reverse xs).\nProof.\n  intros A xs ys.\n  induction xs.\n    simpl.\n    rewrite (Ex_13_5_1 A (reverse ys)).\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    rewrite <- (Ex_13_5_2 A (reverse ys) (reverse xs) (Cons a Nil)).\n    reflexivity.\nQed.\nTheorem r_r_xs_eq_xs : forall (A: Type) (xs: List A),\n  reverse (reverse xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite (reverse_assoc A (reverse xs) (Cons a Nil)).\n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\n(* proof of exercise 13.6 *)\nLemma reverse_xs_x_eq_x_reverse_xs : forall (A: Type) (x: A) (xs: List A),\n  reverse (append xs (Cons x Nil)) = Cons x (reverse xs).\nProof.\n  intros A x xs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    simpl.\n    reflexivity.\nQed.\nTheorem Ex_13_6 : forall (A: Type) (xs: List A),\n  reverse (reverse xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite (reverse_xs_x_eq_x_reverse_xs A a (reverse xs)).\n    rewrite IHxs.\n    reflexivity.\nQed.\n\n\nFixpoint map {A B} (f: A -> B) (xs: List A): List B :=\n  match xs with\n  | Nil => Nil\n  | Cons x xs => Cons (f x) (map f xs)\n  end.\n\nDefinition compose {A B C} (f: B -> C) (g: A -> B) (x: A): C := f (g x).\n\nTheorem Ex_13_7 : forall (A B C: Type) (f: B -> C) (g: A -> B) (xs: List A),\n  map f (map g xs) = map (compose f g) xs.\nProof.\n  intros A B C f g xs.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    unfold compose.\n    reflexivity.\nQed.\n\n\nFixpoint take {A} (n: nat) (xs: List A): List A :=\n  match n, xs with\n  | 0, _ => Nil\n  | _, Nil => Nil\n  | S n, Cons x xs => Cons x (take n xs)\n  end.\nFixpoint drop{A} (n: nat) (xs: List A): List A :=\n  match n, xs with\n  | 0, _ => xs\n  | _, Nil => Nil\n  | S n, Cons _ xs => drop n xs\n  end.\n\nTheorem Ex_13_8 : forall (A: Type) (n: nat) (xs: List A),\n  append (take n xs) (drop n xs) = xs.\nProof.\n  intros A n.\n  induction n.\n    intro xs.\n    simpl.\n    reflexivity.\n    \n    destruct xs.\n      simpl.\n      reflexivity.\n      \n      simpl.\n      rewrite (IHn xs).\n      reflexivity.\nQed.\n\n\nInductive Tree (A: Type) :=\n | Leaf: A -> Tree A\n | Node: Tree A -> Tree A -> Tree A.\n\nFixpoint leafs {A} (xs: Tree A): nat :=\n  match xs with\n  | Leaf _ => 1\n  | Node l r => leafs l + leafs r\n  end.\nFixpoint nodes {A} (xs: Tree A): nat :=\n  match xs with\n  | Leaf _ => 0\n  | Node l r => S (nodes l + nodes r)\n  end.\n\nRequire Import Arith.\n\nTheorem Ex_13_9 : forall (A: Type) (xs: Tree A),\n  leafs xs = S (nodes xs).\nProof.\n  intro A.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs1; rewrite IHxs2.\n    rewrite <- (plus_Snm_nSm (S (nodes xs1)) (nodes xs2)).\n    simpl.\n    reflexivity.\nQed.\n", "meta": {"author": "rf0444", "repo": "coq", "sha": "ea26e698cd68ccc051a309b856c7724181be6aae", "save_path": "github-repos/coq/rf0444-coq", "path": "github-repos/coq/rf0444-coq/coq-ea26e698cd68ccc051a309b856c7724181be6aae/start_haskell/13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8069212162531972}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Logic.\nRequire Coq.omega.Omega.\n\n(* ################################################################# *)\n(** * Inductively Defined Propositions *)\n\n(** In the [Logic] chapter, we looked at several ways of writing\n    propositions, including conjunction, disjunction, and quantifiers.\n    In this chapter, we bring a new tool into the mix: _inductive\n    definitions_.\n\n    Recall that we have seen two ways of stating that a number [n] is\n    even: We can say (1) [evenb n = true], or (2) [exists k, n =\n    double k].  Yet another possibility is to say that [n] is even if\n    we can establish its evenness from the following rules:\n\n       - Rule [ev_0]:  The number [0] is even.\n       - Rule [ev_SS]: If [n] is even, then [S (S n)] is even. *)\n\n(** To illustrate how this definition of evenness works, let's\n    imagine using it to show that [4] is even. By rule [ev_SS], it\n    suffices to show that [2] is even. This, in turn, is again\n    guaranteed by rule [ev_SS], as long as we can show that [0] is\n    even. But this last fact follows directly from the [ev_0] rule. *)\n\n(** We will see many definitions like this one during the rest\n    of the course.  For purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n\n                              ------------                        (ev_0)\n                                 ev 0\n\n                                  ev n\n                             --------------                      (ev_SS)\n                              ev (S (S n))\n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [ev_SS] says that, if [n]\n    satisfies [ev], then [S (S n)] also does.  If a rule has no\n    premises above the line, then its conclusion holds\n    unconditionally.\n\n    We can represent a proof using these rules by combining rule\n    applications into a _proof tree_. Here's how we might transcribe\n    the above proof that [4] is even: *)\n(**\n\n                             ------  (ev_0)\n                              ev 0\n                             ------ (ev_SS)\n                              ev 2\n                             ------ (ev_SS)\n                              ev 4\n*)\n\n(** Why call this a \"tree\" (rather than a \"stack\", for example)?\n    Because, in general, inference rules can have multiple premises.\n    We will see examples of this below. *)\n\n(** Putting all of this together, we can translate the definition of\n    evenness into a formal Coq definition using an [Inductive]\n    declaration, where each constructor corresponds to an inference\n    rule: *)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n(** This definition is different in one crucial respect from\n    previous uses of [Inductive]: its result is not a [Type], but\n    rather a function from [nat] to [Prop] -- that is, a property of\n    numbers.  Note that we've already seen other inductive definitions\n    that result in functions, such as [list], whose type is [Type ->\n    Type].  What is new here is that, because the [nat] argument of\n    [ev] appears _unnamed_, to the _right_ of the colon, it is allowed\n    to take different values in the types of different constructors:\n    [0] in the type of [ev_0] and [S (S n)] in the type of [ev_SS].\n\n    In contrast, the definition of [list] names the [X] parameter\n    _globally_, to the _left_ of the colon, forcing the result of\n    [nil] and [cons] to be the same ([list X]).  Had we tried to bring\n    [nat] to the left in defining [ev], we would have seen an error: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n(** (\"Parameter\" here is Coq jargon for an argument on the left of the\n    colon in an [Inductive] definition; \"index\" is used to refer to\n    arguments on the right of the colon.) *)\n\n(** We can think of the definition of [ev] as defining a Coq property\n    [ev : nat -> Prop], together with theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Such \"constructor\n    theorems\" have the same status as proven theorems.  In particular,\n    we can use Coq's [apply] tactic with the rule names to prove [ev]\n    for particular numbers... *)\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** ... or we can use function application syntax: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** We can also prove theorems that have hypotheses involving [ev]. *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(** More generally, we can show that any number multiplied by 2 is even: *)\n\n(** **** Exercise: 1 star (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Using Evidence in Proofs *)\n\n(** Besides _constructing_ evidence that numbers are even, we can also\n    _reason about_ such evidence.\n\n    Introducing [ev] with an [Inductive] declaration tells Coq not\n    only that the constructors [ev_0] and [ev_SS] are valid ways to\n    build evidence that some number is even, but also that these two\n    constructors are the _only_ ways to build evidence that numbers\n    are even (in the sense of [ev]). *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [ev n], then we know that [E] must have one of two shapes:\n\n      - [E] is [ev_0] (and [n] is [O]), or\n      - [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is\n        evidence for [ev n']). *)\n\n(** This suggests that it should be possible to analyze a hypothesis\n    of the form [ev n] much as we do inductively defined data\n    structures; in particular, it should be possible to argue by\n    _induction_ and _case analysis_ on such evidence.  Let's look at a\n    few examples to see what this means in practice. *)\n\n(* ================================================================= *)\n(** ** Inversion on Evidence *)\n\n(** Suppose we are proving some fact involving a number [n], and we\n    are given [ev n] as a hypothesis.  We already know how to perform\n    case analysis on [n] using the [inversion] tactic, generating\n    separate subgoals for the case where [n = O] and the case where [n\n    = S n'] for some [n'].  But for some proofs we may instead want to\n    analyze the evidence that [ev n] _directly_.\n\n    By the definition of [ev], there are two cases to consider:\n\n    - If the evidence is of the form [ev_0], we know that [n = 0].\n\n    - Otherwise, the evidence must have the form [ev_SS n' E'], where\n      [n = S (S n')] and [E'] is evidence for [ev n']. *)\n\n(** We can perform this kind of reasoning in Coq, again using\n    the [inversion] tactic.  Besides allowing us to reason about\n    equalities involving constructors, [inversion] provides a\n    case-analysis principle for inductively defined propositions.\n    When used in this way, its syntax is similar to [destruct]: We\n    pass it a list of identifiers separated by [|] characters to name\n    the arguments to each of the possible constructors.  *)\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** In words, here is how the inversion reasoning works in this proof:\n\n    - If the evidence is of the form [ev_0], we know that [n = 0].\n      Therefore, it suffices to show that [ev (pred (pred 0))] holds.\n      By the definition of [pred], this is equivalent to showing that\n      [ev 0] holds, which directly follows from [ev_0].\n\n    - Otherwise, the evidence must have the form [ev_SS n' E'], where\n      [n = S (S n')] and [E'] is evidence for [ev n'].  We must then\n      show that [ev (pred (pred (S (S n'))))] holds, which, after\n      simplification, follows directly from [E']. *)\n\n(** This particular proof also works if we replace [inversion] by\n    [destruct]: *)\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** The difference between the two forms is that [inversion] is more\n    convenient when used on a hypothesis that consists of an inductive\n    property applied to a complex expression (as opposed to a single\n    variable).  Here's is a concrete example.  Suppose that we wanted\n    to prove the following variation of [ev_minus2]: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\n\n(** Intuitively, we know that evidence for the hypothesis cannot\n    consist just of the [ev_0] constructor, since [O] and [S] are\n    different constructors of the type [nat]; hence, [ev_SS] is the\n    only case that applies.  Unfortunately, [destruct] is not smart\n    enough to realize this, and it still generates two subgoals.  Even\n    worse, in doing so, it keeps the final goal unchanged, failing to\n    provide any useful information for completing the proof.  *)\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n    replacing all occurrences of the property argument by the values\n    that correspond to each constructor.  This is enough in the case\n    of [ev_minus2'] because that argument, [n], is mentioned directly\n    in the final goal. However, it doesn't help in the case of\n    [evSS_ev] since the term that gets replaced ([S (S n)]) is not\n    mentioned anywhere. *)\n\n(** The [inversion] tactic, on the other hand, can detect (1) that the\n    first case does not apply, and (2) that the [n'] that appears on\n    the [ev_SS] case must be the same as [n].  This allows us to\n    complete the proof: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\n(** By using [inversion], we can also apply the principle of explosion\n    to \"obviously contradictory\" hypotheses involving inductive\n    properties. For example: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(** **** Exercise: 1 star (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The way we've used [inversion] here may seem a bit\n    mysterious at first.  Until now, we've only used [inversion] on\n    equality propositions, to utilize injectivity of constructors or\n    to discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence for\n    inductively defined propositions.\n\n    Here's how [inversion] works in general.  Suppose the name [I]\n    refers to an assumption [P] in the current context, where [P] has\n    been defined by an [Inductive] declaration.  Then, for each of the\n    constructors of [P], [inversion I] generates a subgoal in which\n    [I] has been replaced by the exact, specific conditions under\n    which this constructor could have been used to prove [P].  Some of\n    these subgoals will be self-contradictory; [inversion] throws\n    these away.  The ones that are left represent the cases that must\n    be proved to establish the original goal.  For those, [inversion]\n    adds all equations into the proof context that must hold of the\n    arguments given to [P] (e.g., [S (S n') = n] in the proof of\n    [evSS_ev]). *)\n\n(** The [ev_double] exercise above shows that our new notion of\n    evenness is implied by the two earlier ones (since, by\n    [even_bool_prop] in chapter [Logic], we already know that\n    those are equivalent to each other). To show that all three\n    coincide, we just need the following lemma: *)\n\nLemma ev_even_firsttry : forall n,\n  ev n -> exists k, n = double k.\nProof.\n(* WORKED IN CLASS *)\n\n(** We could try to proceed by case analysis or induction on [n].  But\n    since [ev] is mentioned in a premise, this strategy would probably\n    lead to a dead end, as in the previous section.  Thus, it seems\n    better to first try inversion on the evidence for [ev].  Indeed,\n    the first case can be solved trivially. *)\n\n  intros n E. inversion E as [| n' E'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    k, S (S n') = double k], but the only available assumption is\n    [E'], which states that [ev n'] holds.  Since this isn't directly\n    useful, it seems that we are stuck and that performing case\n    analysis on [E] was a waste of time.\n\n    If we look more closely at our second goal, however, we can see\n    that something interesting happened: By performing case analysis\n    on [E], we were able to reduce the original result to an similar\n    one that involves a _different_ piece of evidence for [ev]: [E'].\n    More formally, we can finish our proof by showing that\n\n        exists k', n' = double k',\n\n    which is the same as the original statement, but with [n'] instead\n    of [n].  Indeed, it is not difficult to convince Coq that this\n    intermediate result suffices. *)\n\n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k'). reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\n\nAdmitted.\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** If this looks familiar, it is no coincidence: We've encountered\n    similar problems in the [Induction] chapter, when trying to use\n    case analysis to prove results that required induction.  And once\n    again the solution is... induction!\n\n    The behavior of [induction] on evidence is the same as its\n    behavior on data: It causes Coq to generate one subgoal for each\n    constructor that could have used to build that evidence, while\n    providing an induction hypotheses for each recursive occurrence of\n    the property in question. *)\n\n(** Let's try our current lemma again: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds to\n    [E'], the single recursive occurrence of [ev] in its own\n    definition.  Since [E'] mentions [n'], the induction hypothesis\n    talks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n    evenness now follows. *)\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique across many areas, and in particular when\n    formalizing the semantics of programming languages, where many\n    properties of interest are defined inductively. *)\n\n(** The following exercises provide simple examples of this\n    technique, to help you familiarize yourself with it. *)\n\n(** **** Exercise: 2 stars (ev_sum)  *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (ev_alternate)  *)\n(** In general, there may be multiple ways of defining a\n    property inductively.  For example, here's a (slightly contrived)\n    alternative definition for [ev]: *)\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\n(** Prove that this definition is logically equivalent to the old\n    one.  (You may want to look at the previous theorem when you get\n    to the induction step.) *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** This exercise just requires applying existing lemmas.  No\n    induction or even case analysis is needed, though some of the\n    rewriting may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [ev])\n    can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule Playground.\n\n(** One useful example is the \"less than or equal to\" relation on\n    numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] above. We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) ->\n    2+2=5].) *)\n\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars, optional (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: This theorem can easily be proved without using [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nModule R.\n\n(** **** Exercise: 3 stars, recommendedM (R_provability)  *)\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** The relation [R] above actually encodes a familiar function.\n    Figure out which function; then state and prove this equivalence\n    in Coq? *)\n\nDefinition fR : nat -> nat -> nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n\n      [1;2;3]\n\n    is a subsequence of each of the lists\n\n      [1;2;3]\n      [1;1;1;2;2;3]\n      [1;2;7;3]\n      [5;6;1;9;9;2;7;3;8]\n\n    but it is _not_ a subsequence of any of the lists\n\n      [1;2]\n      [1;3]\n      [5;6;2;1;7;3;8].\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is,\n      any list is a subsequence of itself.\n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is\n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n      is a subsequence of [l3], then [l1] is a subsequence of [l3].\n      Hint: choose your induction carefully! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optionalM (R_provability2)  *)\n(** Suppose we give Coq the following definition:\n\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n\n    Which of the following propositions are provable?\n\n    - [R 2 [1;0]]\n    - [R 1 [1;2;1;0]]\n    - [R 6 [3;2;1;0]]  *)\n\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Case Study: Regular Expressions *)\n\n(** The [ev] property provides a simple example for illustrating\n    inductive definitions and the basic techniques for reasoning about\n    them, but it is not terribly exciting -- after all, it is\n    equivalent to the two non-inductive of evenness that we had\n    already seen, and does not seem to offer any concrete benefit over\n    them.  To give a better sense of the power of inductive\n    definitions, we now show how to use them to model a classic\n    concept in computer science: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing strings,\n    defined as follows: *)\n\nInductive reg_exp (T : Type) : Type :=\n| EmptySet : reg_exp T\n| EmptyStr : reg_exp T\n| Char : T -> reg_exp T\n| App : reg_exp T -> reg_exp T -> reg_exp T\n| Union : reg_exp T -> reg_exp T -> reg_exp T\n| Star : reg_exp T -> reg_exp T.\n\nArguments EmptySet {T}.\nArguments EmptyStr {T}.\nArguments Char {T} _.\nArguments App {T} _ _.\nArguments Union {T} _ _.\nArguments Star {T} _.\n\n(** Note that this definition is _polymorphic_: Regular\n    expressions in [reg_exp T] describe strings with characters drawn\n    from [T] -- that is, lists of elements of [T].\n\n    (We depart slightly from standard practice in that we do not\n    require the type [T] to be finite.  This results in a somewhat\n    different theory of regular expressions, but the difference is not\n    significant for our purposes.) *)\n\n(** We connect regular expressions and strings via the following\n    rules, which define when a regular expression _matches_ some\n    string:\n\n      - The expression [EmptySet] does not match any string.\n\n      - The expression [EmptyStr] matches the empty string [[]].\n\n      - The expression [Char x] matches the one-character string [[x]].\n\n      - If [re1] matches [s1], and [re2] matches [s2], then [App re1\n        re2] matches [s1 ++ s2].\n\n      - If at least one of [re1] and [re2] matches [s], then [Union re1\n        re2] matches [s].\n\n      - Finally, if we can write some string [s] as the concatenation of\n        a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n        expression [re] matches each one of the strings [s_i], then\n        [Star re] matches [s].\n\n        As a special case, the sequence of strings may be empty, so\n        [Star re] always matches the empty string [[]] no matter what\n        [re] is.\n\n    We can easily translate this informal definition into an\n    [Inductive] one as follows: *)\n\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n| MEmpty : exp_match [] EmptyStr\n| MChar : forall x, exp_match [x] (Char x)\n| MApp : forall s1 re1 s2 re2,\n           exp_match s1 re1 ->\n           exp_match s2 re2 ->\n           exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL : forall s1 re1 re2,\n              exp_match s1 re1 ->\n              exp_match s1 (Union re1 re2)\n| MUnionR : forall re1 s2 re2,\n              exp_match s2 re2 ->\n              exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n               exp_match s1 re ->\n               exp_match s2 (Star re) ->\n               exp_match (s1 ++ s2) (Star re).\n\n(** Again, for readability, we can also display this definition using\n    inference-rule notation.  At the same time, let's introduce a more\n    readable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the informal\n    ones that we gave at the beginning of the section.  First, we\n    don't need to include a rule explicitly stating that no string\n    matches [EmptySet]; we just don't happen to include any rule that\n    would have the effect of some string matching [EmptySet].  (Indeed,\n    the syntax of inductive definitions doesn't even _allow_ us to\n    give such a \"negative rule.\")\n\n    Second, the informal rules for [Union] and [Star] correspond\n    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n    [MStarApp].  The result is logically equivalent to the original\n    rules but more convenient to use in Coq, since the recursive\n    occurrences of [exp_match] are given as direct arguments to the\n    constructors, making it easier to perform induction on evidence.\n    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n    to prove that the constructors given in the inductive declaration\n    and the ones that would arise from a more literal transcription of\n    the informal rules are indeed equivalent.)\n\n    Let's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the strings [[1]]\n    and [[2]] directly.  Since the goal mentions [[1; 2]] instead of\n    [[1] ++ [2]], Coq wouldn't be able to figure out how to split the\n    string on its own.)\n\n    Using [inversion], we can also show that certain strings do _not_\n    match a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** We can define helper functions to help write down regular\n    expressions. The [reg_exp_of_list] function constructs a regular\n    expression that matches exactly the list that it receives as an\n    argument: *)\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n  match l with\n  | [] => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  simpl. apply (MApp [1]).\n  { apply MChar. }\n  apply (MApp [2]).\n  { apply MChar. }\n  apply (MApp [3]).\n  { apply MChar. }\n  apply MEmpty.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n    the following lemma shows that every string [s] that matches [re]\n    also matches [Star re]. *)\n\nLemma MStar1 :\n  forall T s (re : reg_exp T) ,\n    s =~ re ->\n    s =~ Star re.\nProof.\n  intros T s re H.\n  rewrite <- (app_nil_r _ s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n(** (Note the use of [app_nil_r] to change the goal of the theorem to\n    exactly the same shape expected by [MStarApp].) *)\n\n(** **** Exercise: 3 stars (exp_match_ex1)  *)\n(** The following lemmas show that the informal matching rules given\n    at the beginning of the chapter can be obtained from the formal\n    inductive definition. *)\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars (reg_exp_of_list)  *)\n(** Prove that [reg_exp_of_list] satisfies the following\n    specification: *)\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n    structure, we might expect that proofs involving regular\n    expressions will often require induction on evidence.  For\n    example, suppose that we wanted to prove the following intuitive\n    result: If a regular expression [re] matches some string [s], then\n    all elements of [s] must occur somewhere in [re].  To state this\n    theorem, we first define a function [re_chars] that lists all\n    characters that occur in a regular expression: *)\n\nFixpoint re_chars {T} (re : reg_exp T) : list T :=\n  match re with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App re1 re2 => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re => re_chars re\n  end.\n\n(** We can then phrase our theorem as follows: *)\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp T) (x : T),\n  s =~ re ->\n  In x s ->\n  In x (re_chars re).\nProof.\n  intros T s re x Hmatch Hin.\n  induction Hmatch\n    as [\n        |x'\n        |s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n        |re|s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. rewrite in_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      left. apply (IH1 Hin).\n    + (* In x s2 *)\n      right. apply (IH2 Hin).\n  - (* MUnionL *)\n    simpl. rewrite in_app_iff.\n    left. apply (IH Hin).\n  - (* MUnionR *)\n    simpl. rewrite in_app_iff.\n    right. apply (IH Hin).\n  - (* MStar0 *)\n    destruct Hin.\n\n(** Something interesting happens in the [MStarApp] case.  We obtain\n    _two_ induction hypotheses: One that applies when [x] occurs in\n    [s1] (which matches [re]), and a second one that applies when [x]\n    occurs in [s2] (which matches [Star re]).  This is a good\n    illustration of why we need induction on evidence for [exp_match],\n    as opposed to [re]: The latter would only provide an induction\n    hypothesis for strings that match [re], which would not allow us\n    to reason about the case [In x s2]. *)\n\n  - (* MStarApp *)\n    simpl. rewrite in_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      apply (IH1 Hin).\n    + (* In x s2 *)\n      apply (IH2 Hin).\nQed.\n\n(** **** Exercise: 4 stars (re_not_empty)  *)\n(** Write a recursive function [re_not_empty] that tests whether a\n    regular expression matches some string. Prove that your function\n    is correct. *)\n\nFixpoint re_not_empty {T : Type} (re : reg_exp T) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n    that it happily lets you try to set up an induction over a term\n    that isn't sufficiently general.  The effect of this is to lose\n    information (much as [destruct] can do), and leave you unable to\n    complete the proof.  Here's an example: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n\n(** Just doing an [inversion] on [H1] won't get us very far in the\n    recursive cases. (Try it!). So we need induction. Here is a naive\n    first attempt: *)\n\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** But now, although we get seven cases (as we would expect from the\n    definition of [exp_match]), we have lost a very important bit of\n    information from [H1]: the fact that [s1] matched something of the\n    form [Star re].  This means that we have to give proofs for _all_\n    seven constructors of this definition, even though all but two of\n    them ([MStar0] and [MStarApp]) are contradictory.  We can still\n    get the proof to go through for a few constructors, such as\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros H. apply H.\n\n(** ... but most cases get stuck.  For [MChar], for instance, we\n    must show that\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    which is clearly impossible. *)\n\n  - (* MChar. Stuck... *)\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n    properly with hypotheses that are completely general, i.e., ones\n    in which all the arguments are variables, as opposed to more\n    complex expressions, such as [Star re].\n\n    (In this respect, [induction] on evidence behaves more like\n    [destruct] than like [inversion].)\n\n    We can solve this problem by generalizing over the problematic\n    expressions with an explicit equality: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp T),\n  s1 =~ re' ->\n  re' = Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n    because the argument to the first hypothesis is sufficiently\n    general, which means that we can discharge most cases by inverting\n    the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a tactic to\n    automatically generate such equations for us, avoiding thus the\n    need for changing the statements of our theorems. *)\n\n(** Invoking the tactic [remember e as x] causes Coq to (1) replace\n    all occurrences of the expression [e] by the variable [x], and (2)\n    add an equation [x = e] to the context.  Here's how we can use it\n    to show the above result: *)\nAbort.\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  remember (Star re) as re'.\n\n(** We now have [Heqre' : re' = Star re]. *)\n\n  generalize dependent s2.\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** The [Heqre'] is contradictory in most cases, which allows us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)   inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n\n(** The interesting cases are those that correspond to [Star].  Note\n    that the induction hypothesis [IH2] on the [MStarApp] case\n    mentions an additional premise [Star re'' = Star re'], which\n    results from the equality generated by [remember]. *)\n\n  - (* MStar0 *)\n    inversion Heqre'. intros s H. apply H.\n\n  - (* MStarApp *)\n    inversion Heqre'. rewrite H0 in IH2, Hmatch1.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * reflexivity.\n      * apply H1.\nQed.\n\n(** **** Exercise: 4 stars (exp_match_ex2)  *)\n\n(** The [MStar''] lemma below (combined with its converse, the\n    [MStar'] exercise above), shows that our definition of [exp_match]\n    for [Star] is equivalent to the informal one given previously. *)\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp T),\n  s =~ Star re ->\n  exists ss : list (list T),\n    s = fold app ss []\n    /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (pumping)  *)\n(** One of the first really interesting theorems in the theory of\n    regular expressions is the so-called _pumping lemma_, which\n    states, informally, that any sufficiently long string [s] matching\n    a regular expression [re] can be \"pumped\" by repeating some middle\n    section of [s] an arbitrary number of times to produce a new\n    string also matching [re].\n\n    To begin, we need to define \"sufficiently long.\"  Since we are\n    working in a constructive logic, we actually need to be able to\n    calculate, for each regular expression [re], the minimum length\n    for strings [s] to guarantee \"pumpability.\" *)\n\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\n(** Next, it is useful to define an auxiliary function that repeats a\n    string (appends it to itself) some number of times. *)\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\n  end.\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\n  napp (n + m) l = napp n l ++ napp m l.\nProof.\n  intros T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n(** Now, the pumping lemma itself says that, if [s =~ re] and if the\n    length of [s] is at least the pumping constant of [re], then [s]\n    can be split into three substrings [s1 ++ s2 ++ s3] in such a way\n    that [s2] can be repeated any number of times and the result, when\n    combined with [s1] and [s3] will still match [re].  Since [s2] is\n    also guaranteed not to be the empty string, this gives us\n    a (constructive!) way to generate strings matching [re] that are\n    as long as we like. *)\n\nLemma pumping : forall T (re : reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** To streamline the proof (which you are to fill in), the [omega]\n    tactic, which is enabled by the following [Require], is helpful in\n    several places for automatically completing tedious low-level\n    arguments involving equalities or inequalities over natural\n    numbers.  We'll return to [omega] in a later chapter, but feel\n    free to experiment with it now if you like.  The first case of the\n    induction gives an example of how it is used. *)\n\nImport Coq.omega.Omega.\n\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - (* MEmpty *)\n    simpl. omega.\n  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Case Study: Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].  But\n    performing this conversion in the way we did it there can result\n    in tedious proof scripts.  Consider the proof of the following\n    theorem: *)\n\nTheorem filter_not_empty_In : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_nat n m) eqn:H.\n    + (* beq_nat n m = true *)\n      intros _. rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + (* beq_nat n m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly apply\n    the [beq_nat_true_iff] lemma to the equation generated by\n    destructing [beq_nat n m], to convert the assumption [beq_nat n m\n    = true] into the assumption [n = m]; then we had to [rewrite]\n    using this assumption to complete the case.\n\n    We can streamline this by defining an inductive proposition that\n    yields a better case-analysis principle for [beq_nat n m].\n    Instead of generating an equation such as [beq_nat n m = true],\n    which is generally not directly useful, this principle gives us\n    right away the assumption we really need: [n = m].\n\n    We'll actually define something a bit more general, which can be\n    used with arbitrary properties (and not just equalities): *)\n\nModule FirstTry.\n\nInductive reflect : Prop -> bool -> Prop :=\n| ReflectT : forall (P:Prop), P -> reflect P true\n| ReflectF : forall (P:Prop), ~ P -> reflect P false.\n\n(** Before explaining this, let's rearrange it a little: Since the\n    types of both [ReflectT] and [ReflectF] begin with\n    [forall (P:Prop)], we can make the definition a bit more readable\n    and easier to work with by making [P] a parameter of the whole\n    Inductive declaration. *)\n\nEnd FirstTry.\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\n(** The [reflect] property takes two arguments: a proposition\n    [P] and a boolean [b].  Intuitively, it states that the property\n    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: [P]\n    holds if and only if [b = true].  To see this, notice that, by\n    definition, the only way we can produce evidence that [reflect P\n    true] holds is by showing that [P] is true and using the\n    [ReflectT] constructor.  If we invert this statement, this means\n    that it should be possible to extract evidence for [P] from a\n    proof of [reflect P true].  Conversely, the only way to show\n    [reflect P false] is by combining evidence for [~ P] with the\n    [ReflectF] constructor.\n\n    It is easy to formalize this intuition and show that the two\n    statements are indeed equivalent: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  (* WORKED IN CLASS *)\n  intros P b H. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Exercise: 2 stars, recommended (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n    connective is that, by destructing a hypothesis or lemma of the\n    form [reflect P b], we can perform case analysis on [b] while at\n    the same time generating appropriate hypothesis in the two\n    branches ([P] in the first subgoal and [~ P] in the second). *)\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m.\n  apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\n(** The new proof of [filter_not_empty_In] now goes as follows.\n    Notice how the calls to [destruct] and [apply] are combined into a\n    single call to [destruct]. *)\n\n(** (To see this clearly, look at the two proofs of\n    [filter_not_empty_In] with Coq and observe the differences in\n    proof state at the beginning of the first case of the\n    [destruct].) *)\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_natP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** **** Exercise: 3 stars, recommended (beq_natP_practice)  *)\n(** Use [beq_natP] as above to prove the following: *)\n\nFixpoint count n l :=\n  match l with\n  | [] => 0\n  | m :: l' => (if beq_nat n m then 1 else 0) + count n l'\n  end.\n\nTheorem beq_natP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** This technique gives us only a small gain in convenience for\n    the proofs we've seen here, but using [reflect] consistently often\n    leads to noticeably shorter and clearer scripts as proofs get\n    larger.  We'll see many more examples in later chapters.\n\n    The use of the [reflect] property was popularized by _SSReflect_,\n    a Coq library that has been used to formalize important results in\n    mathematics, including as the 4-color theorem and the\n    Feit-Thompson theorem.  The name SSReflect stands for _small-scale\n    reflection_, i.e., the pervasive use of reflection to simplify\n    small proof steps with boolean computations. *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, recommended (nostutter)  *)\n(** Formulating inductive definitions of properties is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all.\n\n    We say that a list \"stutters\" if it repeats the same element\n    consecutively.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n (* FILL IN HERE *)\n.\n(** Make sure each of these tests succeeds, but feel free to change\n    the suggested proof (in comments) if the given one doesn't work\n    for you.  Your definition might be different from ours and still\n    be correct, in which case the examples might need a different\n    proof.  (You'll notice that the suggested proofs use a number of\n    tactics we haven't talked about, to make them more robust to\n    different possible ways of defining [nostutter].  You can probably\n    just uncomment and use them as-is, but you can also prove each\n    example with more basic tactics.)  *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge)  *)\n(** Let's prove that our definition of [filter] from the [Poly]\n    chapter matches an abstract specification.  Here is the\n    specification, written out informally in English:\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example,\n\n    [1;4;6;2;3]\n\n    is an in-order merge of\n\n    [1;6;2]\n\n    and\n\n    [4;3].\n\n    Now, suppose we have a set [X], a function [test: X->bool], and a\n    list [l] of type [list X].  Suppose further that [l] is an\n    in-order merge of two lists, [l1] and [l2], such that every item\n    in [l1] satisfies [test] and no item in [l2] satisfies test.  Then\n    [filter test l = l1].\n\n    Translate this specification into a Coq theorem and prove\n    it.  (You'll need to begin by defining what it means for one list\n    to be a merge of two others.  Do this with an inductive relation,\n    not a [Fixpoint].)  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2)  *)\n(** A different way to characterize the behavior of [filter] goes like\n    this: Among all subsequences of [l] with the property that [test]\n    evaluates to [true] on all their members, [filter test l] is the\n    longest.  Formalize this claim and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (palindromes)  *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor like\n\n        c : forall l, l = rev l -> pal l\n\n      may seem obvious, but will not work very well.)\n\n    - Prove ([pal_app_rev]) that\n\n       forall l, pal (l ++ rev l).\n\n    - Prove ([pal_rev] that)\n\n       forall l, pal l -> l = rev l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Again, the converse direction is significantly more difficult, due\n    to the lack of evidence.  Using your definition of [pal] from the\n    previous exercise, prove that\n\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (NoDup)  *)\n(** Recall the definition of the [In] property from the [Logic]\n    chapter, which asserts that a value [x] appears at least once in a\n    list [l]: *)\n\n(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=\n   match l with\n   | [] => False\n   | x' :: l' => x' = x \\/ In A x l'\n   end *)\n\n(** Your first task is to use [In] to define a proposition [disjoint X\n    l1 l2], which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in\n    common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [In] to define an inductive proposition [NoDup X\n    l], which should be provable exactly when [l] is a list (with\n    elements of type [X]) where every member is different from every\n    other.  For example, [NoDup nat [1;2;3;4]] and [NoDup\n    bool []] should be provable, while [NoDup nat [1;2;1]] and\n    [NoDup bool [true;true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (pigeonhole principle)  *)\n(** The _pigeonhole principle_ states a basic fact about counting: if\n   we distribute more than [n] items into [n] pigeonholes, some\n   pigeonhole must contain at least two items.  As often happens, this\n   apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First prove an easy useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a property [repeats] such that [repeats X l] asserts\n    that [l] contains at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now, here's a way to formalize the pigeonhole principle.  Suppose\n    list [l2] represents a list of pigeonhole labels, and list [l1]\n    represents the labels assigned to a list of items.  If there are\n    more items than labels, at least two items must have the same\n    label -- i.e., list [l1] must contain repeats.\n\n    This proof is much easier if you use the [excluded_middle]\n    hypothesis to show that [In] is decidable, i.e., [forall x l, (In x\n    l) \\/ ~ (In x l)].  However, it is also possible to make the proof\n    go through _without_ assuming that [In] is decidable; if you\n    manage to do this, you will not need the [excluded_middle]\n    hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\n   excluded_middle ->\n   (forall x, In x l1 -> In x l2) ->\n   length l2 < length l1 ->\n   repeats l1.\nProof.\n   intros X l1. induction l1 as [|x l1' IHl1'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** $Date: 2017-04-26 17:33:43 -0400 (Wed, 26 Apr 2017) $ *)\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/sf-experiment/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8840392741081574, "lm_q1q2_score": 0.8066294051880388}}
{"text": "Require Import Nat.\nRequire Import Plus.\nModule NatList.\n\n\nInductive natprod: Type :=\n  | pair (n1 n2: nat).\n\nDefinition fst (p:natprod): nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p:natprod): nat :=\n  match p with\n  | pair x y => y\n  end.\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap_pair (p: natprod): natprod :=\n  match p with\n  | (x, y) => (y, x)\n  end.\n\nTheorem surjective_pairing: forall p: natprod,\n  p = (fst p, snd p).\nProof.\n  intros [n m]. simpl. reflexivity.\nQed.\n\n\nTheorem snd_fst_is_swap: forall p: natprod,\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros [n m].\n  simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd: forall p: natprod,\n  fst (swap_pair p) = snd p.\nProof.\n  intros [a b].\n  reflexivity.\nQed.\n\n\nInductive natlist: Type :=\n  | nil\n  | cons (n: nat) (l : natlist).\n\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nCheck [].\nCheck [1;2;3].\n\nFixpoint repeat (n count: nat): natlist :=\n  match count with\n  | 0 => []\n  | S c => n :: repeat n c\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 append (a: natlist) (b: natlist) :natlist :=\n  match a with\n  | nil => b\n  | h::t => h::append t b\n  end.\n\nNotation \"a ++ b\" := (append a b) (right associativity, at level 60).\n\nDefinition head (default: nat) (a: natlist) : nat :=\n  match a with\n  | nil => default\n  | h::t => h\n  end.\n\nDefinition tail (a: natlist) : natlist :=\n  match a with\n  | nil => nil\n  | h::t => t\n  end.\n\nFixpoint nonzeros (a: natlist) : natlist :=\n  match a with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | h :: t => h :: nonzeros t\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\n\n\n\nFixpoint oddmembers (a:natlist) : natlist :=\n  match a with\n  | nil => nil\n  | h :: t => if even h\n              then oddmembers t\n              else h :: oddmembers t\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint count_odd_members (a: natlist) : nat :=\n  match a with\n  | nil => 0\n  | t :: h =>  (if even t then 0 else 1) + count_odd_members h\n  end.\n\nExample test_countoddmembers1:\n  count_odd_members [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  count_odd_members [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  count_odd_members nil = 0.\nProof. reflexivity. Qed.\n\n(* Fixpoint alternate (a b: natlist) : natlist :=\n  match a with\n  | nil => b\n  | t :: h => t :: alternate b a\n  end. *)\n\nFixpoint alternate (a b: natlist) : natlist :=\n  match a, b with\n  |nil, b' => b'\n  |a', nil => a'\n  |h1::t1, h2::t2 => h1 :: h2 :: alternate t1 t2\n  end.\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\nDefinition bag := natlist.\nFixpoint count (v: nat) (s: bag) : nat :=\n  match s with\n  | nil => 0\n  | x::t => (if v =? x then 1 else 0) + count v t\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\nDefinition sum: bag->bag->bag := append.\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add := cons.\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\nFixpoint member (v:nat) (s: bag) : bool :=\n  match s with\n  | nil => false\n  | cons x t => if x =? v then true else member v t\n  end.\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\nFixpoint remove_one (v: nat) (s: bag) : bag :=\n  match s with\n  | nil => nil\n  | h::t => if h =? v then t else h :: remove_one v t\n  end.\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v: nat) (s: bag) : bag :=\n  match s with\n  | nil => nil\n  | cons x t => if x =? v then remove_all v t else x :: remove_all v t\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. 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 (a: bag) (b: bag) : bool :=\n  match a with\n  | nil => true\n  | x::t => if member x b then subset t (remove_one x b) else false\n  end.\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 count_add_elem: forall (x: nat) (s: bag),\n  count x (add x s) = S (count x s).\nProof.\n  intros x s.\n  simpl. replace (if x =? x then 1 else 0) with (1). reflexivity.\n  induction x as [|x' iHx].\n  - reflexivity.\n  - simpl. rewrite <- iHx. 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 (tail l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity. Qed.\n\nTheorem append_assoc: forall a b c: natlist,\n  (a ++ b) ++ c = a ++ (b ++ c).\nProof.\n  intros a b c.\n  induction a as [|h t H].\n  - reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\nFixpoint rev (a: natlist) :=\n  match a with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem app_length: forall a b: natlist,\n  length (a ++ b) = length a + length b.\nProof.\n  intros a b.\n  induction a as [|t h H].\n  - reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\nTheorem rev_length: forall a: natlist, length a = length (rev a).\nProof.\n  intros a.\n  induction a as [| t h H].\n  - reflexivity.\n  - simpl. rewrite -> app_length. simpl. rewrite <- H.\n    rewrite plus_comm.\n    reflexivity.\nQed.\n\nSearch rev.\n\nTheorem app_nil_r: forall a: natlist, a ++ [] = a.\nProof.\n  intros a.\n  induction a as [| h t H].\n  - reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\n\nTheorem rev_app_distr: forall a b: natlist, rev (a ++ b) = rev b ++ rev a.\nProof.\n  intros a b.\n  induction a as [| h t H].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> H. rewrite append_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive: forall a: natlist, rev (rev a) = a.\nProof.\n  intros a.\n  induction a as [|t h H].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite H. simpl. reflexivity.\nQed.\n\nTheorem app_assoc4: forall a b c d : natlist,\n  a ++ (b ++ (c ++ d)) = ((a ++ b) ++ c) ++ d.\nProof.\n  intros a b c d.\n  rewrite append_assoc. rewrite append_assoc. reflexivity.\nQed.\n\nLemma nozeros_app: forall a b : natlist,\n  nonzeros (a ++ b) = nonzeros a ++ nonzeros b.\nProof.\n  intros a b.\n  induction a as [| t h H].\n  - reflexivity.\n  - simpl. \n    induction t as [|t' iHt'].\n    rewrite H. reflexivity.\n    simpl. rewrite H. reflexivity.\nQed.\n    \nFixpoint eqblist (a b: natlist) : bool :=\n  match a, b with\n  | nil, nil => true\n  | nil, _ => false\n  | _, nil => false\n  | t1::h1, t2::h2 => if t1 =? t2 then eqblist h1 h2 else false\n  end. \n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. reflexivity. Qed.\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl: forall a: natlist, true = eqblist a a.\nProof.\n  intros a.\n  induction a as [|h t H].\n  - reflexivity.\n  - simpl.\n    induction h as [| h' hH].\n    * rewrite H. reflexivity.\n    * simpl. rewrite hH. reflexivity.\nQed.\n\nTheorem count_member_nonzero: forall (s: bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n  induction s as [|h t H].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem leb_n_Sn : forall n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem remove_does_not_increase_count: forall s: bag,\n  count 0 (remove_one 0 s) <=? count 0 s = true.\nProof.\n  intros s.\n  induction s as [| h t H].\n  - reflexivity.\n  - simpl.\n    induction h as [| h' iH'].\n    * simpl. rewrite leb_n_Sn. reflexivity.\n    * simpl. rewrite H. reflexivity.\nQed.\n\n\nTheorem count_distr: forall (a b: bag) (e: nat),\n  count e (sum a b) = count e a + count e b.\nProof.\n  intros a b e.\n  induction a as [|h t H].\n  - simpl. reflexivity.\n  - simpl. rewrite H. rewrite plus_assoc. reflexivity.\nQed.\n\nLemma rev_nil: rev [] = [].\nProof. simpl. reflexivity. Qed.\n\nTheorem rev_injective: forall a b: natlist, \n  rev a = rev b -> a = b.\nProof.\n  intros a b H.\n  rewrite <- rev_involutive. \n  replace (a) with (rev (rev a)).\n  - rewrite H. reflexivity.\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  | nil => None\n  | a :: l' => match n with\n               | O => Some a\n               | S n' => nth_error l' n'\n               end\n  end.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [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\nFixpoint hd_error (a : natlist) : natoption :=\n  match a with \n  | nil => None\n  | h :: t => Some h\n  end.\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\nTheorem option_elim_hd: forall (a: natlist) (default: nat),\n  head default a = option_elim default (hd_error a).\nProof.\n  intros a d.\n  induction a as [|ha ta H].\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\n\nInductive id: Type := | Id (n: nat).\nDefinition eqb_id (a b: id) := \n  match a, b with\n  | Id x, Id y => x =? y\n  end.\n\nTheorem eqb_id_ref: forall x, true = eqb_id x x.\nProof.\n  intros x.\n  destruct x.\n  - simpl.\n    induction n.\n    * reflexivity.\n    * simpl. rewrite IHn. reflexivity.\nQed.\n\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 then Some v else find x d'\n  end.\n\nTheorem update_eq: forall (d: partial_map) (x: id) (v: nat),\n  find x (update d x v) = Some v.\nProof.\n  intros d x v.\n  induction d as [|i' v' d' H].\n  - simpl. \n    replace (eqb_id x x) with (true). reflexivity.\n    rewrite <- eqb_id_ref. reflexivity.\n  - simpl.\n    replace (eqb_id x x) with (true). reflexivity.\n    rewrite <- eqb_id_ref. reflexivity.\nQed.\n\nTheorem update_neq: forall (d: partial_map) (x y: id) (o: nat),\n  eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o H.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\n", "meta": {"author": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8064436707537836}}
{"text": "(* @todo  add as an exercise *)\n\n(** Returns smallest value of x less or equal than b such that (P b x). \n    Otherwise returns b  *)\n\n\nFrom hydras Require Import  primRec extEqualNat.\nFrom Coq Require Import Min ArithRing Lia Compare_dec Arith Lia.\n\n\n(* begin snippet boundedSearch3:: no-out *)\nLemma boundedSearch3 :\n  forall (P : naryRel 2) (b  : nat), boundedSearch P b <= b. \n(* end snippet boundedSearch3 *)\n\nProof.\n  unfold boundedSearch; intros P b; generalize b at 2 3.\n  induction b0.\n  - cbn; auto.\n  - cbn; destruct (Nat.eq_dec (boundedSearchHelp (P  b) b0) b0); auto.\n    case_eq (P b b0); auto.\nQed.\n\n(* begin snippet boundedSearch4:: no-out *)\n\nLemma boundedSearch4 :\n  forall (P : naryRel 2) (b  : nat),\n    P b b = true ->\n    P b (boundedSearch P b) = true. \n(* end snippet boundedSearch4 *)\n\nProof.\n  intros;  destruct (boundedSearch2 P b); auto. \n  now rewrite H0.\nQed.\n\n\nDefinition isqrt_spec n r := r * r <= n < S r * S r.\n\nSection sqrtIsPR.\n\n  Let P (n r: nat) :=  Nat.ltb n (S r * S r).\n  Definition isqrt := boundedSearch P. \n\n  Section Proof_isqrt.\n    Variable n: nat.\n\n    Remark R00 : P n (isqrt n) = true.\n    Proof.\n      apply boundedSearch4.\n      unfold P; cbn;  apply leb_correct; lia.\n    Qed.\n\n    Lemma R01 : n < S (isqrt n) * S (isqrt n).\n    Proof.\n      generalize R00; intro H; apply leb_complete in H; auto.\n    Qed.\n\n    Lemma R02 : isqrt n * isqrt n <= n.\n    Proof.\n     destruct (le_lt_dec (isqrt n * isqrt n) n); auto.\n     case_eq (isqrt n).\n     -  cbn; auto with arith.\n     -  intros n0 H;  assert (H0: n0 < isqrt n).       \n          { rewrite H; auto with arith. }\n          generalize (boundedSearch1 P n n0 H0) ; intro H1.\n          unfold P in H1; rewrite Nat.ltb_ge in H1; auto.\n    Qed.\n\n  End Proof_isqrt.\n\n   Lemma sqrt_correct (n: nat) : isqrt_spec n (isqrt n).\n   Proof.\n     split.\n     - apply R02.\n     - apply R01.\n   Qed.\n\n Lemma issqrtIsPR : isPR 1 isqrt.\n Proof.\n   unfold isqrt; apply boundSearchIsPR; unfold P; red.\n   assert (H: isPR 2 (fun a b => \n                     (charFunction 2 ltBool a (S b * S b)))).\n   {\n     apply compose2_2IsPR.\n     - apply filter10IsPR; apply idIsPR.\n     - apply filter01IsPR;  apply compose1_2IsPR.\n       + apply succIsPR.\n       + apply succIsPR.\n       + apply multIsPR.\n   - apply ltIsPR.\n   }\n   destruct H as [x Hx]; exists x.  \n   eapply extEqualTrans.\n   - apply Hx.\n   - intros a b; simpl .\n     case_eq (ltBool a (S (b + b * S b))).\n    +  case_eq (a <? S (b + b * S b) );  auto.\n       intros.\n       rewrite Nat.ltb_ge in H.\n       apply ltBoolTrue in H0; lia.\n    +  intro H; apply ltBoolFalse in H.\n       case_eq (a <? S (b + b * S b)); auto.\n       intro H0;  rewrite Nat.ltb_lt in H0.\n       now destruct H.\nQed. \n\n\nEnd sqrtIsPR.\n\n(** slow! *)\n\nCompute isqrt 22.\n\n(** Extra work :\n   Define a faster implementation of [sqrt_spec], and prove your function is \n   extensionnaly equal to [isqrt] (hence PR!)\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/isqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8791467722591729, "lm_q1q2_score": 0.806443664409384}}
{"text": "(*  *********************************************** *)\n(*                  example pred1                   *)\n(*  *********************************************** *)\n\nInductive even : nat -> Prop :=\n| evenO : even O\n| evenSS : forall n:nat ,\n           even n -> even (S (S n)) .\n\nPrint le.\n\nTheorem example:\n  forall n:nat,\n  (even n) \\/ (even (S n)).\n\nProof.\nintro n.\ninduction n.\n\nleft.\napply evenO.\n\ninversion IHn.\nright.\napply evenSS.\nassumption.\nleft.\nassumption.\nQed.\n\n\n(* We consider successor (short), predecessor (short),\n   mirror (still quite short), sort (longer).        *)\n\n\n\n(*  *********************************************** *)\n(*                      successor                   *)\n(*  *********************************************** *)\n\n\n(* NB:\n   here we use the notation for existential quantification in Set *)\n\n(* example *)\nTheorem successor:\n  forall n:nat, {m:nat | m = S n} .\n\nProof.\nintro n.\n(* NB: we do not need induction *)\n(* The following step corresponds to an\n   application of the introduction rule for\n   existential quantification, read upwards.\n   Note how the goal is transformed.          *)\nexists (S n).\nreflexivity.\nQed.\n\n(* we see the main part of the extracted program. *)\nExtraction successor.\n\n(* The extracted program is written to a file. *)\nExtraction \"suc\" successor.\n(* The files are saved in your directory on prover\n   and can be seen using load. *)\n\n(* How can we use the extracted program ?\n   (On your vu-account, not on prover.)\n   type \"ocaml\" to activate the ocaml toplevel compiler\n   this gives a prompt #\n   #use \"suc.ml\" ;;\n   makes that the file suc.ml is loaded\n   NB: #is not the prompt but #use is the command !\n   NB: the \"\" are necessary\n   you can use the program by saying for instance\n   successor O ;;\n   NB: the round thing is capital-o\n   NB: every command should end with ;;\n   exit with  #quit ;;\n   NB: again # is not the prompt, and ;; are necessary  *)\n\n\n\n(*  *********************************************** *)\n(*                     predecessor                  *)\n(*  *********************************************** *)\n\n(* exercise 1 *)\n(* A possibility is to proceed by induction on n.\n   Use False elimination to establish the case for n=0. *)\n\nTheorem predecessor :\n  forall n:nat, ~(n=O) -> {m:nat | S m = n}.\nProof.\n(*! proof *)\n \nQed.\n\n(* extraction of the program *)\nExtraction predecessor.\nExtraction \"pred\" predecessor.\n\n\n\n(*  *********************************************** *)\n(*                        mirror                    *)\n(*  *********************************************** *)\n\n(* datatype for binary trees with labels on the leafs *)\nInductive bintree : Set :=\n  | leaf : nat -> bintree\n  | node : bintree -> bintree -> bintree.\n\n(* examples of trees *)\nDefinition tree1 := leaf 1.\nDefinition tree2 := node (leaf 1) (leaf 2).\nDefinition tree3 := node (node (leaf 1) (leaf 2)) (leaf 3).\n\n(* specification *)\nInductive Mirrored : bintree -> bintree -> Prop :=\n  | Mirrored_leaf : forall n : nat, Mirrored (leaf n) (leaf n)\n  | Mirrored_node :\n      forall b b' c c' : bintree,\n      Mirrored b b' -> Mirrored c c' -> Mirrored (node b c) (node c' b').\n\n(* exercise 2 *)\n(* The theorem from which we will extract a program. *)\n(* A possibility is to proceed by induction and to use\n   inversion on the induction hypotheses.              *)\nTheorem Mirror :\n  forall t : bintree,\n  {t' : bintree | Mirrored t t'}.\nProof.\n(*! proof *)\n\nQed.\n\nExtraction Mirror.\nExtraction \"mirror\" Mirror.\n\n(* Alternative approach: we give an implementation ...*)\nFixpoint mirror (t : bintree) : bintree :=\nmatch t with\n  | leaf n => leaf n\n  | node l r => node (mirror r) (mirror l)\nend.\n\n(* exercise 3 *)\n(* ... and prove its correctness *)\nTheorem Mirrored_mirror : forall t : bintree, Mirrored t (mirror t).\nProof.\n(*! proof *)\n\nQed.\n\n(*  *********************************************** *)\n(*                  insertion sort                  *)\n(*  *********************************************** *)\n\n(* We will use properties concerning\n   less-than-or-equal-to from the coq libary. *)\nRequire Import Arith.\n\n(* the datatype *)\nInductive natlist : Set :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(* specification *)\n(* The following predicate was also in practical work 5. *)\nInductive sorted : natlist -> Prop :=\n| sorted0 : sorted nil\n| sorted1 : forall n:nat , sorted (cons n nil)\n| sorted2 : forall n h:nat , forall t:natlist ,\n            le n h -> sorted (cons h t) -> sorted (cons n (cons h t)).\n\n(* week 5 exercise 11 *)\nTheorem sortednil : sorted nil.\nProof.\n(*! proof *)\n\nQed.\n\n(* week 5 exercise 12 *)\nTheorem sortedone : sorted (cons 0 nil).\nProof.\n(*! proof *)\n\nQed.\n\n(* week 5 exercise 13 *)\nTheorem sorted_one_two_three :\n  sorted (cons 1 (cons 2 (cons 3 nil))).\nProof.\n(*! proof *)\n\nQed.\n\n(* week 5 exercise 14 *)\nTheorem sorted_tail :\n  forall (n : nat) (l : natlist),\n  sorted (cons n l) ->\n  sorted l.\nProof.\n(*! proof *)\n\nQed.\n\n\n(* Inserted n l i expresses\n   that the list i equals the list l with n inserted somewhere. *)\nInductive Inserted (n : nat) : natlist -> natlist -> Prop :=\n  | Inserted_front :\n      forall l : natlist, Inserted n l (cons n l)\n  | Inserted_cons :\n      forall (m : nat) (l l' : natlist),\n      Inserted n l l' -> Inserted n (cons m l) (cons m l').\n\n(* exercise 4 *)\nTheorem exercise1_Inserted : Inserted 1 nil (cons 1 nil).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 5 *)\nTheorem exercise2_Inserted : Inserted 1 (cons 1 nil) (cons 1 (cons 1 nil)) .\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 6: same theorem but give a different proof *)\nTheorem exercise3_Inserted : Inserted 1 (cons 1 nil) (cons 1 (cons 1 nil)) .\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 7 *)\nTheorem exercise4_Inserted : ~ Inserted 1 nil (cons 2 nil).\nProof.\n(*! proof *)\n\nQed.\n\nInductive Permutation : natlist -> natlist -> Prop :=\n  | Permutation_nil : Permutation nil nil\n  | Permutation_cons :\n      forall (n : nat) (l l' l'' : natlist),\n      Permutation l l' -> Inserted n l' l'' -> Permutation (cons n l) l''.\n\n(* exercise 8 *)\n(* Hint: use inversion_clear several times.\n   Same as inversion but with less \"pollution\" of hypotheses. *)\nLemma Permutation_neg:\n  ~(Permutation (cons 1 (cons 2 nil)) (cons 2 (cons 3 nil))).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 9 *)\n(* Hint1: use \"apply ... with ...\" if you have to provide Coq\n   with the missing argument. See as an example the first step\n   of the following proof, and try to see the error-message in\n   case you leave out the \"with ...\" part.\n   Hint2: if you want to apply the constructor of an inductive\n   type, you can use the tactic \"constructor\".\n   For instance, instead of \"apply Permutation_nil\"\n   you can use \"constructor\".                          *)\nLemma Permutation_123:\n  Permutation (cons 1 (cons 2 (cons 3 nil))) (cons 3 (cons 2 (cons 1 nil))).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 10 *)\n(* The following lemma will be used\n   in the proof of the lemma Insert.\n   Use induction on l and the \"apply ... with ...\". *)\nLemma Permutation_refl :\n  forall (l : natlist), Permutation l l.\nProof.\n(*! proof *)\n\nQed.\n\n(* We use an auxiliary notion.\n   Lowerbound n l expresses that\n   n <= m for all elements m of l. *)\nInductive Lowerbound (n : nat) : natlist -> Prop :=\n  | Lowerbound_nil : Lowerbound n nil\n  | Lowerbound_cons :\n      forall (m : nat) (l : natlist),\n      n <= m -> Lowerbound n l -> Lowerbound n (cons m l).\n\n(* exercise 11 *)\n(* The following lemma is used in the proof of Insert. *)\n(* You can use the tactic \"rewrite\". *)\nLemma Lowerbound_sorted :\n  forall (l : natlist) (n : nat),\n  Lowerbound n l ->\n  sorted l ->\n  sorted (cons n l).\nProof.\n(*! proof *)\n\nQed.\n\n(* In the proof of the lemma sorted_Lowerbound we will use\n   le_trans from the Coq library.\n   It is a lemma expressing transitivity of the relation le. *)\n\nCheck le_trans.\n\n(* exercise 12 *)\n(* complete the following proof; use \"apply le_trans with ...\" *)\nLemma sorted_Lowerbound :\n  forall (l : natlist) (n : nat),\n  sorted (cons n l) -> Lowerbound n l.\nProof.\n(*! proof *)\n\nQed.\n\n(* given *)\nLemma Inserted_Lowerbound :\n  forall (l l' : natlist) (n m : nat),\n  n <= m ->\n  Inserted m l l' ->\n  Lowerbound n l ->\n  Lowerbound n l'.\nProof.\ninduction l.\nintros.\ninversion_clear H0.\napply Lowerbound_cons.\nexact H.\nexact H1.\nintros k p m H H0 H1.\ninversion_clear H0.\napply Lowerbound_cons.\nexact H.\nexact H1.\ninversion_clear H1.\napply Lowerbound_cons.\nexact H0.\napply IHl with m.\nexact H.\nexact H2.\nexact H3.\nQed.\n\n(* given *)\nLemma Permutation_Lowerbound :\n  forall (l l' : natlist) (n : nat),\n    Permutation l l' -> Lowerbound n l -> Lowerbound n l'.\nProof.\ninduction l.\nintros k n H H0.\ninversion_clear H.\nexact H0.\nintros k m H H0.\ninversion_clear H.\ninversion_clear H0.\napply Inserted_Lowerbound with l' n.\nexact H.\nexact H2.\napply IHl.\nexact H1.\nexact H3.\nQed.\n\n(* given *)\nLemma Insert :\n  forall (l : natlist) (n : nat),\n  sorted l -> {i : natlist | Inserted n l i /\\ sorted i}.\nProof.\ninduction l.\n\n(* case nil *)\nintros n H.\nexists (cons n nil).\nsplit.\napply Inserted_front.\napply sorted1.\n\n(* case (cons n l) *)\nintros m H.\nelim (le_lt_dec m n).\n\nintro I.\nexists (cons m (cons n l)).\nsplit.\napply Inserted_front.\napply sorted2.\nexact I.\nexact H.\n\nintro I.\nelim IHl with m.\nintros i' H1.\nelim H1.\nintros H2 H3.\nexists (cons n i').\nsplit.\napply Inserted_cons.\nexact H2.\napply Lowerbound_sorted.\napply Permutation_Lowerbound with (cons m l).\napply Permutation_cons with l.\napply Permutation_refl.\nexact H2.\napply Lowerbound_cons.\napply lt_le_weak.\nexact I.\napply sorted_Lowerbound.\nexact H.\nexact H3.\ninversion_clear H.\napply sorted0.\nexact H1.\nQed.\n\nExtraction Insert.\n\n(* exercise 13 *)\n(* Use induction on l.\n   In the induction step, after two inversions,\n   use \"elim Insert with x n.\" or parameters\n   appropriate to your development for x and n. *)\nTheorem Sort :\n  forall l : natlist, {l' : natlist | Permutation l l' /\\ sorted l'}.\nProof.\n(*! proof *)\n\nQed.\n\nExtraction Sort.\nExtraction \"insertsort\" Sort.\n\n\n\n(* Now the implementation and its correcness.\n   The remainder is just for reading/curiosity. *)\nFixpoint insert (n : nat) (l : natlist) {struct l} : natlist :=\n  match l with\n  | nil => cons n nil\n  | cons m k =>\n      match le_lt_dec n m with\n      | left _ => cons n (cons m k)\n      | right _ => cons m (insert n k)\n      end\n  end.\n\nFixpoint sort (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons m k => insert m (sort k)\n  end.\n\n(* correctness of the implementation *)\nLemma Inserted_insert :\n  forall (n : nat) (l : natlist), Inserted n l (insert n l).\n\nProof.\ninduction l.\n\nsimpl.\napply Inserted_front.\n\nsimpl.\nelim (le_lt_dec n n0).\nintro.\napply Inserted_front.\nintro.\napply Inserted_cons.\nexact IHl.\nQed.\n\nLemma Lowerbound_insert :\n  forall (l : natlist) (n m : nat),\n  m <= n -> Lowerbound m l -> Lowerbound m (insert n l).\n\nProof.\ninduction l.\n\nintros n m H H0.\nsimpl.\napply Lowerbound_cons.\nexact H.\nexact H0.\n\nintros n' m H H0.\nsimpl.\nelim (le_lt_dec n' n).\nintro H1.\napply Lowerbound_cons.\nexact H.\nexact H0.\nintro H1.\ninversion_clear H0.\napply Lowerbound_cons.\nexact H2.\napply IHl.\nexact H.\nexact H3.\nQed.\n\nLemma sorted_insert :\n  forall (l : natlist) (n : nat), sorted l -> sorted (insert n l).\n\nProof.\ninduction l.\n\nintros n H.\nsimpl.\napply sorted1.\n\nintros m H.\nsimpl.\nelim (le_lt_dec m n).\nintro H0.\napply sorted2.\nexact H0.\nexact H.\nintro H0.\napply Lowerbound_sorted.\napply Lowerbound_insert.\napply lt_le_weak.\nexact H0.\napply sorted_Lowerbound.\nexact H.\napply IHl.\ninversion_clear H.\napply sorted0.\nexact H2.\nQed.\n\nTheorem Permutation_sort :\n  forall l : natlist, Permutation l (sort l).\n\nProof.\ninduction l.\nsimpl.\napply Permutation_nil.\nsimpl.\napply Permutation_cons with (sort l).\nexact IHl.\napply Inserted_insert.\nQed.\n\nTheorem sorted_sort :\n  forall l : natlist, sorted (sort l).\n\nProof.\ninduction l.\nsimpl.\napply sorted0.\nsimpl.\napply sorted_insert.\nexact IHl.\nQed.\n\n\n", "meta": {"author": "danalvi", "repo": "imc010-type-theory-coq", "sha": "13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8", "save_path": "github-repos/coq/danalvi-imc010-type-theory-coq", "path": "github-repos/coq/danalvi-imc010-type-theory-coq/imc010-type-theory-coq-13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8/ex6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.806381717403952}}
{"text": "(*** Introduction to Computational Logic, Coq part of Assignment 4 ***)\n\n\n\n(*** Exercise 4.1 ***)\n\n(* Provide all four definitions by yourself. *)\nDefinition elim_bool_strong : forall (p : bool -> Type), p true -> p false -> forall x, p x :=\n  fun p a b x => match x with true => a | false => b end.\n\nDefinition elim_nat_strong : forall (p : nat -> Type), p O -> (forall x, p x -> p (S x)) -> forall x, p x :=\n  fun p a b => fix F x := match x with O => a | S x => b x (F x) end.\n\nDefinition elim_bool := fun (p : bool -> Prop) => elim_bool_strong p.\n\nDefinition elim_nat := fun (p : nat -> Prop) => elim_nat_strong p.\n\n\n(*** Exercise 4.2 ***)\n\nGoal forall x, x = true \\/ x = false.\nProof.\n  refine (fun x => match x with true => _ | false => _ end).\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nGoal forall x, x = true \\/ x = false.\nProof.\n  intros.\n  pattern x.\n  apply elim_bool.\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nGoal forall (p : bool -> Prop), (forall x y, y = x -> p x) -> forall x, p x.\nProof.\n  intros p f x.\n  destruct x.\n  - apply (f true true). reflexivity.\n  - apply (f false false). reflexivity.\nQed.\n\nGoal forall (p : bool -> Prop), (forall x y, y = x -> p x) -> forall x, p x.\nProof.\n  intros p f x.\n  apply elim_bool.\n  - apply (f true true). reflexivity.\n  - apply (f false false). reflexivity.\nQed.\n\nGoal forall (p : bool -> Prop) x, (x = true -> p true) -> (x = false -> p false) -> p x.\nProof.\n  intros p x f g.\n  destruct x.\n  - apply f. reflexivity.\n  - apply g. reflexivity.\nQed.\n\nGoal forall (p : bool -> Prop) x, (x = true -> p true) -> (x = false -> p false) -> p x.\nProof.\n  intros p x f g.\n  pattern x.\n  Abort.\n\n\n(*** Exercise 4.3 ***)\n\nDefinition bool_and : bool -> bool -> bool :=\n  fun x y => elim_bool_strong (fun _ => bool) y false x. \n\n(* With the correct definition of bool_and this will be provable by reflexivity: *)\n\nLemma bool_and_spec :\n  bool_and = fun x y => match x with true => y | false => false end.\nProof.\n  reflexivity.\nQed.\n\n\n(*** Exercise 4.4 ***)\n\nLemma nat_disjoint x :\n  S x <> O.\nProof.\n  intros H. change ((fun y => match y with O => True | S y' => False end) (S x)).\n  rewrite H. exact I.\nQed.\n\nLemma nat_injective x y :\n  S x = S y -> x = y.\nProof.\n  intros H. change ((fun z => match z with O => False | S z' => z' = y end) (S x)).\n  rewrite H. reflexivity.\nQed.\n\nGoal forall x, S x <> x.\nProof.\n  apply elim_nat.\n  - intros H. change ((fun x => match x with O => True | S _ => False end) (S O)). rewrite H. exact I.\n  - intros x IH H.\n    apply IH.\n    change ((fun y => S x = pred y) (S x)).\n    now rewrite <- H.\nQed.\n\nGoal forall x y z, x + y = x + z -> y = z.\nProof.\n  intros x y z.\n  induction x as [|x IH].\n  - intros H. change ((fun x => y = x) (0 + z)). now rewrite <- H.\n  - intros H. apply IH. \n    Abort.\n\nGoal forall x y : nat, x = y \\/ x <> y.\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 4.5 ***)\n\nDefinition trunc_minus : nat -> nat -> nat :=\n  fun x y => elim_nat_strong (fun _ => nat) x (fun _ r => pred r) y.\n\n(* With the correct definition of trunc_minus,\n   the following tests will be provable by reflexivity.\n   Invent some more tests. *)\n\nLemma trunc_minus_test1 :\n  trunc_minus 2 7 = 0.\nProof.\n  reflexivity.\nQed.\n\nLemma trunc_minus_test2 :\n  trunc_minus 3 0 = 3.\nProof.\n  reflexivity.\nQed.\n\nLemma trunc_minus_test3 :\n  trunc_minus 12 8 = 4.\nProof.\n  reflexivity.\nQed.\n  \n\n\n(*** Exercise 4.6 ***)\n\nDefinition ind_pair :\n  forall X Y (p : X * Y -> Prop), (forall x y, p (x, y)) -> forall a, p a :=\n  fun X Y p H a => match a with (x, y) => H x y end.\n\nDefinition fst X Y (a : X * Y) :=\n  match a with (x, y) => x end.\n\nArguments fst [_ _].\n\nDefinition snd X Y (a : X * Y) :=\n  match a with (x, y) => y end.\n\nArguments snd [_ _].\n\nDefinition swap X Y (a : X * Y) :=\n  match a with (x, y) => (y, x) end.\n\nArguments swap [_ _].\n\nGoal forall X Y (a : X * Y), (fst a, snd a) = a.\nProof.\n  (*...*)\nAdmitted.\n\nGoal forall X Y (a : X * Y), swap (swap a) = a.\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 4.7 ***)\n\n(* Definition elim_pair :\n     forall X Y (p : X * Y -> Type), (forall x y, p (x, y)) -> forall a, p a :=\n     ... *)\n\nDefinition fst' : forall X Y, X * Y -> X :=\n  (*...*) fst.\n\nLemma fst_spec :\n  fst' = fst.\nProof.\n  reflexivity.\nQed.\n\nDefinition snd' : forall X Y, X * Y -> Y :=\n  (*...*) snd.\n\nLemma snd_spec :\n  snd' = snd.\nProof.\n  reflexivity.\nQed.\n\nDefinition swap' :=\n  (*...*) swap.\n\nLemma swap_spec :\n  swap' = swap.\nProof.\n  reflexivity.\nQed.\n\n\n\n(*** Exercise 4.8 ***)\n\nGoal forall X : Prop, X <-> X.\nProof.\n  (*...*)\nAdmitted.\n\nGoal forall X Y : Prop, (X <-> Y) -> (Y <-> X).\nProof.\n  (*...*)\nAdmitted.\n\nGoal forall X Y Z : Prop, (X <-> Y) -> (Y <-> Z) -> (X <-> Z).\nProof.\n  (*...*)\nAdmitted.\n\nGoal forall X Y : Prop, (X <-> Y) -> (~ X <-> ~ Y).\nProof.\n  (*...*)\nAdmitted.\n\nGoal forall X Y Z W : Prop, (X <-> Y) -> (Z <-> W) -> (X \\/ Z <-> Y \\/ W).\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 4.9 ***)\n\nDefinition eq : forall X, X -> X -> Prop :=\n  fun X x y => forall (p : X -> Prop), p y -> p x.\n\nLemma justify_Q X (x : X) :\n  eq X x x.\nProof.\n  (*...*)\nAdmitted.\n\nLemma justify_R X (x y : X) (p : X -> Prop) :\n  eq X x y -> p x -> p y.\nProof.\n  (*...*)\nAdmitted.\n\n\n\n\n  \n\n\n", "meta": {"author": "archbung", "repo": "icl-ss19", "sha": "fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e", "save_path": "github-repos/coq/archbung-icl-ss19", "path": "github-repos/coq/archbung-icl-ss19/icl-ss19-fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e/assignment/4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8063817015886741}}
{"text": "Require Import Arith ArithRing.\n\nLtac defn x := unfold x; fold x.\n\nFixpoint sum (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n => S n + sum n\n  end.\n\nTheorem sum_equals : forall n, 2 * sum n = n * (n + 1).\n  induction n.\n\n  trivial.\n\n  defn sum.\n  rewrite mult_plus_distr_l.\n  rewrite IHn.\n  ring_nat.\nQed.\n\nPrint sum_equals.\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/Lect2/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673113726775, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.8063542162706686}}
{"text": "(** * 6.512 Formal Reasoning About Programs, Spring 2023 - Pset 1 *)\n\n(* Welcome to 6.512!  Read through `Pset1Signature.v` before starting here. *)\n\nRequire Import Frap Pset1Signature.\n\nModule Impl.\n  (* The first part of this assignment involves the [bool] datatype,\n   * which has the following definition.\n   * <<\n       Inductive bool :=\n       | true\n       | false.\n     >>\n   * We will define logical negation and conjunction of Boolean values,\n   * and prove some properties of these definitions.\n   *)\n\n  (* Define [Neg] so that it implements Boolean negation, which flips\n   * the truth value of a Boolean value.\n   *)\n  Definition Neg (b : bool) : bool.\n  Admitted.\n\n  (* For instance, the negation of [true] should be [false].\n   * This proof should follow from reducing both sides of the equation\n   * and observing that they are identical.\n   *)\n  Theorem Neg_true : Neg true = false.\n  Proof.\n  Admitted.\n\n  (* Negation should be involutive, meaning that if we negate\n   * any Boolean value twice, we should get the original value back.\n\n   * To prove a fact like this that holds for all Booleans, it suffices\n   * to prove the fact for both [true] and [false] by using the\n   * [cases] tactic.\n   *)\n  Theorem Neg_involutive : forall b : bool, Neg (Neg b) = b.\n  Proof.\n  Admitted.\n\n  (* Define [And] so that it implements Boolean conjunction. That is,\n   * the result value should be [true] exactly when both inputs\n   * are [true].\n   *)\n  Definition And (x y : bool) : bool.\n  Admitted.\n\n  (* Here are a couple of examples of how [And] should act on\n   * concrete inputs.\n   *)\n  Theorem And_true_true : And true true = true.\n  Proof.\n  Admitted.\n\n  Theorem And_false_true : And false true = false.\n  Proof.\n  Admitted.\n\n  (* Prove that [And] is commutative, meaning that switching the order\n   * of its arguments doesn't affect the result.\n   *)\n  Theorem And_comm : forall x y : bool, And x y = And y x.\n  Proof.\n  Admitted.\n\n  (* Prove that the conjunction of a Boolean value with [true]\n   * doesn't change that value.\n   *)\n  Theorem And_true_r : forall x : bool, And x true = x.\n  Proof.\n  Admitted.\n\n  (* You may have noticed that the [=] operator above does not return a [bool]. *)\n  Check (true = false).\n  \n  (* [a = b] is instead a [Prop], short for proposition, the type of logical\n   * statements. The set of propositions in Coq is large and contains a variety\n   * of statements, many of which are undecideable, so we can't in general\n   * treat statements in [Prop] as functions with Boolean output. This means\n   * that you can't use expressions of type [Prop] when defining a program,\n   * since they don't have computational behavior. For example, compare how\n   * the following two expressions evaluate. The first expression uses functions\n   * we can compute with, while the second uses propositions:\n   *)\n  Compute (if 1 ==n 2 then (And true false) else true).\n  Compute (1 = 2 -> True /\\ False).\n  \n  (* The following operations that you have seen or will see soon are in [Prop],\n   * so they cannot be used in if-then-else statements:\n   * - [a = b] (equality at an arbitrary type)\n   * - [a <= b] (a less than or equal to b for natural numbers)\n   * - [a < b] (a less than b for natural numbers)\n   * - [a >= b] (a greater than or equal to b for natural numbers)\n   * - [a > b] (a greater than b for natural numbers)\n   * - [a <> b] (inequality at an arbitrary type)\n   * - [a /\\ b] (propositional conjunction)\n   * - [~ a] (propositional negation)\n   *\n   * These operations are defined as functions, so you can evalute them:\n   * - [a ==n b] (decidable equality for natural numbers)\n   * - [a ==v b] (decidable equality for variables)\n   * - [And a b] (Boolean conjunction, defined above)\n   * - [Neg a] (Boolean negation, defined above)\n   *)\n  \n  (* In the second part of this assignment, we will work with a simple language\n   * of imperative arithmetic programs that sequentially apply operations\n   * to a natural-number-valued state.\n\n   * The [Prog] datatype defines abstract syntax trees for this language.\n   *)\n\n  Print Prog.\n\n  (* Define [run] such that [run p n] gives the final state\n   * that running the program [p] should result in, when the\n   * initial state is [n].\n   *)\n  Fixpoint run (p : Prog) (initState : nat) : nat.\n  Admitted.\n\n  Theorem run_Example1 : run Done 0 = 0.\n  Proof.\n  Admitted.\n\n  Theorem run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7.\n  Proof.\n  Admitted.\n\n  Theorem run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6.\n  Proof.\n  Admitted.\n\n  (* Define [numInstructions] to compute the number of instructions\n   * in a program, not counting [Done] as an instruction.\n   *)\n  Fixpoint numInstructions (p : Prog) : nat.\n  Admitted.\n\n  Theorem numInstructions_Example :\n    numInstructions (MulThen 5 (AddThen 2 Done)) = 2.\n  Proof.\n  Admitted.\n\n  (* Define [concatProg] such that [concatProg p1 p2] is the program\n   * that first runs [p1] and then runs [p2].\n   *)\n  Fixpoint concatProg (p1 p2 : Prog) : Prog.\n  Admitted.\n\n  Theorem concatProg_Example :\n       concatProg (AddThen 1 Done) (MulThen 2 Done)\n       = AddThen 1 (MulThen 2 Done).\n  Proof.\n  Admitted.\n\n  (* Prove that the number of instructions in the concatenation of\n   * two programs is the sum of the number of instructions in each\n   * program.\n   *)\n  Theorem concatProg_numInstructions\n    : forall (p1 p2 : Prog), numInstructions (concatProg p1 p2)\n                        = numInstructions p1 + numInstructions p2.\n  Proof.\n  Admitted.\n\n  (* Prove that running the concatenation of [p1] with [p2] is\n     equivalent to running [p1] and then running [p2] on the\n     result. *)\n  Theorem concatProg_run\n    : forall (p1 p2 : Prog) (initState : nat),\n      run (concatProg p1 p2) initState =\n      run p2 (run p1 initState).\n  Proof.\n  Admitted.\n\n  (* Read this definition and understand how division by zero is handled. *)\n  Fixpoint runPortable (p : Prog) (state : nat) : bool * nat :=\n    match p with\n    | Done => (true, state)\n    | AddThen n p => runPortable p (n+state)\n    | MulThen n p => runPortable p (n*state)\n    | DivThen n p =>\n        if n ==n 0 then (false, state) else\n        runPortable p (state/n)\n    | VidThen n p =>\n        if state ==n 0 then (false, 0) else\n        runPortable p (n/state)\n    | SetToThen n p =>\n        runPortable p n\n    end.\n  Arguments Nat.div : simpl never. (* you don't need to understand this line *)\n\n  (* Here are a few examples: *)\n\n  Definition goodProgram1 := AddThen 1 (VidThen 10 Done).\n  Example runPortable_good : forall n,\n    runPortable goodProgram1 n = (true, 10/(1+n)).\n  Proof. simplify. equality. Qed.\n\n  Definition badProgram1 := AddThen 0 (VidThen 10 Done).\n  Example runPortable_bad : let n := 0 in\n    runPortable badProgram1 n = (false, 0).\n  Proof. simplify. equality. Qed.\n\n  Definition badProgram2 := AddThen 1 (DivThen 0 Done).\n  Example runPortable_bad2 : forall n,\n    runPortable badProgram2 n = (false, 1+n).\n  Proof. simplify. equality. Qed.\n\n  (* Prove that running the concatenation [p] using [runPortable]\n     coincides with using [run], as long as [runPortable] returns\n     [true] to confirm that no divison by zero occurred. *)\n  Lemma runPortable_run : forall p s0 s1,\n    runPortable p s0 = (true, s1) -> run p s0 = s1.\n  Proof.\n  Admitted.\n\n  (* The final goal of this pset is to implement [validate : Prog -> bool]\n     such that if this function returns [true], the program would not trigger\n     division by zero regardless of what state it starts out in.  [validate] is\n     allowed to return [false] for some perfectly good programs that never cause\n     division by zero, but it must recognize as good the examples given below.  In\n     jargon, [validate] is required to be sound but not complete, but \"complete\n     enough\" for the use cases defined by the examples given here: *)\n\n  Definition goodProgram2 := AddThen 0 (MulThen 10 (AddThen 0 (DivThen 1 Done))).\n  Definition goodProgram3 := AddThen 1 (MulThen 10 (AddThen 0 (VidThen 1 Done))).\n  Definition goodProgram4 := Done.\n  Definition goodProgram5 := SetToThen 0 (DivThen 1 Done).\n  Definition goodProgram6 := SetToThen 1 (VidThen 1 Done).\n  Definition goodProgram7 := AddThen 1 (DivThen 1 (DivThen 1 (VidThen 1 Done))).\n\n  (* If you already see a way to build [validate] that meets the\n   * requirements above, _and have a plan for how to prove it correct_,\n   * feel free to just code away. Our solution uses one intermediate definition\n   * and one intermediate lemma in the soundness proof -- both of which are more\n   * sophisticated than the top-level versions given here. *)\n\n  (* If a clear plan hasn't emerged in 10 minutes (or if you get stuck later),\n   * take a look at the hints for this pset at the end of the signature file.\n   * It is not expected that this pset is doable for everyone without the hints,\n   * and some planning is required to complete the proof successfully.\n   * In particular, repeatedly trying out different combinations of tactics\n   * and ideas from hints until something sticks can go on for arbitrarily long\n   * with little insight and no success; just guessing a solution is unlikely.\n   * Thus, we encourage you to take your time to think, look at the hints when\n   * necessary, and only jump into coding when you have some idea why it should\n   * succeed. Some may call Coq a video game, but it is not a grinding contest. *)\n\n\n  Definition validate (p : Prog) : bool.\n  Admitted.\n\n  (* Start by making sure that your solution passes the following tests, and add\n   * at least one of your own tests: *)\n\n  Example validate1 : validate goodProgram1 = true. Admitted.\n  Example validate2 : validate goodProgram2 = true. Admitted.\n  Example validate3 : validate goodProgram3 = true. Admitted.\n  Example validate4 : validate goodProgram4 = true. Admitted.\n  Example validate5 : validate goodProgram5 = true. Admitted.\n  Example validate6 : validate goodProgram6 = true. Admitted.\n  Example validate7 : validate goodProgram7 = true. Admitted.\n  Example validateb1 : validate badProgram1 = false. Admitted.\n  Example validateb2 : validate badProgram2 = false. Admitted.\n\n  (* Then, add your own example of a bad program here, and check that `validate`\n   * returns `false` on it: *)\n\n  Definition badProgram3 : Prog. Admitted.\n  Example validateb3 : validate badProgram3 = false. Admitted.\n\n\n\n  (* Finally, before diving into the Coq proof, try to convince yourself that\n   * your code is correct by applying induction by hand.  Can you describe the\n   * high-level structure of the proof?  Which cases will you have to reason\n   * about?  What do the induction hypotheses look like?  Which key lemmas do\n   * you need?  Write a short (~10-20 lines) informal proof sketch before\n   * proceeding. *)\n\n  (** Proof sketch: **)\n  (* [[Fill in your proof sketch here.]] *)\n\n  (* Now you're ready to write the proof in Coq: *)\n\n  Lemma validate_sound : forall p, validate p = true ->\n    forall s, runPortable p s = (true, run p s).\n  Admitted.\n\n  (* Here is the complete list of commands used in one possible solution:\n    - Search, for example Search (_ + 0).\n    - induct, for example induct x\n    - simplify\n    - propositional\n    - equality\n    - linear_arithmetic\n    - cases, for example cases (X ==n Y)\n    - apply, for example apply H\n    - apply in, for example apply H1 in H2 or apply somelemma in H1\n    - apply with, for example apply H1 with (x:=2)\n    - apply in with, for example apply H1 with (x:=2) in H2\n    - rewrite, for example rewrite H\n    - rewrite in, for example rewrite H1 in H2 or rewrite somelemma in H1\n    - ;, for example simplify; propositional *)\nEnd Impl.\n\n(* The following line checks that your `Impl` module implements the right\n   signature.  Make sure that it works, or the auto-grader will break!\n   If there are mismatches, Coq will report them (`Signature components for\n   label \u2026 do not match`): *)\nModule ImplCorrect : Pset1Signature.S := Impl.\n", "meta": {"author": "mit-frap", "repo": "spring23", "sha": "10355d5a1cee8464cdd3722efa1fd58527c8a4d2", "save_path": "github-repos/coq/mit-frap-spring23", "path": "github-repos/coq/mit-frap-spring23/spring23-10355d5a1cee8464cdd3722efa1fd58527c8a4d2/pset01_ProgramAnalysis/Pset1Implementation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.806172696622728}}
{"text": "Require Export Induction.\nModule Natlist.\n\n  Inductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\n  Check (pair 3 5).\n\n  Definition fst (p : natprod) : nat :=\n    match p with\n    | pair x _ => x\n    end.\n\n  Definition snd (p : natprod) : nat :=\n    match p with\n    | pair _ y => y\n    end.\n\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Compute (fst (3,5)).\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    refine (fun n m => eq_refl).\n  Qed.\n\n  Theorem surjective_pairing : forall (p : natprod),\n      p = (fst p, snd p).\n  Proof.\n    refine (fun p => match p with\n                  | (x, y) => eq_refl\n                  end).\n  Qed.\n\n  Theorem snd_fst_is_swap : forall (p : natprod),\n      (snd p, fst p) = swap_pair p.\n  Proof.\n    refine (fun p => match p with\n                  | (x, y) => eq_refl\n                  end).\n  Qed.\n\n  Theorem fst_swap_is_snd : forall (p : natprod),\n      fst (swap_pair p) = snd p.\n  Proof.\n    refine (fun p => match p with\n                  | (x, y) => eq_refl\n                  end).\n  Qed.\n\n  Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n  Definition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n  Notation \"x :: l\" := (cons x l)\n                         (at level 60, right associativity).\n\n  Notation \"[ ]\" := nil.\n  Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n  Definition mylist1 := 1 :: (2 :: (3 :: nil)).\n  Definition mylist2 := 1 :: 2 :: 3 :: nil.\n  Definition mylist3 := [1;2;3].\n\n  Notation \"x + y\" := (plus x y)\n                        (at level 50, left associativity).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n    | O => []\n    | S count' => n :: repeat n count'\n    end.\n\n\n  Fixpoint length (l : natlist) : nat :=\n    match l with\n    | [] => O\n    | _ :: tl => S (length tl)\n    end.\n\n  Fixpoint app (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | [] => l2\n    | h :: tl => h :: app tl l2\n    end.\n\n  Notation \"x ++ y\" := (app x y)\n                         (right associativity, at level 60).\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    | [] => default\n    | h :: _ => h\n    end.\n\n  Definition tl (l : natlist) : natlist :=\n    match l with\n    | [] => []\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_tl: tl [1;2;3] = [2;3].\n  Proof. reflexivity. Qed.\n\n\n  Fixpoint nonzeros (l : natlist) : natlist :=\n    match l with\n    | [] => []\n    | h :: t => if beq_nat h 0 then nonzeros t else h :: nonzeros t\n    end.\n\n  Example test_nonzeros:\n    nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  Proof.\n    exact eq_refl.\n  Qed.\n\n  Fixpoint oddmembers (l : natlist) : natlist :=\n    match l with\n    | [] => []\n    | h :: t => if evenb h then oddmembers t else h :: oddmembers t\n    end.\n\n  Example test_oddmembers:\n    oddmembers [0;1;0;2;3;0;0] = [1;3].\n  Proof. \n    exact eq_refl.\n  Qed.\n\n  Definition countoddmembers (l : natlist) : nat :=\n    length (oddmembers l). \n\n  Example test_countoddmembers1:\n    countoddmembers [1;0;3;1;4;5] = 4.\n  exact eq_refl.\n  Qed.\n\n  Example test_countoddmembers2:\n    countoddmembers [0;2;4] = 0.\n  exact eq_refl.\n  Qed.\n\n  Example test_countoddmembers3:\n    countoddmembers nil = 0.\n  exact eq_refl.\n  Qed.\n\n  Fixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | [] => l2\n    | h1 :: t1 => match l2 with\n               | [] => h1 :: t1\n               | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n                 end\n    end.\n\n  Example test_alternate1:\n    alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  exact eq_refl. Qed.\n\n  Example test_alternate2:\n    alternate [1] [4;5;6] = [1;4;5;6].\n  cbn. exact eq_refl. Qed.\n\n  Example test_alternate3:\n    alternate [1;2;3] [4] = [1;4;2;3].\n  exact eq_refl. Qed.\n\n  Example test_alternate4:\n    alternate [] [20;30] = [20;30].\n  exact eq_refl. Qed.\n\n  Definition bag := natlist.\n\n  Fixpoint count (v : nat) (s : bag) : nat :=\n    match s with\n    | [] => 0\n    | h :: t => if beq_nat v h then S (count v t) else count v t\n    end.\n\n  Example test_count1: count 1 [1;2;3;1;4;1] = 3.\n  cbn. exact eq_refl.  Qed.\n  \n  Example test_count2: count 6 [1;2;3;1;4;1] = 0.\n  exact eq_refl. Qed.\n\n  Definition sum := app.\n\n  Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n  exact eq_refl. 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  exact eq_refl. Qed.\n\n  Example test_add2: count 5 (add 1 [1;4;1]) = 0.\n  exact eq_refl. Qed. \n\n  Definition member (v:nat) (s:bag) : bool :=\n    negb (beq_nat (count v s) 0).\n\n  Example test_member1: member 1 [1;4;1] = true.\n  exact eq_refl. Qed.\n\n  Example test_member2: member 2 [1;4;1] = false.\n  exact eq_refl. Qed.\n\n  Fixpoint remove_one (v : nat) (s : bag) : bag :=\n    match s with\n    | [] => []\n    | h :: t => if beq_nat h v then t else h :: remove_one v t\n    end.\n\n  Example test_remove_one1:\n    count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  exact eq_refl. Qed. \n\n  Example test_remove_one2:\n    count 5 (remove_one 5 [2;1;4;1]) = 0.\n  exact eq_refl. Qed.\n  \n  Example test_remove_one3:\n    count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  exact eq_refl. Qed.\n\n  Example test_remove_one4:\n    count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  exact eq_refl. Qed.\n\n  Fixpoint remove_all (v : nat) (s : bag) : bag :=\n    match s with\n    | [] => []\n    | h :: t => if beq_nat v h then remove_all v t else h :: remove_all v t\n    end.\n\n  Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n  exact eq_refl. Qed.\n  \n  Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n  exact eq_refl. Qed.\n  \n  Example test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n  exact eq_refl. Qed.\n  \n  Example test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n  exact eq_refl. Qed.\n\n  Fixpoint subset (s1 : bag) (s2 : bag) : bool :=\n    match s1 with\n    | [] => true\n    | h :: t => if member h s2 then subset t (remove_one h s2) else false\n    end.\n  \n    \n\n  Example test_subset1: subset [1;2] [2;1;4;1] = true.\n  exact eq_refl. Qed.\n\n  Example test_subset2: subset [1;2;2] [2;1;4;1] = false.\n  exact eq_refl. Qed.\n\n  Theorem nil_app : forall l:natlist,\n      [] ++ l = l.\n    refine (fun l => eq_refl).\n  Qed.\n\n  Theorem tl_length_pred : forall l : natlist,\n      pred (length l) = length (tl l).\n  Proof.\n    refine (fun l => match l with\n                  | [] => eq_refl\n                  | h :: t => eq_refl\n                  end).\n  Qed.\n\n  Theorem app_assoc : forall l1 l2 l3 : natlist,\n      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    refine (fix Fn l1 :=\n              match l1 as l1' return (forall l2 l3,  (l1' ++ l2) ++ l3 = l1' ++ l2 ++ l3) with\n              | [] => fun l2 l3 => eq_refl\n              | h :: t => _ (* some more lemma *)\n              end).\n    cbn; intros l2 l3; f_equal; apply Fn.\n  Qed.\n\n  Fixpoint rev (l:natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => rev t ++ [h]\n    end.\n\n  Example test_rev1: rev [1;2;3] = [3;2;1].\n  Proof. reflexivity. Qed.\n  Example test_rev2: rev nil = nil.\n  Proof. reflexivity. Qed.\n\n  Theorem app_length : forall l1 l2 : natlist,\n      length (l1 ++ l2) = length l1 + length l2.\n  Proof.\n    refine (fix Fn l1 :=\n              match l1 as l1' return\n                    l1 = l1' ->  forall l2, length (l1' ++ l2) = length l1' + length l2 with\n              | [] => fun H l2 => eq_refl\n              | h :: t => fun H l2 => _\n              end eq_refl).\n    cbn; f_equal; apply Fn.\n  Qed.\n   \n  Theorem rev_length : forall l : natlist,\n      length (rev l) = length l.\n  Proof.\n    refine (fix Fn l :=\n              match l as l' return l = l' ->  length (rev l') = length l' with\n              | [] => fun H => eq_refl\n              | h :: t => _\n              end eq_refl).\n    cbn; intro H. (* Now we need a way to discharge \n                     length (rev t ++ [h]) = S (length t) => S (length (rev t)) = S (length t) *)\n    rewrite app_length, plus_comm; cbn; f_equal; apply Fn.\n  Qed.\n\n  Inductive subsetrel : natlist -> natlist -> Type :=\n  | emptylist l : subsetrel [] l\n  | firstcons x l1 l2 : subsetrel l1 l2 -> subsetrel (x :: l1) (x :: l2)\n  | secondcons x l1 l2 : subsetrel l1 l2 -> subsetrel l1 (x :: l2)\n  | thirdcons x y l : subsetrel (x :: y :: l) (y :: x :: l).\n\n  Example subset_rel1 : forall l, subsetrel [] l.\n  refine (fun l => match l with\n                | [] => emptylist []\n                | h :: t => emptylist (h :: t)\n                end).\n  Qed.\n\n  Theorem subset_connect : forall l1 l2, subset l1 l2 = true -> subsetrel l1 l2.\n  Proof.\n    induction l1.\n    + cbn; intros l2 H.\n      apply emptylist.\n    + cbn; intros l2 H.\n      remember (member n l2) as Hm.\n      destruct Hm as [H1 | H1].\n      (* At this point  true = member n l2 asserts that In n l2 -> l2 = l3 ++ [n] ++ l4\n         But my subset relation is not good enough to capture it :( *)\n  Admitted.\n\n\n  Theorem app_nil_r : forall l : natlist,\n      l ++ [] = l.\n  Proof.\n    refine (fix Fn l :=\n              match l with\n              | [] => eq_refl\n              | h :: t => _\n              end).\n    cbn. rewrite Fn. exact eq_refl.  Show Proof.\n  Qed.\n\n  Theorem rev_app_distr: forall l1 l2 : natlist,\n      rev (l1 ++ l2) = rev l2 ++ rev l1.\n  Proof.\n    refine (fix Fn l1 :=\n              match l1 as l1' return l1 = l1' -> forall l2, rev (l1' ++ l2) = rev l2 ++ rev l1' with\n              | [] => fun H l2 => _\n              | h :: t => fun H l2 => _\n              end eq_refl).\n    cbn. rewrite app_nil_r. exact eq_refl.\n    cbn. rewrite Fn, app_assoc. exact eq_refl. \n  Qed.\n\n  Theorem rev_involutive : forall l : natlist,\n      rev (rev l) = l.\n  Proof.\n    refine (fix Fn l :=\n              match l with\n              | [] => eq_refl\n              | h :: t => _\n              end).\n    cbn. rewrite rev_app_distr; cbn; f_equal; rewrite Fn; exact eq_refl.\n  Qed.\n\n  Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n      l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros l1 l2 l3 l4.\n    repeat rewrite app_assoc; exact eq_refl.\n  Qed.\n\n  Lemma nonzeros_app : forall l1 l2 : natlist,\n      nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n  Proof.\n    refine (fix Fn l1 :=\n              match l1 with\n              | [] => _\n              | h :: t => _\n              end).\n    + cbn; intro l2; exact eq_refl.\n    + cbn; intro l2. destruct (beq_nat h 0); try auto.\n      cbn; f_equal. rewrite Fn. auto.\n  Qed.\n\n  Fixpoint beq_natlist (l1 l2 : natlist) : bool :=\n    match l1, l2 with\n    | [], [] => true\n    | [], _ => false\n    | _, [] => false\n    | h1 :: t1, h2 :: t2 => if beq_nat h1 h2 then beq_natlist t1 t2 else false\n    end.\n\n  Example test_beq_natlist1 :\n    (beq_natlist nil nil = true).\n  cbn. auto. Qed.\n\n\n  Example test_beq_natlist2 :\n    beq_natlist [1;2;3] [1;2;3] = true.\n  auto. Qed.\n\n  Example test_beq_natlist3 :\n    beq_natlist [1;2;3] [1;2;4] = false.\n  auto. Qed.\n\n  Theorem beq_natlist_refl : forall l:natlist,\n      true = beq_natlist l l.\n  Proof.\n    refine (fix Fn l :=\n              match l with\n              | [] => eq_refl\n              | h :: t => _\n              end).\n    cbn. remember (beq_nat h h) as Hb. destruct Hb as [Hb | Hb].\n    apply Fn. assert (beq_nat h h = true). induction h.  inversion HeqHb.\n    cbn in *. auto. rewrite <- HeqHb in H. inversion H.\n  Qed.\n\n  Theorem count_member_nonzero : forall (s : bag),\n      leb 1 (count 1 (1 :: s)) = true.\n  Proof.\n    cbn. refine (fun H => eq_refl).\n  Qed.\n\n  Theorem ble_n_Sn : forall n,\n      leb n (S n) = true.\n  Proof.\n    refine (fix Fn n :=\n              match n with\n              | O => eq_refl\n              | S n' => _\n              end).\n    cbn. apply Fn.\n  Qed.\n\n  Theorem remove_does_not_increase_count: forall (s : bag),\n      leb (count 0 (remove_one 0 s)) (count 0 s) = true.\n  Proof.\n    refine (fix Fn s :=\n              match s with\n              | [] =>  eq_refl\n              | h :: t => _\n              end).\n    cbn. destruct h; cbn. rewrite ble_n_Sn; auto.\n    apply Fn.\n  Qed.\n\n  Theorem rev_injective :\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2. \n  Proof.\n    intros l1 l2 H.\n    rewrite <- rev_involutive.\n    rewrite <- H. rewrite rev_involutive.\n    auto.\n  Qed.\n\n  Fixpoint nth_bad (l:natlist) (n:nat) : nat :=\n    match l with\n    | nil => 42 (* arbitrary! *)\n    | a :: l' => match beq_nat n O with\n                | true => a\n                | false => nth_bad l' (pred n)\n                end\n    end.\n\n  Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n\n  Fixpoint nth_error (l:natlist) (n:nat) : natoption :=\n    match l with\n    | nil => None\n    | a :: l' => match beq_nat n O with\n                | true => Some a\n                | false => nth_error l' (pred n)\n                end\n    end.\n\n  Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\n  auto. Qed.\n  \n  Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\n  auto. Qed.\n  \n  Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.\n  auto. Qed.\n\n  Fixpoint 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\n  Definition hd_error (l : natlist) : natoption :=\n    match l with\n    | [] => None\n    | h :: t => Some h\n    end.\n    \n \n  Example test_hd_error1 : hd_error [] = None.\n  auto. Qed.\n  \n  Example test_hd_error2 : hd_error [1] = Some 1.\n  auto. Qed.\n  \n  Example test_hd_error3 : hd_error [5;6] = Some 5.\n  auto. Qed.\n\n\n  Theorem option_elim_hd : forall (l:natlist) (default:nat),\n      hd default l = option_elim default (hd_error l).\n  Proof.\n    refine (fix Fn l :=\n              match l with\n              | [] => _\n              | h :: t => _\n              end).\n    + cbn; intro default; try auto.\n    + cbn; intro default; try auto.\n  Qed.\n\nEnd Natlist.\n\nInductive id : Type :=\n| Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) : bool :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intro x. destruct x; cbn.\n  induction n; try auto.\nQed.\n\nModule PartialMap.\n  Export Natlist.\n\n  Inductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n  Definition update (d : partial_map) (x : id) (value : nat) : partial_map :=\n    record x value d.\n\n  Fixpoint find (x : id) (d : partial_map) : natoption :=\n    match d with\n    | empty => None\n    | record x1 n1 d1 => if beq_id x x1 then Some n1 else find x d1\n    end.\n\n  Theorem update_eq :\n    forall (d : partial_map) (x : id) (v: nat),\n      find x (update d x v) = Some v.\n  Proof.\n    unfold update; cbn. intros d x v. rewrite <- beq_id_refl.\n    auto.\n  Qed.\n\n  Theorem update_neq :\n    forall (d : partial_map) (x y : id) (o: nat),\n      beq_id x y = false ->  find x (update d y o) = find x d.\n  Proof.\n    cbn. intros d x y o H. rewrite H. auto.\n  Qed.\n\nEnd PartialMap.\n\n", "meta": {"author": "mukeshtiwari", "repo": "Coq-reading-group", "sha": "3801ef7e534bb00590a062e905a330c7727b4bdd", "save_path": "github-repos/coq/mukeshtiwari-Coq-reading-group", "path": "github-repos/coq/mukeshtiwari-Coq-reading-group/Coq-reading-group-3801ef7e534bb00590a062e905a330c7727b4bdd/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8061299675131496}}
{"text": "Inductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\nDefinition next_weekday (d: day): day := \n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nEval simpl in (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n (next_weekday (next_weekday saturday)) = tuesday.\n\nsimpl. reflexivity. Qed.\n(* \"The assertion we've just made can be proved by observing that both sides\nof the equality evaluate to the same thing, after some simplification.\"*)\n\nExtraction Language Haskell.\nExtraction \"day.hs\" day next_weekday.\n\nInductive bool: Type :=\n  | false: bool\n  | true: bool.\n\nDefinition not (a: bool): bool :=\n  match a with\n  | true => false\n  | false => true\n  end.\n\nDefinition and (a b: bool): bool := \n  match a with\n  | false => false\n  | true => b\n  end.\n\nExample test_and: (and true true) = true.\nProof. simpl. reflexivity. Qed.\n\nInfix \"&&\" := and.\n\nEval simpl in (true && true).\n\nDefinition or (a: bool) (b: bool): bool := \n  match a with\n  | false => b\n  | true => true\n  end.\n\nInfix \"||\" := or.\n\nDefinition nandb (b1:bool) (b2:bool) : bool := not (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\nCompute (false || (not (true && (not false)))).\nCheck and.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  b1 && b2 && b3. (* and (and b1 b2) b3 *)\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\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\nDefinition succ (n : nat) : nat :=\n  match n with\n    | O => S O\n    | n' => S n'\n  end.\n\nCompute (succ (S O)).\n\nExtraction Language Haskell.\nExtraction \"nat.hs\" nat pred.\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 5).\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 := not (evenb n).\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. reflexivity. Qed.\n\nModule Playground2.\n\nFixpoint plus (n m: nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint minus (n m: nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\n\nExample test_plus: plus 5 5 = 10.\nProof. simpl. reflexivity. Qed.\n\nCompute (plus 5 5).\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => S O\n    | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\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.\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n           | O => true\n           | S m' => false\n           end\n  | S n' => match m with\n           | O => false\n           | S m' => beq_nat n' m'\n           end\n  end.\n\nFixpoint beq_nat2 (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | S n', S m' => beq_nat n' m'\n  | _, _ => false\n  end.\n\nExample test_beq_nat: (beq_nat 5 5) = (beq_nat2 5 5).\nProof. simpl. reflexivity. Qed.\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(* less than for natural numbers *)\nDefinition blt_nat (n m : nat) : bool := \n  leb n m && not (beq_nat n m)\n.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Proof by Simplification *)\n(* (Until now) The proofs of these claims were always the same: use simpl\n to simplify both sides of the equation, then use reflexivity to check that\n both sides contain identical values.*)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_0_l : forall n: nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\n(* Example and Theorem (and a few others, including Lemma, Fact, and Remark) \n   mean exactly the same thing to Coq*)\n\n(* Theorem plus_n_O : forall n, n = n + 0.\nProof.\n  intros n. simpl. *)\n\nTheorem plus_id_example : forall n m: nat, n = m -> n+n = m+m .\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros H.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite -> H. \n  reflexivity. Qed.\n\n(* The first line of the proof moves the universally quantified variables\n   n and m into the context.\n   The second moves the 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) by\n   replacing the left side of the equality hypothesis H with the right side. *)\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\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity. Qed.\n\n(* Proof by case analysis *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [| n']. (* intro pattern *)\n  - reflexivity.\n  - reflexivity.\n  Qed.\n  \n", "meta": {"author": "adolfosilva", "repo": "coq-exercises", "sha": "85ae5a19b2504530d4c3e10c98c450464595aa62", "save_path": "github-repos/coq/adolfosilva-coq-exercises", "path": "github-repos/coq/adolfosilva-coq-exercises/coq-exercises-85ae5a19b2504530d4c3e10c98c450464595aa62/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8061299655061417}}
{"text": "Require Import Arith.\n\nDefinition zero_one_dec : forall n:nat, n<=1 -> {n=0}+{n=1}.\n simple destruct n.\n left; auto.\n simple destruct n0.\n right; auto.\n intros  n1 H1; absurd (S (S n1) <= 1); auto with arith.\nDefined.\n\nDefinition div2_mod2 : \n  forall n:nat, {q:nat & {r:nat | n = 2*q + r /\\ r <= 1}}.\n induction n.\n exists 0; exists 0; simpl; auto with arith.\n case IHn; intros q' Hq'; case Hq'; intros r' [H1 H2]; simpl.\n case (zero_one_dec  r' H2); intro H3.\n Require Import Omega.\n exists q'; exists 1; omega. \n exists (S q'); exists 0; omega.\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/progav/SRC/div2_mod2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.8059448004537069}}
{"text": "\n\nInductive day: Type :=\n   | monday:day\n   | tuesday: day\n   | wednesday: day\n   | Thursday : day\n   | friday:day\n   | saturday:day\n   | sunday: day.\n\n\nDefinition next_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\n    end.\n\nCompute (next_day friday).\n\nExample example: next_day monday = tuesday.\nProof. simpl. reflexivity. Qed.\n\nInductive bool: Type :=\n   | true : bool\n   | false : bool.\n\n(* Exercise: 1 star (nandb) *)\n\n\nDefinition negb(b:bool):bool :=\n      match b with\n        | true => false\n        | false => true\n        end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n    match b1 with\n     | false => true\n     | true => negb b2\n     end.\n \nCompute (nandb true true).\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\n\n(* Exercise: 1 star (andb3) *)\n\nDefinition andb (b1:bool) (b2:bool):bool :=\n     match b1 with\n       | true  => b2\n       | false => false\n       \n       end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true  => true\n  | false => b2\n  end.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool:=\n     match b1 with\n       | false => false\n       | true => (andb b2 b3)\n       end.\n \n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n')=> evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).  \n\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 andb3.\n\n\nModule NatPlayground.\n\nInductive nat: Type :=\n   | O : nat\n   | S : nat -> nat.\nEnd NatPlayground.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\nCheck (S(S(O))).\n\nFixpoint plus (n m:nat):nat:=\n   match n with\n    | O => m \n    | S n' => S(plus n' m)\n   end.\n\n\nCompute (plus 5 4).\n\n(* Exercise: 1 star (factorial)*)\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\nFixpoint factorial (n:nat):nat :=\n   match n with\n     | O => S(O)\n     | S n' => mult (S n') (factorial n')\n   end.\n\nCompute (factorial (S(S(S(S(O)))))).\n     \n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\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\n\n\nFixpoint leq1 (n m :nat): bool :=\n      match n with\n        | O => true\n        | S n'=> match m with\n                   | O => false\n                   | S m' => leq1 n' m'\n                 end\n     end.\n\nCompute (leq1 (S(S(S(S(O))))) (S(S(S(S(O)))))).\n\n(* Exercise: 1 star (blt nat)) *)\n\n\nDefinition blt_nat (n m : nat) : bool :=\n     andb (leq1 n m) (negb (beq_nat n m)).\n                  \n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4 ) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n\nTheorem plus_0_n: forall n :nat, 0 + n = n.\nProof. \n  intros n.\n  simpl.\n  reflexivity.\n  Qed.\n     \n\nTheorem plus_id: forall m n:nat,\n n=m ->\n n+n = m+m.\nProof.\n intros n m. \n intros H.\n rewrite -> H. \n reflexivity.\n Qed.\n\n(*Exercise: 1 star (plus id exercise) *)\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 G.\n  rewrite -> H.\n  rewrite -> G.\n  reflexivity.\n  Qed.\n\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\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. Qed.\n\n(* exercise: 2 stars (mult S 1) *)\n\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n   intros  n m .\n   intros H. \n   rewrite -> H.\n   reflexivity. Qed.\n\n\n\n(*Exercise: 1 star (zero_nbeq_plus_1)*)\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n. destruct n as [|n'].\n     reflexivity.\n     reflexivity. Qed.\n\n(* \nExercise: 2 stars (andb_eq_orb)*)\n\n\n\nTheorem andb_eq_orb : forall (b c : bool),\n  (andb b c = orb b c) ->  b = c.\nProof.\n  intros b c. destruct b.\n   simpl. \n   intros H.\n   rewrite -> H.\n   reflexivity.\n   simpl.\n   intros G.\n   rewrite -> G. reflexivity. Qed.\n\n\n   \n   \n\n\n(* Exercise: 2 stars (andb_true_elim2) *)\n\nTheorem andb_true_elim2 : forall b c :bool,\n  andb b c = true -> \n  c = true.\nProof. intros b c . destruct b. simpl.\n       intros H.\n       rewrite -> H.\n       reflexivity.   \n       simpl.\n       intros G.\n       rewrite <- G.\n       destruct c.\n       rewrite -> G.\n       reflexivity.\n       reflexivity. Qed.\n        (* a little bit long, but that's my best solution for now *)\n\n\nTheorem andb3_exchange :\n  forall b c d, andb (andb b c) d = andb (andb b d) c.\nProof.\n  intros b c d. destruct b.\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n  - destruct c.\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\n    { destruct d.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\n\n\n(* Exercise: 2 starsM (boolean_functions)*)\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x : bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n   intros f H b. rewrite -> H. rewrite -> H. reflexivity. Qed.\n\n\n   \n\n\n\n", "meta": {"author": "Tsatia", "repo": "Coq_Basics", "sha": "e787476f8e0cef8576f8efd3546ceb01f908fb62", "save_path": "github-repos/coq/Tsatia-Coq_Basics", "path": "github-repos/coq/Tsatia-Coq_Basics/Coq_Basics-e787476f8e0cef8576f8efd3546ceb01f908fb62/src/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.8059237946924699}}
{"text": "(* From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat. *)\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\n\nModule Playground1.\nTheorem modus_ponens : forall (P Q : Prop),\n  (P -> Q) -> P -> Q.\nProof.\n  move=> P Q PiQ P_holds.\n  (* apply PiQ. clear PiQ. *)\n  apply: PiQ.\n  exact: P_holds.\nQed.\n\n(* Since we know that [P -> Q], proving that [P] holds would also\n   prove that [Q] holds. Therefore, we use [apply] to transform our goal. *)\n\nTheorem modus_ponens_imp : forall (P Q : Prop),\n  (P -> Q) -> P -> Q.\nProof.\n  move=> P Q PiQ P_holds.\n  (* apply PiQ. clear PiQ. *)\n  move: PiQ.\n  apply.\n  exact: P_holds.\nQed.\n\n(* Alternatively, we notice that [P] holds in our context, and\n   because we know that [P -> Q], we can [apply] that implication to\n   our hypothesis that [P] holds to transform it. *)\n\nTheorem modus_ponens' : forall (P Q : Prop),\n  (P -> Q) -> P -> Q.\nProof.\n  move=> P Q PiQ P_holds.\n  apply PiQ in P_holds.\n  (* clear PiQ. *)\n  exact: P_holds.\nQed.\n\n(* Note that this replaces our previous hypothesis (and now its\n   name is no longer very applicable)! To prevent this, we can give\n   our new hypothesis its own name using the [apply..in..as..] syntax. *)\n\nTheorem modus_ponens'' : forall (P Q : Prop),\n  (P -> Q) -> P -> Q.\nProof.\n  move=> P Q PiQ P_holds.\n  apply PiQ in P_holds as Q_holds. (* give a new name to our hypothesis *)\n  (* clear PiQ P_holds. *)\n  exact Q_holds.\nQed.\n\nSection LongSmth.\nVariables A B C D E F G : Prop.\nLemma long_smth' :\n  (A -> B -> C -> D) -> (A -> B -> C) -> (A -> B) -> A -> D.\nProof.\n  move=> H1 H2 H3 H4.\n  move: H2.\n  (* \u0417\u0434\u0435\u0441\u044c C (\u0437\u0430\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u0438\u043c\u043f\u043b\u0438\u043a\u0430\u0446\u0438\u0438) \u0441\u043e\u043f\u043e\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0441 D (\u0445\u0432\u043e\u0441\u0442 \u0446\u0435\u043b\u0438).\n     \u0410 \u043e\u043d\u0438 \u043d\u0435 \u043e\u0434\u0438\u043d\u0430\u043a\u043e\u0432\u044b, \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c \u043e\u0448\u0438\u0431\u043a\u0443. *)\n  Undo 1.\n  move: H1. apply. exact H4.\n  move: H3. apply. exact H4.\n  move: H2. apply. exact H4.\n  move: H3. apply. exact H4.\n  Undo 12.\n  exact: (H1 H4 (H3 H4) (H2 H4 (H3 H4))).\nQed.\nEnd LongSmth.\n\nEnd Playground1.\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/playgrounds/playground1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.8058422926156549}}
{"text": "(******************************************************************************)\n(* A formalization of Folia                                                   *)\n(*   Folia is a problem in a competitive programming contest, NOMURA          *)\n(* programming contest 2020. The problem is described as follows [1]:         *)\n(*                                                                            *)\n(* ``` (the beginning of a quote)                                             *)\n(* Given is an integer sequence of length N + 1: A[0], A[1], A[2], ..., A[N]. *)\n(* Is there a binary tree of depth N such that, for each d = 0, 1, ..., N,    *)\n(* there are exactly A[d] leaves at depth d? If such a tree exists, print the *)\n(* maximum possible number of vertices in such a tree; otherwise, print \u22121.   *)\n(* ``` (the end)                                                              *)\n(*                                                                            *)\n(*   This file extends the problem in the following way:                      *)\n(* - Besides the maximum possible number, compute the minimum possible number *)\n(* - Replace \"a binary tree\" in the above statement with a set of n binary    *)\n(*   trees (a forest); the generalization naturally arises in ensuring the    *)\n(*   correctness of a solution for the original version. Suppose that you     *)\n(*   prove its correctness by structural induction on the sequence [A[0], ... *)\n(*   A[N]]. In this case, the induction hypothesis gives information on all   *)\n(*   nodes in a tree except the root, in other words, the second layer (depth *)\n(*   2) and the lower layers. Since removing the root from a tree may create  *)\n(*   some trees but not a single tree, it is necessary to extend the problem  *)\n(*   to forests.                                                              *)\n(* Then this file verifies the extended version as follows:                   *)\n(* 1. Define functions computing a bound (lb, ub) (a pair of a lower bound    *)\n(*    and an upper bound) of the size of forests satisfying the condition on  *)\n(*    leaves. These functions ignore the condition on the size of forests.    *)\n(* 2. Prove that there exists a forest of size n with the desired property if *)\n(*    and only if lb <= n <= ub, which shows that (lb, ub) is a tight bound.  *)\n(* 3. Define functions computing a bound (lb', ub') of the total numbers of   *)\n(*    nodes in forests consisting n trees and satisfying the condition on     *)\n(*    leaves.                                                                 *)\n(* 4. Prove that there exists a forest that has n trees and m nodes in total  *)\n(*    if and only if lb <= n <= ub and lb' <= m <= ub', which shows that      *)\n(*    (lb', ub') is a tight bound.                                            *)\n(* 5. Define functions that are equivalent to the ones described in (1) but   *)\n(*    are efficiently computed.                                               *)\n(*                                                                            *)\n(*   As a result, we can solve the problem in the following way:              *)\n(* 1. Calculate lb and ub                                                     *)\n(* 2. Check if lb <= n <= ub. If so, go to (3); otherwise print -1            *)\n(* 3. Calculate lb' and ub' and print them                                    *)\n(*                                                                            *)\n(* References:                                                                *)\n(* [1] https://atcoder.jp/contests/nomura2020/tasks/nomura2020_c              *)\n(*                                                                            *)\n(* Binary trees and their forests                                             *)\n(*             bintree := a binary tree                                       *)\n(*              forest := a sequence of trees                                 *)\n(*        count_node t := the number of nodes on a tree t                     *)\n(* count_node_forest f := the number of nodes on a forest f                   *)\n(*          subtrees t := trees just below the root of a tree t               *)\n(*         subforest f := subtrees of trees in a forest f                     *)\n(*                                                                            *)\n(* Specifications of leaves:                                                  *)\n(*             leave_spec := a sequence specifying the number of leaves at    *)\n(*                           each level in a forest                           *)\n(* satisfy_leave_spec f s := check whether a forest f satisfies a spec s      *)\n(*                           (for a tree t, use satisfy_leave_spec [:: t] s)  *)\n(*                                                                            *)\n(* Forest lifts:                                                              *)\n(*    simple_lift f : adds one node on to the top of each tree in a forest f  *)\n(* pairing_lift p f : divides trees in a forest f into p pairs and other      *)\n(*                    individuals, and adds one node on to the top of each    *)\n(*                    group                                                   *)\n(*                                                                            *)\n(* Bounds:                                                                    *)\n(*     lower_bound_bottomup s, : a tight bound of the size of forests that    *)\n(*     upper_bound_bottomup s    satisfy a spec s; see in_bottomup_boundP     *)\n(* lower_bounds_backforth s n, : tight bounds of the number of nodes at all   *)\n(* upper_bounds_backforth s n    levels of forests consisting n trees and     *)\n(*                               satisfying a spec s                          *)\n(*      lower_bound_total s n, : a tight bound of the total numbers of nodes  *)\n(*      upper_bound_total s n    in forests consisting n trees and satisfying *)\n(*                               a spec s; see in_total_boundP                *)\n(*                                                                            *)\n(* Efficiently computed bounds:                                               *)\n(*    lower_bounds_topdown s n, : bounds of the number of nodes at all levels *)\n(*    upper_bounds_topdown s n    of forests consisting n trees and           *)\n(*                                satisfying a spec s; they may not be tight  *)\n(* lower_bounds_backforth' s n, : the same as lower/upper_bound_backforth     *)\n(* upper_bounds_backforth' s n                                                *)\n(*      lower_bound_total' s n, : the same as lower/upper_bound_total; the    *)\n(*      upper_bound_total' s n    time complexity is \u0398(|s|) (|s| is the size  *)\n(*                                of s)                                       *)\n(******************************************************************************)\n\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFrom Coq Require Import Lia.\nFrom mathcomp.zify Require Import zify.\n\nSection SsrnatExt.\nLemma leq_div2 n : n./2 <= n.\nProof. by rewrite -divn2 leq_div. Qed.\n\nLemma leq_uphalf n : uphalf n <= n.\nProof.\n  (* TODO: Use leqRHS instead of [in X in _ <= X] in the later versions of MathComp 1.15.0 *)\n  rewrite [in X in _ <= X](divn_eq n 2) addnC uphalf_half -modn2 -divn2.\n  by apply: leq_add => //; apply: leq_pmulr.\nQed.\n\n(* Note: homo_maxl can be generalized as follows: if a <= b and c <= d, then  *)\n(* maxn a c <= maxn b d                                                       *)\nLemma homo_maxl n :\n  {homo maxn n : m l / m <= l}.\nProof.\n  move=> m l leq_ml.\n  by rewrite geq_max leq_maxl leq_max leq_ml orbT.\nQed.\n\nLemma homo_minl n :\n  {homo minn n : m l / m <= l}.\nProof.\n  move=> m l leq_ml.\n  by rewrite leq_min geq_minl geq_min leq_ml orbT.\nQed.\nEnd SsrnatExt.\n\nSection SeqExt.\nLemma flatten_nseq_nil (T : Type) (n : nat) :\n  @flatten T (nseq n [::]) = [::].\nProof. by elim: n. Qed.\n\nSection Map.\n  Variable A B C : Type.\n\n  (* Note: [map2] is defined by fix, instead of Fixpoint, to exclude [f] from the recursive definition *)\n  Definition map2 (f : A -> B -> C) :=\n    fix map2 (s1 : seq A) (s2 : seq B) :=\n      match s1, s2 with\n        x :: s1', y :: s2' => f x y :: map2 s1' s2'\n      | _, _ => [::]\n      end.\nEnd Map.\n\nSection Scan.\nVariable T S : Type.\nVariable f : T -> S -> S.\nVariable y0 : S.\n\n(* Note: scanr_aux corresponds to scanr in Haskell, although the former       *)\n(* definition is rather complicated than the latter one. In Coq, partial      *)\n(* functions are rejected so it is required to guarantee that scanr_aux does  *)\n(* not return the empty sequence.                                             *)\nFixpoint scanr_aux (s : seq T) : {r : seq S | size r > 0} :=\n  match s with\n    [::] => exist _ [:: y0] erefl\n  | x :: s' =>\n      match scanr_aux s' with\n        exist r Hr =>\n          (match r return size r > 0 -> {r : seq S | size r > 0} with\n             [::] => fun cont => match notF cont with end\n           | y :: _ => fun Hr => exist _ (f x y :: r) erefl\n           end) Hr\n      end\n  end.\n\nLemma scanr_auxE (x : T) (s' : seq T) :\n  scanr_aux (x :: s') =\n    match scanr_aux s' with\n      exist r Hr =>\n        (match r return size r > 0 -> {r : seq S | size r > 0} with\n           [::] => fun cont => match notF cont with end\n         | y :: _ => fun Hr => exist _ (f x y :: r) erefl\n         end) Hr\n    end.\nProof. by []. Qed.\n\nDefinition scanr (s : seq T) := proj1_sig (scanr_aux s).\n\nLemma scanrE (x : T) (s : seq T) :\n  scanr (x :: s) = foldr f y0 (x :: s) :: scanr s.\nProof.\n  rewrite /scanr.\n  elim: s => // x' s' IH in x *.\n  rewrite scanr_auxE.\n  case: (scanr_aux (x' :: s')) (IH x') => /= r Hr Er.\n  rewrite Er /= in Hr *.\n  by congr (_ :: _).\nQed.\nEnd Scan.\nEnd SeqExt.\n\nSection BinaryTree.\nInductive bintree := L | B1 of bintree | B2 of bintree & bintree.\nDefinition forest := seq bintree.\n\nFixpoint bintree_eq (t1 t2 : bintree) :=  \n  match t1, t2 with\n  | L, L => true\n  | B1 t1', B1 t2' => bintree_eq t1' t2'\n  | B2 t11 t12, B2 t21 t22 => bintree_eq t11 t21 && bintree_eq t12 t22\n  | _, _ => false\n  end.\n\nLemma bintree_eqP : Equality.axiom bintree_eq.\nProof.\nmove=> t1 t2; apply/(iffP idP).\n- elim: t1 t2 => [| t1' IH | t11 IH1 t12 IH2].\n  + by case.\n  + by case => //= t2' E; congr B1; apply: IH.\n  + by case => //= t21 t22 /andP [E1 E2]; congr B2; [ apply: IH1 | apply: IH2 ].\n- by move<-; elim: t1 => //= t11 IH1 t12 IH2; rewrite IH1 IH2.\nQed.\n\nCanonical bintree_eqMixin := EqMixin bintree_eqP.\nCanonical bintree_eqType := Eval hnf in EqType bintree bintree_eqMixin.\n\nFixpoint count_node (t : bintree) :=\n  match t with\n    L => 1\n  | B1 t1 => (count_node t1).+1\n  | B2 t1 t2 => (count_node t1 + count_node t2).+1\n  end.\n\nDefinition count_node_forest (f : forest) :=\n  sumn (map count_node f).\n\nLemma count_node_forest_cat (f1 f2 : forest) :\n  count_node_forest (f1 ++ f2) = count_node_forest f1 + count_node_forest f2.\nProof. by rewrite /count_node_forest map_cat sumn_cat. Qed.\n\nLemma count_node_forest_nseq n t :\n  count_node_forest (nseq n t) = (count_node t) * n.\nProof. by rewrite /count_node_forest map_nseq sumn_nseq. Qed.\n\nDefinition subtrees (t : bintree) : forest :=\n  match t with\n    L => [::]\n  | B1 t => [:: t]\n  | B2 t1 t2 => [:: t1; t2]\n  end.\n\nDefinition subforest (f : forest) : forest :=\n  flatten (map subtrees f).\n\nLemma subforest_cat f1 f2 :\n  subforest (f1 ++ f2) = subforest f1 ++ subforest f2.\nProof. by rewrite /subforest map_cat flatten_cat. Qed.\n\nLemma subforest_nseq n t :\n  subforest (nseq n t) = flatten (nseq n (subtrees t)).\nProof. by rewrite /subforest map_nseq. Qed.\n\nLemma eq_count_node t :\n  count_node t = (count_node_forest (subtrees t)).+1.\nProof.\n  rewrite /count_node_forest.\n  by case: t => //= [t1 | t1 t2]; rewrite addn0.\nQed.\n\nLemma eq_count_node_forest f :\n  count_node_forest f = size f + count_node_forest (subforest f).\nProof.\n  rewrite /count_node_forest /subforest.\n  elim: f => //= t0 f' IH.\n  rewrite map_cat sumn_cat.\n  (* Note: addn.[AC (2*2) ((3*2)*(1*4))] replaces a term like (a + b) + (c + d) *)\n  (* with (c + b) + (a + d). In general, MathComp provides a handy tool to      *)\n  (* rewrite terms built by an operation using its commutativity and its        *)\n  (* associativity; see ssrAC.v in MathComp.                                    *)\n  rewrite -addn1 addn.[AC (2*2) ((3*2)*(1*4))] addn1.\n  congr (_ + _) => //.\n  by apply: eq_count_node.\nQed.\nEnd BinaryTree.\n\nSection LeaveSpec.\nDefinition leave_spec := seq nat.\n\nFixpoint satisfy_leave_spec (f : forest) (s : leave_spec) :=\n  match s with\n    [::] => f == [::]\n  | l0 :: s' =>\n      let f' := subforest f in\n      (count_mem L f == l0) && satisfy_leave_spec f' s'\n  end.\nEnd LeaveSpec.\n\n(******************************************************************************)\n(* Step 1: Compute a bound of the size of forests                             *)\n(******************************************************************************)\n\nDefinition lower_bound_bottomup (s : leave_spec) :=\n  foldr (fun l0 lb => l0 + uphalf lb) 0 s.\n\nDefinition upper_bound_bottomup (s : leave_spec) :=\n  foldr (fun l0 ub => l0 + ub) 0 s.\n\nLemma leq_bottomup_bound (s : leave_spec) :\n  lower_bound_bottomup s <= upper_bound_bottomup s.\nProof.\n  elim: s => //= l0 s' IH.\n  by rewrite leq_add2l (leq_trans _ IH) ?leq_uphalf.\nQed.\n\nSection ForestLift.\nDefinition simple_lift (f : forest) := map B1 f.\n\nFixpoint pairing_lift (p : nat) (f : forest) :=\n  match p, f with\n    p'.+1, t0 :: t1 :: f' => B2 t0 t1 :: pairing_lift p' f'\n  | _, _ => simple_lift f\n  end.\n\nLemma subforest_simple_lift f :\n  subforest (simple_lift f) = f.\nProof.\n  rewrite /subforest.\n  elim: f => //= t0 f' IH.\n  by congr (_ :: _).\nQed.\n\nLemma subforest_pairing_lift p f :\n  subforest (pairing_lift p f) = f.\nProof.\n  rewrite /subforest.\n  elim: p f => [| p' IH]; first by apply: subforest_simple_lift.\n  case => [| t0 [| t1 f']] //=.\n  by congr (_ :: _ :: _).\nQed.\n\nLemma size_simple_lift f :\n  size (simple_lift f) = size f.\nProof. by rewrite size_map. Qed.\n\nLemma size_pairing_lift p f :\n  p <= half (size f) ->\n  size (pairing_lift p f) = size f - p.\nProof.\n  elim: p => [| p' IH] in f *.\n  - by rewrite subn0 size_simple_lift.\n  - case: f => [| t0 [| t1 f']] //= /[!ltnS] ltn_p'.\n    rewrite subSS subSn; last first.\n    + by apply/(leq_trans ltn_p')/leq_div2.\n    + by congr _.+1; apply: IH.\nQed.\n\nLemma count_mem_L_simple_lift f :\n  count_mem L (simple_lift f) = 0.\nProof. by rewrite count_map count_pred0. Qed.\n\nLemma count_mem_L_pairing_lift p f :\n  count_mem L (pairing_lift p f) = 0.\nProof.\n  elim: p => [| p' IH] in f *; first by rewrite count_mem_L_simple_lift.\n  case: f => [| t0 [| t1 f']] //=.\n  by rewrite add0n.\nQed.\n\nLemma count_node_forest_pairing_lift p f :\n  p <= half (size f) ->\n  count_node_forest (pairing_lift p f) = count_node_forest f + (size f - p).\nProof.\n  move=> ltn_p.\n  rewrite eq_count_node_forest.\n  by rewrite size_pairing_lift // subforest_pairing_lift addnC.\nQed.\nEnd ForestLift.\n\nLemma in_size_forest f :\n  count_mem L f + uphalf (size (subforest f)) <= size f <= count_mem L f + size (subforest f).\nProof.\n  rewrite /subforest.\n  elim: f => // t0 f' IH.\n  case: t0 => [| t0' | t01 t02] /=.\n  - by rewrite add1n !addSn ltnS.\n  - case/andP: IH => IHlb IHub.\n    rewrite add0n !addnS !ltnS; apply/andP; split => //.\n    by rewrite (leq_trans _ IHlb) ?leq_add2l ?uphalf_half ?leq_addl.\n  - case/andP: IH => IHlb IHub.\n    rewrite add0n !addnS !ltnS; apply/andP; split => //.\n    by rewrite (leq_trans IHub).\nQed.\n\n(******************************************************************************)\n(* Step 2: Prove the existence of a forest whose size is included in the      *)\n(*         bound defined in Step 1                                            *)\n(******************************************************************************)\n\nProposition in_bottomup_boundP (n : nat) (s : leave_spec) :\n  reflect (exists2 f, size f = n & satisfy_leave_spec f s) (lower_bound_bottomup s <= n <= upper_bound_bottomup s).\nProof.\n  apply: (iffP idP).\n  - elim: s => [| l0 s' IH] /= in n *.\n    + by rewrite leqn0 => /eqP ->; exists [::].\n    + move=> ineq_n.\n      set lbb' := lower_bound_bottomup s'.\n      set ubb' := upper_bound_bottomup s'.\n      (* the number of internal nodes on the top *)\n      set i0 := n - l0.\n      case: (leqP lbb' i0).\n      * (* The case where lbb' <= i0:                                                 *)\n        (*   Since lbb' <= i0 <= ubb', using the induction hypothesis, we obtain a    *)\n        (* forest f' of size i0 satisfying the spec s'. We can construct a desired    *)\n        (* forest from f' by adding one node on to the top of each tree in f' and     *)\n        (* creating l0 roots. The total number of trees is i0 + l0 = n.               *)\n        move=> le_lbb'_i0.\n        have ineq_i0 : lbb' <= i0 <= ubb' by lia.\n        case: (IH _ ineq_i0) => f' eq_size_f' sat_f'.\n        exists (simple_lift f' ++ nseq l0 L).\n        -- by rewrite size_cat size_simple_lift eq_size_f' size_nseq; lia.\n        -- apply/andP; split.\n           ++ by rewrite count_cat count_mem_L_simple_lift count_nseq mul1n.\n           ++ rewrite subforest_cat subforest_simple_lift.\n              by rewrite subforest_nseq flatten_nseq_nil cats0.\n      * (* The case where i0 < lbb':                                                  *)\n        (*   Since lbb' <= lbb' <= ubb', using the induction hypothesis, we obtain a  *)\n        (* forest f' of size lbb' satisfying the spec s'. Combining trees in f', we   *)\n        (* can make at most floor(lbb' / 2) pairs. By the hypothesis on n, we obtain  *)\n        (* the inequality lbb' - i0 <= floor(lbb' / 2). Hence we can make lbb' - i0   *)\n        (* pairs. Using them, we construct a desired forest. We first connect each    *)\n        (* pair with one node, then, for the remaining trees, add one node on to the  *)\n        (* top of each tree. Finally, we create l0 roots. The size of the resulting   *)\n        (* forest is (lbb' - i0) + (lbb' - 2 * (lbb' - i0)) + l0 = n.                 *)\n        move=> lt_i0_lbb'.\n        have ? := leq_bottomup_bound s'.\n        have ineq_lbb' : lbb' <= lbb' <= ubb' by lia.\n        case: (IH _ ineq_lbb') => f' eq_size_f' sat_f'.\n        exists (pairing_lift (lbb' - i0) f' ++ nseq l0 L).\n        -- by rewrite size_cat size_pairing_lift ?eq_size_f' ?size_nseq; lia.\n        -- apply/andP; split. \n           ++ by rewrite count_cat count_mem_L_pairing_lift count_nseq mul1n.\n           ++ rewrite subforest_cat subforest_pairing_lift.\n              by rewrite subforest_nseq flatten_nseq_nil cats0.\n  - elim: s => [| l0 s' IH] in n *.\n    + by case; case; case: n. (* :) *)\n    + set lbb' := lower_bound_bottomup s'.\n      set ubb' := upper_bound_bottomup s'.\n      case => f Esize /= /andP [/eqP EcountL sat].\n      have /[!Esize] /[!EcountL] := in_size_forest f.\n      have : lbb' <= size (subforest f) <= ubb'.\n      { by apply: IH; exists (subforest f). }\n      by lia.\nQed.\n\n(******************************************************************************)\n(* Step 3: Define a bound of the number of nodes                              *)\n(******************************************************************************)\n\nFixpoint lower_bounds_backforth (s : leave_spec) (n : nat) :=\n  match s with\n    [::] => [::]\n  | l0 :: s' =>\n      n :: lower_bounds_backforth s' (maxn (lower_bound_bottomup s') (n - l0))\n  end.\n\nFixpoint upper_bounds_backforth (s : leave_spec) (n : nat) :=\n  match s with\n    [::] => [::]\n  | l0 :: s' =>\n      n :: upper_bounds_backforth s' (minn (upper_bound_bottomup s') (n - l0).*2)\n  end.\n\n(* N.B. lower/upper_bounds_total are slow. The time complexity is \u0398(|s|^2).   *)\n(* We will define the faster version in Step 5; see lower/upper_bound_total'. *)\nDefinition lower_bound_total s n :=\n  sumn (lower_bounds_backforth s n).\n\nDefinition upper_bound_total s n :=\n  sumn (upper_bounds_backforth s n).\n\nLemma homo_lower_bound_total s :\n  {homo lower_bound_total s : n m / n <= m}.\nProof.\n  rewrite /lower_bound_total.\n  elim: s => //= l0 s' IH n m leq_nm.\n  by apply/leq_add => //; apply/IH/homo_maxl/leq_sub2r.\nQed.\n\nLemma homo_upper_bound_total s :\n  {homo (upper_bound_total s) : n m / n <= m}.\nProof.\n  rewrite /upper_bound_total.\n  elim: s => //= l0 s' IH n m leq_nm.\n  apply/leq_add => //; apply/IH.\n  by rewrite homo_minl ?leq_double ?leq_sub2r.\nQed.\n\nLemma leq_total_bound s n m :\n  [&& lower_bound_bottomup s <= n, n <= m & m <= upper_bound_bottomup s] ->\n  lower_bound_total s n <= upper_bound_total s m.\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  elim: s => //= l0 s' IH in n m *.\n  move=> ineq_nm.\n  apply: leq_add; first by lia.\n  by apply: IH; move: (leq_bottomup_bound s'); lia.\nQed.\n\n(* The lemma below shows that the closed intervals of the form                *)\n(*   [lower_bound_total s n, upper_bound_total s n]                           *)\n(*   (lower_bound_bottomup s <= n <= upper_bound_bottomup s)                  *)\n(* can be depicted as follows (double-headed arrows represent intervals):     *)\n(*                                                                            *)\n(*              1st: <-------->                                               *)\n(*              2nd:       <------>                                           *)\n(*              3rd:            <------->                                     *)\n(*                                    <--- ........ --->                      *)\n(* the last but one:                                  <---->                  *)\n(*         the last:                                      <------>            *)\n(*                                                                            *)\n(* This picture tells us that they cover the closed interval                  *)\n(*   [lower_bound_total s (lower_bound_bottomup s),                           *)\n(*    upper_bound_total s (upper_bound_bottomup s)].                          *)\nLemma consecutive_total_bounds_touch_each_other s n :\n  lower_bound_bottomup s <= n ->\n  n.+1 <= upper_bound_bottomup s ->\n  lower_bound_total s n <= lower_bound_total s n.+1 <= (upper_bound_total s n).+1.\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  case: s => //= l0 s' in n *.\n  move=> geq_n leq_n1.\n  apply/andP; split.\n  - rewrite ltnW // addSn ltnS leq_add2l homo_lower_bound_total //.\n    by lia.\n  - rewrite addSn ltnS leq_add2l.\n    apply: leq_total_bound.\n    apply/and3P; split; [ apply: leq_maxl | | apply: geq_minl ].\n    have := leq_bottomup_bound s'.\n    suff : 1 <= n - l0 by lia.\n    rewrite ltnNge.\n    apply/negP => leq_nl0.\n    have : upper_bound_bottomup s' > 0 by lia.\n    apply/negP.\n    rewrite -leqNgt leqn0.\n    have : lower_bound_bottomup s' == 0 by lia.\n    elim: s' {l0 n geq_n leq_n1 leq_nl0} => //= l1 s'' IH.\n    by lia.\nQed.\n\nLemma interval_chain_forms_closed_interval (f g : nat -> nat) (a b n : nat) :\n  a <= b ->\n  (forall x, a <= x <= b -> f x <= g x) ->\n  (forall x, a <= x -> x.+1 <= b -> f x <= f x.+1 <= (g x).+1) ->\n  f a <= n <= g b ->\n  exists2 m, a <= m <= b & f m <= n <= g m.\nProof.\n  move/leP.\n  elim: b / => [| b /leP leq_ab IH] leq_fg touching ineq_n.\n  - by exists a; rewrite ?leqnn.\n  - case: (leqP n (g b)) => [le_n_gb | lt_gb_n].\n    + case: IH.\n      * by move=> ??; apply: leq_fg; lia.\n      * by move=> ???; apply: touching; lia.\n      * by lia.\n      * move=> m ineq_m ineq_fgm.\n        exists m => //.\n        by lia.\n    + have ? := touching b leq_ab (leqnn _).\n      by exists b.+1; lia.\nQed.\n\nLemma total_bound_chain_forms_closed_interval m s lb ub :\n  [&& lower_bound_bottomup s <= lb, lb <= ub & ub <= upper_bound_bottomup s] ->\n  lower_bound_total s lb <= m <= upper_bound_total s ub ->\n  exists2 n, lb <= n <= ub & lower_bound_total s n <= m <= upper_bound_total s n.\nProof.\n  move=> ineq_bound ineq_m.\n  case: (@interval_chain_forms_closed_interval (lower_bound_total s) (upper_bound_total s) lb ub m) => //.\n  - by lia.\n  - by move=> ??; apply: leq_total_bound; lia.\n  - by move=> ???; apply: consecutive_total_bounds_touch_each_other; lia.\n  - by move=> n ??; exists n.\nQed.\n\n(******************************************************************************)\n(* Step 4: Prove the existence of a forest in which the number of nodes is    *)\n(*         included in the bound defined in Step 3                            *)\n(******************************************************************************)\n\nProposition in_total_boundP (n m : nat) (s : leave_spec) :\n  lower_bound_bottomup s <= n <= upper_bound_bottomup s ->\n  reflect (exists f, [/\\ count_node_forest f = m, size f = n & satisfy_leave_spec f s]) (lower_bound_total s n <= m <= upper_bound_total s n).\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  move=> ineq_n.\n  apply: (iffP idP).\n  - elim: s => [| l0 s' IH] /= in m n ineq_n *.\n    + move: ineq_n; rewrite !leqn0; do 2!move/eqP->.\n      by exists [::].\n    + move=> ineq_m.\n      set lb := maxn _ _ in ineq_m.\n      set ub := minn _ _ in ineq_m.\n      (* By the combination of total_bound_chain_forms_closed_interval and the      *)\n      (* induction hypothesis, for all m' \\in [lb, ub], we obtain a forest of size  *)\n      (* m' satisfying the spec s'. See total_bound_chain_forms_closed_interval.    *)\n      case: (@total_bound_chain_forms_closed_interval (m - n) s' lb ub).\n      * by move: (leq_bottomup_bound s'); lia.\n      * by rewrite /lower_bound_total /upper_bound_total; lia.\n      * move=> n' ineq_n' ineq_m'.\n        case: (IH (m - n) n').\n        -- by lia.\n        -- by rewrite /lower_bound_total /upper_bound_total in ineq_m'; lia.\n        -- move=> f' [Ecount Esize sat].\n           exists (pairing_lift (n' - (n - l0)) f' ++ nseq l0 L); split.\n           ++ by rewrite count_node_forest_cat count_node_forest_pairing_lift ?Ecount ?Esize ?count_node_forest_nseq /=; lia.\n           ++ by rewrite size_cat size_pairing_lift Esize ?size_nseq; lia.\n           ++ apply/andP; split.\n              ** by rewrite count_cat count_mem_L_pairing_lift count_nseq mul1n.\n              ** rewrite subforest_cat subforest_pairing_lift.\n                 by rewrite subforest_nseq flatten_nseq_nil cats0.\n  - elim: s => [| l0 s' IH] /= in m n ineq_n *.\n    + case => f [Ecount _ /eqP Ef].\n      rewrite Ef in Ecount.\n      by rewrite -Ecount.\n    + case => f [Ecount Esize /andP [/eqP EcountL sat]].\n      set f' := subforest f.\n      have ineq_size_f' : lower_bound_bottomup s' <= size f' <= upper_bound_bottomup s'.\n      { by apply/in_bottomup_boundP; exists f' => //. }\n      have ex_f' : exists f, [/\\ count_node_forest f = m - n, size f = size f' & satisfy_leave_spec f s'].\n      { \n        exists f'; split => //.\n        (* Note: To obtain the equality (n + m) - n = m, use addKn. It is hard to search. *)\n        by rewrite -Ecount (eq_count_node_forest f) Esize addKn.\n      }\n      have {ex_f'} := IH _ _ ineq_size_f' ex_f'.\n      set lb := maxn _ _.\n      set ub := minn _ _. \n      have ineq_n' := in_size_forest f.\n      rewrite EcountL Esize -/f' in ineq_n'.\n      have : lower_bound_total s' lb <= lower_bound_total s' (size f').\n      { by apply: homo_lower_bound_total; lia. }\n      have : upper_bound_total s' (size f') <= upper_bound_total s' ub.\n      { by apply: homo_upper_bound_total; lia. }\n      have : n <= m.\n      { by rewrite -Esize -Ecount eq_count_node_forest leq_addr. }\n      rewrite /lower_bound_total /upper_bound_total.\n      by lia.\nQed.\n\n(******************************************************************************)\n(* Step 5: Speed up the functions defined in Step 3                           *)\n(******************************************************************************)\n\nDefinition lower_bounds_topdown (s : leave_spec) (n : nat) :=\n  belast n (scanl subn n s).\n\nDefinition upper_bounds_topdown (s : leave_spec) (n : nat) :=\n  belast n (scanl (fun ub l0 => (ub - l0).*2) n s).\n\nDefinition lower_bounds_bottomup s :=\n  scanr (fun l0 lb : nat => l0 + uphalf lb) 0 s.\n\nDefinition upper_bounds_bottomup s :=\n  scanr (fun l0 ub : nat => l0 + ub) 0 s.\n\nDefinition lower_bounds_backforth' s n :=\n  map2 maxn (lower_bounds_bottomup s) (lower_bounds_topdown s n).\n\nDefinition upper_bounds_backforth' s n :=\n  map2 minn (upper_bounds_bottomup s) (upper_bounds_topdown s n).\n\nLemma lower_bounds_backforth'E l0 s n :\n  lower_bounds_backforth' (l0 :: s) n =\n    maxn (lower_bound_bottomup (l0 :: s)) n :: lower_bounds_backforth' s (n - l0).\nProof. by rewrite /lower_bounds_backforth' /lower_bounds_bottomup scanrE. Qed.\n\nLemma upper_bounds_backforth'E l0 s n :\n  upper_bounds_backforth' (l0 :: s) n =\n    minn (upper_bound_bottomup (l0 :: s)) n :: upper_bounds_backforth' s (n - l0).*2.\nProof. by rewrite /upper_bounds_backforth' /upper_bounds_bottomup scanrE. Qed.\n\nDefinition lower_bound_total' s n :=\n  sumn (lower_bounds_backforth' s n).\n\nDefinition upper_bound_total' s n :=\n  sumn (upper_bounds_backforth' s n).\n\nLemma lower_bound_lower_bounds_backforth' s n :\n  n <= lower_bound_bottomup s ->\n  lower_bounds_backforth' s n = lower_bounds_backforth' s (lower_bound_bottomup s).\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite !lower_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by rewrite maxnn; apply/maxn_idPl.\n  - rewrite addKn !IH //.\n    + by apply: leq_uphalf.\n    + by lia.\nQed.\n\nLemma upper_bound_upper_bounds_backforth' s n :\n  upper_bound_bottomup s <= n ->\n  upper_bounds_backforth' s n = upper_bounds_backforth' s (upper_bound_bottomup s).\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite !upper_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by rewrite minnn; apply/minn_idPl.\n  - rewrite addKn !IH //.\n    + by rewrite -mul2n leq_pmull.\n    + by lia.\nQed.\n\nLemma lower_bounds_backforth_equiv s n :\n  lower_bound_bottomup s <= n ->\n  lower_bounds_backforth' s n = lower_bounds_backforth s n.\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> geq_n.\n  rewrite lower_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by apply/maxn_idPr.\n  - set lbb' := lower_bound_bottomup s'.\n    case: (ltnP lbb' (n - l0)).\n    + by move=> ?; apply/IH/ltnW.\n    + by move=> le_nl0_lbb'; rewrite lower_bound_lower_bounds_backforth' // IH.\nQed.\n\nLemma upper_bounds_backforth_equiv s n :\n  n <= upper_bound_bottomup s ->\n  upper_bounds_backforth' s n = upper_bounds_backforth s n.\nProof.\n  rewrite /upper_bound_total /upper_bound_total'.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite upper_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by apply/minn_idPr.\n  - set ubb' := upper_bound_bottomup s'.\n    case: (ltnP (n - l0).*2 ubb').\n    + by move=> ?; apply/IH/ltnW.\n    + by move=> le_ubb'_nl02; rewrite upper_bound_upper_bounds_backforth' // IH.\nQed.\n\nLemma lower_bound_total_equiv s n :\n  lower_bound_bottomup s <= n ->\n  lower_bound_total' s n = lower_bound_total s n.\nProof. by move=> ?; rewrite /lower_bound_total' lower_bounds_backforth_equiv. Qed.\n\nLemma upper_bound_total_equiv s n :\n  n <= upper_bound_bottomup s ->\n  upper_bound_total' s n = upper_bound_total s n.\nProof. by move=> ?; rewrite /upper_bound_total' upper_bounds_backforth_equiv. Qed.\n\nRequire Extraction.\nExtract Inductive list => \"list\" [ \"[]\" \"( :: )\" ].\nExtract Inductive nat => \"int\" [ \"0\" \"succ\" ] \"(fun fO fS n -> if n = 0 then fO () else fS (n - 1))\".\nExtract Inlined Constant addn => \"( + )\".\nExtract Inlined Constant subn => \"( - )\".\nExtract Inlined Constant maxn => \"max\".\nExtract Inlined Constant minn => \"min\".\nExtract Inlined Constant double => \"(fun n -> n * 2)\".\nExtract Inlined Constant half => \"(fun n -> n / 2)\".\nExtract Inlined Constant uphalf => \"(fun n -> (n + 1) / 2)\".\nExtraction Inline scanr_aux.\n\nExtraction \"folia\" lower_bound_bottomup upper_bound_total'.\n", "meta": {"author": "samosica", "repo": "folia-formalization", "sha": "e17942a1d6b7ac4e7a726266e2b697de2e029862", "save_path": "github-repos/coq/samosica-folia-formalization", "path": "github-repos/coq/samosica-folia-formalization/folia-formalization-e17942a1d6b7ac4e7a726266e2b697de2e029862/Folia_with_commentary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.8058420847275287}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n\n\n(* ####################################################### *)\n(** * From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\n(** * Inductively Defined Propositions *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n. induction n as [|n'].\n  - apply ev_0.\n  - simpl. apply ev_SS. apply IHn'.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  intros. induction H as [|n' E'].\n  - apply H0.\n  - simpl. apply ev_SS. apply IHE'.\nQed.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Example *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n(** ** Inference Rules *)\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n(** *** *)\n(** \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* infinitely many *)\n(** [] *)\n\n(** *** *)\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n*)\n(** *** *)\n(** \n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. apply b_sum. apply H. rewrite plus_0_r. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros. induction m as [|m'].\n  - simpl. apply b_0.\n  - simpl. apply b_sum. apply H. apply IHm'.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros. apply g_plus5. apply g_plus5. apply g_plus3. apply H.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros. induction H as [|n g|n g].\n  - apply H0.\n  - simpl. apply g_plus3. apply IHg.\n  - simpl. apply g_plus5. apply IHg.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros. induction H as [| | | m k a ga b gb].\n  - apply g_0.\n  - apply g_plus3. apply g_0.\n  - apply g_plus5. apply g_0.\n  - apply gorgeous_sum. apply ga. apply gb.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n  intros. rewrite plus_assoc. replace (x + z) with (z + x) by apply plus_comm.\n  reflexivity.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   - apply g_0.\n   - simpl. apply g_plus3. rewrite <- plus_n_Sm.\n     rewrite <- plus_n_Sm. rewrite <- plus_n_Sm. apply g_plus3. apply IHgorgeous.\n   - rewrite plus_0_r. rewrite helper_g_times2. simpl. apply g_plus5. apply g_plus5.\n     rewrite <- plus_0_r. rewrite <- plus_assoc. apply IHgorgeous.\nQed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** *** *)\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E'] . \n  apply E'. Qed.\n\n(** ** [inversion] revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. 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. inversion H. inversion H1. inversion H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m H Q.\n  induction Q.\n  - apply H.\n  - simpl in H. inversion H. apply IHQ. apply H1.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p H. apply ev_ev__ev. rewrite <- plus_assoc.\n  rewrite (plus_comm p (m + p)). rewrite <- plus_assoc.\n  rewrite plus_assoc. apply ev_sum. assumption. rewrite <- double_plus.\n  apply double_even.\nQed.\n(** [] *)\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n *)\nInductive pal {A:Type} : list A -> Prop :=\n| nil_pal : pal nil\n| one_pal x : pal [x]\n| add_pal x xs : pal xs -> pal (x :: snoc xs x).\n\nTheorem pal_l_rev_l : forall (A:Type) (l:list A), pal (l ++ rev l).\nProof.\n  intros. induction l as [|h t].\n  - apply nil_pal.\n  - simpl. rewrite <- snoc_with_append. apply add_pal. apply IHt.\nQed.\n\nTheorem snoc_rev : forall (A:Type) (l:list A) (x:A), snoc (rev l) x = rev (x :: l).\nProof. reflexivity. Qed.\n\nTheorem pal_rev : forall (A:Type) (l:list A), pal l -> l = rev l.\nProof.\n  intros A l H. induction H.\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite rev_snoc. rewrite <- IHpal. reflexivity.\nQed.\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\nTheorem rev_inj : forall (A:Type) (l:list A) (l2:list A), rev l = rev l2 -> l = l2.\nProof.\n  intros. rewrite <- rev_involutive. rewrite <- H. rewrite rev_involutive. reflexivity.\nQed.\n\nTheorem nil_app_r : forall (A:Type) (l:list A), l ++ [] = l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. apply f_equal. apply IHl.\nQed.\n\nTheorem rev_distrib_app:\n  forall (A:Type) (xs:list A) (ys:list A), rev (xs ++ ys) = rev ys ++ rev xs.\nProof.\n  intros. induction xs as [|x xt].\n  - simpl. rewrite nil_app_r. reflexivity.\n  - simpl. rewrite IHxt. rewrite snoc_with_append. reflexivity.\nQed.\n\n(*Theorem cons_app_snoc :\n  forall (A:Type) (a b:A) (xs ys:list A),\n    a :: snoc xs b = ys ++ ys*)\n\nTheorem pal_twice : forall (A:Type) (l:list A), pal (l ++ l) -> pal l.\nProof.\nAbort.\n\nTheorem rev_pal_gen : forall (A:Type) (l:list A) (l':list A), l = rev l' -> l = l' -> pal l.\nProof.\n  intros A l. destruct l as [|h t].\n  - intros. apply nil_pal.\n  - intros. induction l' as [|e m] eqn:rx.\n    + intros. inversion H0.\nAbort.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\nInductive subseq {X:Type} : list X -> list X -> Prop :=\n| sub_nil  : subseq [] []\n| sub_skip : forall (x:X) (xs ys:list X), subseq xs ys -> subseq xs (x :: ys)\n| sub_elem : forall (x:X) (xs ys:list X), subseq xs ys -> subseq (x :: xs) (x :: ys).\n\nTheorem subseq_refl : forall (X:Type) (xs:list X), subseq xs xs.\nProof.\n  intros. induction xs as [|h t].\n  - apply sub_nil.\n  - apply sub_elem. apply IHt.\nQed.\n\nTheorem subseq_nil_all : forall (X:Type) (xs:list X), subseq [] xs.\nProof.\n  intros. induction xs as [|h t].\n  - apply sub_nil.\n  - apply sub_skip. apply IHt.\nQed.\n\nTheorem subseq_app:\n  forall (X:Type) (xs ys zs : list X), subseq xs ys -> subseq xs (ys ++ zs).\nProof.\n  intros. induction H.\n  + apply subseq_nil_all.\n  + simpl. apply sub_skip. apply IHsubseq.\n  + simpl. apply sub_elem. apply IHsubseq.\nQed.\n\nTheorem subseq_intro_app_left:\n  forall (X:Type) (xs ys zs : list X),\n    subseq (xs ++ ys) zs -> subseq xs zs.\nProof.\n  intros X xs. induction xs as [|h t].\n  - intros ys zs H. apply subseq_nil_all.\n  - intros ys zs. generalize dependent ys. induction zs as [|i s].\n    + intros ys H. inversion H.\n    + intros xs H. inversion H as [|x' xs' ys' seq|x' xs' ys' seq].\n      * apply sub_skip. apply IHs with xs. apply seq.\n      * apply sub_elem. apply IHt with xs. apply seq.\nQed.\n\nTheorem subseq_intro_app_right:\n  forall (X:Type) (xs ys zs : list X),\n    subseq (xs ++ ys) zs -> subseq ys zs.\nProof.\n  intros X xs. induction xs as [|h t].\n  - intros ys zs H. apply H.\n  - intros ys zs. generalize dependent ys. induction zs as [|i s].\n    + intros ys H. inversion H.\n    + intros ys H. inversion H as [|x' xs' ys' seq|x' xs' ys' seq].\n      * apply sub_skip. apply IHs. apply seq.\n      * apply IHt. apply sub_skip. apply seq.\nQed.\n\nTheorem subseq_trans:\n  forall (X:Type) (xs ys zs : list X), subseq xs ys -> subseq ys zs -> subseq xs zs.\nProof.\n  intros X xs ys zs H. generalize dependent zs. induction H.\n  - intros. apply H.\n  - intros. apply IHsubseq. replace (x :: ys) with ([x] ++ ys) in H0.\n    apply subseq_intro_app_right in H0. apply H0. reflexivity.\n  - intros. induction zs as [|h t].\n    + inversion H0.\n    + inversion H0.\n      * apply sub_skip. apply IHt. apply H3.\n      * apply sub_elem. apply IHsubseq. apply H2.\nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n  | total_relation_1 : forall (n m : nat), total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hno. induction Hno.\n  - apply Hmn.\n  - apply le_S. apply IHHno.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n. apply le_n.  apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  intros. induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros. generalize dependent n. induction m as [|m'].\n  - intros. inversion H. apply le_n. inversion H1.\n  - intros. inversion H. apply le_n. apply le_S. apply IHm'. apply H1.\nQed.\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  intros. induction a as [|a'].\n  - intros. simpl. apply O_le_n.\n  - intros. simpl. apply n_le_m__Sn_le_Sm. apply IHa'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n unfold lt. \n induction n1 as [|a].\n - intros. simpl in H. destruct m. inversion H. split.\n   + apply n_le_m__Sn_le_Sm. apply O_le_n.\n   + apply H.\n - intros. simpl in H. destruct m. inversion H. destruct IHa with n2 m.\n   + apply Sn_le_Sm__n_le_m.  apply H.\n   + split.\n     * apply n_le_m__Sn_le_Sm. apply H0.\n     * apply le_S. apply H1.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros. unfold lt.\n  induction H.\n  - apply le_S. apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  induction n as [|n'].\n  - intros. apply O_le_n.\n  - intros. destruct m as [|m'].\n    + inversion H.\n    + apply n_le_m__Sn_le_Sm. apply IHn'. apply H.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  induction n as [|n'].\n  - intros. reflexivity.\n  - intros. destruct m as [|m'].\n    + inversion H.\n    + simpl. apply IHn'. apply Sn_le_Sm__n_le_m. apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.                        \nProof.\n  intros n m o H Q. apply le_ble_nat. apply le_trans with m.\n  + apply ble_nat_true. apply H.\n  + apply ble_nat_true. apply Q.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros. unfold not. intros. apply le_ble_nat in H0. rewrite H in H0. discriminate H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (R_provability2) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function. \n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\nTheorem r_plus_eq : forall m n o : nat, R m n o -> m + n = o.\nProof.\n  intros. induction H.\n  - reflexivity.\n  - simpl. apply f_equal. apply IHR.\n  - rewrite plus_comm. simpl. apply f_equal. rewrite plus_comm. apply IHR.\n  - simpl in IHR. rewrite <- plus_n_Sm in IHR. injection IHR. intro X. apply X.\n  - rewrite plus_comm. apply IHR.\nQed.\n\nTheorem plus_eq_r : forall m n o : nat, m + n = o -> R m n o.\n  intro m. induction m as [|m'].\n  - intro n. induction n as [|n'].\n    + intros. rewrite <- H. apply c1.\n    + intros. rewrite <- H. apply c3. apply IHn'. reflexivity.\n  - intros. rewrite <- H. simpl. apply c2. apply IHm'. reflexivity.\nQed.\n(** [] *)\n\nEnd R.\n\n\n(* ##################################################### *)\n(** * Programming with Propositions Revisited *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 : \n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true : \n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.  \n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even. \n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.  \n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P -> \n    true_for_all_numbers P. \n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even) *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) (n:nat) : Prop :=\n  if evenb n then Peven n else Podd n.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro : \n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros. unfold combine_odd_even. destruct (evenb n) eqn:E.\n  - apply H0. unfold oddb. rewrite E. reflexivity.\n  - apply H. unfold oddb. rewrite E. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros. unfold combine_odd_even in H.\n  replace (evenb n) with (negb (negb (evenb n))) in H. unfold oddb in H0.\n  rewrite H0 in H. simpl in H. apply H. apply negb_involutive.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros. unfold combine_odd_even in H. unfold oddb in H0.\n  rewrite <- negb_involutive with (evenb n) in H. rewrite H0 in H.\n  simpl in H. apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\n\nFixpoint true_upto_n__true_everywhere (n:nat) (f:nat -> Prop) : Prop :=\n  match n with\n    | 0    => forall n : nat, f n\n    | S n' => f n -> true_upto_n__true_everywhere n' f\n  end.\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n\n(** [] *)\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\n", "meta": {"author": "bennofs", "repo": "software-foundations", "sha": "4278136ca18c0909603cab17fbc0c190dedf69c7", "save_path": "github-repos/coq/bennofs-software-foundations", "path": "github-repos/coq/bennofs-software-foundations/software-foundations-4278136ca18c0909603cab17fbc0c190dedf69c7/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.8058420804333684}}
{"text": "Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n \nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint append(m n :natlist) : natlist :=\nmatch m with\n|[] => n\n|a :: b => a::(append b n)\nend.\n\nNotation \"x ++ y\" := (append x y)(at level 60, right associativity).\n\nFixpoint snoc(m:natlist)(n:nat) :natlist:=\nmatch m with\n|[] => [n]\n|a::b => a:: (snoc b n)\nend.\n\nFixpoint reverse(n:natlist) : natlist :=\nmatch n with\n|[] => []\n|a::b => snoc(reverse b) a\nend.\n\nTheorem appendEmptyList : forall list : natlist, list ++ [] = list.   \nProof.\n  intros.    \n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. \n    rewrite -> IHxs.\n    reflexivity.\nQed.\n\nTheorem rev_snoc : forall l :natlist, forall n:nat, reverse(snoc l n) = n :: reverse l.\nProof.\nintros.\ninduction l.\nsimpl.\nsimpl. reflexivity.\nsimpl. rewrite -> IHl.\nsimpl. reflexivity.\nQed.\n\nTheorem reverseInvolutive : forall list : natlist, reverse(reverse list) = list.   \nProof.\nintros.\ninduction list as [| x xs].\nsimpl. reflexivity.\nsimpl. rewrite -> rev_snoc.\nrewrite IHxs.\nreflexivity.\nQed.\n\n", "meta": {"author": "psjyothiprasad", "repo": "Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "sha": "bda5df849ce973def8aa145660aa806e7743af35", "save_path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography/Software-Modelling---Theorem-Provers---Program-Verification---Cryptography-bda5df849ce973def8aa145660aa806e7743af35/Exercise1/reverseInvolutive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.805842076345897}}
{"text": "Require Import Arith.\nRequire Import Recdef.\n\nDefinition nat_leb := leb.\n\nRequire Import Bool.\n\nInductive nat_list : Set :=\n    nil : nat_list \n  | cons : nat -> nat_list -> nat_list.\n\nInductive is_sorted : nat_list -> Prop :=\n    s_nil       : is_sorted nil\n  | s_singleton : forall x, is_sorted (cons x nil)\n  | s_cons      : forall x y ys, x <= y -> is_sorted (cons y ys) -> is_sorted (cons x (cons y ys)).\n\nLemma test_is_sorted : is_sorted (cons 1 (cons 2 nil)).\nProof.\n  apply s_cons.\n  auto.\n  apply s_singleton.\nQed.\n\nFixpoint less_than_list (x : nat) (xs : nat_list) : bool :=\n  match xs with\n  | nil       => true\n  | cons y ys => andb (nat_leb x y) (less_than_list x ys)\n  end.\n\nFixpoint append (xs : nat_list) (ys : nat_list) : nat_list :=\n  match xs with\n  | nil       => ys\n  | cons z zs => cons z (append zs ys)\n  end.\n\nFixpoint noccs (x : nat) (xs : nat_list) : nat :=\n  match xs with\n  | nil       => 0\n  | cons y ys => noccs x ys + if beq_nat x y then 1 else 0\n  end.\n\nDefinition perm (xs : nat_list) (ys : nat_list) :=\n  forall x, noccs x xs = noccs x ys.\n\nFixpoint nat_list_min (xs : nat_list) : nat :=\n  match xs with\n  | nil        => 0 \n  | cons y ys  =>\n    (match ys with\n    | nil      => y\n    | cons _ _ => min y (nat_list_min ys)\n    end)\n  end.\n\nLemma noccs_gt_0_cons :\n  forall x y xs,\n    noccs y (cons x xs) > 0 -> (y = x \\/ noccs y xs > 0).\nProof.\n  unfold noccs; fold noccs.\n  intros x y xs H.\n  case_eq (beq_nat y x).\n    (* true *)\n    intro. left.\n    apply beq_nat_true; assumption.\n    (* false *)\n    intro. right.\n    replace (beq_nat y x) with false in H.\n    replace (noccs y xs + 0) with (noccs y xs) in H.\n    assumption.\n    apply plus_n_O.\nQed.\n\nLemma nat_list_min_is_min :\n  forall (xs : nat_list) (x : nat),\n    noccs x xs > 0 -> nat_list_min xs <= x.\nProof.\n  intros xs x noccs_gt_0.\n  induction xs.\n    (* nil *)\n    apply le_Sn_0 in noccs_gt_0.\n    contradiction.\n    (* cons *)\n    unfold nat_list_min; fold nat_list_min.\n    apply noccs_gt_0_cons in noccs_gt_0.\n    case noccs_gt_0.\n      (* x = n *)\n      intro.\n      replace n with x.\n      induction xs.\n        apply le_refl.\n        apply Min.le_min_l.\n      (* noccs x xs > 0 *)\n      intro.\n      apply le_trans with (nat_list_min xs).\n      induction xs.\n        apply le_Sn_0 in H; contradiction.\n      apply Min.le_min_r.\n      apply IHxs.\n      assumption.\nQed.\n\nFixpoint nat_list_remove1 (x : nat) (xs : nat_list) : nat_list :=\n  match xs with\n  | nil       => nil\n  | cons y ys =>\n    if beq_nat x y\n     then ys\n     else cons y (nat_list_remove1 x ys)\n  end.\n\nFixpoint nat_list_len (xs : nat_list) :=\n  match xs with\n  | nil       => 0\n  | cons _ ys => 1 + nat_list_len ys\n  end.\n\nLemma leqmin_imp_eqmin :\n  forall n m, n <= min n m -> n = min n m.\nProof.\n  intros n m.\n  intro.\n  symmetry.\n  apply min_l.\n  apply Min.min_glb_r with n.\n  assumption.\nQed.\n\nLemma remove_different_cons :\n  forall x y xs,\n  y <> x -> nat_list_remove1 y (cons x xs) = cons x (nat_list_remove1 y xs).\nProof.\n  intros.\n  simpl.\n  replace (beq_nat y x) with false.\n  reflexivity.\n  symmetry.\n  apply beq_nat_false_iff.\n  assumption.\nQed.\n\nLemma list_length_after_removal :\n  forall xs, xs <> nil ->\n  nat_list_len (nat_list_remove1 (nat_list_min xs) xs)\n  < nat_list_len xs.\nProof.\n  induction xs.\n    (* nil *)\n    intro H; elim H; reflexivity.\n    (* cons *)\n    intro.\n    unfold nat_list_min; fold nat_list_min.\n    case_eq xs.\n      (* nil *)\n      simpl.\n      rewrite <- beq_nat_refl.\n      simpl.\n      intro.\n      apply lt_0_Sn.\n      (* cons *)\n      intros y ys shape_xs.\n      assert ({n <= nat_list_min (cons y ys)} +\n              {n > nat_list_min (cons y ys)})\n             as n_options.\n      apply le_gt_dec.\n      case n_options.\n        (* case n is min *)\n        intro.\n        replace (min n (nat_list_min (cons y ys))) with n.\n        simpl.\n        rewrite <- beq_nat_refl.\n        simpl.\n        apply lt_n_S.\n        apply lt_n_Sn.\n        symmetry.\n        apply min_l.\n        assumption.\n        (* case (nat_list_min (cons n0 xs)) is min *)\n        intro.\n        replace (min n (nat_list_min (cons y ys))) with (nat_list_min (cons y ys)).\n          replace (cons y ys) with xs.\n          rewrite remove_different_cons.\n            apply lt_n_S.\n            fold nat_list_len.\n            apply IHxs.\n            replace xs with (cons y ys).\n            discriminate.\n            replace xs with (cons y ys).\n            apply NPeano.Nat.lt_neq.\n            assumption.\n          (* proof that (min n (nat_list_min (cons y ys))) = (nat_list_min (cons y ys)) *)\n          symmetry.\n          apply min_r.\n          apply lt_le_weak in g.\n          assumption.\nQed.            \n\nFunction selection_sort (xs : nat_list)\n    { measure nat_list_len xs } : nat_list :=\n  match xs with\n  | nil       => nil\n  | cons y ys =>\n      let m := nat_list_min (cons y ys) in\n        cons m (selection_sort (nat_list_remove1 m (cons y ys)))\n  end.\n  intros.\n  apply list_length_after_removal.\n  discriminate.\nDefined.\n\nEval compute in (selection_sort (cons 2 (cons 3 (cons 1 nil)))).\n\nDefinition is_permutation xs ys := forall x, noccs x xs = noccs x ys.\n\nLemma eq_neq_dec : forall x y : nat, {x <> y} + {x = y}.\nProof.\n  intros x y.\n  assert ({x < y} + {x = y} + {x > y}) as xy_options.\n  apply lt_eq_lt_dec.\n  case xy_options. intro xy_options2; case xy_options2.\n  (* x < y *)\n  left.\n  apply NPeano.Nat.lt_neq.\n  assumption.\n  (* x = y *)\n  right.\n  assumption.\n  (* x > y *)\n  left.\n  apply not_eq_sym.\n  apply NPeano.Nat.lt_neq.\n  assumption.\nQed.\n\nLemma noccs_remove_present :\n  forall x xs,\n    noccs x xs > 0 ->\n    noccs x xs = noccs x (nat_list_remove1 x xs) + 1.\nProof.\n  induction xs.  \n  (* nil *)\n  intro. compute in H. apply le_Sn_0 in H; contradiction.\n  (* cons *)\n  intro.\n  assert ({x <> n} + {x = n}) as x_options.\n  apply eq_neq_dec.\n  case x_options.\n  (* x <> n *)\n    intro.\n    unfold nat_list_remove1; fold nat_list_remove1.\n    assert (beq_nat x n = false).\n      apply beq_nat_false_iff.\n      assumption.\n    replace (beq_nat x n) with false.\n    unfold noccs; fold noccs.\n    replace (beq_nat x n) with false.\n    rewrite plus_0_r.\n    rewrite plus_0_r.\n    apply IHxs.\n    unfold noccs in H; fold noccs in H.\n    replace (beq_nat x n) with false in H.\n    rewrite plus_0_r in H.\n    assumption.\n  (* x = n *)\n    intro.\n    unfold nat_list_remove1; fold nat_list_remove1.\n    assert (beq_nat x n = true).\n      apply beq_nat_true_iff.\n      assumption.\n    replace (beq_nat x n) with true.\n    unfold noccs; fold noccs.\n    replace (beq_nat x n) with true.\n    reflexivity.\nQed.\n\nLemma plus_compat :\n  forall x y z, x = y -> x + z = y + z.\nProof.\n  induction z.\n  (* base *)\n  intro.\n  rewrite plus_0_r.\n  rewrite plus_0_r.\n  assumption.\n  (* ind *)\n  intro.\n  rewrite <- plus_n_Sm.\n  rewrite <- plus_n_Sm.\n  apply eq_S.\n  apply IHz.\n  assumption.\nQed.\n\nLemma noccs_remove_not_present :\n  forall x y xs,\n    x <> y ->\n    noccs y xs > 0 ->\n    noccs x xs = noccs x (nat_list_remove1 y xs).\nProof.\n  intros x y xs H0 H1.\n  induction xs.\n  (* nil *)\n  compute in H1. apply le_Sn_0 in H1; contradiction.\n  (* cons *)\n  unfold nat_list_remove1; fold nat_list_remove1.\n  assert ({y <> n} + {y = n}) as y_options.\n  apply eq_neq_dec.\n  case y_options.\n  (* y <> n *)\n  intro.\n  assert (beq_nat y n = false).\n    apply beq_nat_false_iff.\n    assumption.\n  replace (beq_nat y n) with false.\n  unfold noccs; fold noccs.\n  apply plus_compat.\n  apply IHxs.\n  unfold noccs in H1; fold noccs in H1.\n  replace (beq_nat y n) with false in H1.\n  rewrite plus_0_r in H1.\n  assumption.\n  (* y = n *)\n  intro.\n  assert (beq_nat y n = true).\n    apply beq_nat_true_iff.\n    assumption.\n  replace (beq_nat y n) with true.\n  unfold noccs; fold noccs.\n  assert (beq_nat x n = false).\n    apply beq_nat_false_iff.\n    replace n with y.\n    assumption.\n  replace (beq_nat x n) with false.\n  rewrite plus_0_r.\n  reflexivity.\nQed.\n\nLemma min_neq_l : forall x y, min x y <> x -> y <= x.\nProof.\n  intros x y.\n  intro.\n  assert ({min x y = x} + {min x y = y}) as min_options.\n    apply Min.min_case.\n    left. reflexivity.\n    right. reflexivity.\n  case min_options. \n  (* min x y = x *)\n    intro. elim H; assumption.  \n  (* min x y = y *)\n    intro.\n    apply Min.min_glb_l with y.\n    replace (min x y) with y.\n    apply le_refl.\nQed.\n\nLemma min_of_cons :\n  forall x xs,\n  nat_list_min (cons x xs) <> x -> \n  nat_list_min (cons x xs) = nat_list_min xs.\nProof.\n  intro.\n  unfold nat_list_min; fold nat_list_min.\n  intro xs.\n  case xs.\n  (* nil *)\n  intro H; elim H; reflexivity.\n  (* cons *)\n  intros y ys.\n  intro.\n  apply min_r.\n  apply min_neq_l.\n  assumption.\nQed.\n  \nLemma min_in_list :\n  forall xs,\n    xs <> nil -> noccs (nat_list_min xs) xs > 0.\nProof.\n  induction xs.\n  (* nil *)\n  intro H. elim H. reflexivity.\n  (* cons *)\n  case_eq xs.\n    (* nil *)\n    intros.\n    unfold nat_list_min; fold nat_list_min.\n    simpl.\n    assert (beq_nat n n = true).\n      apply beq_nat_true_iff.\n      reflexivity.\n    replace (beq_nat n n) with true.\n    apply lt_0_Sn.\n    (* cons *)\n    intros y ys.\n    intros.\n    assert ({n <> nat_list_min (cons n (cons y ys))} +\n            {n = nat_list_min (cons n (cons y ys))})\n        as n_options.\n      apply eq_neq_dec.\n    case n_options.\n    (* n <> nat_list_min ... *)\n    intro.\n    replace (cons y ys) with xs.\n    unfold noccs; fold noccs.\n    assert (beq_nat (nat_list_min (cons n xs)) n = false).\n      apply beq_nat_false_iff.\n      apply not_eq_sym.\n      replace xs with (cons y ys).\n      assumption.\n    replace (beq_nat (nat_list_min (cons n xs)) n) with false.\n    rewrite plus_0_r.\n    replace xs with (cons y ys).\n    replace xs with (cons y ys) in IHxs.\n    rewrite min_of_cons.\n      apply IHxs.\n      discriminate.\n      apply not_eq_sym.\n      assumption.\n    (* n = nat_list_min ... *)\n      intro n_shape.\n      rewrite <- n_shape.\n      unfold noccs; fold noccs.\n      assert (beq_nat n n = true).\n        apply beq_nat_true_iff.\n        reflexivity.\n      replace (beq_nat n n) with true.\n        rewrite plus_comm.\n        simpl.\n        apply lt_0_Sn.\n Qed.\n\nLemma remove_min_perm :\n  forall xs,\n    xs <> nil ->\n    is_permutation xs (cons (nat_list_min xs) (nat_list_remove1 (nat_list_min xs) xs)).\nProof.\n  intro xs.\n  case_eq xs.\n  (* nil *)\n  intro xs_shape. intro H; elim H; reflexivity.\n  (* cons *)\n  intros y ys xs_shape.\n  intro.\n  replace (cons y ys) with xs.\n  unfold is_permutation.\n  intro x.\n  assert ({x <> nat_list_min xs} +\n          {x = nat_list_min xs})\n      as x_options.\n    apply eq_neq_dec.\n  case x_options.\n  (* x <> nat_list_min xs *)\n    intro.\n    unfold noccs; fold noccs.\n    assert (beq_nat x (nat_list_min xs) = false).\n      apply beq_nat_false_iff.\n      assumption.\n    replace (beq_nat x (nat_list_min xs)) with false.\n    rewrite plus_0_r.\n    apply noccs_remove_not_present.\n    assumption.\n    apply min_in_list.\n    rewrite xs_shape.\n    discriminate.\n  (* x = nat_list_min xs *)\n    intro.\n    unfold noccs; fold noccs.\n    assert (beq_nat x (nat_list_min xs) = true).\n      apply beq_nat_true_iff.\n      assumption.\n    replace (beq_nat x (nat_list_min xs)) with true.\n    replace x with (nat_list_min xs).\n    apply noccs_remove_present.\n    apply min_in_list.\n    rewrite xs_shape.\n    discriminate.\nQed.      \n\nLemma cons_is_not_perm_nil :\n  forall x xs,\n  ~is_permutation (cons x xs) nil.\nProof.\n  intros x xs.\n  unfold is_permutation.\n  intro H.\n  specialize H with x.\n  unfold noccs in H; fold noccs in H.\n  assert (beq_nat x x = true).\n    apply beq_nat_true_iff.\n    reflexivity.\n  replace (beq_nat x x) with true in H.\n  rewrite plus_comm in H.\n  simpl in H. \n  apply eq_sym in H.\n  apply O_S in H.\n  contradiction.\nQed.\n\nLemma permutation_cons :\n  forall x xs ys,\n  is_permutation xs ys ->\n  is_permutation (cons x xs) (cons x ys).\nProof.\n  intros x xs ys.\n  unfold is_permutation.\n  intro H.\n  intro y.\n  unfold noccs; fold noccs.\n  apply plus_compat.\n  specialize H with y.\n  assumption.\nQed.\n\nLemma permutation_equiv :\n  forall x xs ys zs,\n  is_permutation xs ys ->\n  is_permutation (cons x xs) zs ->\n  is_permutation (cons x ys) zs.\nProof. \n  intros x xs ys zs perm_xs_ys perm_xxs_zs.\n  unfold is_permutation.\n  intro y.\n  assert (is_permutation (cons x xs) (cons x ys)) as perm_xxs_xys.\n    apply permutation_cons.\n    assumption.\n  unfold is_permutation in perm_xxs_xys.\n  specialize perm_xxs_xys with y.\n  transitivity (noccs y (cons x xs)).\n  symmetry.\n  assumption.\n  unfold is_permutation in perm_xxs_zs.\n  specialize perm_xxs_zs with y.\n  assumption.\nQed. \n\nLemma permutation_symm :\n  forall xs ys,\n    is_permutation xs ys -> is_permutation ys xs.\nProof.\n  intros xs ys H.\n  unfold is_permutation.\n  intro x.\n  unfold is_permutation in H.\n  specialize H with x.\n  symmetry.\n  assumption.\nQed.\n\nLemma selection_sort_is_permutation :\n  forall xs, is_permutation (selection_sort xs) xs.\nProof.\n  intro.\n  functional induction selection_sort xs.\n  (* nil *)\n  compute.\n  reflexivity.\n  (* cons *)\n  apply permutation_equiv\n   with (xs := (nat_list_remove1 (nat_list_min (cons y ys)) (cons y ys))).\n  apply permutation_symm.\n  apply IHn.\n  apply permutation_symm.\n  apply remove_min_perm.\n  discriminate.\nQed.  \n\nLemma selection_sort_cons :\n  forall xs,\n    ~(xs = nil) ->\n    selection_sort xs =\n    cons (nat_list_min xs)\n         (selection_sort (nat_list_remove1 (nat_list_min xs) xs)).\n Proof.\n   intro xs.\n   functional induction selection_sort xs.\n   (* nil *)\n   intro H; elim H; reflexivity.\n   (* cons *)\n   intro xs_shape.\n   reflexivity.\nQed.\n \nLemma nat_list_remove_not_nil :\n  forall x y xs,\n    xs <> nil ->\n    nat_list_remove1 y (cons x xs) <> nil.\n Proof.\n   intros x y xs xs_not_nil.\n   unfold nat_list_remove1.\n   assert ({x <> y} + {x = y}) as xy_options.\n     apply eq_neq_dec.\n   case xy_options. \n   (* x <> y *)\n     intro.\n     assert (beq_nat y x = false).\n       apply beq_nat_false_iff.\n       apply not_eq_sym.\n       assumption.\n     replace (beq_nat y x) with false.\n     discriminate.\n   (* x = y *)\n     intro.\n     assert (beq_nat y x = true).\n       apply beq_nat_true_iff.\n       symmetry.\n       assumption.\n     replace (beq_nat y x) with true.\n     assumption.\nQed.\n \nLemma noccs_in_remove :\n  forall x y xs,\n    noccs y (nat_list_remove1 x xs) > 0 ->\n    noccs y xs > 0.\nProof.\n  intros x y xs.\n  induction xs.\n  (* nil *)\n  intro H.\n  simpl in H.\n  apply lt_irrefl in H.\n  contradiction.\n  (* cons *)\n  intro H. \n  assert ({x <> n} + {x = n}) as x_options.\n    apply eq_neq_dec.\n  case x_options.\n  (* x <> n *)\n    intro.\n    unfold nat_list_remove1 in H; fold nat_list_remove1 in H.\n    assert (beq_nat x n = false).\n      apply beq_nat_false_iff.\n      assumption.\n     replace (beq_nat x n) with false in H.\n     unfold noccs; fold noccs.\n     unfold noccs in H; fold noccs in H.\n     (* case y *)\n     assert ({y <> n} + {y = n}) as y_options.\n       apply eq_neq_dec.\n       case y_options.\n       (* y <> n *)\n       intro.\n       assert (beq_nat y n = false). apply beq_nat_false_iff. assumption.\n       replace (beq_nat y n) with false in H.\n       replace (beq_nat y n) with false.\n       rewrite plus_0_r in H.\n       rewrite plus_0_r.\n       apply IHxs.\n       assumption.\n       (* y = n *)\n       intro.\n       assert (beq_nat y n = true). apply beq_nat_true_iff. assumption.\n       replace (beq_nat y n) with true.\n       rewrite plus_comm.\n       simpl.\n       apply lt_0_Sn.\n  (* x = n *)\n    intro.\n    unfold nat_list_remove1 in H; fold nat_list_remove1 in H.\n    assert (beq_nat x n = true). apply beq_nat_true_iff. assumption.\n    replace (beq_nat x n) with true in H.\n    unfold noccs; fold noccs.\n    apply lt_plus_trans.\n    assumption.\nQed.\n\nLemma selection_sort_sorts :\n  forall xs, is_sorted (selection_sort xs).\nProof.\n  intro.\n  functional induction selection_sort xs.\n  (* nil *)\n  apply s_nil.\n  (* cons *)\n  case_eq ys.\n  (* cons / nil *)\n    intro ys_shape.\n    unfold nat_list_min.\n    unfold nat_list_remove1.\n    assert (beq_nat y y = true).\n      apply beq_nat_true_iff.\n      reflexivity.\n    replace (beq_nat y y) with true.\n    apply s_singleton.\n  (* cons / cons *)\n    intros z zs ys_shape.\n    replace (cons z zs) with ys.\n    rewrite selection_sort_cons.\n    apply s_cons.\n      (* [1] first element is lesser than the second *)\n      assert (noccs\n                (nat_list_min (nat_list_remove1 (nat_list_min (cons y ys)) (cons y ys)))\n                (nat_list_remove1 (nat_list_min (cons y ys)) (cons y ys))\n                > 0) as noccs_min2_in_list1.\n        apply min_in_list.\n        apply nat_list_remove_not_nil.\n        rewrite ys_shape.               \n        discriminate.\n      apply nat_list_min_is_min.\n      apply noccs_in_remove with (x := (nat_list_min (cons y ys))).\n      assumption.\n      (* [2] remainder of the list is sorted *)\n      rewrite selection_sort_cons in IHn.\n      assumption.\n      (* trivial conditions of non-emptiness *)\n      apply nat_list_remove_not_nil.\n      rewrite ys_shape; discriminate.\n      apply nat_list_remove_not_nil.\n      rewrite ys_shape; discriminate.\nQed.", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/selection_sort/sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.805836761724695}}
{"text": "(* ************************************************* *)\n(* introduction and examples                         *)\n(* ************************************************* *)\n\n\n(* example of a polymorphic function: identity *)\n\n(* first the identity on natural numbers *)\nDefinition natid : nat -> nat :=\n  fun n : nat => n.\nCheck (natid O).\nEval compute in (natid O).\n\n(* then the identity on booleans *)\nDefinition boolid: bool -> bool :=\n  fun b : bool => b.\nCheck (boolid true).\nEval compute in (boolid true).\n\n(* now the polymorphic identity *)\nDefinition polyid : forall A : Set, A -> A :=\n  fun (A : Set) => fun (a : A) => a.\nCheck polyid.\n\nCheck (polyid nat).\nCheck (polyid nat O).\nEval compute in (polyid nat O).\nCheck (polyid _ O).\n\nCheck (polyid bool).\nCheck (polyid bool true).\nEval compute in (polyid bool true).\nCheck (polyid _ true).\n\n(* the following does not work:\nCheck (polyid _).\nbecause Coq cannot infer what should be on the place of _ *)\n\n(* notation *)\nNotation id := (polyid _).\nCheck (id O).\nEval compute in (id O).\nCheck (id true).\nEval compute in (id true).\n\n\n\n(* example of a polymorphic inductive definition: polylists *)\n\n(* first the lists of natural numbers *)\nInductive natlist : Set :=\n  natnil : natlist\n| natcons : nat -> natlist -> natlist.\n\n(* the list 2;1;0 *)\nCheck (natcons 2 (natcons 1 (natcons 0 natnil))).\n\n(* then the lists of booleans *)\nInductive boollist : Set :=\n  boolnil : boollist\n| boolcons : bool -> boollist -> boollist.\n\n(* now the polymorphic lists *)\nInductive polylist (X : Set) : Set :=\n    polynil  : polylist X\n  | polycons : X -> polylist X -> polylist X.\n\nCheck polylist.\nCheck (polylist nat).\nCheck (polylist bool).\n\nCheck polynil.\nCheck (polynil nat).\nCheck (polynil bool).\nCheck polycons.\nCheck (polycons nat).\nCheck (polycons bool).\n\n(* again the list 2;1;0 *)\nCheck (polycons nat 2 (polycons nat 1 (polycons nat 0 (polynil nat)))).\n\n(* we introduce some handy notation *)\nNotation ni := (polynil _).\nNotation co := (polycons _).\n(* and write the list 2;1;0 again *)\nCheck (co 2 (co 1 (co 0 ni))).\nCheck (co true (co false ni)).\n\n(* induction principle for polymorphic lists;\n   more about this later *)\nCheck polylist_ind.\n\n(* length of lists of natural numbers *)\nFixpoint natlength (l:natlist) {struct l} : nat :=\n  match l with\n    natnil => O\n  | natcons h t => S (natlength t)\n  end.\n\nEval compute in (natlength (natcons 2 (natcons 1 (natcons 0 natnil)))).\n\n(* length of polymorphic lists *)\nFixpoint polylength (A:Set)(l:(polylist A)){struct l} : nat :=\n  match l with\n    polynil => O\n  | polycons h t => S (polylength A t)\n  end.\n\n(* NB: in the recursive definition,\n   polynil and polycons do _not_ get an argument A left of =>;\n   they do get such arguments right of => *)\n\nEval compute in (polylength nat (polycons nat 2 (polycons nat 1 (polycons nat 0 (polynil nat))))).\nEval compute in (polylength nat (co 2 (co 1 (co 0 ni)))).\n\nEval compute in (polylength bool (polycons bool true (polycons bool false (polynil bool)))).\nEval compute in (polylength bool (co true (co false ni))).\n\n(* remark1 about Coq notation:\n   In the definition of polylist\n   we use a parameter declaration (X:Set).\n   Alternatively, we could define a type Set -> Type\n   as follows: *)\nInductive polylistb : Set -> Type :=\n  polynilb : forall X:Set, polylistb X\n| polyconsb: forall X:Set, X -> polylistb X -> polylistb X.\n\n(* but then we get a quite strange induction predicate *)\nCheck polylistb_ind.\n\n(* so we usually take the first definition *)\n\n\n\n\n(* ************************************************* *)\n(*        start of the  exercises                    *)\n(* ************************************************* *)\n\n(*        exercises about polymorphic lists          *)\n(*        see pw04 for similar exercises on natlists *)\n\n(* exercise 1 *)\n(* give the definition of polyappend for polymorphic lists *)\n(* test it using Eval compute on an example *)\n\nFixpoint polyappend (X:Set) (k l : polylist X) {struct k} : (polylist X) :=\n  match k with\n  | polynil => l\n  | polycons h t => polycons X h (polyappend X t l)\n  end\n  .\n\nEval compute in polyappend nat (co 1 (co 2 ni)) (co 42 (co 43 ni))\n  .\n\n(* prove the following lemma, to be used later*)\nLemma append_nil :\n  forall X:Set, forall l: polylist X,\n  polyappend X l (polynil X) = l.\nProof.\nintros X l. induction l.\nsimpl. reflexivity.\nsimpl. rewrite -> IHl. reflexivity.\nQed.\n\n\n(* exercise 3 *)\n(* prove the following lemma, to be used later *)\nLemma append_assoc : forall X, forall k l m,\n  (polyappend X (polyappend X k l) m) = (polyappend X k (polyappend X l m)).\nProof.\nintros X k l m.\n\n(* k = nil *)\ninduction k as [| kh kt].\nsimpl. reflexivity.\n\n(* k = cons h t *)\nsimpl. induction l as [| lh lt].\n\n(* l = nil *)\nsimpl. rewrite append_nil. reflexivity.\n\n(* l = cons lh lt *)\nsimpl. rewrite IHkt. induction m as [| mh mt].\n\n(* m = nil *)\nsimpl. reflexivity.\n\n(* m = cons mh mt *)\nsimpl. reflexivity.\nQed.\n\n\n(* exercise 4 *)\n(* prove the following lemma *)\nLemma length_append :\n forall X:Set, forall k l : (polylist X),\n  polylength X (polyappend X k l) = plus (polylength X k) (polylength X l).\nProof.\nintros X k l.\ninduction k as [| kh kt].\n\n(* k = nil *)\nsimpl. reflexivity.\n\n(* k = cons kh kt *)\nsimpl. rewrite IHkt. reflexivity.\nQed.\n\n\n(* exercise 5 *)\n(* give the definition of polyreverse for polymorphic lists *)\n(* test it using Eval compute on an example *)\n\nFixpoint polyreverse (X:Set) (l : polylist X) {struct l} :(polylist X) :=\n  match l with\n  | ni => ni\n  | co h t => polyappend X (polyreverse X t) (co h ni)\n  end\n  .\n\nEval compute in (polyreverse nat (co 1 (co 2 (co 3 ni)))).\n\n(* exercise 6 *)\n(* prove the following lemma *)\nLemma reverse_append :\n  forall X:Set, forall k l: (polylist X),\n  polyreverse X (polyappend X k l) =\n  polyappend X (polyreverse X l) (polyreverse X k).\nProof.\nintros X.\ninduction k as [| kh kt].\n\n(* k = nil *)\nsimpl. induction l as [| lh lt].\n\n(* l = nil *)\nsimpl. reflexivity.\n\n(* l = co lh lt *)\nsimpl. rewrite append_nil. reflexivity.\n\n(* k = co kh kt *)\nsimpl. induction l as [| lh lt].\n\n(* l = nil *)\nsimpl. rewrite IHkt. simpl. reflexivity.\n\n(* l = co lh lt *)\nsimpl. rewrite IHkt. simpl. rewrite append_assoc.\nreflexivity.\nQed.\n\n(* exercise 7 *)\n(* prove the following lemma *)\n(* this does not correspond to a lemma in pw04 *)\nLemma rev_cons_app :\n  forall X:Set, forall k l : (polylist X), forall x:X,\n  polyappend X (polyreverse X (polycons X x k)) l =\n  polyappend X (polyreverse X k) (polycons X x l).\nProof.\nintro X.\ninduction k as [| kh kt]. induction l.\n\n(* k = nil, l = nil *)\nsimpl. reflexivity.\n\n(* k = nil, l = h t *)\nsimpl. reflexivity.\n\ninduction l as [| lh lt].\n\n(* k = co kh kt, l = nil *)\nintro x. simpl. rewrite append_nil. reflexivity.\n\n(* k = co kh kt, l = co lh lt *)\nintro x. simpl. rewrite <- IHkt. rewrite append_nil.\nrewrite append_assoc.\n\nsimpl. reflexivity.\nQed.\n\n\n\n(*        exercises about polymorphic pairs         *)\n\n\n\n(* definition of pairs of natural numbers *)\nInductive natprod : Set :=\n| natpair : nat -> nat -> natprod.\n\nCheck natpair.\nCheck natpair 1.\nCheck (natpair 1 2).\n\nCheck natprod_ind.\n\n(* we define the first and second projection *)\n\nDefinition natprodfirst (p : natprod) : nat :=\nmatch p with\n| natpair x y => x\nend.\nEval compute in (natprodfirst (natpair 1 2)).\n\nDefinition natprodsecond (p : natprod) : nat :=\nmatch p with\n| natpair x y => y\nend.\nEval compute in (natprodsecond (natpair 1 2)).\n\n(* exercise 8 *)\n(* give a definition prod of polymorphic pairs\n   where the first element comes from a set X\n   and the second element comes from a set Y    *)\n\nInductive prod (X Y :Set) : Set :=\n  | pair : forall (x : X) (y : Y), prod X Y.\n\n(* exercise 9 *)\n(* give definitions of the first and second projection *)\n\nDefinition fst (X Y : Set) (p: prod X Y) : X :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (X Y : Set) (p : prod X Y) : Y :=\n  match p with\n  | pair x y => y\n  end.\n\n\n(*        exercises about polymorphic trees       *)\n\n\n\n(* definition of natbintrees\n   with labels on the nodes  *)\nInductive natbintree : Set :=\n    natleaf : natbintree\n  | natnode : nat -> natbintree -> natbintree -> natbintree.\n\nCheck natleaf.\nCheck (natnode 1 natleaf natleaf).\nCheck (natnode 2 (natnode 1 natleaf natleaf) (natnode 3 natleaf natleaf)).\n\n(* the last is the tree\n               2\n              / \\\n             1   3\n*)\n\n(* exercise 10 *)\n(* give the definition polybintree with constructors polyleaf and polynode\n   of polymorphic binary trees\n   with labels on the nodes\n   you may introduce handy notation *)\n\nInductive polybintree (X : Set) : Set :=\n  | leaf : polybintree X\n  | node : forall x:X, polybintree X -> polybintree X -> polybintree X\n  .\n\n\n\n(* exercise 11 *)\n(* complete the definition of polyflatten\n   polyflatten puts the labels of a polybintree from left to right in a polylist *)\n\nFixpoint polyflatten (X:Set) (t:polybintree X) {struct t} : (polylist X) :=\nmatch t with\n| leaf => polynil X\n| node x l r => polyappend X (polyappend X (polyflatten X l) (co x ni)) (polyflatten X r)\nend\n.\n\n(* perform some tests using the trees above *)\n\nDefinition tree123 := (node nat 2 (node nat 1 (leaf nat) (leaf nat)) (node nat 3 (leaf nat) (leaf nat))).\nEval compute in polyflatten nat tree123.\n\n(*\nvim: filetype=coq\n*)\n", "meta": {"author": "mklinik", "repo": "radboud", "sha": "1b79730dbf7979221ca0de97fc369db82c405331", "save_path": "github-repos/coq/mklinik-radboud", "path": "github-repos/coq/mklinik-radboud/radboud-1b79730dbf7979221ca0de97fc369db82c405331/type-theory-IMC010/pw10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.8057845587321197}}
{"text": "Require Export D.\n\nInductive and (P Q:Prop): Prop :=\n|conj : P -> Q -> and P Q\n.\n\nInductive or (P Q:Prop): Prop :=\n|left : P -> or P Q\n|right : Q -> or P Q\n.\n\nTheorem proj1 : forall (P Q:Prop),\n  P/\\Q -> P.\nProof.\n  intros. destruct H. assumption. Qed.\n\nTheorem or_commut : forall (P Q:Prop),\n  P \\/ Q -> Q \\/ P.\nProof. \n  intros. destruct H. right. assumption. left. assumption. Qed.\n\n", "meta": {"author": "YeongjinOh", "repo": "Programming-language", "sha": "a235e30cec9cab33fa52a7f708ae15d84b869615", "save_path": "github-repos/coq/YeongjinOh-Programming-language", "path": "github-repos/coq/YeongjinOh-Programming-language/Programming-language-a235e30cec9cab33fa52a7f708ae15d84b869615/practice/Logic_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.805778034772516}}
{"text": "(* begin hide *)\nSet Implicit Arguments.\nRequire Import Cpdt.CpdtTactics.\nRequire Export Coq.Strings.String.\nRequire Import Bool. \n(* end hide *)\n\n(*\n03. From Coinductive.\n\n1. (a) Define a co-inductive type of infinite trees carrying data of a fixed parameter type.\nEach node should contain a data value and two child trees.\n *)\n\nSection tree.\n  \n  Variable A : Type.\n  CoInductive tree : Type :=\n  | Node : tree -> A -> tree -> tree.\n\n(*\n(b) Define a function everywhere for building a tree with the same data value at every\nnode. *)\n  \nCoFixpoint everywhere (v : A) : tree := Node (everywhere v) v (everywhere v).\n  \nEnd tree.\n\n(* \n(c) Define a function map for building an output tree out of two input trees by travers-\ning them in parallel and applying a two-argument function to their corresponding\ndata values.\n *)\n\nSection map.\n  Variables A B C : Type.\n  Variable f : A -> B -> C.\n  CoFixpoint map (t1 : tree A) (t2 : tree B) : tree C :=\n    match (t1, t2) with\n    | ((Node t1' a t1''), (Node t2' b t2'')) => Node (map t1' t2') (f a b) (map t1'' t2'')\n    end.\nEnd map.\n\n(* (d) Define a tree falses where every node has the value false. *)\n\nDefinition falses := everywhere false.\n\n(* (e) Define a tree true_false where the root node has value true, its children have value\nfalse, all nodes at the next have the value true, and so on, alternating boolean\nvalues from level to level. *)\n\nCoFixpoint true_false : tree bool := Node false_true true false_true\nwith false_true : tree bool := Node true_false false true_false.\n\n(* (f ) Prove that true_false is equal to the result of mapping the boolean \"or\" function\norb over true_false and falses. You can make orb available with Require Import\nBool.. You may find the lemma orb_false_r from the same module helpful. Your\nproof here should not be about the standard equality =, but rather about some\nnew equality relation that you define. *)\n\n        \nCoInductive trees_eq : tree bool -> tree bool -> Prop :=\n| Trees_eq : forall t1' t1'' t2' t2'' x y,\n    eq x y ->\n    trees_eq t1' t2' ->\n    trees_eq t1'' t2'' ->\n    trees_eq (Node t1' x t1'') (Node t2' y t2'').\n\nDefinition frob (t : tree bool) : tree bool :=\n  match t with\n  | Node t1 x t2 => Node t1 x t2\n  end.                        \n\nTheorem frob_eq : forall t : tree bool, t = frob t.\ndestruct t. simpl. reflexivity. Qed. \n    (* Frob didn't help below abowe. So we try to create co_induction principle according to book \nLemma F_case : trees_eq true_false ( map orb true_false falses ).\n  cofix trees_eq.\n  rewrite (frob_eq true_false) at 1.\n  rewrite (frob_eq (map orb true_false falses)).\n  simpl. \n  constructor.\n  - reflexivity.\n  - cofix trees_eq'.\n    rewrite (frob_eq false_true) at 1.\n    rewrite (frob_eq (((cofix map (t1 t2 : tree bool) : tree bool :=\n        match t1 with\n        | Node t1' a t1'' =>\n            match t2 with\n            | Node t2' b t2'' => Node (map t1' t2') (a || b) (map t1'' t2'')\n            end\n        end) false_true\n       ((cofix everywhere (v : bool) : tree bool := Node (everywhere v) v (everywhere v)) false)))).\n    simpl.\n    constructor.\n    + reflexivity.\n    + assumption.\n    + assumption.\n  - cofix trees_eq'.\n    rewrite (frob_eq false_true) at 1.\n    rewrite (frob_eq (((cofix map (t1 t2 : tree bool) : tree bool :=\n        match t1 with\n        | Node t1' a t1'' =>\n            match t2 with\n            | Node t2' b t2'' => Node (map t1' t2') (a || b) (map t1'' t2'')\n            end\n        end) false_true\n       ((cofix everywhere (v : bool) : tree bool := Node (everywhere v) v (everywhere v)) false)))).\n    simpl.\n    constructor.\n    + reflexivity.\n    + assumption.\n    + assumption.\nQed.     *)\n    \n    (* Frob didn't help abowe. So we try to create co_induction principle according to book *)\n\nDefinition mdl A (t : tree A) : A :=\n  match t with\n  | Node _ x _ => x\n  end.                    \n\nDefinition left_tree A (t : tree A) : tree A :=\n  match t with\n  | Node lt _ _ => lt\n  end.                    \n\nDefinition right_tree A (t : tree A) : tree A :=\n  match t with\n  | Node _ _ rt => rt\n  end.\n\nSection tree_eq_coind.\n  Variable R : tree bool -> tree bool -> Prop.\n  Hypothesis Node_case_mdl : forall t1 t2, R t1 t2 -> mdl t1 = mdl t2.\n  Hypothesis Node_case_left_tree : forall t1 t2, R t1 t2 -> R (left_tree t1) (left_tree t2).\n  Hypothesis Node_case_right_tree : forall t1 t2, R t1 t2 -> R (right_tree t1) (right_tree t2).\n\n  Theorem tree_eq_coind : forall t1 t2, R t1 t2 -> trees_eq t1 t2.\n    cofix tree_eq_coind; destruct t1; destruct t2; intro.\n    generalize (Node_case_mdl H). intro Heq; simpl in Heq; rewrite Heq.\n    constructor; auto.\n    apply Node_case_left_tree in H. simpl in H. \n    apply tree_eq_coind in H. auto. \n    apply Node_case_right_tree in H.\n    apply tree_eq_coind in H. auto. \n  Qed. \nEnd tree_eq_coind. \n\nPrint tree_eq_coind. \n\n(* final lemma : exercise (f) *)\nLemma F_case : trees_eq true_false ( map orb true_false falses ).\n  apply (tree_eq_coind (fun t1 t2 => (t1 = true_false /\\\n                                      t2 = (map orb true_false falses)) \\/\n(t1 = false_true /\\ t2 = (map orb false_true falses))\n        )); crush.\nQed. \n\n\n  (* Helping \nPrint orb_false_r.\n  \norb_false_r = \nfun b : bool => if b as b0 return (b0 || false = b0) then eq_refl else eq_refl\n     : forall b : bool, b || false = b\n\nArguments orb_false_r _%bool_scope\n\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_03_From_Coinductive_Natasha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8933094053442511, "lm_q1q2_score": 0.8056942255733254}}
{"text": "Require Import nat.\n\nDefinition square (n:nat) : nat := n * n.\n\nLemma square_mult : forall (n m:nat), \n    square (n * m) = square n * square m.\nProof.\n    intros n m. unfold square.\n    assert ((n * m) * (n * m) = ((n * m) * n) * m) as H1.\n        { rewrite <- mult_assoc. reflexivity. }\n    assert (((n * m) * n) * m = (n * (m * n)) * m) as H2.\n        { rewrite (mult_assoc n m n). reflexivity. } \n    assert ((n * (m * n)) * m = n * (n * m) * m) as H3.\n        { rewrite (mult_comm m n). reflexivity. }\n    assert (n * (n * m) * m = ((n * n) * m) * m) as H4.\n        { rewrite <- (mult_assoc n n m). reflexivity. }\n    assert (((n * n) * m) * m = (n * n) * (m * m)) as H5.\n        { rewrite (mult_assoc (n * n) m m).  reflexivity. }\n    rewrite H1, H2, H3, H4, H5. 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/unfold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.8056746878404769}}
{"text": "Require Import Bool Arith List CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive binop : Set :=\n| Plus\n| Times.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nCheck mult.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n\n(* syntactic sugar *)\n\nDefinition binopDenoteReal : binop -> nat -> nat -> nat :=\n  fun (b : binop) => match b with\n                  | Plus => plus\n                  | Times => mult\n                  end.\n\n(* CIC enjoys properties like strong normalization and relative consistency *)\n\n(* every Coq source file is a series of vernacular commands, where many command forms take arguments that are Gallina or Ltac programs. *)\n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\n(* Unlike with ML, which hardcodes an eager reduction strategy,\n   or Haskell, which hardcodes a lazy strategy,\n   in Coq we are free to choose between these and many other orders of evaluation,\n   because all Coq programs terminate. *)\n\nEval simpl in expDenote (Const 42).\nEval simpl in expDenote (Binop Plus (Const 2) (Const 2)).\nEval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n  | iConst n => Some (n :: s)\n  | iBinop b => match s with\n               | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n               | _ => None\n               end\n  end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n  | nil => Some s\n  | i :: p' =>\n    match instrDenote i s with\n    | None => None\n    | Some s' => progDenote p' s'\n    end\n  end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n => iConst n :: nil\n  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in compile (Const 42).\nEval simpl in compile (Binop Plus (Const 2) (Const 2)).\nEval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nLemma compile_correct' : forall e p s,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e.\n  - intros. unfold expDenote.\n    unfold progDenote at 1. simpl. fold progDenote.\n    reflexivity.\n  (* Hypos are based on term e1 e2 *)\n  - intros.\n    unfold compile. fold compile.\n    unfold expDenote. fold expDenote.\n    rewrite app_assoc_reverse.\n    rewrite IHe2.\n    rewrite app_assoc_reverse.\n    rewrite IHe1.\n    simpl. reflexivity.\nQed.\n\nLemma compile_correct'' : forall e s p,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e,\n    progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  intro e.\n  rewrite (app_nil_end (compile e)).\n  apply compile_correct'.\nQed.\n\n(* Coq uses case-sensitive variable names *)\n\nInductive type : Set :=\n| Nat\n| Bool.\n\n(* We define tbinop as an indexed type family.\n   Indexed inductive types are at the heart of Coq\u2019s expressive power;\n   almost everything else of interest is defined in terms of them *)\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq : forall t, tbinop t t Bool\n| TLt : tbinop Nat Nat Bool.\n\n(* ML and Haskell have indexed algebraic datatypes.\n   For instance, their list types are indexed by the type of data that the list carries.\n   However, compared to Coq, ML and Haskell 98 place two important restrictions on datatype definitions. *)\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res) : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | TPlus => plus\n  | TTimes => mult\n  | TEq Nat => beq_nat\n  | TEq Bool => eqb\n  | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\n(* I bet first examples are very confused to me ! *)\n", "meta": {"author": "juniorxxue", "repo": "CPDT", "sha": "abf8950b246d3f505d04013a5feb2c684420bf51", "save_path": "github-repos/coq/juniorxxue-CPDT", "path": "github-repos/coq/juniorxxue-CPDT/CPDT-abf8950b246d3f505d04013a5feb2c684420bf51/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8055186458079762}}
{"text": "Require Import Coq.Arith.Wf_nat.\nRequire Import Coq.Logic.Classical_Prop.\nSection MINIMAL_EXISTENCE.\n\nVariable P : nat -> Prop.\n\nLemma P_upto_n_dec:\n  forall n, (exists m, m < n /\\ P m) \\/ (forall m, m < n -> ~ P m).\nProof.\n  intros.\n  destruct (classic(exists m, m < n /\\ P m)).\n  tauto.\n  firstorder.\nQed.\n\nLemma minimal_exists_aux: \n  forall n, P n -> exists m, P m /\\ forall p, p < m -> ~ P p.\nProof.\n  intro n.\n  induction n as [n IH] using lt_wf_ind.\n  destruct (P_upto_n_dec n) as [[m [A B]] | C].\n  apply IH in A.\n  intro.\n  assumption.\n  assumption.\n  intro.\n  exists n.\n  tauto.\nQed.\n\nLemma minimal_exists:\n  (exists n, P n) -> exists m, P m /\\ forall p, p < m -> ~ P p.\nProof.\n  intros.\n  destruct H as [n].\n  apply minimal_exists_aux in H.\n  assumption.\nQed.\n\n\nEnd MINIMAL_EXISTENCE.", "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/shortest-path-problem/minimal_existence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793907, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.8053999159596067}}
{"text": "From Coq Require Export String.\nFrom LF Require Export Basics.\n\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. (* \u867d\u7136\u76ee\u524d\u8fd8\u6ca1\u5565\u95ee\u9898... *)\n  - (* n = S n' *)\n    simpl. (* ...\u4e0d\u8fc7\u6211\u4eec\u53c8\u5361\u5728\u8fd9\u513f\u4e86 *)\nAbort.\n\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* \u8bfe\u4e0a\u5df2\u5b8c\u6210 *)\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(*my proof*)\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  -(* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.\nQed.\n(*my proof*)\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  -(* n = 0 *)\n    destruct m as [| m'] eqn:E.\n    +(* m = 0 *)\n      simpl. reflexivity.\n    +(* m = S m' *)\n      simpl. reflexivity.\n  - (* n = S n' *)\n    destruct m as [| m'] eqn:E.\n    +(* m = 0 *)\n      simpl. rewrite -> IHn'. reflexivity.\n    +(* m = S m' *)\n      simpl. rewrite -> IHn'. reflexivity.\nQed.\n(*my proof*)\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  -(* n = 0 *)\n    induction m as [| m' IHm'].\n    +(* m = 0 *)\n      simpl. reflexivity.\n    +(* m = S m' *)\n      simpl. rewrite <- IHm'. reflexivity.\n  - (* n = S n' *)\n    induction m as [| m' IHm'].\n    +(* m = 0 *)\n      simpl. rewrite -> IHn'. reflexivity.\n    +(* m = S m' *)\n      simpl. rewrite -> IHn'. simpl. rewrite <- plus_n_Sm. reflexivity.\nQed.\n(*my proof*)\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  - simpl. reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n(*my proof*)\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n(*my proof*)\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n. induction n as [| n' IHn'].\n  -(* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n(*my proof*)\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  -(* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    rewrite -> IHn'. simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n\n(* \u8bf7\u52ff\u4fee\u6539\u4e0b\u9762\u8fd9\u4e00\u884c\uff1a *)\nDefinition manual_grade_for_destruct_induction : option (nat*string) := None.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n). { reflexivity. }\n  rewrite -> H.\n  reflexivity. \nQed.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nCheck plus_comm.\n(*forall n m : nat, n + m = m + n*)\nProof.\n  intros n m p q.\n  (* \u6211\u4eec\u53ea\u9700\u8981\u5c06 (m + n) \u4ea4\u6362\u4e3a (n + m)... \u770b\u8d77\u6765 plus_comm \u80fd\u641e\u5b9a\uff01*)\n  rewrite -> plus_comm.\n  (* \u641e\u4e0d\u5b9a... Coq \u9009\u9519\u4e86\u8981\u6539\u5199\u7684\u52a0\u6cd5\uff01 *)\nAbort.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity. Qed.\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n  simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_assoc'' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n(*my proof*)\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. \n  rewrite -> plus_comm.\n  assert (H: p+n=n+p). { rewrite -> plus_comm. reflexivity. }\n  rewrite <- H. rewrite <- plus_assoc'. reflexivity.\nQed. \n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (p + n).\nProof.\n  intros n m p. \n  rewrite -> plus_comm.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed. \n\nTheorem plus_swap'' : forall n m p q : nat,\n  n + m + (p + q)  = n + p + (m+ q).\nProof.\n  intros n m p q.  \n  rewrite <- plus_assoc.\n  assert (H: m + (p + q) = p + (m + q)). \n  { rewrite -> plus_swap. reflexivity. }\n  rewrite -> H. rewrite <- plus_assoc.\n  reflexivity.\nQed. \n\n(* ===> forall n m : nat, n * m + n = n * S m *)\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m as [].\n  - induction n as [].\n    + reflexivity.\n    + simpl. rewrite <- IHn. simpl. \n      reflexivity.\n  - induction n as [].\n    + simpl. rewrite -> IHm. simpl. \n      reflexivity.\n    + simpl. rewrite -> IHm. simpl.\n      rewrite <- mult_n_Sm. simpl.\n      rewrite -> plus_swap'. reflexivity.\nQed.\n\nTheorem leb_refl : forall n:nat,\n  true = (n <= n).\nProof.\n  intros n.\n  simpl. induction n as []. simpl. \n  reflexivity. simpl. apply IHn.\nQed.\nTheorem zero_nbeq_S : forall n:nat,\n  (0 = (S n)) = false.\nProof.\n  intros n.\n  simpl. reflexivity.\nQed.\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros b. destruct b as []. simpl.\n  reflexivity. simpl. reflexivity.\nQed.\nTheorem plus_ble_compat_l : forall n m p : nat,\n  (n <= m) = true -> ((p + n) <= (p + m)) = true.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n m p eq. induction p as []. \n  - simpl. rewrite -> eq. reflexivity.\n  - simpl. rewrite -> IHp. reflexivity.\nQed.\nTheorem S_nbeq_0 : forall n:nat,\n  ((S n) = 0) = false.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n. simpl. reflexivity. \nQed.\nTheorem mult_1_l :forall n:nat, 1* n = n.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n. simpl.\n  induction n as []. \n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn.\n    reflexivity.\nQed.\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n               (negb c))\n  = true.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros b c.\n  destruct b as [].\n  - destruct c as [].\n    * simpl. reflexivity.\n    * simpl. reflexivity.\n  - destruct c as [].\n    * simpl. reflexivity.\n    * simpl. reflexivity.\nQed.\n\n(* mult_n_Sm ===> forall n m : nat, n * m + n = n * S m *)\n\n  \n(*  plus_swap'' ===> forall n m p q : nat,\n  n + m + (p + q)  = n + p + (m+ q) *)\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n m p.\n  induction p as [].\n  - simpl. rewrite <- mult_n_O.\n    rewrite -> mult_n_0_m_0.\n    reflexivity.\n  - simpl. rewrite <- mult_n_Sm. \n    rewrite <- mult_n_Sm. rewrite <- mult_n_Sm.\n    rewrite -> IHp. rewrite -> plus_swap''.\n    reflexivity.\nQed.\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n m p.\n  rewrite -> mult_comm.\n  induction n as [].\n  - simpl. rewrite <- mult_n_O.\n    reflexivity.\n  - simpl. rewrite -> mult_plus_distr_r.\n    rewrite <- IHn. rewrite <- mult_n_Sm.\n    rewrite <- plus_comm. reflexivity.\nQed.\n\nTheorem eqb_refl : forall n : nat,\n  true = (n = n).\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n. induction n as [].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem plus_swap''' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *) \n  intros n m p.\n  rewrite -> plus_assoc''.\n  rewrite -> plus_assoc''.\n  replace (m+n) with (n+m). \n  - reflexivity.\n  - rewrite -> plus_comm. reflexivity.\nQed.\n\nLemma nat_add' : forall n : nat,\n  S (n +S (n+0)) = S (S (n+(n+0))).\nProof.\n  intros n. rewrite <- plus_n_O.\n  rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nLemma  bin_to_nat_pres_incr : forall b : bin , \n  bin_to_nat (incr b) = S (bin_to_nat b). \nProof.\n  intros b.\n  induction b as [].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHb. simpl.\n    rewrite -> nat_add'. reflexivity. \nQed.\n\nFixpoint nat_to_bin (n:nat) : bin :=\n  (* \u5c06\u672c\u884c\u66ff\u6362\u6210 \":= _\u4f60\u7684_\u5b9a\u4e49_ .\" *) \n  match n with\n  |O => Z\n  |S n' => incr (nat_to_bin n')\nend.\n\nCompute (nat_to_bin 8).\n\nTheorem nat_bin_nat : forall n, \n  bin_to_nat (nat_to_bin n) = n.\nProof.\n  (* \u8bf7\u5728\u6b64\u5904\u89e3\u7b54 *)\n  intros n. induction n as [].\n  - simpl. reflexivity. \n  - simpl. rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IHn. reflexivity. \nQed.\n\nFixpoint normalize (b : bin) : bin := \n  match b with\n  |Z=>Z\n  |A b' => match normalize b' with\n           |Z => Z\n           |b'' => A b''\n           end\n  |B b' => B (normalize b')\nend.\n\nCompute (normalize (A (A (A (A Z))))).\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Doughnut09", "repo": "sf_proof", "sha": "7cd8f950b2dd3ed2845bc502ffaaa02c72dc42a4", "save_path": "github-repos/coq/Doughnut09-sf_proof", "path": "github-repos/coq/Doughnut09-sf_proof/sf_proof-7cd8f950b2dd3ed2845bc502ffaaa02c72dc42a4/coq-sf-prove-main/LF/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8053948083723388}}
{"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 len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nFixpoint rotate (rotate_arg0 : Nat) (rotate_arg1 : Lst) : Lst\n           := match rotate_arg0, rotate_arg1 with\n              | zero, x => x\n              | succ n, nil => nil\n              | succ n, cons y x => rotate n (append x (cons y nil))\n              end.\n\nLemma append_nil : forall (x : Lst), append x nil = x.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma append_assoc : forall (x y z : Lst), append (append x y) z = append x (append y z).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (rotate (len x) (append x y)) (append y x).\nProof.\n  induction x.\n  - intros. simpl. rewrite append_nil. reflexivity.\n  - intros. simpl. rewrite append_assoc. rewrite IHx. rewrite append_assoc. simpl. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal83.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8053948036971309}}
{"text": "(** * 6.887 Formal Reasoning About Programs - Lab 1 *)\n\nRequire Import Frap.\n\n(* Authors: Peng Wang (wangpeng@csail.mit.edu), Adam Chlipala (adamc@csail.mit.edu) *)\n\n(** * MapReduce *)\n\n(* *MapReduce* is a popular model for distributed computing in data centers.  See:\n *   https://en.wikipedia.org/wiki/MapReduce\n * But we'll explain our tiny subset of it from scratch here and prove some\n * algebraic properties.  We'll make the simplifying assumption that every\n * MapReduce job starts as a list of natural numbers.  Our goal is to compute\n * some summary of such lists. *)\n\n(* The first step of a MapReduce job is a *map*, which applies a pure function\n * to every element of the input list, producing a new derived list.\n * We can define a syntactic type of allowed map operations. *)\nInductive map_ :=\n| Constant (n : nat)\n| Input \n| Add (e1 e2 : map_)\n| Compose (e1 e2 : map_).\n\n(* After replacing each input element with some new value, we apply some\n * operator repeatedly to reduce to a final summary.  Here are the operators\n * supported in our modest simplification. *)\nInductive reduce :=\n| Sum\n| Max.\n\n(* Paired together, they form a whole MapReduce task. *)\nDefinition mapReduce := (map_ * reduce)%type.\n                           (* ^-- pair type *)\n\n(* Here's what a [map_] does to a number. *)\nFixpoint interp_map (e : map_) (x : nat) : nat :=\n  match e with\n  | Constant n => n\n  | Input => x\n  | Add e1 e2 => interp_map e1 x + interp_map e2 x\n  | Compose e1 e2 => interp_map e1 (interp_map e2 x)\n  end.\n\n(* And here's what a [reduce] does to a list of numbers. *)\nDefinition interp_reduce (e : reduce) (ls : list nat) : nat :=\n  match e with\n  | Sum => fold_left plus ls 0\n  | Max => fold_left max ls 0\n  end.\n(* It may be helpful to examine the definition of [fold_left]. *)\nPrint fold_left.\n\n\n\n(* Now we have the overall MapReduce job executor. *)\nDefinition interp_mr (e : mapReduce) ls :=\n  interp_reduce (snd e) (map (interp_map (fst e)) ls).\n              (* ^-- projection functions --^ *)\n\n(* Here's a simple condition on a [map_], capturing when it only contains\n * positive constants.  That will imply that, given a positive input, the\n * output is also positive, which you will prove, as specified below. *)\nFixpoint allPositive (m : map_) : Prop :=\n  match m with\n  | Constant n => n > 0\n  | Input => True\n  | Add m1 m2 => allPositive m1 /\\ allPositive m2\n  | Compose m1 m2 => allPositive m1 /\\ allPositive m2\n  end.\n\n\n(* Finally, the module type listing the theorems that we ask you to prove. *)\nModule Type S.\n  (* Prove that [allPositive] means what we want it to mean. *)\n  Axiom allPositive_ok : forall (m : map_) (x : nat),\n    allPositive m\n    -> x > 0\n    -> interp_map m x > 0.\n\n  (* Input order is irrelevant to the results of MapReduce jobs. *)\n  Axiom reduce_swap : forall (e : reduce) (ls1 ls2 : list nat),\n    interp_reduce e (ls1 ++ ls2) = interp_reduce e (ls2 ++ ls1).\n  Axiom interp_swap : forall (e : mapReduce) (ls1 ls2 : list nat),\n    interp_mr e (ls1 ++ ls2) = interp_mr e (ls2 ++ ls1).\n  (* Note that a list of length [n] can, in general, be expressed as [n+1]\n   * different concatenations of other lists.  These theorems tell us that\n   * swapping at any split point in the input list preserves output values.\n   * Iterating these results shows that any permutation on an input list leads\n   * to the same output. *)\n\n  (* Furthermore, we can decompose computation into arbitrary treelike structures.\n   * That is, we can break the input list into chunks, or *partitions*, and\n   * reduce them separately, then do a further reduce on those results.\n   * Imagine a different server in a cluster assigned to each partition, so that\n   * they can all run in parallel, saving significant time over treating the\n   * whole input list sequentially. *)\n  Axiom mapReduce_partition_two : forall (m : map_) (r : reduce) (ls1 ls2 : list nat),\n    interp_mr (m, r) (ls1 ++ ls2) = interp_reduce r [interp_mr (m, r) ls1; interp_mr (m, r) ls2].\n  Arguments app {_} _ _ . (* Some magic to allow us to use [app] below,\n                           * without specifying its type parameter *)\n  Axiom mapReduce_partition : forall (m : map_) (r : reduce) (lsls : list (list nat)),\n    interp_mr (m, r) (fold_left app lsls []) = interp_reduce r (map (interp_mr (m, r)) lsls).\n  (* Note that here [lsls], a list of lists, expresses an arbitrary division of\n   * a list into contiguous partitions. *)\n  \nEnd S.\n\n\n(* That's the end of the required part of this assignment.\n * Since we are still working on gauging difficulty, we're also including\n * another, optional part, in case you are looking for something else to do!\n * When you submit your solution, we'll appreciate your feedback on whether we\n * should have made this next part required. *)\n\n(** * Interpreting unbounded loops *)\n\n(* First, let's copy in the last lecture's interpreter for a loopy language. *)\n\nInductive arith : Set :=\n| Const (n : nat)\n| Var (x : var)\n| Plus (e1 e2 : arith)\n| Minus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\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 (* 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  | Times e1 e2 => interp e1 v * interp e2 v\n  end.\n\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : arith)\n| Sequence (c1 c2 : cmd)\n| Repeat (e : arith) (body : cmd).\n\nFixpoint selfCompose {A} (f : A -> A) (n : nat) : A -> A :=\n  match n with\n  | O => fun x => x\n  | S n' => fun x => selfCompose f n' (f x)\n  end.\n\nFixpoint exec (c : cmd) (v : valuation) : valuation :=\n  match c with\n  | Skip => v\n  | Assign x e => v $+ (x, interp e v)\n  | Sequence c1 c2 => exec c2 (exec c1 v)\n  | Repeat e body => selfCompose (exec body) (interp e v) v\n  end.\n\n(* That's the end of the copied code.  Next, we define a popular optimization\n * for languages of this type: *constant propagation*, which infers that certain\n * variables hold known values at certain points, so that mentions of those\n * variables can be *replaced* with constants. *)\n\n(* This function applies constant propagation to an arithmetic expression.\n * It takes a variable valuation as an argument.  Recall that valuations are\n * *partial* finite maps; not all variables will be present.  In fact, even\n * fewer variables will be present than for the interpreter: we only include\n * mappings for those variables *whose values are known at compile time*.\n * Those are exactly the variables that we should replace in the expression! *)\nFixpoint constPropArith (e : arith) (v : valuation) : arith :=\n  match e with\n  | Const _ => e\n  | Var x => match v $? x with\n             | None => e\n             | Some n => Const n (* Found a replaceable variable! *)\n             end\n  | Plus e1 e2 =>\n    let e1' := constPropArith e1 v in\n    let e2' := constPropArith e2 v in\n    match e1', e2' with\n    | Const n1, Const n2 => Const (n1 + n2)\n    | _, _ => Plus e1' e2'\n    end\n  | Minus e1 e2 =>\n    let e1' := constPropArith e1 v in\n    let e2' := constPropArith e2 v in\n    match e1', e2' with\n    | Const n1, Const n2 => Const (n1 - n2)\n    | _, _ => Minus e1' e2'\n    end\n  | Times e1 e2 =>\n    let e1' := constPropArith e1 v in\n    let e2' := constPropArith e2 v in\n    match e1', e2' with\n    | Const n1, Const n2 => Const (n1 * n2)\n    | _, _ => Times e1' e2'\n    end\n  end.\n\n(* Crucial helper function.  It takes in a valuation assigning constant values\n * to those variables where we can figure out the constants.  It then models how\n * that knowledge *changes* based on the effect of a command. *)\nFixpoint effectOf (c : cmd) (v : valuation) : valuation :=\n  match c with\n  | Skip => v\n  | Assign x e =>\n    let e' := constPropArith e v in\n    match e' with\n    | Const n =>\n      v $+ (x, n)\n      (* We inferred the value that is being assigned.\n       * Record that knowledge in the valuation. *)\n    | _ =>\n      v $- x\n      (* We couldn't be sure what value is assigned.\n       * Conservatively, *remove* this variable from the valuation.\n       * (Note the use of a new infix operator for removal.) *)\n    end\n  | Sequence c1 c2 =>\n    effectOf c2 (effectOf c1 v)\n    (* Crucial pattern: we take the effect of [c1], followed by the effect of\n     * [c2]. *)\n  | Repeat _ _ => $0\n    (* It would take much more advanced analysis to summarize the effect of a\n     * loop, so let's punt and return an empty set of knowledge. *)\n  end.\n\n(* OK, we come to the main transformation, parameterized on knowledge, like the\n * other functions have been. *)\nFixpoint constProp (c : cmd) (v : valuation) : cmd :=\n  match c with\n  | Skip => c\n  | Assign x e => Assign x (constPropArith e v)\n  | Sequence c1 c2 =>\n    Sequence (constProp c1 v) (constProp c2 (effectOf c1 v))\n    (* Here we have a crucial use of [effectOf], to expand the knowledge as we\n     * descend into the second command. *)\n  | Repeat e c1 =>\n    Repeat (constPropArith e v) (constProp c1 $0)\n    (* Again, because analyzing loops is beyond our intentions, we reset\n     * knowledge to empty as we descend into the loop body. *)\n  end.\n\n(* You may remember this helpful lemma from class.\n * It's likely to come in handy again here. *)\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(* Finally, we come to your task: prove this fact. *)\nDefinition whatToProve := forall (c : cmd) (v1 v2 : valuation),\n  (* [v1] captures compile-time knowledge of variable values,\n   * while [v2] captures the full runtime knowledge.\n   * The premise here captures that [v1] includes a subset of the mappings known\n   * in [v2]. *)\n  (forall x n, v1 $? x = Some n -> v2 $? x = Some n)\n  (* Given that premise, we conclude that constant propagation doesn't change\n   * the semantics of commands. *)\n  -> exec (constProp c v1) v2 = exec c v2.\n", "meta": {"author": "emzhang", "repo": "887psets", "sha": "7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918", "save_path": "github-repos/coq/emzhang-887psets", "path": "github-repos/coq/emzhang-887psets/887psets-7b5c19f2eb0b0e549f10fa7bcbb1c873e5a77918/pset1/Pset1Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8052107892285165}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Category.\nRequire Import Category.Opposite.\n\nLocal Open Scope morphism_scope.\n\n(** The basic Definition of an isomorphism in a category.\nAn isomorphism is a pair of arrows f : a -> b and g : b -> a such that g \u2218 f = id a and f \u2218 g = id b. *)\nRecord Isomorphism {C : Category} (a b : C) : Type := \n{\n  iso_morphism : a \u2013\u227b b;\n  \n  inverse_morphism : b \u2013\u227b a;\n  \n  left_inverse : (inverse_morphism \u2218 iso_morphism)%morphism = id;\n  \n  right_inverse : (iso_morphism \u2218 inverse_morphism)%morphism = id\n}.\n\n\nBind Scope morphism_scope with Isomorphism.\nBind Scope isomorphism_scope with Isomorphism.\n\nHint Resolve left_inverse.\n\nHint Resolve right_inverse.\n\nCoercion iso_morphism : Isomorphism >-> Hom.\n\nArguments iso_morphism {_ _ _} _.\nArguments inverse_morphism {_ _ _} _.\nArguments left_inverse {_ _ _} _.\nArguments right_inverse {_ _ _} _.\n\nNotation \"f '\u207b\u00b9'\" := (inverse_morphism f) : morphism_scope.\n\nNotation \"a \u2243 b\" := (Isomorphism a b) : isomorphism_scope.\n\nNotation \"a \u2243\u2243 b ::> C\" := (@Isomorphism C a b) : isomorphism_scope.\n\nLocal Open Scope isomorphism_scope.\n\n(* basic tactics for isomorphisms *)\n\nLtac simpl_isos_in_goal :=\n  repeat(\n      match goal with\n        | [|- context[(iso_morphism ?A \u2218 inverse_morphism ?A)%morphism]] => rewrite (right_inverse A); simpl_ids\n        | [|- context[(inverse_morphism ?A \u2218 iso_morphism ?A)%morphism] ] => rewrite (left_inverse A); simpl_ids\n(* disabled due to problems with reveal_comp complexity *)\n(*        | [|- context[iso_morphism ?A] ] =>\n          reveal_comp (inverse_morphism A) (iso_morphism A) +\n          reveal_comp (iso_morphism A) (inverse_morphism A) *)\n      end\n    )\n.\n\nLtac simpl_isos_in_I I :=\n  repeat(\n      match type of I with\n        | context[(iso_morphism ?A \u2218 inverse_morphism ?A)%morphism] => rewrite (right_inverse A) in I; simpl_ids in I\n        | context[(inverse_morphism ?A \u2218 iso_morphism ?A)%morphism] => rewrite (left_inverse A) in I; simpl_ids in I\n(* disabled due to problems with reveal_comp complexity *)\n(*        | context[inverse_morphism ?A] =>\n          reveal_comp (inverse_morphism A) (iso_morphism A) in I +\n          reveal_comp (iso_morphism A) (inverse_morphism A) in I *)\n      end\n    )\n.\n\nTactic Notation \"simpl_isos\" := simpl_isos_in_goal.\n\nTactic Notation \"simpl_isos\" \"in\" hyp(I) := simpl_isos_in_I I.\n\nHint Extern 3 => progress simpl_isos.\n\nHint Extern 3 => progress (dohyps (fun H => simpl_isos in H)).\n\n(** simplifies equality of iso-morphisms. This theorem uses proof irrelevance to assume any two proofs for left and right inverse properties are equal.\nIn other words, two isomorphisms are equal if their underlying morphisms are. *)\nTheorem Isomorphism_eq_simplify {C : Category} {a b : C} (I I' : a \u2243 b) : (iso_morphism I = iso_morphism I') \u2192 (inverse_morphism I = inverse_morphism I') \u2192 I = I'.\nProof.\n  intros H1 H2.\n  destruct I as [iI inI Il Ir]; destruct I' as [iI' inI' Il' Ir'].\n  cbn in *.\n  ElimEq.\n  doHomPIR.\n  trivial.  \nQed.\n\n(** Isomorphism is an equivalence relation on objects. *)\n\n(** The identity morphism forms an isomorphism, i.e., it is inverse to itself.\nThis is reflexivity property for the equivalence relation of isomorphism on objects. *)\nProgram Definition Isomorphism_id {C : Category} {a : C} : a \u2243 a :=\n{|\n  iso_morphism := id;\n  inverse_morphism := id\n|}.\n\n(** Each ismorphism has an inverse isomorphism. Simply swap the morphisms and proofs of left and right inverse properties.\nThis is symmetry property for the equivalence relation of isomorphism on objects. *)\nDefinition Inverse_Isomorphism {C : Category} {a b : C} (I : a \u2243 b) : b \u2243 a :=\n{|\n  iso_morphism := I\u207b\u00b9;\n  inverse_morphism := I;\n  left_inverse := right_inverse I;\n  right_inverse := left_inverse I\n|}.\n\nNotation \"f '\u207b\u00b9'\" := (Inverse_Isomorphism f) : isomorphism_scope.\n\n(** Isomorphisms compose. Simply compose the underlying morphisms of the isomorphism. Left and right inverse properties follow straightforwardly.\nThis is transitivty property for the equivalence relation of isomorphism on objects. *)\nProgram Definition Isomorphism_Compose\n        {C : Category} {a b c : C} (I : a \u2243 b) (I' : b \u2243 c) : a \u2243 c\n  :=\n{|\n  iso_morphism := I' \u2218 I;\n  inverse_morphism := I\u207b\u00b9 \u2218 I'\u207b\u00b9\n|}.\n\nNext Obligation.\nProof.\n  rewrite assoc.\n  rewrite (assoc_sym I).\n  auto.\nQed.\n\nNext Obligation.\nProof.\n  rewrite assoc.\n  rewrite (assoc_sym (I'\u207b\u00b9)).\n  auto.\nQed.\n\nNotation \"f \u2218 g\" := (Isomorphism_Compose g f) : isomorphism_scope.\n\nLocal Close Scope isomorphism_scope.\n\n(** A monic arrow (AKA, mono, monomorphic arrow and monomorphism) m is an arrow such that for any two arrows g and h (of the appropriate domain and codomain) we have if m \u2218 g = m \u2218 h then g = h. *)\nRecord Monic {C : Category} (a b : Obj) :=\n{\n  mono_morphism : a \u2013\u227b b;\n  mono_morphism_monomorphic : \u2200 (c : Obj) (g h : c \u2013\u227b a), (mono_morphism \u2218 g = mono_morphism \u2218 h) \u2192 g = h\n}.\n\nCoercion mono_morphism : Monic >-> Hom.\n\nArguments mono_morphism {_ _ _} _.\nArguments mono_morphism_monomorphic {_ _ _} _ _ _ _ _.\n\nNotation \"a \u226b\u2013> b\" := (Monic a b) : morphism_scope.\n\nBind Scope morphism_scope with Monic.\n\n(** An epic arrow (AKA, epi, epimorphic arrow and epimorphism) is a monomorphism in the opposite category. That is, m is epic if for any pair of arrows g and h (of the appropriate domain and codomain) we have if g \u2218 m = h \u2218 m then g = h. *)\nDefinition Epic {C : Category} (a b : C) := @Monic (C^op) b a.\n\nNotation \"a \u2013\u226b b\" := (Epic a b) : morphism_scope.\n\nBind Scope morphism_scope with Epic.\n\n(** The condition for a morphism to be mono-morphic. *)\nDefinition is_Monic {C : Category} {a b : Obj} (f : a \u2013\u227b b) :=\n  \u2200 (c : Obj) (g h : c \u2013\u227b a), (f \u2218 g = f \u2218 h) \u2192 g = h.\n\n(** A mono-morphic morphism forms a Monic. *)\nDefinition is_Monic_Monic\n           {C : Category}\n           {a b : Obj}\n           {f : a \u2013\u227b b}\n           (H : is_Monic f)\n  : Monic a b\n  :=\n    {|\n      mono_morphism := f;\n      mono_morphism_monomorphic := H\n    |}\n.\n\n(** A morphism is ipic if it is monic in the opposit category. *)\nDefinition is_Epic {C : Category} {a b : C} (f : a \u2013\u227b b) := @is_Monic (C^op) b a f.\n\n(** A morphism f : a \u2013\u227b b is split monic if there is another morphism\ng : b \u2013\u227b a such that g \u2218 f = id\u2090 *)\nRecord is_split_Monic {C : Category} {a b : Obj} (f : a \u2013\u227b b) :=\n  {\n    is_split_monic_left_inverse : b \u2013\u227b a;\n    is_split_monic_left_inverse_is_left_inverse :\n      (is_split_monic_left_inverse \u2218 f) = id\n  }\n.\n\nArguments is_split_monic_left_inverse {_ _ _ _} _.\nArguments is_split_monic_left_inverse_is_left_inverse {_ _ _ _} _.\n\n(** A morphism is ipic if it is monic in the opposit category. *)\nDefinition is_split_Epic {C : Category} {a b : C} (f : a \u2013\u227b b) := @is_split_Monic (C^op) b a f.\n\n(** A split monic morphism is a monomorphism. *)\nProgram Definition is_split_Monic_Monic\n           {C : Category}\n           {a b : Obj}\n           {f : a \u2013\u227b b}\n           (H : is_split_Monic f)\n  : Monic a b\n  :=\n    {|\n      mono_morphism := f;\n      mono_morphism_monomorphic := fun c g h H1 => _\n    |}\n.\n\nNext Obligation.\nProof.\n  assert (H2 := f_equal (fun w : c \u2013\u227b b => (is_split_monic_left_inverse H) \u2218 w) H1).\n  cbn in H2.\n  repeat rewrite assoc_sym in H2.\n  rewrite is_split_monic_left_inverse_is_left_inverse in H2.\n  auto.\nQed.\n\n(** If a monic morphism is split epic, it forms an isomorphism. *)\nProgram Definition Monic_is_split_Epic_Iso\n        {C : Category}\n        (a b : Obj)\n        (f : a \u226b\u2013> b)\n        (H : is_split_Epic f)\n  :\n    (a \u2243 b)%isomorphism\n  :=\n    {|\n      iso_morphism := f;\n      inverse_morphism := is_split_monic_left_inverse H;\n      right_inverse := is_split_monic_left_inverse_is_left_inverse H\n    |}\n.\n\nNext Obligation.\nProof.\n  apply (mono_morphism_monomorphic f).\n  rewrite assoc_sym.\n  cbn_rewrite (is_split_monic_left_inverse_is_left_inverse H).\n  auto.\nQed.\n\n(** If both g and (f \u2218 g) are monic, then so is f. *)\nProgram Definition Compose_Monic_is_Monic_then_Monic\n           {C : Category}\n           {a b c : C}\n           (M : a \u2013\u227b b)\n           (M' : b \u226b\u2013> c)\n           (H : is_Monic (M' \u2218 M))\n  :\n    Monic a b\n  :=\n    {|\n      mono_morphism := M;\n      mono_morphism_monomorphic := fun d g h H1 => _\n    |}\n.\n\nNext Obligation.\nProof.\n  assert (H2 := f_equal (fun w : d \u2013\u227b b => M' \u2218 w) H1).\n  cbn in H2.\n  repeat rewrite assoc_sym in H2.\n  apply H; trivial.\nQed.\n\n(** Monomorphisms compose. The case for epis follows by duality.*)\nSection Mono_compose.\n  Context {C : Category} {a b c : C} (M : a \u226b\u2013> b) (M' : b \u226b\u2013> c).\n\n  Local Hint Resolve mono_morphism_monomorphic.\n\n  Local Obligation Tactic := eauto.\n  \n  Program Definition Mono_compose : a \u226b\u2013> c :=\n    {|\n      mono_morphism := M' \u2218 M\n    |}.\n    \nEnd Mono_compose.\n\nLocal Open Scope isomorphism_scope.\n\n(** An isomorphism is both monic and epic. *)\nSection Iso_Mono_Epi.\n  Context {C : Category} {a b : Obj} (I : a \u2243 b).\n\n  Program Definition Ismorphism_Monic : a \u226b\u2013> b :=\n    {|\n      mono_morphism := I\n    |}.\n\n  Next Obligation. (* mono_morphism_monomorphism *)\n  Proof.\n    match goal with\n        [ H : (_ \u2218 ?f = _ \u2218 ?f')%morphism |- ?f = ?f'] =>\n        match type of H with\n            ?A = ?B =>\n            let H' := fresh \"H\" in\n            cut (I\u207b\u00b9 \u2218 A = I\u207b\u00b9 \u2218 B)%morphism; [auto | rewrite H; trivial]\n        end\n    end.\n    repeat rewrite assoc_sym.\n    auto.\n  Qed.\n\n  Program Definition Ismorphism_Epic : b \u2013\u226b a :=\n    {|\n      mono_morphism := inverse_morphism I\n    |}.\n  Next Obligation. (* epi_morphism_epimorphism *)\n  Proof.\n    match goal with\n        [ H : (?f \u2218 _ = ?f' \u2218 _)%morphism |- ?f = ?f'] =>\n        match type of H with\n            ?A = ?B =>\n            let H' := fresh \"H\" in\n            cut (A \u2218 I = B \u2218 I)%morphism; [auto | rewrite H; trivial]\n        end\n    end.\n    repeat rewrite assoc.\n    auto.\n  Qed.\n\nEnd Iso_Mono_Epi.\n\n(** If two objects are isomorphic in category C then they are also isomorphic in C^op. *)\nTheorem CoIso {C : Category} (a b : C) : a \u2243\u2243 b ::> C \u2192 a \u2243\u2243 b ::> C^op. \nProof.\n  intros I.\n  eapply (Build_Isomorphism (C^op)%category _ _ (I\u207b\u00b9) I); unfold compose; simpl; auto.\nQed.", "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/Category/Morph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8887587890727755, "lm_q1q2_score": 0.805206420188165}}
{"text": "Require Export List.\nRequire Export Omega.\n\nModule Type Comparable_data.\nParameter A : Type.\nParameter Ale : A -> A -> Prop.\nParameter Ale_dec : forall x y:A, {Ale x y} + {Ale y x}.\nEnd Comparable_data.\n\nModule Type SORTING_BASICS.\nParameter A : Type.\nParameter Ale : A -> A -> Prop.\nParameter Ale_dec : forall x y:A, {Ale x y} + {Ale y x}.\nParameter sort : list A -> list A.\n\nInductive sorted : list A -> Prop :=\n  | sorted0 : sorted nil\n  | sorted1 : forall x:A, sorted (x :: nil)\n  | sorted2 :\n      forall (x y:A) (l:list A),\n        Ale x y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nInductive permutation : list A -> list A -> Prop :=\n  | transpose_first :\n      forall (a b:A) (l:list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_same_head :\n      forall (a:A) (l1 l2:list A),\n        permutation l1 l2 -> permutation (a :: l1) (a :: l2)\n  | permutation_empty : permutation nil nil\n  | permutation_transitive :\n      forall l1 l2 l3:list A,\n        permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\n\nParameter sort_sorted : forall l:list A, sorted (sort l).\n\nParameter sort_permutation : forall l:list A, permutation (sort l) l.\n\nEnd SORTING_BASICS.\n\nModule merge_sort_basics (Data: Comparable_data) : \n  SORTING_BASICS \n  with   Definition A := Data.A \n  with Definition Ale := Data.Ale \n  with Definition  Ale_dec := Data.Ale_dec.\n\nDefinition A := Data.A.\nDefinition Ale := Data.Ale.\nDefinition Ale_dec := Data.Ale_dec.\n\nFixpoint merge_aux (l1 l2:list A) (b:nat) {struct b} : \n list A :=\n  match b with\n  | O => nil (A:=A)\n  | S b' =>\n      match l1, l2 with\n      | nil, l => l\n      | l, nil => l\n      | a :: l, b :: l' =>\n          match Ale_dec a b with\n          | left _ => a :: merge_aux l (b :: l') b'\n          | right _ => b :: merge_aux (a :: l) l' b'\n          end\n      end\n  end.\n\nDefinition merge (l1 l2:list A) := merge_aux l1 l2 (length l1 + length l2).\n\n(* Make a list of singleton lists to initiate merging. *)\n\nFixpoint mk_singletons (l:list A) : list (list A) :=\n  match l with\n  | nil => nil (A:=(list A))\n  | a :: tl => (a :: nil) :: mk_singletons tl\n  end.\n\n(* Given a list of lists, merge the first with the second,\n  then the third with the fourth, and so on. *)\n\nFixpoint sort_aux1 (l:list (list A)) : list (list A) :=\n  match l with\n  | l1 :: l2 :: tl => merge l1 l2 :: sort_aux1 tl\n  | _ => l\n  end.\n\n\nFixpoint sort_aux2 (l:list (list A)) (b:nat) {struct b} : \n list A :=\n  match b with\n  | O => nil (A:=A)\n  | S b' =>\n      match l with\n      | nil => nil (A:=A)\n      | l' :: nil => l'\n      | _ => sort_aux2 (sort_aux1 l) b'\n      end\n  end.\n\nDefinition sort (l:list A) := sort_aux2 (mk_singletons l) (length l).\n\n(* In principle the exercise stops here.  But what follows is\n  used to ensure that the sorting function we have defined does really\n  sort a list of data. *)\n\nInductive sorted : list A -> Prop :=\n  | sorted0 : sorted nil\n  | sorted1 : forall x:A, sorted (x :: nil)\n  | sorted2 :\n      forall (x y:A) (l:list A),\n        Ale x y -> sorted (y :: l) -> sorted (x :: y :: l).\n\n\nTheorem sorted_inv : forall (a:A) (l:list A), sorted (a :: l) -> sorted l.\nProof.\n intros a l H; inversion H; assumption || constructor.\nQed.\n\n\nInductive all_sorted : list (list A) -> Prop :=\n  | all_sorted_nil : all_sorted nil\n  | all_sorted_rec :\n      forall (l:list A) (tl:list (list A)),\n        sorted l -> all_sorted tl -> all_sorted (l :: tl).\n\nTheorem mk_singletons_all_sorted :\n forall l:list A, all_sorted (mk_singletons l).\nProof.\n intros l; elim l; simpl in |- *; repeat (intros; constructor || assumption).\nQed.\n\nTheorem mk_singletons_length :\n forall l:list A, length (mk_singletons l) = length l.\nProof.\n simple induction l; simpl in |- *; auto.\nQed.\n\nInductive first_elem_prop : list A -> list A -> list A -> Prop :=\n  | all_empty : first_elem_prop nil nil nil\n  | fep_first :\n      forall (a:A) (l1 l2 l3:list A), \n        first_elem_prop (a :: l1) l2 (a :: l3)\n  | fep_second :\n      forall (a:A) (l1 l2 l3:list A), \n       first_elem_prop l1 (a :: l2) (a :: l3).\n\nTheorem merge_aux_sorted :\n forall (b:nat) (l1 l2:list A),\n   length l1 + length l2 <= b ->\n   sorted l1 ->\n   sorted l2 ->\n   sorted (merge_aux l1 l2 b) /\\ \n   first_elem_prop l1 l2 (merge_aux l1 l2 b).\nProof.\n intros b; elim b.\n -  intros l1 l2.\n    case l1; case l2; simpl in |- *;\n    try (intros; match goal with\n                   | id:(S _ <= _) |- _ => inversion id; fail\n                 end).\n    repeat constructor.\n\n -  intros b' Hrec l1; case l1.\n    simpl in |- *; intros; split; [ assumption | case l2; constructor ].\n    intros a l l2; case l2.\n    +  simpl in |- *; intros; split; [ assumption | constructor ].\n    +  simpl in |- *; intros a' l' Hle Hsorted1 Hsorted2; case (Ale_dec a a').\n       *  elim (Hrec l (a' :: l')); auto.\n          intros Hsorted' Hfep.\n          generalize Hsorted' Hsorted1 Hsorted2; clear Hsorted1 Hsorted2 Hsorted'. \n          inversion Hfep.\n          intros Hsorted' Hsorted1 Hsorted2 Hale.\n          inversion Hsorted1; repeat constructor || assumption.\n          intros Hsorted' Hsorted1 Hsorted2 Hale.\n          inversion Hsorted2; repeat constructor || assumption.\n          simpl in |- *; omega.\n          eapply sorted_inv; eauto.\n       * elim (Hrec (a :: l) l'); auto.\n         intros Hsorted' Hfep.\n         generalize Hsorted' Hsorted1 Hsorted2; clear Hsorted1 Hsorted2 Hsorted'. \n         inversion Hfep.\n         intros Hsorted' Hsorted1 Hsorted2 Hale.\n         inversion Hsorted1; repeat constructor || assumption.\n         intros Hsorted' Hsorted1 Hsorted2 Hale.\n         inversion Hsorted2; repeat constructor || assumption.\n         simpl in |- *; omega.\n         eapply sorted_inv; eauto.\nQed.\n\nTheorem merge_sorted :\n forall l1 l2:list A, sorted l1 -> sorted l2 -> sorted (merge l1 l2).\nProof.\n unfold merge in |- *; intros l1 l2 H1 H2; \n  elim (merge_aux_sorted (length l1 + length l2) l1 l2);\n  auto.\nQed.\n\n(* sort_aux1 has a multiple recursion step, we need a\n   specific induction principle to work on this function. *)\n\nTheorem list_ind2 :\n forall (B:Type) (P:list B -> Prop),\n   P nil ->\n   (forall x:B, P (x :: nil)) ->\n   (forall (x1 x2:B) (l:list B), P l -> P (x1 :: x2 :: l)) ->\n   forall l:list B, P l.\nProof.\n intros B P P0 P1 Pr l;assert (H: P l /\\  forall x:B, P (x :: l)) by\n     (elim l; intuition).\n now destruct H. \nQed.\n\nTheorem sort_aux1_all_sorted :\n forall l:list (list A), all_sorted l -> all_sorted (sort_aux1 l).\nProof.\n intros l; elim l using list_ind2.\n -  simpl in |- *; trivial.\n -  simpl in |- *; trivial.\n -  intros x1 x2 tl Hrec Has; inversion Has; clear Has.\n     match goal with\n       | id:(all_sorted _) |- _ => inversion id\n     end.\n     simpl in |- *; constructor.\n     + apply merge_sorted; auto.\n     +  auto.\nQed.\n\nTheorem sort_aux1_shorter :\n forall l:list (list A), length (sort_aux1 l) <= length l.\nProof.\n intros l; elim l using list_ind2; simpl in |- *; auto with arith.\nQed.\n\nTheorem sort_aux2_sorted :\n forall (b:nat) (l:list (list A)),\n   length l <= b -> all_sorted l -> sorted (sort_aux2 l b).\nProof.\n induction b as [ | b IHb].\n -  intros l; case l.\n  +  intros; constructor.\n  +  simpl in |- *; intros a l' Hle; inversion Hle.\n - intro  l; case l.\n   +  simpl in |- *; intros; constructor.\n   +  intros l1 tl; case tl.\n      *  intros Hle Has; inversion Has; assumption.\n      *  simpl in |- *; intros l2 tl' Hle Has; apply IHb.\n         simpl in |- *.\n         generalize (sort_aux1_shorter tl'); intros; omega.\n         inversion Has; clear Has.\n         match goal with\n           | id:(all_sorted _) |- _ => inversion id\n         end.\n         constructor.\n         apply merge_sorted; assumption.\n         apply sort_aux1_all_sorted; assumption.\nQed.\n\nTheorem sort_sorted : forall l:list A, sorted (sort l).\nProof.\n intros l; unfold sort in |- *.\n apply sort_aux2_sorted.\n rewrite mk_singletons_length; auto.\n apply mk_singletons_all_sorted.\nQed.\n\nInductive permutation : list A -> list A -> Prop :=\n  | transpose_first :\n      forall (a b:A) (l:list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_same_head :\n      forall (a:A) (l1 l2:list A),\n        permutation l1 l2 -> permutation (a :: l1) (a :: l2)\n  | permutation_empty : permutation nil nil\n  | permutation_transitive :\n      forall l1 l2 l3:list A,\n        permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\n        \nTheorem permutation_reflexive : forall l:list A, permutation l l.\nProof.\n intros l; elim l; constructor; assumption.\nQed.\n\nTheorem permutation_symmetric :\n forall l1 l2:list A, permutation l1 l2 -> permutation l2 l1.\nProof.\n intros l1 l2 H; elim H; try (intros; constructor; assumption).\n intros l3 l4 l5; intros; apply permutation_transitive with l4; \n  assumption.\nQed.\n\nTheorem permutation_app_cons :\n forall (l:list A) (a:A) (l':list A),\n   permutation (l ++ a :: l') (a :: l ++ l').\nProof.\n intros l; elim l.\n simpl in |- *; intros; apply permutation_reflexive.\n simpl in |- *; intros a' tl Hrec a l'.\n apply permutation_transitive with (a' :: a :: tl ++ l'); \n  constructor; auto.\nQed.\n\nTheorem merge_aux_permutation :\n forall (b:nat) (l1 l2:list A),\n   length l1 + length l2 <= b -> \n   permutation (merge_aux l1 l2 b) (l1 ++ l2).\nProof.\n intros b; elim b.\n -  intros l1 l2; case l1; case l2;\n    try\n      (simpl in |- *; intros;\n       match goal with\n         | id:(S _ <= _) |- _ => inversion id; fail\n       end).\n    simpl in |- *; constructor.\n -  intros b' Hrec l1 l2; case l1.\n    simpl in |- *; intros Hle; apply permutation_reflexive.\n    + simpl in |- *; intros a l; case l2.\n      simpl in |- *; intros Hle; rewrite <- app_nil_end;\n      apply permutation_reflexive.\n      simpl in |- *; intros a' l'; case (Ale_dec a a').\n      * intros Hale Hle;\n        apply permutation_transitive with (a :: a' :: l ++ l').\n        apply permutation_same_head.\n        apply permutation_transitive with (l ++ a' :: l').\n        apply (Hrec l (a' :: l')).\n        simpl in |- *; omega.\n        apply permutation_app_cons.\n        constructor.\n        apply permutation_symmetric.\n        apply permutation_app_cons.\n      *  intros Hale Hle.\n         apply permutation_transitive with (a' :: a :: l ++ l').\n         apply permutation_same_head.\n         apply (Hrec (a :: l) l').\n         simpl in |- *; omega.\n         apply permutation_transitive with (a :: a' :: l ++ l').\n         constructor.\n         apply permutation_same_head.\n         apply permutation_symmetric.\n         apply permutation_app_cons.\nQed.\n\nTheorem merge_permutation :\n forall l1 l2:list A, permutation (merge l1 l2) (l1 ++ l2).\nProof.\n unfold merge in |- *; intros l1 l2; apply merge_aux_permutation; auto.\nQed.\n\nFixpoint app_all (l:list (list A)) : list A :=\n  match l with\n  | nil => nil (A:=A)\n  | l1 :: tl => l1 ++ app_all tl\n  end.\n\nTheorem app_all_mk_singletons_eq :\n forall l:list A, app_all (mk_singletons l) = l.\nProof.\n intros l; elim l; simpl in |- *; auto.\n intros a l' Hrec; rewrite Hrec; auto.\nQed.\n\nTheorem permutation_app :\n forall l1 l2:list A, permutation (l1 ++ l2) (l2 ++ l1).\nProof.\n intros l1; elim l1; simpl in |- *.\n -  intros l2; rewrite <- app_nil_end.\n     apply permutation_reflexive.\n - intros a tl Hrec l2.\n   apply permutation_transitive with (a :: l2 ++ tl).\n   +  apply permutation_same_head.\n      apply Hrec.\n   + apply permutation_symmetric; apply permutation_app_cons.\nQed.\n\nTheorem permutation_long_head :\n forall l1 l2 l3:list A,\n   permutation l2 l3 -> permutation (l1 ++ l2) (l1 ++ l3).\nProof.\n intros l1; elim l1; simpl in |- *; auto.\n intros a l1' Hrec l2 l3 H.\n  constructor; auto.\nQed.\n\nTheorem permutation_app4 :\n forall l1 l2 l3 l4:list A,\n   permutation l1 l2 ->\n   permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nProof.\n intros l1 l2 l3 l4 H H0.\n apply permutation_transitive with (l1 ++ l4).\n -  apply permutation_long_head; assumption.\n -  apply permutation_transitive with (l4 ++ l1).\n    +  apply permutation_app.\n    +  apply permutation_transitive with (l4 ++ l2).\n     *  apply permutation_long_head; assumption.\n     * apply permutation_app.\nQed.\n\nTheorem sort_aux1_permutation :\n forall l:list (list A), permutation (app_all (sort_aux1 l)) (app_all l).\nProof.\n intros l; elim l using list_ind2.\n -  simpl in |- *; constructor.\n -  simpl in |- *; intros; apply permutation_reflexive.\n -  intros l1 l2 tl Hrec; simpl in |- *.\n    rewrite ass_app.\n    apply permutation_app4;auto.\n    apply merge_permutation; auto.\nQed.\n\nTheorem sort_aux2_permutation :\n forall (b:nat) (l:list (list A)),\n   length l <= b -> permutation (sort_aux2 l b) (app_all l).\nProof.\n intros b; elim b; simpl in |- *; auto.\n -  intros l; case l; simpl in |- *; try constructor.\n    intros l' tl H; inversion H.\n -  intros b' Hrec l; case l.\n   +  simpl in |- *; intros; constructor.\n   +  intros l1 tl; case tl.\n      *  simpl in |- *; intros; \n         rewrite <- app_nil_end; apply permutation_reflexive.\n      *  intros l2 tl' Hle;\n        apply permutation_transitive with \n        (app_all (sort_aux1 (l1 :: l2 :: tl'))).\n        apply Hrec.\n        simpl in Hle; generalize (sort_aux1_shorter tl').\n        simpl in |- *; intros Hle'; omega.\n        apply sort_aux1_permutation.\nQed.\n\nTheorem sort_permutation : forall l:list A, permutation (sort l) l.\nProof.\n unfold sort in |- *; intros l; rewrite <- mk_singletons_length.\n pattern l at 3 in |- *; rewrite <- app_all_mk_singletons_eq.\n apply sort_aux2_permutation; auto.\nQed.\n\n(* A nice complement to the exercise would be to define another merge-sorting\n  function, but this time using well-founded induction, and yet another\n  step would be to use an ad-hoc domain predicate. *)\n\nEnd merge_sort_basics.\n", "meta": {"author": "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/merge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.804911786914299}}
{"text": "Require Import Arith Lia.\n\nDefinition zero_one_dec : forall n:nat, n<=1 -> {n=0}+{n=1}.\nProof.\n simple destruct n.\n -  left; auto.\n -  simple destruct n0.\n    +  right; auto.\n    +  intros  n1 H1; absurd (S (S n1) <= 1); auto with arith.\nDefined.\n\nDefinition div2_mod2 : \n  forall n:nat, {q:nat & {r:nat | n = 2*q + r /\\ r <= 1}}.\nProof.  \n induction n as [ |n IHn].\n -  exists 0, 0; cbn ; auto with arith.\n -  case IHn; intros q' Hq'; case Hq'; intros r' [H1 H2]; cbn.\n    case (zero_one_dec  r' H2); intro H3.\n    +  exists q', 1; lia.\n    +  exists (S q'), 0; lia.\nDefined.\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/ch9_function_specification/SRC/div2_mod2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.8049078686751185}}
{"text": "Require Import Arith.\n\nSection LargeProofTerm.\n\nInductive is_even : nat -> Prop :=\n| even_O : is_even 0\n| even_SS : forall n, is_even n -> is_even (S (S n)).\n\nGoal is_even 10.\nProof.\n    repeat (apply even_SS || apply even_O).\n    Show Proof.\nQed.\n\nGoal is_even (10 * 10 * 10 * 10).\nProof.\n    Time (repeat (apply even_SS || apply even_O)).\n    Show Proof.\nAbort.\n\n(* Proof by Reflection *)\nFixpoint dec_even (n : nat) :=\n    match n with\n    | 0 => true\n    | 1 => false\n    | S (S n') => dec_even n'\n    end.\n\nLemma strong_induction (P : nat -> Prop) :\n    (forall m, (forall k, k < m -> P k) -> P m)\n    -> (forall n, P n).\nProof.\n    intros sIH n.\n    enough (G : forall p, p <= n -> P p).\n    - apply G. constructor.\n    - induction n.\n        + intros p H. inversion H. apply sIH. intros k HH. inversion HH.\n        + intros p H. apply sIH. intros k Hk. apply IHn.\n          enough (HH : k < S n) by (apply (Nat.lt_succ_r); assumption).\n          apply (Nat.lt_le_trans k p (S n)); assumption.\nQed.\n\nLemma dec_even_sound (n : nat): \n    dec_even n = true -> is_even n.\nProof.\n    induction n as [n IH] using strong_induction.\n    destruct n. constructor. destruct n. discriminate.\n    simpl. intros Hn. apply even_SS. auto.\nQed.\n\nGoal is_even (10 * 10 * 10 * 10).\nProof.\n    apply dec_even_sound. \n    (* dec_even (10 * 10 * 10 * 10) == dec_even 10000 == true *)\n    (* vm_compute is faster than simpl, but produces less readable result *)\n    vm_compute.\n    reflexivity.\n    Show Proof. \n    (* !!!!!!!! The key part of the proof term is just some eq_refl !!!!!!!! *)\nQed.\n\nGoal is_even (100 * 100 * 100 * 100).\nProof.\n    apply dec_even_sound.\nAbort.\n\nInductive mexp : Set :=\n| Num (n : nat)\n| Mul (e1 e2 : mexp).\n\nFixpoint meval (e : mexp) :=\n    match e with\n    | Num n => n\n    | Mul e1 e2 => (meval e1) * (meval e2)\n    end.\n\nCheck (eq_refl : meval (Mul (Num 10) (Num 10)) = 10 * 10).\n\nFixpoint dec_even_mexp (e : mexp) :=\n    match e with\n    | Num n => dec_even n\n    | Mul e1 e2 => orb (dec_even_mexp e1) (dec_even_mexp e2)\n    end.\n\nLemma is_even_add x y :\n    is_even x -> is_even y -> is_even (x + y).\nProof.\n    revert y.\n    induction x as [x IH] using strong_induction. intros y Hx. \n    destruct x. intros; assumption. destruct x; inversion Hx.\n    intros Hy. simpl. constructor. auto.\nQed.\n    \nLemma is_even_mul x y :\n    is_even x \\/ is_even y -> is_even (x * y).\nProof.\n    intros H. case H.\n    - intros Hx. rewrite Nat.mul_comm. induction y.\n      + constructor.\n      + simpl. apply is_even_add; auto.\n    - intros Hy. induction x.\n      + constructor.\n      + simpl. apply is_even_add; auto.\nQed.\n\n\nLemma dec_even_mexp_sound e :\n    dec_even_mexp e = true -> is_even (meval e).\nProof.\n    induction e.\n    - simpl. apply dec_even_sound.\n    - simpl. intros H. apply Bool.orb_prop in H. apply is_even_mul. case H.\n      + intros H1. left. auto.\n      + intros H2. right. auto.\nQed.\n\nGoal is_even (100 * 100 * 100 * 100).\nProof.\n    (* change P replace the current goal with P, \n       when P and the current goal are judgementally equal (convertible) *)\n    Fail change (true = true).\n    change (is_even (meval (Mul (Mul (Mul (Num 100) (Num 100)) (Num 100)) (Num 100)))).\n    apply dec_even_mexp_sound.\n    simpl.\n    reflexivity.\nQed.\n\n(*  How to obtain (meval (Mul (Mul (Mul (Num 100) (Num 100)) (Num 100)) (Num 100)))\n    from 100 * 100 * 100 * 100 ?\n\n    Reification\n*)\n\nLtac rf_mul x := \n    match x with\n    | ?n * ?m =>\n        let n' := rf_mul n in\n        let m' := rf_mul m in\n            constr:(Mul n' m')\n    | _ => constr:(Num x)\n    end.\n\n(* For Ltac, see Section 7.6 in CoqArt and Chapter 14 in Certified Programming with Dependent Types *)\n\nGoal is_even (123 * 100 * 100 * 100).\nProof.\n    match goal with\n    | [|- is_even ?x] => \n        let x' := rf_mul x in\n            change (is_even (meval x'))\n    end.\n    apply dec_even_mexp_sound.\n    simpl.\n    reflexivity.\n    Show Proof.\nQed.\n\nEnd LargeProofTerm.\n\nSection PlusExp.\n\nFixpoint plusn0 (n x : nat) :=\n    match n with\n    | 0 => x\n    | S n => plusn0 n (x + 0)\n    end.\n\nVariable n : nat.\nGoal plusn0 10 n = n.\nProof.\n    simpl. rewrite <- !plus_n_O. reflexivity.\n    Show Proof.\nQed.\n\nGoal plusn0 100 n = n.\nProof.\n    Time (vm_compute; rewrite <- !plus_n_O; reflexivity).\nQed.\n\nInductive aexp : Set :=\n| AZero\n| ANum (n : nat)\n| APlus (a1 a2 : aexp).\n\nFixpoint aeval (a : aexp) : nat :=\n    match a with\n    | AZero => 0\n    | ANum n => n\n    | APlus a1 a2 => (aeval a1) + (aeval a2)\n    end.\n\nFixpoint opt0 (a : aexp) : aexp :=\n    match a with\n    | APlus AZero a => opt0 a\n    | APlus a AZero => opt0 a\n    | APlus a1 a2 => APlus (opt0 a1) (opt0 a2)\n    | _ => a\n    end.\n\nLemma opt0_sound (a : aexp) :\n    aeval a = aeval (opt0 a).\nProof.\n    induction a as [ | | a1 IHa1 a2 IHa2]; try reflexivity.\n    destruct a1 eqn:Ea1.\n    - simpl. rewrite IHa2. reflexivity.\n    - simpl. destruct a2; try reflexivity.\n        + simpl. rewrite <- plus_n_O. reflexivity.\n        + simpl. simpl in IHa2. rewrite IHa2. reflexivity.\n    - destruct a2 eqn:Ea2.\n        + simpl. simpl in IHa1. rewrite IHa1. rewrite <- plus_n_O. reflexivity.\n        + simpl. simpl in IHa1. rewrite IHa1. reflexivity.\n        + simpl. simpl in IHa1. simpl in IHa2. rewrite IHa1. rewrite IHa2. reflexivity.\nQed.\n\n\nFixpoint plusn0_aexp (n x : nat) :=\n    match n with\n    | 0 => ANum x\n    | S n => APlus (plusn0_aexp n x) AZero\n    end.\n\nEval simpl in (plusn0_aexp 10 n).\nEval simpl in aeval (plusn0_aexp 10 n).\n\n\nGoal plusn0 10 n = n.\nProof.\n    (* plusn0 10 n == aeval (plusn0_aexp 10 n) *)\n    change (aeval (plusn0_aexp 10 n) = n).\n    rewrite opt0_sound.\n    simpl.\n    reflexivity.\n    Show Proof.\nQed.\n\nGoal plusn0 20 n = n.\nProof.\n    Time (simpl; rewrite <- !plus_n_O; reflexivity).\n    Restart.\n    Time (change (aeval (plusn0_aexp 20 n) = n);\n    rewrite opt0_sound;\n    simpl;\n    reflexivity).\nQed.\n\n(* how to obtain (APlus (ANum a) AZero) from (a + 0)? *)\n\nLtac rf_plus a :=\n    match a with\n    | (?x + ?y) => \n        let x' := rf_plus x in\n        let y' := rf_plus y in\n        constr:(APlus x' y')\n    | 0 => constr:(AZero)\n    | _ => constr:(ANum a)\n    end.\n\nGoal False.\nlet x := rf_plus (n + (n + 0) + 0) in pose x as a.\nAbort.\n\nGoal plusn0 10 n = n.\nProof.\n    simpl.\n    match goal with\n    | [|- ?x = ?y] => \n        let x' := rf_plus x in \n        change (aeval x' = y)\n    end.\n    rewrite opt0_sound.\n    simpl.\n    reflexivity.\nDefined.\n\n(* association *)\n\n(* h + (t1 + t2 + t3 + ...) -> (((h + t1) + t2) + t3) + ... *)\nFixpoint norm_asc_tail (h t : aexp) :=\n    match t with\n    | APlus t1 t2 => norm_asc_tail (norm_asc_tail h t1) t2\n    | _ => APlus h t\n    end.\n\nFixpoint norm_asc (a : aexp) :=\n    match a with\n    | APlus a1 a2 => norm_asc_tail (norm_asc a1) a2\n    | _ => a\n    end.\n\nEval simpl in (norm_asc (APlus (APlus AZero AZero) (APlus AZero AZero))).\n\nLemma norm_asc_tail_sound (h t : aexp):\n    aeval (APlus h t) = aeval (norm_asc_tail h t).\nProof.\n    generalize dependent h.\n    induction t as [| | t1 IHt1 t2 IHt2]; try reflexivity.\n    intros h. simpl. rewrite <- IHt2. simpl. rewrite <- IHt1.\n    simpl. rewrite Nat.add_assoc. reflexivity.\nQed.\n    \nLemma norm_asc_sound : forall t,\n    aeval t = aeval (norm_asc t).\nProof.\n    induction t as [| | t1 IHt1 t2 IHt2]; try reflexivity.\n    simpl. rewrite <- norm_asc_tail_sound. simpl. rewrite <- IHt1. reflexivity.\nQed.\n\nGoal forall (x y z m n : nat),\n    x + ((y + (z + m)) + n) = x + (y + (z + (m + n))).\nProof.\n    intros.\n    rewrite !Nat.add_assoc.\n    reflexivity.\n    Show Proof.\nQed.\n\nGoal forall (x y z m n : nat),\n    x + ((y + (z + m)) + n) = x + (y + (z + (m + n))).\nProof.\n    intros.\n    match goal with\n    | [|- ?l = ?r] => \n        let l' := rf_plus l in\n        let r' := rf_plus r in\n        refine (_ : aeval l' = aeval r');\n        rewrite (norm_asc_sound l');\n        rewrite (norm_asc_sound r')\n    end.\n    simpl.\n    reflexivity.\n    Show Proof.\nQed.\n\nEnd PlusExp.\n\n(* For more on reification, see\n   http://adam.chlipala.net/papers/ReificationITP18/\n   https://github.com/LPCIC/coq-elpi\n*)", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/stories/tech_reification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850084148385, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.8048902801969442}}
{"text": "Inductive Nat : Type :=\n  | O : Nat\n  | S : Nat -> Nat.\n\nFixpoint plus (n m : Nat) {struct n} : Nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nNotation \"n + m\" := (plus n m)\n  (at level 50, left associativity).\n\nFixpoint mul (n m : Nat) {struct n} : Nat :=\n  match n with\n  | O => O\n  | S n' => m + (mul n' m)\n  end.\n\n\nNotation \"n * m\" := (mul n m)\n  (at level 40, left associativity).\n\nExample mul_test_1 : S (S O) * S O = S (S O).\nProof.\n  compute.\n  trivial.\nQed.\n\nExample mul_test_2 : S (S O) * S (S (S O)) = S (S (S (S (S (S O))))).\nProof.\n  compute.\n  trivial.\nQed.\n\nExample mul_test_3 : S (S O) * O = O.\nProof.\n  compute.\n  trivial.\nQed.\n\nExample mul_test_4 : O * S (S O) = O.\nProof.\n  compute.\n  trivial.\nQed.\n\nLemma add_associativity (n m o : Nat) : n + (m + o) = (n + m) + o.\nProof.\n  intros.\n  induction n.\n  (* Inductional Hyptothesis *)\n    simpl.\n    trivial.\n  (* Inductional step *)\n    simpl.\n    rewrite IHn.\n    trivial.\nQed.\n\nLemma add_right_id (a : Nat) : a + O = a.\nProof.\n  induction a.\n    simpl. trivial.\n    simpl. congruence.\nQed.\n\nLemma add_right_suc (a b : Nat) : a + S b = S a + b.\nProof.\n  induction a.\n    simpl. trivial.\n    simpl. rewrite IHa. simpl. trivial.\nQed.\n\nLemma add_commutativity (a b: Nat) : a + b = b + a.\nProof.\n  induction a.\n  (* Inductional Hyptothesis *)\n    simpl. rewrite add_right_id. trivial.\n  (* Inductional step *)\n    simpl. rewrite add_right_suc. simpl. congruence.\nQed.\n\nLemma add_eq_prop (a x y : Nat) : x = y -> a + x = a + y.\nProof.\n  intros.\n  induction a.\n    simpl. trivial.\n    simpl. congruence.\nQed.\n\nLemma mul_add_distributivity (a b c : Nat) : a * (b + c) = a*b + a*c.\nProof.\n  induction a.\n  (* IH *)\n    simpl. trivial.\n\n  (* step *)\n    simpl.\n    rewrite IHa.\n    rewrite <- add_associativity.\n    rewrite <- add_associativity.\n\n    remember (c + (a * b + a * c)) as lhs.\n    remember (a * b + (c + a * c)) as rhs.\n    assert (reductionH : lhs = rhs).\n\n    rewrite Heqlhs. rewrite Heqrhs.\n    rewrite (add_commutativity c _).\n    rewrite (add_commutativity c _).\n    rewrite (add_associativity _ _ c).\n    trivial.\n\n    rewrite (add_eq_prop _ _ _ reductionH).\n    trivial.\nQed.\n\n\nLemma mul_right_zero (a : Nat) : a * O = O.\nProof.\n  induction a.\n    trivial.\n\n    trivial.\nQed.\n\nLemma add_suc (a : Nat) : S a = a + (S O).\nProof.\n  rewrite add_right_suc.\n  rewrite add_right_id.\n  trivial.\nQed.\n\nLemma mul_right_id (a : Nat) : a * S O = a.\nProof.\n  induction a.\n    trivial.\n    simpl. congruence.\nQed.\n\nLemma mul_right_suc (a b : Nat) : a * S b = a + a * b.\nProof.\n  rewrite (add_suc b).\n  rewrite mul_add_distributivity.\n  rewrite mul_right_id.\n  rewrite add_commutativity.\n  trivial.\nQed.\n\nLemma mul_associativity (a b c : Nat) : a * (b * c) = a * b * c.\nProof.\n  induction c.\n    simpl.\n    rewrite mul_right_zero.\n    rewrite mul_right_zero.\n    rewrite mul_right_zero.\n    trivial.\n\n    rewrite mul_right_suc.\n    rewrite mul_add_distributivity.\n    rewrite mul_right_suc.\n    rewrite IHc.\n    trivial.\nQed.\n\nLemma mul_commutativity (a b : Nat) : a * b = b * a.\nProof.\n  induction a.\n    rewrite mul_right_zero. trivial.\n\n    simpl. rewrite mul_right_suc.\n    rewrite IHa.\n    trivial.\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/homework/naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.8047974985499805}}
{"text": "Require Import Coq.ZArith.ZArith.\nOpen Scope Z_scope.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\n\nInductive bit : Type :=\n  | B0\n  | B1.\n\nDefinition bin : Type := list bit.\n\nFixpoint incr (b : bin) : bin :=\n  match b with\n  | [] => [B1]\n  | B0 :: b' => B1 :: b'\n  | B1 :: b' => B0 :: (incr b')\n  end.\n\nFixpoint incr_signed (b : bin) : bin :=\n  match b with\n  | [] | [B0] => [B1; B0]\n  | [B1] => [B1; B1]\n  | B0 :: b' => B1 :: b'\n  | B1 :: b' => B0 :: (incr_signed b')\n  end.\n\nFixpoint to_nat (b : bin) : nat :=\n  match b with\n  | [] => 0\n  | B0 :: b' => 2 * to_nat b'\n  | B1 :: b' => 1 + 2 * to_nat b'\n  end.\n\nFixpoint of_nat (n : nat) : bin :=\n  match n with\n  | O => [B0]\n  | S n' => incr (of_nat n')\n  end.\n\nFixpoint of_nat_signed (n : nat) : bin :=\n  match n with\n  | O => [B0; B0]\n  | S n' => incr_signed (of_nat_signed n')\n  end.\n\nFixpoint to_positive (b : bin) : option positive :=\n  let fix digits_to_positive (b : bin) : positive :=\n    match b with\n    | [] => xH\n    | B0 :: b' => xO (digits_to_positive b')\n    | B1 :: b' => xI (digits_to_positive b')\n    end in\n  match b with\n  | [] => None\n  | B0 :: b' => to_positive b'\n  | B1 :: b' => Some (digits_to_positive b')\n  end.\n\nFixpoint of_positive (p : positive) : bin :=\n  match p with\n  | xH => [B1]\n  | xO p' => B0 :: of_positive p'\n  | xI p' => B0 :: of_positive p'\n  end.\n\nDefinition to_Z (b : bin) : Z :=\n  match hd B0 b, to_positive (tl b) with\n  | _, None => Z0\n  | B0, Some p => Zpos p\n  | B1, Some p => Zneg p\n  end.\n\nDefinition of_Z (z : Z) : bin :=\n  match z with\n  | Z0 => [B0]\n  | Zpos p => B0 :: of_positive p\n  | Zneg p => B1 :: of_positive p\n  end.\n\nDefinition to_N (b : bin) : N :=\n  match to_positive b with\n  | None => N0\n  | Some p => Npos p\n  end.\n\nDefinition of_N (n : N) : bin :=\n  match n with\n  | N0 => [B0]\n  | Npos p => of_positive p\n  end.\n\nDefinition bit_to_bool (b : bit) : bool :=\n  match b with\n  | B0 => false\n  | B1 => true\n  end.\n\nDefinition bool_to_bit (b : bool) : bit :=\n  match b with\n  | false => B0\n  | true => B1\n  end.\n\nTheorem bit_bool_bit : forall b,\n  bool_to_bit (bit_to_bool b) = b.\nProof. intros []; reflexivity. Qed.\n\nTheorem bool_bit_bool : forall b,\n  bit_to_bool (bool_to_bit b) = b.\nProof. intros []; reflexivity. Qed.\n\nDefinition bits_to_ascii (b0 b1 b2 b3 b4 b5 b6 b7 : bit) : ascii :=\n  Ascii (bit_to_bool b0)\n        (bit_to_bool b1)\n        (bit_to_bool b2)\n        (bit_to_bool b3)\n        (bit_to_bool b4)\n        (bit_to_bool b5)\n        (bit_to_bool b6)\n        (bit_to_bool b7).\n\nFixpoint to_string (b : bin) : option string :=\n  match b with\n  | [] => Some EmptyString\n  | b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: b' =>\n      match to_string b' with\n      | None => None\n      | Some s =>\n          Some (String (bits_to_ascii b0 b1 b2 b3 b4 b5 b6 b7) s)\n      end\n  | _ => None\n  end.\n\nFixpoint of_string (s : string) : bin :=\n  match s with\n  | EmptyString => []\n  | String (Ascii b0 b1 b2 b3 b4 b5 b6 b7) s' =>\n      bool_to_bit b0 ::\n          bool_to_bit b1 ::\n          bool_to_bit b2 ::\n          bool_to_bit b3 ::\n          bool_to_bit b4 ::\n          bool_to_bit b5 ::\n          bool_to_bit b6 ::\n          bool_to_bit b7 ::\n          of_string s'\n  end.\n\nTheorem bin_string_bin : forall b s,\n  to_string b = Some s -> of_string s = b.\nProof.\n  induction b as [|b0 [|b1 [|b2 [|b3 [|b4 [|b5 [|b6 [|b7 b']]]]]]]];\n  intros; inversion H; subst; clear H.\n  - reflexivity.\n  - generalize dependent s.\n    induction b'. cbn in *. Admitted.\n\nTheorem string_bin_string : forall s,\n  to_string (of_string s) = Some s.\nProof.\n  induction s.\n  - reflexivity.\n  - destruct a. cbn. rewrite IHs.\n    unfold bits_to_ascii. repeat rewrite bool_bit_bool. reflexivity.\nQed.\n\nFixpoint positive_to_nat (p : positive) : nat :=\n  match p with\n  | xH => 1\n  | xO p' => 2 * positive_to_nat p'\n  | xI p' => 1 + 2 * positive_to_nat p'\n  end.\n\nDefinition Z_to_nat (z : Z) : option nat :=\n  match z with\n  | Z0 => Some O\n  | Zpos p => Some (positive_to_nat p)\n  | Zneg _ => None\n  end.\n\nDefinition N_to_nat (n : N) : nat :=\n  match n with\n  | N0 => 0\n  | Npos p => positive_to_nat p\n  end.\n", "meta": {"author": "thaliaarchi", "repo": "wscoq", "sha": "052d5eab598cdaf684c479e079bb9aea2eaed1ac", "save_path": "github-repos/coq/thaliaarchi-wscoq", "path": "github-repos/coq/thaliaarchi-wscoq/wscoq-052d5eab598cdaf684c479e079bb9aea2eaed1ac/Bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.8047974729916186}}
{"text": "Inductive Z : Type :=\n| Pos : nat -> Z\n| Zero : Z\n| Neg : nat -> Z.\n\nDefinition neg (n: Z) : Z :=\nmatch n with\n| Pos k => Neg k\n| Zero => Zero\n| Neg k => Pos k\nend.\n\nDefinition abs (n: Z) : Z :=\nmatch n with\n| Pos k => Pos k\n| Zero => Zero\n| Neg k => Pos k\nend.\n\nDefinition succ (n: Z) : Z :=\nmatch n with\n| Pos k => Pos (S k)\n| Zero => Pos O\n| Neg O => Zero\n| Neg (S n) => Neg n\nend.\n\nDefinition pred (n: Z) : Z :=\nmatch n with\n| Pos (S n) => Pos n\n| Pos O => Zero\n| Zero => Neg O\n| Neg n => Neg (S n)\nend.\n\nTheorem one_is_zero_succ : Pos O = succ Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem succ_S : forall n: nat, Pos (S n) = succ (Pos n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem minus_one_is_zero_pred : Neg O = pred Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem pred_S : forall n: nat, Neg (S n) = pred (Neg n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem Z_ind' (P : Z -> Prop) (base: P Zero) (suc: forall z: Z, P z -> P (succ z)) \n  (pre: forall z: Z, P z -> P (pred z)) : forall z: Z, P z.\nProof.\n  intro z. destruct z; [| assumption |].\n  - induction n.\n    + rewrite one_is_zero_succ. apply suc. assumption.\n    + rewrite succ_S. apply suc. assumption.\n  - induction n.\n    + rewrite minus_one_is_zero_pred. apply pre. assumption.\n    + rewrite pred_S. apply pre. assumption.\nQed.\n\nTheorem Z_ind'' (P : Z -> Prop) (base: P Zero) (base_pos: P (Pos O)) (base_neg: P (Neg O))\n  (suc: forall n: nat, P (Pos n) -> P (Pos (S n))) \n  (pre: forall n: nat, P (Neg n) -> P (Neg (S n))) : forall z: Z, P z.\nProof.\n  intro z. destruct z.\n  - induction n.\n    + assumption.\n    + apply suc. assumption.\n  - assumption.\n  - induction n.\n    + assumption.\n    + apply pre. assumption.\nQed.\n\nTheorem neg_neg: forall n : Z, neg (neg n) = n.\nProof.\n  intro n. destruct n; cbn; reflexivity.\nQed.\n\nTheorem abs_impotent: forall n : Z, abs n = abs (abs n).\nProof.\n  intro n. destruct n; cbn; reflexivity.\nQed.\n\nTheorem succ_pred : forall n: Z, succ (pred n) = n.\nProof.\n  intro n. destruct n; [| auto |]; now destruct n.\nQed.\n\nTheorem pred_succ : forall n: Z, pred (succ n) = n.\nProof.\n  intro n. destruct n; [| auto |]; now destruct n.\nQed.\n\n\n\n\n\n\n\n(* add *)\n\nFixpoint map_n {A: Type} (n: nat) (f: A -> A) (x: A) : A :=\nmatch n with\n| O => x\n| S n' => f (map_n n' f x)\nend.\n\nDefinition add (a b : Z) : Z :=\nmatch a with \n| Pos n => map_n (S n) succ b\n| Zero => b\n| Neg n => map_n (S n) pred b\nend.\n\nTheorem add_r_zero : forall x: Z, add x Zero = x.\nProof.\n  induction x using Z_ind''; cbn; [trivial | trivial | trivial |rewrite succ_S | rewrite pred_S];\n  f_equal; apply IHx.\nQed.\n\nTheorem add_r_succ : forall x y: Z, add x (succ y) = succ (add x y).\nProof.\n  intros x y. induction x using Z_ind''; trivial; cbn in *.\n  - rewrite pred_succ. rewrite succ_pred. trivial.\n  - f_equal. apply IHx.\n  - rewrite succ_pred. rewrite succ_pred in IHx. rewrite IHx. trivial.\nQed.\n\nTheorem add_r_pred : forall x y: Z, add x (pred y) = pred (add x y).\nProof.\n  intros x y. induction x using Z_ind''; trivial; cbn in *.\n  - rewrite pred_succ, succ_pred. trivial.\n  - rewrite pred_succ, IHx in *. trivial.\n  - f_equal. apply IHx.\nQed.\n\nTheorem add_sym: forall x y: Z, add x y = add y x.\nProof.\n  intro x. induction x using Z_ind''; intro y; cbn.\n  - rewrite add_r_zero. cbn. trivial.\n  - rewrite one_is_zero_succ, add_r_succ, add_r_zero. trivial.\n  - rewrite minus_one_is_zero_pred, add_r_pred, add_r_zero. trivial.\n  - rewrite succ_S, add_r_succ. f_equal. apply IHx.\n  - rewrite pred_S, add_r_pred. f_equal. apply IHx.\nQed.\n\nTheorem neg_succ : forall x: Z, neg (succ x) = pred (neg x).\nProof.\n  destruct x; [| auto |]; now destruct n.\nQed.\n\nTheorem neg_pred : forall x: Z, neg (pred x) = succ (neg x).\nProof.\n  destruct x; [| auto |]; now destruct n.\nQed.\n\nTheorem add_pred_succ : forall x y: Z, add (pred x) (succ y) = add x y.\nProof.\n  intros x y. \n  now rewrite add_r_succ, (add_sym (pred x) y), add_r_pred, succ_pred, add_sym.\nQed.\n\nTheorem neg_is_add_inv : forall x: Z, add x (neg x) = Zero.\nProof.\n  induction x using Z_ind''; trivial.\n  - now rewrite succ_S, neg_succ, add_sym, add_pred_succ, add_sym.\n  - now rewrite pred_S, neg_pred, add_pred_succ.\nQed.\n\n\nTheorem add_l_succ : forall x y: Z, add (succ x) y = succ (add x y).\nProof.\n  intros x y. rewrite (add_sym (succ x) y), add_r_succ. f_equal. apply add_sym.\nQed.\n\nTheorem add_succ_swap : forall x y: Z,  add x (succ y) = add (succ x) y.\nProof.\n  intros x y. rewrite add_r_succ, add_l_succ. trivial.\nQed.\n\nTheorem add_l_pred : forall x y: Z, add (pred x) y = pred (add x y).\nProof.\n  intros x y. rewrite (add_sym (pred x) y), add_r_pred. f_equal.\n  apply add_sym.\nQed.\n\nTheorem add_pred_swap : forall x y: Z, add x (pred y) = add (pred x) y.\nProof.\n  intros x y. rewrite add_r_pred, add_l_pred. trivial.\nQed.\n\nTheorem add_assoc : forall x y z: Z, add (add x y) z = add x (add y z).\nProof.\n  intros x y z. induction x using Z_ind'';\n  [ auto | cbn; apply add_l_succ | cbn; apply add_l_pred | ..].\n  - rewrite succ_S, add_l_succ, add_l_succ, add_l_succ. f_equal. apply IHx.\n  - rewrite pred_S, add_l_pred, add_l_pred, add_l_pred. f_equal. apply IHx.\nQed.\n\nTheorem add_one : forall x: Z, add x (Pos O) = succ x.\nProof.\n  intro x. rewrite one_is_zero_succ, add_r_succ, add_r_zero. trivial.\nQed.\n\nTheorem add_minus_one : forall x: Z, add x (Neg O) = pred x.\nProof.\n  intro x. now rewrite minus_one_is_zero_pred, add_r_pred, add_r_zero.\nQed.\n\nTheorem add_neg : forall x y: Z, add (neg x) (neg y) =  neg (add x y).\nProof.\n  intros x y. induction x using Z_ind''; \n  [ trivial | cbn; symmetry; apply neg_succ | cbn; symmetry; apply neg_pred | ..].\n  - now rewrite succ_S, add_l_succ, neg_succ, neg_succ, <- IHx, add_l_pred.\n  - now rewrite pred_S, add_l_pred, neg_pred, neg_pred, <- IHx, add_l_succ.\nQed.\n\nTheorem add_r_neg : forall x y: Z, add x (neg y) =  neg (add (neg x) y).\nProof.\n  intros x y. induction x using Z_ind'';\n  [ trivial | cbn; now rewrite neg_pred | cbn; now rewrite neg_succ | ..].\n  - now rewrite succ_S, add_l_succ, IHx, neg_succ, add_l_pred, neg_pred. \n  - now rewrite pred_S, add_l_pred, neg_pred, add_l_succ, neg_succ, IHx. \nQed.\n\nTheorem add_l_neg : forall x y: Z, add (neg x) y =  neg (add x (neg y)).\nProof.\n  intros x y. now rewrite add_sym, add_r_neg, add_sym.\nQed.\n\n\n\n\n\n(* mul *)\n  \nDefinition mul (a b: Z) : Z :=\nmatch a with \n| Pos n => map_n (S n) (add b) Zero\n| Zero => Zero\n| Neg n => neg (map_n (S n) (add b) Zero)\nend.\n\nDefinition id {A: Type} (x: A) := x.\n\nTheorem mul_r_zero : forall x: Z, mul x Zero = Zero.\nProof.\n  intros x. destruct x; cbn; [| auto |]; now induction n.\nQed.\n\nTheorem mul_r_one : forall x: Z, mul x (Pos O) = x.\nProof.\n  induction x using Z_ind''; [auto | auto | auto | ..]; cbn.\n  - rewrite succ_S. now f_equal.\n  - rewrite pred_S, neg_succ. now f_equal. \nQed.\n\nTheorem mul_r_minus_one : forall x: Z, mul x (Neg O) = neg x.\nProof.\n  induction x using Z_ind''; [auto | auto | auto | ..]; cbn.\n  - rewrite pred_S. now f_equal.\n  - rewrite succ_S, neg_pred. now f_equal.\nQed.\n\nTheorem mul_r_succ : forall x y: Z, mul x (succ y) = add (mul x y) x.\nProof.\n  intros x y. induction x using Z_ind''; [trivial|..]; cbn in *.\n  - now rewrite add_r_zero, add_r_zero, add_one.\n  - now rewrite add_r_zero, add_r_zero, add_minus_one, neg_succ.\n  - rewrite IHx, add_l_succ, succ_S, add_r_succ. f_equal. \n    now rewrite add_assoc, add_assoc, add_assoc.\n  - rewrite pred_S, <- add_neg, IHx, <- add_neg, <- add_neg, <- add_neg,\n    add_r_pred, neg_succ, add_l_pred. f_equal.\n    now rewrite add_assoc, add_assoc, add_assoc.\nQed.\n\nTheorem mul_r_pred : forall x y: Z, mul x (pred y) = add (mul x y) (neg x).\nProof.\n  intros x y. induction x using Z_ind''; [trivial| ..]; cbn in *.\n  - now rewrite add_r_zero, add_r_zero, add_minus_one.\n  - now rewrite add_r_zero, add_r_zero, add_one, neg_pred.\n  - rewrite IHx, add_l_pred, pred_S, add_r_pred. f_equal. \n    now rewrite add_assoc, add_assoc, add_assoc.\n  - rewrite succ_S, <- add_neg, IHx, <- add_neg,  <- add_neg, <- add_neg,\n    add_r_succ, neg_pred, add_l_succ. f_equal.\n    now rewrite add_assoc, add_assoc, add_assoc.\nQed.\n\nTheorem mul_sym : forall x y: Z, mul x y = mul y x.\nProof.\n  intros x y. induction x using Z_ind''.\n  - now rewrite mul_r_zero.\n  - cbn. now rewrite mul_r_one, add_r_zero.\n  - cbn. now rewrite mul_r_minus_one, add_r_zero.\n  - rewrite succ_S, mul_r_succ, <- IHx. cbn. rewrite add_assoc.\n    f_equal. apply add_sym.\n  - rewrite pred_S, mul_r_pred, <- IHx. cbn.\n    now rewrite <- add_neg, <- add_neg, add_sym.\nQed.\n\nTheorem mul_l_succ : forall x y: Z, mul (succ x) y = add (mul x y) y.\nProof.\n  intros x y. now rewrite mul_sym, mul_r_succ, (mul_sym x y).\nQed.\n\nTheorem mul_l_pred : forall x y: Z, mul (pred x) y = add (mul x y) (neg y).\nProof.\n  intros x y. now rewrite mul_sym, mul_r_pred, (mul_sym x y).\nQed.\n\nTheorem mul_r_neg : forall x y: Z, mul x (neg y) = neg (mul x y).\nProof.\n  intros x y. induction x using Z_ind'; [auto | auto | auto |..].\n  - now rewrite mul_l_succ, mul_l_succ, IHx, add_neg.\n  - now rewrite mul_l_pred, mul_l_pred, IHx, add_r_neg, neg_neg.\nQed.\n\nTheorem mul_l_neg : forall x y: Z, mul (neg x) y = neg (mul x y).\nProof.\n  intros x y. now rewrite mul_sym, mul_r_neg, mul_sym.\nQed.\n\nTheorem mul_neg : forall x y: Z, mul (neg x) (neg y) = mul x y.\nProof.\n  intros x y. now rewrite mul_r_neg, mul_l_neg, neg_neg.\nQed.\n\nTheorem mul_neg_swap : forall x y: Z, mul (neg x) y = mul x (neg y).\nProof.\n  intros x y. now rewrite mul_r_neg, mul_l_neg.\nQed.\n\nTheorem mul_dist_add : forall x y z: Z, mul x (add y z) = add (mul x y) (mul x z).\nProof.\n  intros x y z. induction x using Z_ind'; [auto | auto | auto |..].\n  - now rewrite mul_l_succ, mul_l_succ, mul_l_succ, IHx, add_assoc, add_assoc,\n    (add_sym (mul x z) (add y z)), (add_sym (mul x z) z), add_assoc.\n  - now rewrite mul_l_pred, mul_l_pred, mul_l_pred, IHx, add_assoc, add_assoc,\n    (add_sym (neg y) (add (mul x z) (neg z))), (add_sym y z), add_assoc, add_neg.\nQed.\n\nTheorem mul_assoc : forall x y z: Z, mul (mul x y) z = mul x (mul y z).\nProof.\n  intros x y z. induction x using Z_ind'; [auto | auto | auto |..].\n  - rewrite mul_l_succ, mul_l_succ, mul_sym, mul_dist_add, <- IHx. \n    f_equal; apply mul_sym.\n  - rewrite mul_l_pred, mul_l_pred, add_r_neg, mul_l_neg, add_r_neg. \n    f_equal. rewrite mul_sym, mul_dist_add. f_equal.\n    + rewrite <- IHx, mul_r_neg. f_equal. apply mul_sym.\n    + apply mul_sym.\nQed.\n\n", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/Master/integer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8047636156873201}}
{"text": "From NAT Require Import Peanos_axioms.\nFrom NAT Require Import Tutorial_World.\nFrom NAT Require Import Addition_World.\nFrom NAT Require Import Multiplication_World.\nFrom NAT Require Import Power_World.\nFrom NAT Require Import Function_World.\nFrom NAT Require Import Proposition_World.\nFrom NAT Require Import Advanced_Proposition_World.\nFrom NAT Require Import Advanced_Addition_World.\n\n\n\n\nSection Inequality_World.\n\n(*Now for our final section, Inequality World!*)\n(*Up until now we have been working with strict equality, which is great, but a lot of the things we want to do with the naturals will require a notion of order. \nJust like in Power World, we should consider what it even means for a <= b. Initially, these are just random meaninless symbols and we can derive nothing from them, since our premise is not clear in the first place!\nThe best place to start is to realise that for a < b, there should be some `space` between them. That is b should be some distance away from a. From this idea we easily see how to define less than or equal to. *)\nDefinition less_than_or_equal (a b : nat):= \n    exists c : nat, b = a + c.\n\nNotation \"a <= b\" := (less_than_or_equal (a)(b)).\n\n(*Now let us just restate the definition in a way that will be more useable later, and of course show that it is a true iff statement.*)\nProposition le_iff_exists_add (a b : nat) : \na <= b <-> exists c : nat, b = a + c.\nProof.\n    split.\n    intro h. exact (h).\n    intro h. exact (h).\nQed.\n\nProposition one_add_le_self (x : nat) : x <= 1 + x.\nProof.\n    apply le_iff_exists_add.\n    exists 1.\n    rewrite commute.\n    reflexivity.\nQed.\n(*If you find yourself trying some crazy proof method, take a step back and see if it cannot be done simpler.*)\nProposition le_refl (x : nat) : x <= x.\nProof. \n    apply le_iff_exists_add.\n    exists 0.\n    rewrite add_zero.\n    reflexivity.\nQed.\n(*There are a few good ways to do this, both with previous results and just with tactics.*)\nProposition le_succ (a b : nat) : a <= b -> a <= S b.\nProof.\n    intro h.\n    apply le_iff_exists_add.\n    assert (exists c : nat, b = a + c). exact h.\n    destruct H.\n    exists (x + 1). \n    rewrite add_one. rewrite H. rewrite add_assoc.\n    reflexivity.\nQed.\n(*This is one of those theorems that you must prove in order to satisfy a lot of base cases and to make sure your definition is functioning in the way that you inteded it to.*)\nProposition zero_le (a : nat) : 0 <= a.\nProof.\n    apply le_iff_exists_add.\n    exists a.\n    rewrite zero_add.\n    reflexivity.\nQed.\n\nProposition le_trans (a b c : nat)(hab : a <= b)(hbc : b <= c): a <= c.\nProof.\n     apply le_iff_exists_add.\n     assert (exists c0 : nat, b = a + c0). exact hab.\n     assert (exists c0 : nat, c = b + c0). exact hbc.\n     destruct H. destruct H0.\n     exists (x + x0).\n     rewrite H0. rewrite H. rewrite add_assoc. reflexivity.\nQed.\n\nLemma left_cancel (a b c: nat): a + b= a + c -> b = c.\nProof.\n    intro h.\n    rewrite (commute (a)(b)) in h. rewrite (commute (a)(c)) in h.\n    apply add_right_cancel_iff in h. exact h.\nQed.\n\nProposition le_antisymm (a b : nat) (hab : a <= b)(hba : b <= a): a = b.\nProof.\n    assert (exists c : nat, b = a + c). exact hab.\n    assert (exists c : nat, a = b + c). exact hba.\n    destruct H. destruct H0.\n    rewrite H in H0.\n    rewrite <- (add_zero (a)) in H0.\n    rewrite add_assoc in H0. rewrite add_assoc in H0.\n    apply (left_cancel (a)(0)((0 + x + x0))) in H0.\n    rewrite zero_add in H0. \n    symmetry in H0.\n    apply add_right_eq_zero in H0.\n    rewrite H0 in H.\n    rewrite add_zero in H.\n    symmetry in H.\n    exact H.\nQed.\n\nProposition le_zero (a : nat)(h :  a <= 0) : a = 0.\nProof.\n    assert (0 <= a).\n    apply le_iff_exists_add.\n    exists a. rewrite zero_add. reflexivity.\n    exact (le_antisymm (a)(0)(h)(H)).\nQed.\n\nProposition succ_le_succ (a b : nat)(h : a <= b) : \nS a <= S b.\nProof.\n    apply le_iff_exists_add.\n    assert (exists c : nat, b = a + c). exact h.\n    destruct H.\n    exists x.\n    rewrite add_succ. \n    rewrite H. reflexivity.\nQed.\n\nLemma n_less_than_succ (n : nat): n <= S n.\nProof.\n    apply le_iff_exists_add.\n    exists 1. rewrite add_one. reflexivity. \nQed.\nProposition le_total (a b : nat) : a <= b \\/ b <=a.\nProof.\n    elim b.\n    right. exact (zero_le (a) ).\n    intros h1 h2. destruct h2.\n    left. \n    assert  (exists c : nat, h1 = a + c). exact H.\n    destruct H0.\n    apply le_iff_exists_add. exists (x+1). \n    rewrite add_one. rewrite H0. rewrite add_assoc.\n    reflexivity.\n    assert (exists c, a = h1 + c). exact H.\n    destruct H0. induction x. rewrite add_zero in H0.\n    left. rewrite H0. exact (n_less_than_succ (h1)).\n    right.\n    apply le_iff_exists_add.\n    exists x.\n    rewrite add_succ. rewrite succ_add in H0.\n    exact H0.\nQed.\n\nProposition add_le_add_right (a b : nat) :\na <= b -> forall t, (a + t) <= (b + t).\nProof.\n    intros h ht.\n    assert (exists c, b = a + c). exact h.\n    destruct H.\n    apply le_iff_exists_add.\n    exists (x).\n    rewrite H. rewrite add_assoc. rewrite (commute (x)(ht)).\n    rewrite add_assoc. reflexivity.\nQed.\n\nProposition le_of_succ_le_succ (a b : nat) : \nS a <= S b -> a <= b.\nProof.\n    intro h.\n    assert (exists c, S b = S a + c ). exact h.\n    destruct H. \n    rewrite add_one in H.\n    rewrite (add_one (a)) in H.\n    rewrite commute in H. rewrite (commute (a)(1)) in H.\n    rewrite add_assoc in H.\n    apply add_left_cancel in H.\n    apply le_iff_exists_add.\n    exists x. exact H.\nQed.\n\nProposition not_succ_le_self (a : nat) : ~(S a <= a).\nProof.\n    intro h.\n    assert (exists c, a = S a + c). exact h.\n    destruct H. rewrite add_one in H. rewrite add_assoc in H.\n    symmetry in H.\n    rewrite <- (add_zero) in H.\n    apply (add_left_cancel) in H.\n    rewrite commute in H.\n    rewrite <- (add_one) in H.\n    apply zero_not_succ in H. exact H.\nQed.\n\nProposition add_le_add_left (a b : nat) (h : a <= b) (t :nat):\nt +a <= t + b.\nProof.\n    assert (exists c, b = a + c). exact h. destruct H.\n    apply le_iff_exists_add. exists x.\n    rewrite H. rewrite add_assoc. reflexivity.\nQed.\n\nProposition lt_aux_one (a b : nat) : \na <= b /\\ ~(b <= a) -> S a <= b.\nProof.\n    intro h.\n    destruct h as [hab hba].\n    assert (exists c, b = a + c). exact hab. destruct H.\n    induction x. rewrite add_zero in H. symmetry in H.\n    rewrite <- (add_zero) in H.\n    assert (b <= a). exists 0. exact H. \n    exfalso. exact (hba (H0)).\n    apply le_iff_exists_add.\n    exists x. rewrite add_succ.\n    rewrite succ_add in H.\n    exact H.\nQed.\n\nProposition lt_aux_two (a b : nat):\nS a <= b -> a <= b /\\ ~(b <= a).\nProof.\n    intro h.\n    split.\n    assert (exists c, b = S a + c). exact h. destruct H.\n    apply le_iff_exists_add.\n    exists (1 + x).\n    rewrite add_one in H. rewrite add_assoc in H.\n    exact H.\n\n    assert (exists c, b = S a + c). exact h. destruct H.\n    intro hba. \n    assert (exists c, a = b + c). exact hba. destruct H0.\n    rewrite H0 in H. \n    clear h. clear hba. clear H0.\n    rewrite <- succ_add in H.\n    rewrite add_assoc in H. symmetry in H. \n    rewrite <- add_zero in H.\n    symmetry in H. apply add_left_cancel in H.\n    rewrite add_succ in H. symmetry in H.\n    apply (zero_not_succ) in H. exact H.\nQed.\n\nDefinition less_than (a b : nat) := (a <= b) /\\ ~(b <= a).\nNotation \"a < b\" := (less_than (a)(b)).\n\nProposition lt_iff_succ_le (a b : nat) :\na < b <-> S a <= b.\nProof.\n    split.\n    intro h.\n    assert ((a <= b) /\\ ~(b <= a)). exact h.\n    exact (lt_aux_one (a)(b)(H)).\n\n    intro h.\n    apply lt_aux_two in h. exact h.\nQed.\n\n\nEnd Inequality_World.", "meta": {"author": "brandon-sisler", "repo": "Intros-Blockly", "sha": "c8a64ba3a8e8ce5dbe066b448bfe359221535c5d", "save_path": "github-repos/coq/brandon-sisler-Intros-Blockly", "path": "github-repos/coq/brandon-sisler-Intros-Blockly/Intros-Blockly-c8a64ba3a8e8ce5dbe066b448bfe359221535c5d/natural_number_game/Inequality_World.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8046115719980628}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import fintype finfun finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule POSETDef.\n  Class POSET (T : Type) :=\n    Mixin\n      {\n        rel_op : T -> T -> bool;\n        refl (x : T) : rel_op x x;\n        asym (x y : T) : rel_op x y -> rel_op y x -> x = y;\n        trans (y x z : T) : rel_op x y -> rel_op y z -> rel_op x z\n      }.\n  Notation \"x <== y\" := (rel_op x y) (at level 70, no associativity).\nEnd POSETDef.  \nExport POSETDef.\n\nSection NatPosetExamples.\n  Check leqnn : forall n : nat, n <= n.\n  Lemma eqn_leq' : forall m n, 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  Check leq_trans : forall n m p : nat, m <= n -> n <= p -> m <= p.\n  \n  Instance natPOSET : POSET nat :=\n    {\n    (* *** *)\n    }.\n  Proof.\n    by apply leqnn.\n    by apply eqn_leq'.\n    by apply leq_trans.\n  Qed.\n  \n  Variables x y z : nat.\n  \n  Goal x <== x.\n  Proof.\n    by apply: refl.\n  Qed.\n\n  Goal x <== y -> y <== x -> x = y.\n  Proof.\n    by apply: asym.\n  Qed.\n  \n  Goal x <== y -> y <== z -> x <== z.\n  Proof.\n    by apply: trans.\n  Qed.\nEnd NatPosetExamples.\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_cls_poset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.8045553464493624}}
{"text": "From QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Open Scope qc_scope.\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\nSet Warnings \"-notation-overridden,-parsing\".\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import seq ssreflect ssrbool ssrnat eqtype.\n\nRequire Import List Arith_base PeanoNat String.\nImport ListNotations.\n\nOpen Scope coq_nat.\n\nSection ISORT.\n\n  Fixpoint insert (x : nat)(xs : list nat) : list nat :=\n    match xs with\n    | [] => [ x ]\n    | (y :: ys) =>\n      if leb x y then x :: y :: ys else y :: (insert x ys)\n    end.\n\n  Fixpoint isort (xs : list nat) : list nat :=\n    match xs with\n    | [] => []\n    | (x :: xs) => insert x (isort xs)          \n    end.\nEnd ISORT.\n\nSection TEST_SPEC.\n\n  Fixpoint is_sorted (xs : list nat) : bool :=\n    match xs with\n    | [] => true\n    | [ x ] => true\n    | (x :: x' :: xs) => leb x x' && is_sorted xs\n    end.\n\n  Fixpoint elem (x : nat)(xs : list nat) : bool :=\n    match xs with\n    | [] => false\n    | (y :: ys) => beq_nat x y || elem x ys\n    end.\n  \n  Definition is_permutation (xs ys : list nat) :=\n    forallb (fun x => elem x ys) xs &&\n            forallb (fun y => elem y xs) ys.  \n  \n  Definition isort_is_sorted (xs : list nat) := is_sorted (isort xs).\n  \n  Definition isort_permutation (xs : list nat) := is_permutation xs (isort xs).\n\n  Definition isort_correct (xs : list nat) :=\n    isort_is_sorted xs && isort_permutation xs.\n\nEnd TEST_SPEC.\n\nQuickChick isort_correct.\n\nSection PROOF.\n\n  Inductive sorted : list nat -> Prop :=\n  | SortedNil : sorted []\n  | SortedSing : forall x, sorted [ x ]\n  | SortedRec : forall x y l, x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\n  Hint Constructors sorted.\n\n  Require Import Omega.\n\n  Ltac inv H := inversion H ; clear H ; subst.\n\n  Lemma sorted_inv : forall x l, sorted (x :: l) -> sorted l.\n  Proof.\n    intros x l H ; inv H ; auto.\n  Qed.\n\n  Lemma insert_sorted\n    : forall l x, sorted l -> sorted (insert x l).\n  Proof.\n    intros l x H ; elim H ; simpl ; eauto.\n    intros z ; destruct (x <=? z) eqn : Heqn; simpl ; eauto.\n    +\n      apply leb_iff in Heqn ; eauto.\n    +\n      apply leb_iff_conv in Heqn.\n      assert (z <= x) by omega.\n      eauto.\n    +\n      intros.\n      destruct (x <=? y) eqn : Heqn ; destruct (x <=? x0) eqn : Heqm.\n      apply leb_iff in Heqn.\n      apply leb_iff in Heqm.\n      eauto.\n      apply leb_iff in Heqn.\n      apply leb_iff_conv in Heqm.\n      assert (x0 <= x) by omega.\n      eauto.\n      apply leb_iff_conv in Heqn.\n      apply leb_iff in Heqm.\n      eauto.\n      apply leb_iff_conv in Heqn.\n      apply leb_iff_conv in Heqm.\n      eauto.\n  Qed.\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  Hint Constructors permutation.\n\n  Lemma permutation_refl {A : Type}: forall (l : list A), permutation l l.\n  Proof.\n    induction l ; eauto.\n  Qed.\n\n  Lemma permutation_sym {A : Type}\n    : forall (l l' : list A), permutation l l' -> permutation l' l.\n  Proof.\n    induction 1 ; eauto.\n  Qed.\n\n  Lemma permutation_trans {A : Type}\n    : forall (l1 l2 l3 : list A), permutation l1 l2 ->\n                  permutation l2 l3 ->\n                  permutation l1 l3.\n  Proof.\n    induction 1 ; intros ; eauto.\n  Qed.\n\n  Lemma permutation_nil {A : Type} : forall (l : list A), permutation [] l -> l = [].\n  Proof.\n      intros l HF.\n      remember (@nil A) as m in HF.\n      induction HF; discriminate || auto.\n  Qed.\n\n  Lemma insert_permutation\n    : forall l x, permutation (x :: l) (insert x l).\n  Proof.\n    induction l ; intros ; simpl in * ; eauto.\n    destruct (x <=? a) eqn : Ha ; eauto.\n  Qed.\n\n  Lemma isort_permutation_thm : forall l, permutation l (isort l).\n  Proof.\n    Hint Resolve insert_permutation.\n    induction l ; simpl in * ; eauto.\n  Qed.\n\n  Theorem isort_correct_thm : forall l, permutation l (isort l) /\\\n                                   sorted (isort l).\n  Proof.\n    induction l ; split ; simpl ; eauto.\n    +\n      destruct IHl ; simpl ; eauto.\n    +\n      destruct IHl.\n      apply insert_sorted ; auto.\n  Qed.\nEnd PROOF. ", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/insertsort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8705972583359806, "lm_q1q2_score": 0.8045553366060271}}
{"text": "Require Import PeanoNat.\nRequire Import Arith.\nRequire Import List.\n\n(*** Zadanie 1 - 4p *)\n\n(* Struktury algebraiczne mo\u017cemy wygodnie reprezentowa\u0107 w Coqu za\npomoc\u0105 rekord\u00f3w zale\u017cnych, kt\u00f3rych pola opisuj\u0105 w\u0142asno\u015bci definiuj\u0105ce\ndan\u0105 struktur\u0119. *)\n\n(* 1. Zapoznaj si\u0119 z komend\u0105 Record. *)\n\n(* 2. Zdefiniuj typ monoidu jako rekord zale\u017cny, zawieraj\u0105cy odpowiednie\npola, w tym \u0142\u0105czno\u015b\u0107 operacji i obustronn\u0105 neutralno\u015b\u0107 wyr\u00f3\u017cnionego\nelementu. *)\nRecord Monoid {A:Type} (dot : A -> A -> A) (empty : A) : Prop := mkMonoid\n  { dot_assoc : forall a b c, dot a (dot b c) = dot (dot a b) c\n  ; empty_r : forall a, dot a empty = a\n  ; empty_l : forall a, dot empty a = a\n  }.\n\n(* 3. Udowodnij, \u017ce w ka\u017cdym monoidzie istnieje dok\u0142adnie jeden element\nneutralny. *)\nGoal forall (A:Type) (dot : A -> A -> A) (e : A) (e' : A),\n  Monoid dot e -> Monoid dot e' -> e = e'.\nProof.\n  intros.\n  (* e = dot e e' = e' *)\n  assert (dot e e' = e).\n  apply empty_r. assumption.\n  rewrite <- H1.\n  apply empty_l. assumption.\nQed.\n\n(* 4. Zdefiniuj w Coqu poj\u0119cie homomorfizmu mi\u0119dzy monoidami. *)\n(* Record Homomorphism {A B: Type} (f : A -> B) := mkHomomorphism\n  { homomorph : forall dot dot' e e', Monoid dot e -> Monoid dot' e' -> \n      forall a b, f (dot a b) = dot' (f a) (f b)\n  }. *)\nRecord Homomorphism {A B: Type} \n  {dot: A -> A -> A} {e : A} {dot' : B -> B -> B} {e' : B}\n  (f : A -> B)\n  (* (dot : A -> A -> A) (e : A) (dot' : B -> B -> B) (e' : B) *)\n  (m1 : Monoid dot e) (m2 : Monoid dot' e') := mkHomomorphism\n    { homomorph : forall a b, f (dot a b) = dot' (f a) (f b)\n    }.\n\n(* 5. Podaj dwa przyk\u0142ady monoid\u00f3w i zainstaluj je w typie monoid. Napisz\nfunkcj\u0119 pomi\u0119dzy no\u015bnikami tych monoid\u00f3w, kt\u00f3ra definiuje homomorfizm\npomi\u0119dzy nimi. Udowodnij, \u017ce jest to homomorfizm. *)\n\n(* Search (_ + (_ + _) = _ + _ + _).\nSearch (_ + 0).\nSearch (0 + _).\nSearch (forall a b c, a + (b + c) = a + b + c).\nSearchHead (Nat.add_assoc). *)\n\nDefinition mono_add := \n  mkMonoid nat Nat.add 0 Nat.add_assoc Nat.add_0_r Nat.add_0_l.\n\nImport ListNotations.\n\nDefinition app_unit (xs : list unit) (ys : list unit) : list unit :=\n  app xs ys.\n\nLemma app_assoc_unit : forall a b c,\n  app_unit a (app_unit b c) = app_unit (app_unit a b) c.\nProof.\n  intros. unfold app_unit. apply app_assoc.\nQed.\n\nLemma app_nil_l_unit : forall a, app_unit [] a = a.\nProof.\n  intros. unfold app_unit. apply app_nil_l.\nQed.\n\nLemma app_nil_r_unit : forall a, app_unit a [] = a.\nProof.\n  intros. unfold app_unit. apply app_nil_r.\nQed.\n\nDefinition mono_list :=\n  mkMonoid (list unit) app_unit [] app_assoc_unit app_nil_r_unit app_nil_l_unit.\n\nFixpoint nat_to_list (n : nat) : list unit :=\n  match n with\n  | 0 => []\n  | S n => tt :: (nat_to_list n)\n  end.\n\nLemma homomorph_nat_to_list :\n  forall a b, nat_to_list (a + b) = app_unit (nat_to_list a) (nat_to_list b).\nProof.\n  intros.\n  unfold app_unit.\n  induction a.\n  - cbn. reflexivity.\n  - cbn. rewrite IHa. reflexivity.\nQed.\n\nDefinition hom_nat_to_list := \n  mkHomomorphism nat (list unit) Nat.add 0 app_unit []\n    nat_to_list mono_add mono_list homomorph_nat_to_list.\n\n(* 6. Record jest cukrem syntaktycznym. W jaki spos\u00f3b za pomoc\u0105 znanych\nkonstrukcji Coqa mo\u017cemy inaczej zdefiniowa\u0107 typ monoid? *)\n\nInductive monoid' {A:Type} (dot : A -> A -> A) (empty : A) : Prop :=\n| mkMonoid' :\n    forall a b c, dot a (dot b c) = dot (dot a b) c ->\n    forall a, dot a empty = a ->\n    forall a, dot empty a = a ->\n    monoid' dot empty.\n\n\n(* -------------------------------------------------------------------------- *)\n\n\n(*** Zadanie 2 - 4p + 10p *)\n\n(* 1. Zdefiniuj indukcyjny typ danych reprezentuj\u0105cy drzewa\nczerwono-czarne  *)\nInductive color := black | red.\n\nInductive rbtree (A : Set) : color -> nat -> Set :=\n| rb_e : rbtree A black 0\n| rb_r : forall h, rbtree A black h -> A -> rbtree A black h -> rbtree A red h\n| rb_b : forall h c c', rbtree A c h -> A -> rbtree A c' h -> rbtree A black (S h).\n\n(* taki, \u017ce typ rbtree A c h reprezentuje drzewa zawieraj\u0105ce elementy\ntypu A, kt\u00f3rych korze\u0144 ma kolor c i g\u0142\u0119boko\u015b\u0107 czarnych w\u0119z\u0142\u00f3w h. *)\n\n(* 2. Zdefiniuj funkcj\u0119  *)\n(* Fixpoint depth {A : Set} {c : color} {n : nat} *)\nFixpoint depth {A : Set} {c : color} {n : nat}\n    (cmp : nat -> nat -> nat) (t : rbtree A c n) : nat :=\n  match t with\n  | rb_e _ => 0\n  | rb_r _ h tl _ tr => S (cmp (depth cmp tl) (depth cmp tr))\n  | rb_b _ _ _ _ tl _ tr => S (cmp (depth cmp tl) (depth cmp tr))\n  end.\n\n(* pozwalaj\u0105c\u0105 obliczy\u0107 maksymaln\u0105 i minimaln\u0105 g\u0142\u0119boko\u015b\u0107 drzewa, w\nzale\u017cno\u015bci od tego, jak\u0105 funkcj\u0119 podamy jako argument. *)\n\nRequire Import Coq.Structures.GenericMinMax.\n\nSearchPattern (_ <= _ -> S _ <= S _).\n\n(* 3. Udowodnij w\u0142asno\u015bci  *)\nGoal forall A c n (t : rbtree A c n), depth min t >= n.\nProof.\n  intros.\n  induction t; cbn; unfold ge in *; auto.\n  - apply le_S. apply Nat.min_glb_iff. split; assumption.\n  - apply le_n_S. apply Nat.min_glb_iff. split; assumption.\nQed.\n\nSearch (forall n m, n*m = m*n).\nSearch (forall n, n + 1 = S n).\nSearch (forall a b c, a + (b + c) = (a + b) + c).\nCheck Nat.add_assoc.\n\nLemma depth_max' : forall A c n (t : rbtree A c n),\n  match c with\n    | red => depth max t <= 2 * n + 1\n    | black => depth max t <= 2 * n\n  end.\nProof.\n  intros.\n\n  assert (forall h, 2 * h = h + h). intro.\n  assert (h * 1 + h = h + h). auto with arith.\n  rewrite <- H.\n  rewrite mult_n_Sm.\n  rewrite Nat.mul_comm.\n  rewrite Nat.mul_comm.\n  reflexivity.\n\n  induction t; cbn; auto.\n  - rewrite Nat.add_0_r.\n    rewrite Nat.add_1_r.\n    apply le_n_S.\n    rewrite <- H.\n    apply Nat.max_lub_iff.\n    split; assumption.\n  - apply le_n_S.\n    assert (2 * h + 1 = h + S (h + 0)).\n      rewrite Nat.add_0_r.\n      rewrite <- Nat.add_1_r with (n := h).\n      rewrite Nat.add_assoc.\n      rewrite H. reflexivity.\n    rewrite <- H0.\n    case c, c'; apply Nat.max_lub_iff; split; auto with arith.\nQed.\n\nGoal forall A c n (t : rbtree A c n), depth max t <= 2 * n + 1.\nProof.\n  intros.\n  cut (match c with\n    | red => depth max t <= 2 * n + 1\n    | black => depth max t <= 2 * n\n  end).\n  - induction c; auto with arith.\n  - apply depth_max'.\nQed.\n\n(* 4**. Chcieliby\u015bmy teraz napisa\u0107 funkcj\u0119, kt\u00f3ra wstawia element do\ndrzewa. Taka operacja mo\u017ce zepsu\u0107 w\u0142asno\u015b\u0107 drzewa czerwono-czarnego,\ndlatego potrzebujemy zdefiniowa\u0107 nowy typ danych, kt\u00f3ry reprezentuje\ntakie po\u015brednie drzewo, kt\u00f3re nast\u0119pnie b\u0119dziemy rebalansowa\u0107. Spr\u00f3buj\nnapisa\u0107 funkcj\u0119 balansowania, a nast\u0119pnie wstawiania elementu do\ndrzewa, stosuj\u0105c rozwi\u0105zanie Okasakiego opisane tutaj:\nhttps://pdfs.semanticscholar.org/7756/16cf29e9c4e6d06e5999116f777e431cafa3.pdfs *)\n\n\n(* -------------------------------------------------------------------------- *)\n\n\n(*** Zadanie 3 - 3p *)\n(* 1. Zdefiniuj indukcyjny typ danych reprezentuj\u0105cy termy rachunku\nkombinator\u00f3w: https://pl.wikipedia.org/wiki/Rachunek_kombinator\u00f3w *)\n\nInductive comb := S | K | app : comb -> comb -> comb.\n\nNotation \"a \u00b7 b\" :=\n  (app a b)\n  (at level 61, left associativity).\n\n(* 2. Zdefiniuj redukcj\u0119 na termach rachunku kombinator\u00f3w.  Podstawowy\nkrok redukcji zdefiniowany jest przez regu\u0142y \nK t s -> t \nS r s t -> (r t) (s t)\nkt\u00f3re mo\u017cna stosowa\u0107 w dowolnym podtermie danego termu. *)\n\nReserved Notation \"a ->p b\"\n  (at level 70, no associativity).\n\nInductive redu : comb -> comb -> Prop :=\n| red_K : forall t s, K \u00b7 t \u00b7 s ->p t\n| red_S : forall r s t, S \u00b7 r \u00b7 s \u00b7 t ->p r \u00b7 t \u00b7 (s \u00b7 t)\n| red_l : forall r r' s, r ->p r' -> r \u00b7 s ->p r' \u00b7 s\n| red_r : forall r s' s, s ->p s' -> r \u00b7 s ->p r \u00b7 s'\nwhere \"a ->p b\" := (redu a b).\n\n(* Nast\u0119pnie zdefiniuj relacj\u0119 normalizacji jako zwrotno-przechodnie domkni\u0119cie\nrelacji redukcji. *)\n\n(* refl_trans_closure *)\nInductive rt_clo {A : Set} (f : A -> A -> Prop) : A -> A -> Prop :=\n| rt_clo_r : forall x, rt_clo f x x\n| rt_clo_t : forall a b c, f a b -> rt_clo f b c -> rt_clo f a c.\n\nDefinition redu_t : comb -> comb -> Prop := rt_clo redu.\n\nNotation \"a ->* b\" :=\n  (redu_t a b)\n  (at level 50, no associativity).\n\n(* 3. Zdefiniuj typ danych reprezentuj\u0105cy typy proste z jednym typem bazowym. *)\n\n(* t ::= a | t -> t *)\nInductive type := alpha | appT : type -> type -> type.\n\nNotation \"a => b\" :=\n  (appT a b)\n  (at level 62, right associativity).\n\n(* 4. Zdefiniuj indukcyjny predykat, kt\u00f3ry przypisuje typy termom\nrachunku kombinator\u00f3w wg poni\u017cszych regu\u0142:\nK : A -> B -> A \nS : (A -> B -> C) -> (A -> B) -> (A -> C)\nM N : B je\u015bli M : A -> B i N : A\n*)\n\nReserved Notation \"a : b\"\n  (at level 70, no associativity).\n\nInductive comb_type : comb -> type -> Prop :=\n| type_K : forall A B, K : (A => B => A)\n| type_S : forall A B C, S : ((A => B => C) => (A => B) => (A => C))\n| type_app : forall M N A B, M : (A => B) -> N : A -> M \u00b7 N : B\nwhere \"a : b\" := (comb_type a b).\n\n(* 5. Udowodnij, \u017ce redukcja zachowuje typy (subject reduction). *)\n\nLemma primitive_preservation : forall M N A, \n  M ->p N -> \n  M : A -> \n  N : A.\nProof.\n  intros M N A H.\n  generalize A.\n  induction H.\n  - intros. \n    inversion H. clear H. subst.\n    inversion H2. clear H2. subst.\n    inversion H1. clear H1. subst.\n    assumption.\n  - intros.\n    inversion H. clear H. subst.\n    inversion H2. clear H2. subst. \n    inversion H1. clear H1. subst.  \n    inversion H2. clear H2. subst.\n    apply type_app with (M := r \u00b7 t) (N := s \u00b7 t) (A := B).\n    + apply type_app with (A := A1); assumption.\n    + apply type_app with (A := A1); assumption.\n  - intros.\n    inversion H0. clear H0. subst.\n    apply IHredu in H3.\n    apply type_app with (A := A1); assumption.\n  - intros.\n    inversion H0. clear H0. subst.\n    apply IHredu in H5.\n    apply type_app with (A := A1); assumption.\nQed.\n\nLemma preservation : forall M N A,\n  M : A ->\n  M ->* N ->\n  N : A.\nProof.\n  intros.\n  induction H0.\n  - assumption.\n  - clear H1.\n    apply IHrt_clo.\n    apply primitive_preservation with (M := a); assumption.\nQed.\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/l4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8791467801752451, "lm_q1q2_score": 0.8043322328411479}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export Logic.\n\n(* ####################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n\n(** The first line declares that [ev] 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    even\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.\n\n    The last two lines declare the two ways to give evidence that a\n    number [m] is even.  First, [0] is even, and [ev_0] is evidence\n    for this.  Second, if [m = S (S n)] for some [n] and we can give\n    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n\n    e] is the evidence.\n*)\n\n\n(** **** Exercise: 1 star (double_even)  *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n.\n  induction n.\n  simpl. apply ev_0.\n  simpl. apply ev_SS.\n  apply IHn.\nQed.\n(** [] *)\n\n\n\n(* ##################################################### *)\n\n(** For [ev], we had already defined [even] as a function (returning a\n   boolean), and then defined an inductive relation that agreed with\n   it. However, we don't necessarily need to think about propositions\n   first as boolean functions, we can start off with the inductive\n   definition.\n*)\n\n(** As another example of an inductively defined proposition, 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(** *** *)\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion holds unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n(** *** *)\n(**\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty)  *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* 2 *)\n(** [] *)\n\n(* ####################################################### *)\n(** ** Constructing Evidence *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n(** *** *)\n(**\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** *** *)\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_times2)  *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros.\n  simpl. rewrite <- plus_n_O.\n  apply b_sum with (n:=n) (m:=n).\n  apply H. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (b_timesm)  *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros.\n  induction m. simpl. apply b_0.\n  simpl. apply b_sum with (n:=n) (m:=(m * n)).\n  apply H. apply IHm.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Using Evidence in Proofs *)\n(** ** Induction over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** *** *)\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree)  *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n...\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13)  *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros.\n  apply g_plus3 in H.\n  apply g_plus5 in H.\n  apply g_plus5 in H.\n  apply H.\nQed.\n(** [] *)\n\n(** *** *)\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n(** *** *)\n\n(** Let's see what happens if we try to prove this by induction on the evidence [H]\n   instead of on [n]. *)\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\n(* These exercises also require the use of induction on the evidence. *)\n\n(** **** Exercise: 2 stars (gorgeous_sum)  *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros.\n  induction H.\n  apply H0.\n  apply g_plus3 in IHgorgeous.\n  apply IHgorgeous.\n  apply g_plus5 in IHgorgeous.\n  apply IHgorgeous.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous)  *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros.\n  induction H.\n  apply g_0.\n  apply g_plus3.\n  apply g_0.\n  apply g_plus5.\n  apply g_0.\n  apply gorgeous_sum.\n  apply IHbeautiful1.\n  apply IHbeautiful2.\nQed.\n(** [] *)\n\n\n\n\n(** **** Exercise: 3 stars, optional (g_times2)  *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.\nProof.\n  intros.\n  induction z. reflexivity.\n  simpl. rewrite <- plus_n_Sm. apply f_equal. apply IHz.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. rewrite <- plus_n_O.\n   induction H.\n   apply g_0.\n   rewrite helper_g_times2.\n   apply g_plus3 in IHgorgeous.\n   apply g_plus3 in IHgorgeous.\n   apply IHgorgeous.\n   rewrite helper_g_times2.\n   apply g_plus5 in IHgorgeous.\n   apply g_plus5 in IHgorgeous.\n   apply IHgorgeous.\n Qed.\n(** [] *)\n\n\n\n(** Here is a proof that the inductive definition of evenness implies\nthe 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(** **** Exercise: 1 star (ev__even)  *)\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* no, it gets stuck when n is odd. *)\n(** [] *)\n\n(** Intuitively, the induction principle [ev n] evidence [ev n] is\n    similar to induction on [n], but restricts our attention to only\n    those numbers for which evidence [ev n] could be generated. *)\n\n(** **** Exercise: 1 star (l_fails)  *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n   no evidence\n*)\n(** [] *)\n\n(** Here's another exercise requiring induction on evidence. *)\n(** **** Exercise: 2 stars (ev_sum)  *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros.\n  induction H. apply H0.\n  apply ev_SS in IHev.\n  apply IHev.\nQed.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Inversion on Evidence *)\n\n\n(** Having evidence for a proposition is useful while proving, because we\n   can _look_ at that evidence for more information. For example, consider\n    proving that, if [n] is even, then [pred (pred n)] is\n    too.  In this case, we don't need to do an inductive proof.  Instead\n    the [inversion] tactic provides all of the information that we need.\n\n *)\n\nTheorem ev_minus2: forall n,  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n)  *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* fail *)\n(** [] *)\n\n(** *** *)\n(** Here is another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** 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(** **** 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. induction H0.\n  apply H.\n  inversion H.\n  apply IHev.\n  apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros.\n  apply ev_ev__ev with (n:=n+n).\n  rewrite plus_swap. rewrite <- plus_assoc.\n  rewrite plus_swap. rewrite plus_assoc.\n  apply ev_sum. apply H. apply H0.\n  rewrite <- double_plus.\n  apply double_even.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Discussion and Variations *)\n(** ** Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(* ####################################################### *)\n(** ** Parameterized Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However,\n   we can define inductive predicates about any type of data. For example,\n   suppose we would like to characterize lists of _even_ length. We can\n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof.\n    intros X l H. induction H.\n    Case \"el_nil\". simpl. apply ev_0.\n    Case \"el_cc\".  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\nevidence for [ev_list], the converse direction must be stated very\ncarefully. *)\n\nLemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H.\n  induction H.\n  Case \"ev_0\". intros l H. destruct l.\n    SCase \"[]\". apply el_nil.\n    SCase \"x::l\". inversion H.\n  Case \"ev_SS\". intros l H2. destruct l.\n    SCase \"[]\". inversion H2. destruct l.\n    SCase \"[x]\". inversion H2.\n    SCase \"x :: x0 :: l\". apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n\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 [pal_app_rev] that\n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that\n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X:Type} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_1 : forall x, pal [x]\n  | pal_cc  : forall x l, pal l -> pal (x :: (snoc l x)).\n\n\nTheorem pal_app_rev : forall (X:Type) (l:list X),\n  pal (l ++ rev l).\nProof.\n  intros.\n  induction l.\n  apply pal_nil.\n  simpl. rewrite <- snoc_with_append.\n  apply pal_cc.\n  apply IHl.\nQed.\n\n\nTheorem pal_rev : forall (X:Type) (l:list X),\n  pal l -> l = rev l.\nProof.\n  intros.\n  induction H.\n  reflexivity.\n  simpl. reflexivity.\n  simpl. rewrite rev_snoc.\n  simpl. apply f_equal.\n  rewrite <- IHpal.\n  reflexivity.\nQed.\n(** [] *)\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\nTheorem palindrome_converse : forall (X:Type) (l:list X),\n  l = rev l -> pal l.\nProof.\n  intros.\n(* FILL IN HERE *)\nAbort.\n(** [] *)\n\n\n\n(* ####################################################### *)\n(** ** Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** *** *)\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** *** *)\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n  | all : forall n m:nat, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros.\n  induction H0. apply H.\n  apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n.\n  apply le_n.\n  apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros.\n  induction H. 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  inversion H. apply le_n.\n  apply le_trans with (n:=S n).\n  apply le_S. apply le_n. apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros.\n  induction b.\n  rewrite <- plus_n_O.\n  apply le_n.\n  rewrite <- plus_n_Sm.\n  apply le_S. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt.\n  intros.\n  split. apply le_trans with (n:=S (n1 + n2)).\n  rewrite plus_comm. rewrite plus_n_Sm. rewrite plus_comm.\n  apply le_plus_l. apply H.\n  apply le_trans with (n:=S (n1 + n2)).\n  rewrite plus_n_Sm. rewrite plus_comm.\n  apply le_plus_l. apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros.\n  apply le_trans with (n:=m).\n  apply H. apply le_S. apply le_n.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intros n.\n  induction n.\n  intros. apply O_le_n.\n  intros.\n  simpl in H. destruct m.\n  inversion H. apply n_le_m__Sn_le_Sm.\n  apply IHn. apply H.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  intros n m.\n  generalize n.\n  induction m.\n  intros. inversion H. reflexivity.\n  intros. destruct n0. reflexivity.\n  simpl. apply IHm. apply Sn_le_Sm__n_le_m.\n  apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  intros.\n  apply le_ble_nat.\n  apply ble_nat_true in H.\n  apply ble_nat_true in H0.\n  apply le_trans with (n:=m).\n  apply H. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false)  *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply le_ble_nat in H0. rewrite H in H0.\n  inversion H0.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (R_provability2)  *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n[R 1 1 2] is provable.\nno, only c1-3 is enough for nat +.\nsame.\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\nTheorem R_m_n_o : forall (m n o:nat),\n  R m n o <-> m + n = o.\nProof.\n  split.\n  intros. induction H. reflexivity.\n  rewrite plus_comm. rewrite <- plus_n_Sm.\n  rewrite plus_comm. apply f_equal.\n  apply IHR. rewrite <- plus_n_Sm.\n  apply f_equal. apply IHR.\n  inversion IHR. rewrite <- plus_n_Sm in H1.\n  inversion H1. reflexivity. rewrite plus_comm.\n  apply IHR.\n  generalize n o. induction m.\n  intros n0. induction n0.\n  intros. rewrite <- H. apply c1.\n  intros. simpl in H. destruct o0. inversion H.\n  apply c3. apply IHn0. inversion H. reflexivity.\n  intros n0. induction n0.\n  intros. destruct o0. inversion H.\n  apply c2. inversion H. rewrite H1. apply IHm. apply H1.\n  intros. destruct o0. inversion H.\n  destruct o0. inversion H. rewrite <- plus_n_Sm in H1.\n  inversion H1.\n  apply c2. apply c3. apply IHm.\n  inversion H. rewrite <- plus_n_Sm in H1.\n  inversion H1. reflexivity.\nQed.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is,\n      any list is a subsequence of itself.\n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is\n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n      is a subsequence of [l3], then [l1] is a subsequence of [l3].\n      Hint: choose your induction carefully!\n*)\n\nInductive subseq {X:Type} : list X -> list X -> Prop :=\n  | sub_nil : forall l, subseq [] l\n  | sub2 : forall n l1 l2, subseq l1 l2 -> subseq l1 (n :: l2)\n  | sub3 : forall n l1 l2, subseq l1 l2 -> subseq (n :: l1) (n :: l2).\n\nTheorem cons_app : forall (X:Type) (l1 l2:list X) (x:X),\n  (x :: l1) ++ l2 = x :: (l1 ++ l2).\nProof.\n  intros. destruct l1. reflexivity.\n  simpl. reflexivity.\nQed.\n\nTheorem subseq_refl : forall (X:Type) (l:list X), subseq l l.\nProof.\n  intros. induction l. apply sub_nil.\n  apply sub3. apply IHl.\nQed.\n\nTheorem subseq_app_nil : forall (X:Type) (l:list X), subseq nil l.\nProof.\n  intros.\n  induction l. apply subseq_refl.\n  apply sub2. apply IHl.\nQed.\n\nTheorem subseq_app_self : forall (X:Type) (l1 l2:list X), subseq l1 (l1 ++ l2).\nProof.\n  intros.\n  induction l1. apply subseq_app_nil. rewrite cons_app.\n  apply sub3. apply IHl1.\nQed.\n\nTheorem subseq_app : forall (X:Type) (l1 l2 l3:list X),\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H. apply sub_nil.\n  rewrite cons_app. apply sub2. apply IHsubseq.\n  rewrite cons_app. apply sub3. apply IHsubseq.\nQed.\n\nTheorem subseq_cons : forall (X:Type) (l1 l2:list X) (n:X),\n  subseq (n :: l1) l2 -> subseq l1 l2.\nProof.\n  intros X l1 l2 n.\n  generalize n l1.\n  induction l2.\n  intros. inversion H. intros.\n  inversion H. apply sub2. apply IHl2 with (n:=n0).\n  apply H2. apply sub2. apply H1.\nQed.\n\nTheorem subseq_cut : forall (X:Type) (l1 l2:list X) (n1 n2:X),\n  subseq (n1 :: l1) (n2 :: l2) -> subseq l1 l2.\nProof.\n  intros. inversion H.\n  apply subseq_cons in H2. apply H2. apply H1.\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. generalize dependent l1.\n  generalize dependent l2. induction l3.\n  intros l1 l2 h i. inversion i.\n  rewrite <- H in h. inversion h. apply sub_nil.\n  intros l1 l2 h i. inversion i.\n  rewrite <- H in h. inversion h. apply sub_nil.\n  destruct h as [| h' | h'].\n  apply sub_nil.\n  apply sub2. apply IHl3 with (l2:=h' :: l2). apply sub2. apply h.\n  apply H1.\n  apply sub2. apply IHl3 with (l2:=h' :: l2). apply sub3. apply h.\n  apply H1.\n  destruct h as [| h' | h'].\n  apply sub_nil. apply sub2. apply IHl3 with (l2:=l2).\n  apply h. apply subseq_cut in i. apply i.\n  inversion H0. rewrite <- H4. rewrite H. apply sub3. apply IHl3 with (l2:=l2).\n  apply h. apply subseq_cut in i. apply i.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability)  *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n  1 - [R 2 [1,0]]\n  1 - [R 1 [1,2,1,0]]\n  1 - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Programming with Propositions *)\n\n(** As we have seen, a _proposition_ is a statement expressing a factual claim,\n    like \"two plus two equals four.\"  In Coq, propositions are written\n    as expressions of type [Prop]. . *)\n\nCheck (2 + 2 = 4).\n(* ===> 2 + 2 = 4 : Prop *)\n\nCheck (ble_nat 3 2 = false).\n(* ===> ble_nat 3 2 = false : Prop *)\n\nCheck (beautiful 8).\n(* ===> beautiful 8 : Prop *)\n\n(** *** *)\n(** Both provable and unprovable claims are perfectly good\n    propositions.  Simply _being_ a proposition is one thing; being\n    _provable_ is something else! *)\n\nCheck (2 + 2 = 5).\n(* ===> 2 + 2 = 5 : Prop *)\n\nCheck (beautiful 4).\n(* ===> beautiful 4 : Prop *)\n\n(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions\n    of type [Prop]. *)\n\n(** *** *)\n(** We've mainly seen one place that propositions can appear in Coq: in\n    [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But they can be used in many other ways.  For example, we have also seen that\n    we can give a name to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** *** *)\n(** We've seen several ways of constructing propositions.\n\n       - We can define a new proposition primitively using [Inductive].\n\n       - Given two expressions [e1] and [e2] of the same type, we can\n         form the proposition [e1 = e2], which states that their\n         values are equal.\n\n       - We can combine propositions using implication and\n         quantification. *)\n(** *** *)\n(** We have also seen _parameterized propositions_, such as [even] and\n    [beautiful]. *)\n\nCheck (even 4).\n(* ===> even 4 : Prop *)\nCheck (even 3).\n(* ===> even 3 : Prop *)\nCheck even.\n(* ===> even : nat -> Prop *)\n\n(** *** *)\n(** The type of [even], i.e., [nat->Prop], can be pronounced in\n    three equivalent ways: (1) \"[even] is a _function_ from numbers to\n    propositions,\" (2) \"[even] is a _family_ of propositions, indexed\n    by a number [n],\" or (3) \"[even] is a _property_ of numbers.\"  *)\n\n(** Propositions -- including parameterized propositions -- are\n    first-class citizens in Coq.  For example, we can define functions\n    from numbers to propositions... *)\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\n(** ... and then partially apply them: *)\n\nDefinition teen : nat->Prop := between 13 19.\n\n(** We can even pass propositions -- including parameterized\n    propositions -- as arguments to functions: *)\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\n(** *** *)\n(** Here are two more examples of passing parameterized propositions\n    as arguments to a function.\n\n    The first function, [true_for_all_numbers], takes a proposition\n    [P] as argument and builds the proposition that [P] is true for\n    all natural numbers. *)\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\n(** The second, [preserved_by_S], takes [P] and builds the proposition\n    that, if [P] is true for some natural number [n'], then it is also\n    true by the successor of [n'] -- i.e. that [P] is _preserved by\n    successor_: *)\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\n(** *** *)\n(** Finally, we can put these ingredients together to define\na proposition stating that induction is valid for natural numbers: *)\n\nDefinition natural_number_induction_valid : Prop :=\n  forall (P:nat->Prop),\n    true_for_zero P ->\n    preserved_by_S P ->\n    true_for_all_numbers P.\n\n\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function\n    below. It takes as arguments two properties of numbers [Podd] and\n    [Peven]. As its result, it should return a new property [P] such\n    that [P n] is equivalent to [Podd n] when [n] is odd, and\n    equivalent to [Peven n] otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun (n:nat) => match (oddb n) with\n                 | true => Podd n\n                 | false => Peven n\n               end.\n\n(** To test your definition, see whether you can prove the following\n    facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  apply H. reflexivity. apply H0. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  unfold combine_odd_even.\n  intros.\n  destruct (oddb n). apply H.\n  inversion H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  unfold combine_odd_even.\n  intros.\n  destruct (oddb n). inversion H0.\n  apply H.\nQed.\n\n(** [] *)\n\n(* ##################################################### *)\n(** One more quick digression, for adventurous souls: if we can define\n    parameterized propositions using [Definition], then can we also\n    define them using [Fixpoint]?  Of course we can!  However, this\n    kind of \"recursive parameterization\" doesn't correspond to\n    anything very familiar from everyday mathematics.  The following\n    exercise gives a slightly contrived example. *)\n\n(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)\n(** Define a recursive function\n    [true_upto_n__true_everywhere] that makes\n    [true_upto_n_example] work. *)\n\nFixpoint true_upto_n__true_everywhere (n:nat) (p:nat -> Prop) : Prop :=\n  match n with\n      | 0 => true_for_all_numbers p\n      | S n' => p n -> true_upto_n__true_everywhere n' p\n  end.\n\nExample true_upto_n_example :\n    (true_upto_n__true_everywhere 3 (fun n => even n))\n  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)", "meta": {"author": "fabriceleal", "repo": "Software-Foundations-Solutions", "sha": "a6fcbe4c0711a90cd364c075b2a8c1edfd3b30cc", "save_path": "github-repos/coq/fabriceleal-Software-Foundations-Solutions", "path": "github-repos/coq/fabriceleal-Software-Foundations-Solutions/Software-Foundations-Solutions-a6fcbe4c0711a90cd364c075b2a8c1edfd3b30cc/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.804332229352757}}
{"text": "(**\n  This module defines the Abelian Group record type which can be\n  used to represent abelian groups and provides a collection of\n  axioms and theorems describing them.\n\n  Copyright (C) 2018 Larry D. Lee Jr. <llee454@gmail.com>\n\n  This program is free software: you can redistribute it and/or modify\n  it under the terms of the GNU Lesser General Public License as\n  published by the Free Software Foundation, either version 3 of the\n  License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this program. If not, see\n  <https://www.gnu.org/licenses/>.\n*)\n\nRequire Import Description.\nRequire Import base.\nRequire Import function.\nRequire Import monoid.\nRequire Import group.\n\nModule Abelian_Group.\n\n(**\n  Accepts one argument: f, a binary function;\n  and asserts that f is commutative.\n*)\nDefinition is_comm (T : Type) (f : T -> T -> T)\n  :  Prop\n  := forall x y : T, f x y = f y x.\n\n(** Represents algebraic abelian groups. *)\nStructure Abelian_Group : Type := abelian_group {\n\n  (** Represents the set of group elements. *)\n  E : Set;\n\n  (** Represents the identity element. *)\n  E_0 : E;\n\n  (** Represents the group operation. *)\n  op : E -> E -> E;\n\n  (** Asserts that the group operator is associative. *)\n  op_is_assoc : Monoid.is_assoc E op;\n\n  (** Asserts that the group operator is commutative. *)\n  op_is_comm : is_comm E op;\n\n  (** Asserts that E_0 is the left identity element. *)\n  op_id_l : Monoid.is_id_l E op E_0;\n\n  (**\n    Asserts that every element has a left inverse.\n\n    Strictly speaking, this axiom should be:\n\n      forall x : E, exists y : E,\n        Monoid.is_inv_l E op E_0 op_id x y\n\n    which asserts and verifies that op y x equals\n    the identity element. Technically, we haven't\n    shown that E_0 is the identity element yet, so\n    we're being a bit presumptuous defining inverses\n    in this way. While we could prove op_id in this\n    structure definition, we prefer not to to improve\n    readability and instead use the form given below,\n    which Monoid.is_inv_l reduces to anyway.\n  *)\n  op_inv_l_ex : forall x : E, exists y : E, op y x = E_0\n}.\n\n(** Enable implicit arguments for group properties. *)\n\nArguments E_0 {a}.\n\nArguments op {a} x y.\n\nArguments op_is_assoc {a} x y z.\n\nArguments op_is_comm {a} x y.\n\nArguments op_id_l {a} x.\n\nArguments op_inv_l_ex {a} x.\n\n(** Define notations for group properties. *)\n\nNotation \"0\" := E_0 : abelian_group_scope.\n\nNotation \"x + y\" := (op x y) (at level 50, left associativity) : abelian_group_scope.\n\nNotation \"{+}\" := op : abelian_group_scope.\n\nOpen Scope abelian_group_scope.\n\nSection Theorems.\n\n(**\n  Represents an arbitrary abelian group.\n\n  Note: we use Variable rather than Parameter\n  to ensure that the following theorems are\n  generalized w.r.t ag.\n*)\nVariable g : Abelian_Group.\n\n(**\n  Represents the set of group elements.\n\n  Note: We use Let to define E as a \n  local abbreviation.\n*)\nLet E := E g.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the left identity element.\n*)\nDefinition op_is_id_l := Monoid.is_id_l E {+}.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the right identity element.\n*)\nDefinition op_is_id_r := Monoid.is_id_r E {+}.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the identity element.\n*)\nDefinition op_is_id := Monoid.is_id E {+}.\n\n(**\n  Proves that every left identity must also\n  be a right identity.\n*)\nTheorem op_is_id_lr\n  :  forall x : E, op_is_id_l x -> op_is_id_r x.\nProof\n  fun x H y\n    => H y\n    || a = y @a by op_is_comm y x.\n\n(**\n  Proves that every left identity is an\n  identity.\n*)\nTheorem op_is_id_lid\n  : forall x : E, op_is_id_l x -> op_is_id x.\nProof\n  fun x H\n    => conj H (op_is_id_lr x H).\n\n(** Proves that 0 is the right identity element. *)\nTheorem op_id_r\n  :  op_is_id_r 0.\nProof op_is_id_lr 0 op_id_l.\n\n(** Proves that 0 is the identity element. *)\nTheorem op_id\n  :  op_is_id 0.\nProof conj op_id_l op_id_r.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's left inverse.\n*)\nDefinition op_is_inv_l := Monoid.is_inv_l E {+} 0 op_id.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's right inverse.\n*)\nDefinition op_is_inv_r := Monoid.is_inv_r E {+} 0 op_id.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's inverse.\n*)\nDefinition op_is_inv := Monoid.is_inv E {+} 0 op_id.\n\n(** Proves that every element has a right inverse. *)\nTheorem op_inv_r_ex\n  :  forall x : E, exists y : E, op_is_inv_r x y.\nProof\n  fun x\n    => ex_ind\n         (fun (y : E) (H : op_is_inv_l x y)\n           => ex_intro\n                (op_is_inv_r x)\n                y\n                (H || a = 0 @a by op_is_comm x y))\n         (op_inv_l_ex x).\n\n(**\n  Represents the group structure formed by\n  op over E.\n*)\nDefinition op_group := Group.group E 0 {+} op_is_assoc op_id_l op_id_r op_inv_l_ex op_inv_r_ex.\n\n(** Represents the monoid formed by op over E. *)\nDefinition op_monoid := Group.op_monoid op_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a left inverse.\n*)\nDefinition has_inv_l := Group.has_inv_l op_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a right inverse.\n*)\nDefinition has_inv_r := Group.has_inv_r op_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has an inverse.\n*)\nDefinition has_inv := Group.has_inv op_group.\n\n(** Proves that the left identity element is unique. *)\nTheorem op_id_l_uniq\n  :  forall x : E, Monoid.is_id_l E {+} x -> x = 0.\nProof Group.op_id_l_uniq op_group.\n\n(** Proves that the right identity element is unique. *)\nTheorem op_id_r_uniq\n  :  forall x : E, Monoid.is_id_r E {+} x -> x = 0.\nProof Group.op_id_r_uniq op_group.\n\n(** Proves that the identity element is unique. *)\nTheorem op_id_uniq\n  :  forall x : E, Monoid.is_id E {+} x -> x = 0.\nProof Group.op_id_uniq op_group.\n\n(**\n  Proves that for every group element, x,\n  its left and right inverses are equal.\n*)\nTheorem op_inv_l_r_eq\n  :  forall x y : E, op_is_inv_l x y -> forall z : E, op_is_inv_r x z -> y = z.\nProof Group.op_inv_l_r_eq op_group.\n\n(**\n  Proves that the inverse relation is\n  symmetrical.\n*)\nTheorem op_inv_sym\n  :  forall x y : E, op_is_inv x y <-> op_is_inv y x.\nProof Group.op_inv_sym op_group.\n\n(**\n  Proves that every group element has an\n  inverse.\n*)\nTheorem op_inv_ex\n  :  forall x : E, exists y : E, op_is_inv x y.\nProof Group.op_inv_ex op_group.\n\n(** Proves the left introduction rule. *)\nTheorem op_intro_l\n  :  forall x y z : E, x = y -> z + x = z + y.\nProof Group.op_intro_l op_group.\n\n(** Proves the right introduction rule. *)\nTheorem op_intro_r\n  :  forall x y z : E, x = y -> x + z = y + z.\nProof Group.op_intro_r op_group.\n\n(** Proves the left cancellation rule. *)\nTheorem op_cancel_l\n  :   forall x y z : E, z + x = z + y -> x = y.\nProof Group.op_cancel_l op_group.\n\n(** Proves the right cancellation rule. *)\nTheorem op_cancel_r\n  :   forall x y z : E, x + z = y + z -> x = y.\nProof Group.op_cancel_r op_group.\n\n(**\n  Proves that an element's left inverse\n  is unique.\n*)\nTheorem op_inv_l_uniq\n  :  forall x y z : E, op_is_inv_l x y -> op_is_inv_l x z -> z = y.\nProof Group.op_inv_l_uniq op_group.\n\n(**\n  Proves that an element's right inverse\n  is unique.\n*)\nTheorem op_inv_r_uniq\n  :  forall x y z : E, op_is_inv_r x y -> op_is_inv_r x z -> z = y.\nProof Group.op_inv_r_uniq op_group.\n\n(** Proves that an element's inverse is unique. *)\nTheorem op_inv_uniq\n  :  forall x y z : E, op_is_inv x y -> op_is_inv x z -> z = y.\nProof Group.op_inv_uniq op_group.\n\n(**\n  Proves explicitly that every element has a\n  unique inverse.\n*)\nTheorem op_inv_uniq_ex\n  :  forall x : E, exists! y : E, op_is_inv x y.\nProof Group.op_inv_uniq_ex op_group.\n\n(**\n  Proves that the identity element is its own\n  left inverse.\n*)\nTheorem op_inv_0_l\n  :  op_is_inv_l 0 0.\nProof Group.op_inv_0_l op_group.\n\n(**\n  Proves that the identity element is its own\n  right inverse.\n*)\nTheorem op_inv_0_r\n  :  op_is_inv_r 0 0.\nProof Group.op_inv_0_r op_group.\n\n(**\n  Proves that the identity element is its own\n  inverse.\n*)\nTheorem op_inv_0\n  :  op_is_inv 0 0.\nProof Group.op_inv_0 op_group.\n\n(**\n  Proves that the identity element has a\n  left inverse.\n*)\nTheorem op_has_inv_l_0\n  :  has_inv_l 0.\nProof Group.op_has_inv_l_0 op_group.\n\n(**\n  Proves that the identity element has a\n  right inverse.\n*)\nTheorem op_has_inv_r_0\n  :  has_inv_r 0.\nProof Group.op_has_inv_r_0 op_group.\n\n(**\n  Proves that the identity element has an\n  inverse.\n*)\nTheorem op_has_inv_0\n  :  has_inv 0.\nProof Group.op_has_inv_0 op_group.\n\n(**\n  Proves that if an element's, x, inverse\n  equals 0, x equals 0.\n*)\nTheorem op_inv_0_eq_0\n  :  forall x : E, op_is_inv x 0 -> x = 0.\nProof Group.op_inv_0_eq_0 op_group.\n\n(**\n  Proves that 0 is the only element whose\n  inverse is 0.\n*)\nTheorem op_inv_0_uniq\n  :  unique (fun x => op_is_inv x 0) 0.\nProof Group.op_inv_0_uniq op_group.\n \n(** Represents strongly-specified negation. *)\nDefinition op_neg_strong\n  :  forall x : E, { y | op_is_inv x y }\n  := Group.op_neg_strong op_group.\n\n(** Represents negation. *)\nDefinition op_neg\n  :  E -> E\n  := Group.op_neg op_group.\n\nClose Scope nat_scope.\n\nNotation \"{-}\" := (op_neg) : abelian_group_scope.\n\nNotation \"- x\" := (op_neg x) : abelian_group_scope.\n\n(**\n  Asserts that the negation returns the inverse\n  of its argument.\n*)\nTheorem op_neg_def\n  :  forall x : E, op_is_inv x (- x).\nProof Group.op_neg_def op_group.\n\n(** Proves that negation is one-to-one *)\nTheorem op_neg_inj\n  :  is_injective E E op_neg.\nProof Group.op_neg_inj op_group.\n\n(** Proves the cancellation property for negation. *)\nTheorem op_cancel_neg\n  :  forall x : E, op_neg (- x) = x.\nProof Group.op_cancel_neg op_group.\n\n(** Proves that negation is onto *)\nTheorem op_neg_onto\n  :  is_onto E E op_neg.\nProof Group.op_neg_onto op_group.\n\n(** Proves that negation is surjective *)\nTheorem op_neg_bijective\n  :  is_bijective E E op_neg.\nProof Group.op_neg_bijective op_group.\n\n(** Proves that neg x = y -> neg y = x *)\nTheorem op_neg_rev\n  :  forall x y : E, - x = y -> - y = x.\nProof Group.op_neg_rev op_group.\n\n(**\n  Proves that the left inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv_l\n  :  forall x y : E, op_is_inv_l (x + y) (- y + - x).\nProof Group.op_neg_distrib_inv_l op_group.\n\n(**\n  Proves that the right inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv_r\n  :  forall x y : E, op_is_inv_r (x + y) (- y + - x).\nProof Group.op_neg_distrib_inv_r op_group.\n\n(**\n  Proves that the inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv\n  :  forall x y : E, op_is_inv (x + y) (- y + - x).\nProof Group.op_neg_distrib_inv op_group.\n\n(**\n  Proves that negation is distributive: i.e.\n  -(x + y) = -y + -x.\n*)\nTheorem op_neg_distrib\n  :  forall x y : E, - (x + y) = - y + - x.\nProof Group.op_neg_distrib op_group.\n\nEnd Theorems.\n\nEnd Abelian_Group.\n\nNotation \"0\" := (Abelian_Group.E_0) : abelian_group_scope.\n\nNotation \"x + y\" := (Abelian_Group.op x y) (at level 50, left associativity) : abelian_group_scope.\n\nNotation \"{+}\" := (Abelian_Group.op) : abelian_group_scope.\n\nNotation \"{-}\" := (Abelian_Group.op_neg _) : abelian_group_scope.\n\nNotation \"- x\" := (Abelian_Group.op_neg _ x) : abelian_group_scope.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/functional-algebra/abelian_group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8043322180305219}}
{"text": "Inductive UBTree : Set :=\n  | leaf0 : UBTree\n  | node2 : UBTree -> UBTree -> UBTree\n  | node1 : UBTree -> UBTree.\n\nFixpoint right_UB (t:UBTree) (s:UBTree) : UBTree :=\n  match t with\n    | leaf0 => node2 leaf0 s\n    | node2 t0 t1 => node2 t0 (right_UB t1 s)\n    | node1 t => node1 (right_UB t s)\n  end. \n\nEval compute in right_UB (node2 leaf0 leaf0) (node2 leaf0 (node2 leaf0 leaf0)).\nEval compute in right_UB (node2 leaf0 (node1 leaf0)) (node2 leaf0 (node2 leaf0 leaf0)).\n\nFixpoint length_UB (t:UBTree) : nat :=\n  match t with\n    | leaf0 => 1\n    | node2 t1 t2 => (length_UB t1) + (length_UB t2)\n    | node1 t => length_UB t\n  end.\n\nEval compute in length_UB (right_UB (node2 leaf0 leaf0) (node2 leaf0 (node2 leaf0 leaf0))).\nEval compute in length_UB (right_UB (node2 leaf0 (node1 leaf0)) (node2 leaf0 (node2 leaf0 leaf0))).\n\nTheorem right_UB_length : forall s t:UBTree, length_UB(right_UB s t) = length_UB s + length_UB t.\nProof.\n  induction s, t.\n  simpl; reflexivity.\n  simpl; reflexivity.\n  simpl; reflexivity.\n  Require Import Omega.\n  simpl. rewrite IHs2. simpl. omega.\n  simpl. rewrite IHs2. simpl. omega.\n  simpl. rewrite IHs2. simpl. omega.\n  simpl. rewrite IHs. simpl. reflexivity.\n  simpl. rewrite IHs. simpl. reflexivity.\n  simpl. rewrite IHs. simpl. reflexivity.\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_3_hf_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8043322133592865}}
{"text": "Require Import Algebra Tactics Equal ZArith.\nOpen Scope Z_scope.\n\nInductive Vec3 : Type :=\n  | vec3 : Z -> Z -> Z -> Vec3.\n\nDefinition specification_add_vec3 (add : Vec3 -> Vec3 -> Vec3) :=\n  forall x1 y1 z1 x2 y2 z2 : Z,\n    add (vec3 x1 y1 z1) \n        (vec3 x2 y2 z2) =\n    vec3 (x1 + x2) \n          (y1 + y2)\n          (z1 + z2).\n\nTheorem specification_of_add_vec3_is_unique :\n  forall add add' : Vec3 -> Vec3 -> Vec3,\n    specification_add_vec3 add  ->\n    specification_add_vec3 add' ->\n    forall v1 v2 : Vec3,\n      add v1 v2 = add' v1 v2.\nProof.\n  intros add add'.\n  unfold specification_add_vec3.\n  intros S_add S_add'.\n  intros v1 v2.\n  destruct v1 as [x1 y1 z1].\n  destruct v2 as [x2 y2 z2].\n  rewrite -> S_add.\n  symmetry.\n  exact (S_add' x1 y1 z1 x2 y2 z2).\nQed.\n\nFunction add_vec3 (v1 v2 : Vec3) : Vec3 :=\n  match v1, v2 with\n    | vec3 x1 y1 z1, vec3 x2 y2 z2 =>\n      vec3 (x1 + x2) (y1 + y2) (z1 + z2)\n  end.\n\nLemma unfold_add_vec3 :\n  forall x1 y1 z1 x2 y2 z2 : Z,\n    add_vec3 (vec3 x1 y1 z1) \n              (vec3 x2 y2 z2) =\n    vec3 (x1 + x2) \n          (y1 + y2)\n          (z1 + z2).\nProof.\n  unfold_tactic add_vec3.\nQed.\n\nTheorem add_vec3_satisfies_the_specification :\n  specification_add_vec3 add_vec3.\nProof.\n  unfold specification_add_vec3.\n  exact unfold_add_vec3.\nQed.\n\nTheorem Vec3_and_addition_is_associative :\n  Associative Vec3 add_vec3 eq.\nProof.\n  unfold Associative.\n  intros [x1 y1 z1] [x2 y2 z2] [x3 y3 z3].\n  rewrite ->4 unfold_add_vec3.\n  rewrite ->3 Z.add_assoc.\n  reflexivity.\nQed.\n\nCorollary Vec3_and_addition_is_a_semi_group :\n    Semi_Group Vec3 add_vec3 eq.\nProof.\n  unfold Semi_Group.\n  split.\n  exact (eq_is_a_valid_Equal Vec3).\n  exact Vec3_and_addition_is_associative.\nQed.\n\nDefinition O_vec3 : Vec3 := vec3 0 0 0.\n\nLemma add_O_vec3_l :\n  forall v : Vec3,\n    add_vec3 O_vec3 v = v.\nProof.\n  intros [x y z].\n  unfold O_vec3.\n  rewrite -> unfold_add_vec3.\n  rewrite ->3 Z.add_0_l.\n  reflexivity.\nQed.\n\nLemma add_O_vec3_r :\n  forall v : Vec3,\n    add_vec3 v O_vec3 = v.\nProof.\n  intros [x y z].\n  unfold O_vec3.\n  rewrite -> unfold_add_vec3.\n  rewrite ->3 Z.add_0_r.\n  reflexivity.\nQed.\n\nTheorem Vec3_and_addition_has_a_neutral_element :\n  exists (O : Vec3), \n    Neutral Vec3 add_vec3 O eq.\nProof.\n  unfold Neutral.\n  exists O_vec3.\n  intro v.\n  split.\n    exact (add_O_vec3_r v).\n\n    exact (add_O_vec3_l v).\nQed.\n\n\nCorollary Vec3_and_addition_is_a_monoid :\n  Monoid Vec3 add_vec3 eq.\nProof.\n  unfold Monoid.\n  split.\n  exact Vec3_and_addition_has_a_neutral_element.\n  exact Vec3_and_addition_is_a_semi_group.\nQed.\n\nTheorem Vec3_and_addition_is_commutative :\n  Commutative Vec3 add_vec3 eq.\nProof.\n  unfold Commutative.\n  intros [x1 y1 z1] [x2 y2 z2].\n  rewrite ->2 unfold_add_vec3.\n  symmetry.\n  rewrite -> (Z.add_comm x2 x1).\n  rewrite -> (Z.add_comm y2 y1).\n  rewrite -> (Z.add_comm z2 z1).\n  reflexivity.\nQed.\n\nDefinition opp_vec3 (v : Vec3) : Vec3 :=\n  match v with\n    | vec3 x y z => vec3 (Z.opp x) (Z.opp y) (Z.opp z)\n  end.\n\nLemma add_opp_vec3_r :\n  forall v : Vec3,\n    add_vec3 v (opp_vec3 v) = O_vec3.\nProof.\n  intros [x y z].\n  unfold opp_vec3.\n  unfold O_vec3.\n  rewrite -> unfold_add_vec3.\n  rewrite ->3 Zegal_left; reflexivity.\nQed.\n\nLemma add_opp_vec3_l :\n  forall v : Vec3,\n    add_vec3 (opp_vec3 v) v = O_vec3.\nProof.\n  intro v.\n  rewrite -> (Vec3_and_addition_is_commutative (opp_vec3 v) v).\n  exact (add_opp_vec3_r v).\nQed.\n\nTheorem Vec3_and_addition_has_an_inverse :\n  Inverse Vec3 add_vec3 eq.\nProof.\n  unfold Inverse. \n  intro v.\n  exists O_vec3.\n  exists (opp_vec3 v).\n  exact (add_opp_vec3_r v).\nQed.\n\nCorollary Vec3_and_addition_is_a_Abelian_group :\n  Abelian_Group Vec3 add_vec3 eq.\nProof.\n  unfold Abelian_Group.\n  split. \n    exact Vec3_and_addition_is_commutative.\n    split.\n      exact Vec3_and_addition_has_an_inverse.\n      exact Vec3_and_addition_is_a_monoid.\nQed.\n\n(* Vector multiplication is not assciative, because of its type : Vec3 -> Vec3 -> Z *)\n(* Therefore it is not a semi group. *)\n(* I assume that the vectors is transposed properly *)\n\nDefinition specification_of_vec3_multiplication (mult : Vec3 -> Vec3 -> Z) :=\n  forall x1 y1 z1 x2 y2 z2 : Z,\n    mult (vec3 x1 y1 z1) (vec3 x2 y2 z2) = x1 * x2 + y1 * y2 + z1 * z2.\n\nTheorem specification_of_vec3_multiplication_is_unique :\n  forall mult mult' : Vec3 -> Vec3 -> Z,\n    specification_of_vec3_multiplication mult ->\n    specification_of_vec3_multiplication mult' ->\n    forall v w : Vec3,\n      mult v w = mult' v w.\nProof.\n  intros mult mult'.\n  unfold specification_of_vec3_multiplication.\n  intros S_mult S_mult'.\n  intros [x1 y1 z1] [x2 y2 z2].\n  rewrite -> S_mult.\n  symmetry.\n  exact (S_mult' x1 y1 z1 x2 y2 z2).\nQed.\n\nFunction mult_vec3 (v w : Vec3) : Z :=\n  match v, w with\n    | vec3 x1 y1 z1, vec3 x2 y2 z2 =>\n      x1 * x2 + y1 * y2 + z1 * z2\n  end.\n\nLemma unfold_mult_vec3 :\n  forall x1 y1 z1 x2 y2 z2 : Z,\n    mult_vec3 (vec3 x1 y1 z1) (vec3 x2 y2 z2) = x1 * x2 + y1 * y2 + z1 * z2.\nProof.\n  unfold_tactic mult_vec3.\nQed.\n\nSearch (_ * _ = _ * _).\n\nTheorem mult_vec3_is_commutative :\n  forall v w : Vec3,\n    mult_vec3 v w = mult_vec3 w v.\nProof.\n  intros [x1 y1 z1] [x2 y2 z2].\n  rewrite ->2 unfold_mult_vec3.\n  symmetry.\n  rewrite -> (Z.mul_comm x2 x1).\n  rewrite -> (Z.mul_comm y2 y1).\n  rewrite -> (Z.mul_comm z2 z1).\n  reflexivity.\nQed.\n\n(* Please continue with Matrix3x3 *)\n", "meta": {"author": "klausfyhn", "repo": "A-Programming-Journey", "sha": "e8a669afd2cd0192c28639b5226fe8a1513d88c0", "save_path": "github-repos/coq/klausfyhn-A-Programming-Journey", "path": "github-repos/coq/klausfyhn-A-Programming-Journey/A-Programming-Journey-e8a669afd2cd0192c28639b5226fe8a1513d88c0/Vec3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8042169151751812}}
{"text": "(* Final Exam --- January 7, 2019 *)\n\n(****** 10152160137 \n\n        \u9648\u5f08\u541b\n******)\nRequire Import Nat.\nRequire Import List.\n\nNotation \"[ ]\" := nil. \nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nDefinition admit {T: Type} : T.  Admitted.\n\n\n(* 1. Prove the following two facts about natural numbers. *)\n\nLemma mul_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intro n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. \nQed.\n\n\nLemma mul_1_r : forall n : nat, n * 1 = n.\nProof. \n  intro n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\n(* 2. Complete the following definition so that (div5 n) returns true \niff n is divisible by 5. *)\n\nFixpoint div5 (n : nat) : bool :=\n  match n with\n   | O => true\n   | S O => false\n   | S (S O) => false\n   | S (S (S 0)) => false\n   | S (S (S (S 0))) => false\n   | S (S (S (S (S n')))) => (div5 n')\n  end.\n\nExample test1: div5 15 = true.\nProof. \n  simpl. reflexivity.\nQed.\n\nExample test2: div5 23 = false.\nProof. \n  simpl. reflexivity.\nQed.\n\n\n(* 3. Define a function createList such that (createList n) returns \na list of n numbers from 2n to 1. *)\n\n\nFixpoint createList (n : nat) : list nat :=\n  match n with\n  | O => nil\n  | S n' => [n*2; n*2-1] ++ (createList n')\n  end.\n\nExample test3 : createList 4 = [8;7;6;5;4;3;2;1].\nProof. \n  simpl. reflexivity.\nQed.\n\n\n(* 4. (1) Define the relation gtodd between odd numbers such that \n   (gtodd m n) holds if and only if m is greater than n for odd numbers m and n.\n(2) Show the transitivity of the relation gtodd. *)\n\nInductive od : nat -> Prop :=\n  | od_1 : od (S 0)\n  | od_SS : forall n : nat, od n -> od (S (S n)).\n\nInductive gtodd : nat -> nat -> Prop :=\n  | equal : forall n, od n -> gtodd n n\n  | greater : forall n m, (gtodd n m) -> (gtodd (S (S n)) m).\n\nExample test4 : gtodd 3 1.\nProof.\n  apply greater.\n  apply equal.\n  apply od_1.\nQed.\n\nExample test5 : ~ (gtodd 4 3).\nProof.\n  unfold not. intros. inversion H. inversion H1. inversion H4.\nQed.\n\nTheorem gtodd_trans : forall m n p,\n  gtodd m n -> gtodd n p -> gtodd m p.\nProof.\n  intros. induction H.\n  - apply H0.\n  - apply greater. apply IHgtodd. apply H0.\nQed.\n\n\n(* 5. Write a function (partition):\n\n      partition : list nat -> list (list nat )\n\n   which partitions a list into a list of 3 sublists. The first sublist\n   contains all even numbers in the original list. The second sublist \n   contains all odd numbers divisible by 5 in the original list. The last \n   sublist contains all other elements. The order of elements in the\n   three sublists should be the same as their order in the original list. \n\n   Hint: You can make use of the Coq function (filter).\n*)\n\n(********* Start Define evenb , oddb , orb  *************)\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 oddb (n:nat) : bool   :=   negb (evenb n).\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n(********* End Define evenb , oddb , orb *************)\n\nDefinition partition (l : list nat) : list (list nat) :=\n  [ filter evenb l;  \n    filter div5 l; \n    filter (fun n => if orb (evenb n) (div5 n) then false else true) l].\n\nExample test6: partition [1;2;3;9;4;5;6;15] = [[2;4;6]; [5;15]; [1;3;9]].\nProof.\n  unfold partition.\n  simpl. reflexivity.\nQed.\n\n\n(* 6. Prove that the excluded middle axiom implies the Peirce's law. *)\n\nTheorem peirce : \n  (forall P, P \\/ ~P) -> (forall P Q : Prop, ((P->Q)->P)->P).\nProof. \n  intros. destruct (H P).\n  - apply H1.\n  - unfold not in H1. apply H1 in H0.\n    + inversion H0.\n    + intros. apply H1 in H2. inversion H2.\nQed.\n\n\n(* 7. Let a sequence of numbers F(n) be given as follows.\n   F(0) = 0\n   F(1) = 1\n   F(2) = 1\n   F(n) = F(n-1) + F(n-2) + F(n-3)   for n > 2.\n\nDefine the function Seq such that (Seq n) returns the sequence.\n\n[0; F(0); 1; F(1); 2; F(2); 3; F(3); ... ; n; F(n)].\n*)\n\nFixpoint Seq (n: nat) : list nat :=\n  match n with\n  | O => [0;0]\n  | S n' => match n' with\n            | O => (Seq n') ++ [1;1] \n            | S m => match m with\n                     | O => (Seq n') ++ [2;1]\n                     | S o => (Seq n') ++ [n; (hd 0 (rev(Seq m)) + hd 0 (rev(Seq n')) + hd 0 (rev(Seq o)))]\n                     end\n            end\n  end.\n\nExample test7 :  Seq 10 = \n[0; 0; 1; 1; 2; 1; 3; 2; 4; 4; 5; 7; 6; 13; 7; 24; 8; 44; 9; 81; 10; 149].\nProof.\n  simpl. reflexivity.\nQed.\n\n\n(* 8. Consider the following type:\n\nInductive btree : Set :=\n | leaf : btree \n | node : nat->btree->btree->btree.\n\nDefine a function taking as argument a natural number n\nand a tree t and returning the number of occurrences of n in t.\n\nHint: You may use the function (eqb n m) which returns true iff the two natural\nnumbers n and m are equal.\n*)\n\nInductive btree : Set :=\n  | leaf : btree \n  | node : nat->btree->btree->btree.\n\nFixpoint occur (n: nat)(t: btree) : nat :=\n  match t with\n  | leaf => 0\n  | node m tl tr => match (eqb m n) with\n                    | true => (occur n tl) + (occur n tr) + 1\n                    | false => (occur n tl) + (occur n tr)\n                    end\n  end.\n\nExample test8 : occur 2 (node 1 (node 2 leaf (node 2 leaf leaf)) (node 3 (node 2 leaf leaf) leaf)) = 3.\nProof.\n  simpl. reflexivity.\nQed.\n\n(* 9 Design a sorting algorithm which transforms a list of natural numbers into \na list sorted in ascending oder. *)\n\n(************* Start define insert *************)\nFixpoint insert (n : nat)(l : list nat) : list nat :=\n  match l with\n  | nil => n :: nil\n  | h :: l' => match (leb h n) with\n               | false => n :: l\n               | true => h :: insert n l'\n               end\n  end.\n(************* End define insert *************)\n\nFixpoint transform (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h :: l' => insert h (transform l')\n  end.\n\nExample test10 : transform [2;4;1;6;9;6;4;1;3;5;10] = [1;1;2;3;4;4;5;6;6;9;10].\nProof.\n  simpl. reflexivity.\nQed.\n\n\n(* 10. The following definitions specify the abstract syntax of\n    some arithmetic expressions and an evaluation function. *)\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\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(* Suppose we define a function that takes an arithmetic expression \n   and slightly simplifies it, changing every occurrence of [e * 1] \n   (i.e., [(AMult e (ANum 1)]) into just [e]. *)\n\nFixpoint optimize_mult1 (a:aexp) : aexp :=\n  match a with\n  | ANum n => ANum n\n  | APlus e1 e2 => APlus (optimize_mult1 e1) (optimize_mult1 e2)\n  | AMinus e1 e2 => AMinus (optimize_mult1 e1) (optimize_mult1 e2)\n  | AMult e1 (ANum (S O)) => optimize_mult1 e1\n  | AMult e1 e2 => AMult (optimize_mult1 e1) (optimize_mult1 e2)\n  end.\n\n(* Prove the following theorem that states the correctness of the \noptimization with respect to the evaluation of arithmetic expressions. *)\n\nTheorem optimize_mult1_sound: forall a,\n aeval (optimize_mult1 a) = aeval a.\nProof. \n  intros a. induction a.\n  - reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - destruct a2; try (simpl; simpl in IHa2; rewrite IHa1; rewrite IHa2; reflexivity).\n  + simpl. destruct n eqn:eq.\n    * simpl. rewrite IHa1. reflexivity.\n    * simpl. destruct n0.\n      ** rewrite IHa1. rewrite mul_1_r. reflexivity.\n      ** simpl. rewrite IHa1. reflexivity.\nQed.", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/Solutions/exam2019.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8902942355821459, "lm_q1q2_score": 0.8041976322164409}}
{"text": "Require Import exer19.\nRequire Import Arith_base.\n   Fixpoint times (n m : nat) : nat :=\n      match n with\n      | 0    => 0\n      | S n' => m + (times n' m)\n      end.\n    Lemma zero_identity_add_right : forall n, n + 0 = n.\n    Proof.\n      intro n.\n      induction n as [ | n' IHn'].\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite IHn'.\n        reflexivity.\n    Qed.\nLemma mult_zero: forall n, n * 0 = 0.\n  Proof.\n  intro n.\n  induction n as [ | n' IHn'].\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\n\n\n\n \nLemma mult_um_esquerda: forall n, 1*n=n.\n  Proof.\n  intro n.\n  simpl.\n  apply zero_identity_add_right.\nQed.\n\nLemma mult_um_direita: forall n, n*1=n.\n  Proof.\n  intro n.\n   induction n as [ | n' IHn'].\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\n Lemma mult_s : forall m n, m + m * n = m * S n.\n Proof.\n   induction m ; simpl ; intros ; try reflexivity.\n   assert (m + (n + m * n) = n + (m + m * n)).\n   +\n          rewrite  add_associative.\n          rewrite  add_associative.\n          assert (m + n = n + m) by apply plus_comm.\n          rewrite H.\n          reflexivity.\n    +\n          rewrite H.\n          rewrite (IHm n).\n          reflexivity.\nQed.\n\nLemma mult_commut: forall n m , n * m = m * n.\n  Proof.\n    induction n.\n    +\n      intros m.\n      simpl.\n      rewrite (mult_zero).\n      reflexivity.\n    +\n      intros m.\n      simpl.\n      rewrite (IHn m).\n      apply mult_s.\nQed.\n\nLemma mult_aux: forall p m n, m * p + n * m * p = (m + n * m) * p.\n    induction m;simpl ; intros ; try reflexivity.\n    assert (p + m * p + n * S m * p = p + (m + n * S m) * p).\n     +\n      rewrite plus_comm.\n      rewrite plus_assoc.\n      rewrite plus_comm.\n      rewrite plus_assoc.\n      \n      reflexivity.\n      \n    +\n      intros.\n      simpl.\n      \n      \n      \n      \n\nLemma mul_associative:forall n m p, n * (m * p) = (n * m) * p.\n  induction n.\n  +\n    intros.\n    simpl.\n    reflexivity.\n  +\n    intros.\n    simpl.\n    rewrite (IHn m).\n", "meta": {"author": "Wesleycdias27", "repo": "COQ", "sha": "3be97b2e61dba97e92d0f15d40890b0277bb116c", "save_path": "github-repos/coq/Wesleycdias27-COQ", "path": "github-repos/coq/Wesleycdias27-COQ/COQ-3be97b2e61dba97e92d0f15d40890b0277bb116c/exer20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.8041863094345291}}
{"text": "Require Import Arith.\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n\nSearchAbout (_ + _ < _ + _).\n\nintros.\napply NPeano.Nat.add_lt_mono_r.\nassumption.\nQed.\n\nGoal forall P Q: nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\n  intros.\n  apply H0 . apply H.\nQed.\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\n  intros.\n  exists 1.\n  simpl.\n  apply H.\nQed.\n\nGoal forall P : nat -> Prop, (forall n m, P n -> P m) -> (exists p, P p) -> forall q, P q.\nProof.\n  intros. \n  destruct H0.\n  apply (H x).\n  assumption.\nQed.\n\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nintros.\nassert(n * 10 = 10 * n).\napply mult_comm.\nrewrite H. reflexivity.\nQed.\n(* SearchAbout (_ * _ = _ * _). *)\n\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  SearchAbout (_ + _ = _ + _).\n  apply plus_permute_2_in_4.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\nSearchAbout ((_ + _) * _).\nintros.\nrewrite mult_plus_distr_l.\nrewrite mult_plus_distr_r.\nrewrite mult_plus_distr_r.\nassert(H: m * n = n * m).\nrewrite mult_comm.\nreflexivity.\nrewrite H.\nassert(H2: n * m + n * m = 2 * n * m). \nsimpl.  rewrite mult_plus_distr_r.\nrewrite mult_plus_distr_r.\nsimpl.  SearchAbout (_ + 0).\nrewrite <- plus_n_O.\nreflexivity.\nrewrite <- H2.\nSearchAbout (_ + _ + _).\nrewrite -> plus_assoc.\nrewrite -> plus_assoc.\nassert(H3:n * m + m * m = m * m + n * m).\nrewrite -> plus_comm. reflexivity.\nrewrite <- plus_assoc. rewrite H3.\nSearchAbout (_ + _ + _).\nrewrite <- plus_permute_2_in_4.\nrewrite -> plus_assoc.\nreflexivity.\nQed.\n\n(* \u8ab2\u984c10 *)\n\nParameter G : Set.\nParameter mult : G -> G -> G.\nNotation \"x * y\" := (mult x y).\nParameter one : G.\nNotation \"1\" := one.\nParameter inv : G -> G.\nNotation \"/ x\" := (inv x).\nNotation \"x / y\" := (mult x (inv y)).\nAxiom mult_assoc : forall x y z, x * (y * z) = (x * y) * z.\nAxiom one_unit_l : forall x, 1 * x = x.\nAxiom inv_l : forall x, /x * x = 1.\n\nLemma inv_inv_inv_l : forall x : G, //x*/x=1.\nProof.\n intros.\n  rewrite inv_l. reflexivity.\nQed.\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  intros.\n  assert (H1: 1 * x / x = x / x).\n  rewrite one_unit_l.  reflexivity.\n  rewrite <- H1. \n  assert (H2: 1 * x / x = //x*/x*x/x). \n  rewrite inv_inv_inv_l. reflexivity.\n  rewrite H2.\n  assert(H3: //x/x*x/x=//x*(/x*x)*/x).\n  rewrite -> mult_assoc. reflexivity.\n  rewrite H3. rewrite inv_l.\n  rewrite <- mult_assoc.\n  rewrite one_unit_l.   \n  rewrite inv_inv_inv_l. reflexivity.\nQed.\n\nLemma one_unit_r: forall x, x * 1 = x.\nProof.\n intros.\n assert(H1: x * 1 = x * /x * x).\n rewrite <- mult_assoc.\n rewrite inv_l. reflexivity.\n rewrite  H1.  rewrite inv_r. rewrite one_unit_l.\n reflexivity.\nQed.\n", "meta": {"author": "moritanon", "repo": "Coq2014", "sha": "08d72e37ad035c91d1bcf109a68d1225fdaa11b4", "save_path": "github-repos/coq/moritanon-Coq2014", "path": "github-repos/coq/moritanon-Coq2014/Coq2014-08d72e37ad035c91d1bcf109a68d1225fdaa11b4/ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8041863045844216}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Nat Lia.\n\nSet Implicit Arguments.\n\nSection interval.\n\n  (* A small interval & valuation library *)\n\n  Definition interval := (nat * nat)%type. (* (a,b) <~~~> [a,b[ *)\n\n  Implicit Types (i j : interval).\n\n  Definition in_interval i x := let (a,b) := i in a <= x < b.\n  Definition out_interval i x := let (a,b) := i in x < a \\/ b <= x.\n  Definition interval_disjoint i j := forall x, in_interval i x -> in_interval j x -> False.\n\n  Definition interval_union (i j : interval) :=\n    match i, j with (a1,b1),(a2,b2) => (min a1 a2, max b1 b2) end.\n\n  Fact in_out_interval i x : in_interval i x -> out_interval i x -> False.\n  Proof. destruct i; simpl; lia. Qed.\n\n  Fact in_out_interval_dec i x : { in_interval i x } + { out_interval i x }.\n  Proof. \n    destruct i as (a,b); simpl.\n    destruct (le_lt_dec a x); destruct (le_lt_dec b x); try (left; lia);right; lia.\n  Qed. \n\n  Fact interval_union_left i j x : in_interval i x -> in_interval (interval_union i j) x.\n  Proof.\n    revert i j; intros (a,b) (u,v); simpl.\n    generalize (Nat.le_min_l a u) (Nat.le_max_l b v); lia.\n  Qed.\n\n  Fact interval_union_right i j x : in_interval j x -> in_interval (interval_union i j) x.\n  Proof.\n    revert i j; intros (a,b) (u,v); simpl.\n    generalize (Nat.le_min_r a u) (Nat.le_max_r b v); lia.\n  Qed.\n\n  Definition valuation_union i1 (g1 : nat -> nat) i2 g2 : \n               interval_disjoint i1 i2 \n            -> { g | (forall x, in_interval i1 x -> g x = g1 x)\n                  /\\ (forall x, in_interval i2 x -> g x = g2 x) }.\n  Proof.\n    intros H2.\n    exists (fun x => if in_out_interval_dec i1 x then g1 x else g2 x).\n    split; intros x Hx.\n    + destruct (in_out_interval_dec i1 x) as [ | H3 ]; auto.\n      exfalso; revert Hx H3; apply in_out_interval.\n    + destruct (in_out_interval_dec i1 x) as [ H3 | ]; auto.\n      exfalso; revert H3 Hx; apply H2.\n  Qed.\n\n  Definition valuation_one_union k v i1 (g1 : nat -> nat) i2 g2 : \n               ~ in_interval (interval_union i1 i2) k \n            -> interval_disjoint i1 i2 \n            -> { g | g k = v /\\ (forall x, in_interval i1 x -> g x = g1 x)\n                             /\\ (forall x, in_interval i2 x -> g x = g2 x) }.\n  Proof.\n    intros H1 H2.\n    exists (fun x => if eq_nat_dec x k then v \n                     else if in_out_interval_dec i1 x then g1 x \n                     else g2 x).\n    split; [ | split ].\n    + destruct (eq_nat_dec k k) as [ | [] ]; auto.\n    + intros x Hx.\n      destruct (eq_nat_dec x k) as [ | ].\n      * subst; destruct H1; apply interval_union_left; auto.\n      * destruct (in_out_interval_dec i1 x) as [ | H3 ]; auto.\n        exfalso; revert Hx H3; apply in_out_interval.\n    + intros x Hx.\n      destruct (eq_nat_dec x k) as [ | ].\n      * subst; destruct H1; apply interval_union_right; auto.\n      * destruct (in_out_interval_dec i1 x) as [ H3 | ]; auto.\n        exfalso; revert H3 Hx; apply H2.\n  Qed.\n\nEnd interval.", "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/interval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.8041742126236993}}
{"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(*                   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_Exp.v                                 *)\n(****************************************************************************)\n\n\nRequire Export Lib_Mult.\n\n\nFixpoint exp_2 (n : nat) : nat :=\n  match n return nat with\n  | O =>\n      (*O*)  1 \n      (*S p*) \n  | S p => 2 * exp_2 p\n  end.\n\n\n\nFixpoint exp_n (n m : nat) {struct m} : nat :=\n  match m return nat with\n  | O =>\n      (*O*)  1 \n      (*S p*) \n  | S p => n * exp_n n p\n  end.\n\n\n\n\n(************************************************************************)\n(********************************* Base 2 *******************************)\n(************************************************************************)\n\nLemma eq_exp_2_exp_n : forall n : nat, exp_2 n = exp_n 2 n.\nsimple induction n; auto with arith.\nintros.\nchange (exp_2 (S n0) = 2 * exp_n 2 n0) in |- *.\nelim H; auto with arith.\nQed.\nHint Resolve eq_exp_2_exp_n.\n\n\n\nLemma exp_2_n_plus_n : forall n : nat, exp_2 n + exp_2 n = exp_2 (S n).\nintro.\nrewrite plus_mult.\nchange (2 * exp_2 n = 2 * exp_2 n) in |- *.\nreflexivity.\nQed.\nHint Resolve exp_2_n_plus_n.\n\n\n\nLemma exp_2_plus_pn_pn :\n forall n : nat, 0 < n -> exp_2 (pred n) + exp_2 (pred n) = exp_2 n.\nintros.\nrewrite exp_2_n_plus_n.\nrewrite S_pred_n; auto with arith.\nQed.\nHint Resolve exp_2_plus_pn_pn.\n\n\n\nLemma exp_2_le_pn_n : forall n : nat, exp_2 (pred n) <= exp_2 n.\nsimple induction n; auto with arith.\nintros.\nsimpl in |- *.\nelim plus_n_O; auto with arith.\nQed.\nHint Resolve exp_2_le_pn_n.\n\n\n\nLemma exp_2_pos : forall n : nat, 0 < exp_2 n.\nsimple induction n; auto with arith.\nintros.\nsimpl in |- *.\nelim plus_n_O; auto with arith.\nQed.\nHint Resolve exp_2_pos.\n\n\n\nLemma exp_2_incr : forall n m : nat, n <= m -> exp_2 n <= exp_2 m.\nintros.\nelim H; auto with arith.\nintros.\nsimpl in |- *.\nelim plus_n_O.\nelim H1; auto with arith.\nQed.\nHint Resolve exp_2_incr.\n\n\n\nLemma exp_2_n_plus_m : forall n m : nat, exp_2 (n + m) = exp_2 n * exp_2 m.\nsimple induction n.\nintro.\nsimpl in |- *.\nelim plus_n_O; reflexivity.\nintros.\nsimpl in |- *.\nelim plus_n_O.\napply sym_equal.\nelim plus_n_O.\nrewrite H.\nelim mult_plus_distr_r; reflexivity.\nQed.\nHint Resolve exp_2_n_plus_m.\n\n\n(************************************************************************)\n(********************************** Base n ******************************)\n(************************************************************************)\n\nLemma exp_n_incr : forall n m p : nat, n <= m -> exp_n n p <= exp_n m p.\nsimple induction p; auto with arith.\nintros.\nsimpl in |- *.\napply le_mult_csts; auto with arith.\nQed.\nHint Resolve exp_n_incr.\n\n\n\nLemma exp_n_neutre : forall n : nat, exp_n 1 n = 1.\nsimple induction n; auto with arith.\nintros.\nsimpl in |- *.\nrewrite H; auto with arith.\nQed.\nHint Resolve exp_n_neutre.\n\n\n\nLemma exp_n_plus_mult :\n forall n m p : nat, exp_n n (m + p) = exp_n n m * exp_n n p.\nsimple induction p.\nsimpl in |- *.\nelim plus_n_O.\nelim mult_n_Sm.\nauto with arith.\nelim mult_n_O; auto with arith.\n\nclear p; intros p H_rec.\nelim plus_n_Sm.\nsimpl in |- *.\nrewrite H_rec.\nelim mult_assoc_reverse.\nrewrite (mult_comm n (exp_n n m)).\nauto with arith.\nQed.\nHint Resolve exp_n_plus_mult.\n\n\n\nLemma exp_n_permut :\n forall n m p : nat, exp_n n (m * p) = exp_n (exp_n n p) m.\nsimple induction m; auto with arith.\nintros.\nsimpl in |- *.\nelim H.\nelim exp_n_plus_mult; auto with arith.\nQed.\nHint Resolve exp_n_permut.\n\n\n\nLemma exp_n_plus_p1 : forall n p : nat, exp_n n (p + 1) = n * exp_n n p.\nsimple induction p; simpl in |- *.\nauto with arith.\nintros no H; rewrite H; auto with arith.\nQed.\nHint Resolve exp_n_plus_p1.\n\n\nLemma exp_n_pos : forall n p : nat, 0 < n -> 0 < exp_n n p.\nsimple induction p.\nsimpl in |- *; auto with arith.\nintros.\nsimpl in |- *.\napply lt_nm_mult; auto with arith.\nQed.\nHint Resolve exp_n_pos.\n\n\n\nLemma le_exp_n_mult : forall n p : nat, 0 < n -> exp_n n p <= n * exp_n n p.\nauto with arith.\nQed.\nHint Resolve le_exp_n_mult.\n\n\n(************************************************************************)\n", "meta": {"author": "coq-contribs", "repo": "hardware", "sha": "cc92b5cb860fd857da744cc39628c6ad1508ddf9", "save_path": "github-repos/coq/coq-contribs-hardware", "path": "github-repos/coq/coq-contribs-hardware/hardware-cc92b5cb860fd857da744cc39628c6ad1508ddf9/Libraries/Lib_Arithmetic/Lib_Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8040834840287461}}
{"text": "\n\nInductive natural : Type :=  Zero : natural| Succ : natural -> natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint fac (fac_arg0 : natural) : natural\n           := match fac_arg0 with\n              | Zero => Succ Zero\n              | Succ n => mult (fac n) n\n              end.\n\nFixpoint qfac (qfac_arg0 : natural) (qfac_arg1 : natural) : natural\n           := match qfac_arg0, qfac_arg1 with\n              | Zero, n => n\n              | Succ n, m => qfac n (mult m n)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\nintros.\ninduction x.\n- rewrite plus_zero. reflexivity.\n- simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_zero : forall (x : natural), mult x Zero = Zero.\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_succ : forall (x y : natural), plus (mult x y) x = mult x (Succ y).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite plus_succ. rewrite plus_assoc. rewrite (plus_commut y x). rewrite <- plus_assoc. rewrite IHx. rewrite plus_succ. reflexivity.\nQed.\n\nLemma mult_commut : forall (x y : natural), mult x y = mult y x.\nProof.\nintros.\ninduction x.\n- rewrite mult_zero. reflexivity.\n- simpl. rewrite IHx. rewrite mult_succ. reflexivity.\nQed.\n\nLemma distrib : forall (x y z : natural), mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut (mult y z) z). rewrite <- plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall (x y z : natural), mult (mult x y) z = mult x (mult y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite distrib. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural), eq (mult (fac x) y) (qfac x y).\nProof.\ninduction x.\n- reflexivity.\n- intros. simpl. rewrite <- IHx. rewrite mult_assoc. rewrite (mult_commut x y). reflexivity.\nQed.\n              \n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.8039095245179827}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, bag_more_functions *)\n\nInductive natlist: Type:=\n|nil: natlist\n|cons: nat -> natlist -> natlist.\n\nNotation \"[]\" := nil.\nNotation \" x :: l\" := (cons x l).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition bag := natlist.\n\nFixpoint count (v: nat) (s: bag) : nat :=\nmatch s with\n|nil     => O\n|h :: t => if (Nat.eqb v h) then S(count v t) else count v t\nend.\n\nDefinition member (v:nat) (s:bag) : bool := \nmatch (count v s) with \n|O => false \n| _ => true \nend.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\nmatch s with \n|nil => nil\n|h::t => if (Nat.eqb h v) then t else h::(remove_one v t)\nend.\n\nExample test_remove_one1 : count 5 (remove_one 5 [2;1;5;4;1]) = 0. Proof. reflexivity. Qed.\nExample test_remove_one2 : count 5 (remove_one 5 [2;1;4;1]) = 0. Proof. reflexivity. Qed.\nExample test_remove_one3 : count 4 (remove_one 5 [2;1;4;5;1;4]) = 2. Proof. reflexivity. Qed.\nExample test_remove_one4 : count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1. Proof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag := \nmatch s with \n|nil => nil\n|h::t => if (Nat.eqb h v) 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. Proof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0. Proof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2. Proof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0. Proof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool := \nmatch s1 with\n|nil  => true\n|h::t => if (member h s2) then subset t (remove_one h s2) else false\nend.\nExample test_subset1 : subset [1;2] [2;1;4;1] = true. Proof. reflexivity. Qed.\nExample test_subset2 : subset [1;2;2] [2;1;4;1] = false. Proof. reflexivity. Qed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter5_Library_List/bag_more_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.803864926584262}}
{"text": "(*******************************************************************************\n\nTitle: Arith.v\nAuthors: Jeremy Avigad, Chris Kapulkin, Peter LeFanu Lumsdaine\nDate: 1 March 2013\n\nThis file contains some basic arithmetic, ported from Coq\u2019s standard Peano.v.\n(We cannot import that, since it is not all homotopy-compatible.)\n\nOnce the HoTT library contains its own development of arithmetic, this\nfile will be obsolete.\n\n*******************************************************************************)\n\nRequire Import HoTT.\nRequire Import Auxiliary.\n\nOpen Scope nat_scope.\n\nHint Resolve (ap S): v62.\nHint Resolve (ap (A:=nat)): core.\n\n(** Booleans *)\nInductive Bool : Type :=\n  | true : Bool\n  | false : Bool.\n\nDefinition is_true (b:Bool) : Type\n  := match b with true => Unit | false => Empty end.\n\nDefinition true_neq_false : true = false -> Empty\n  := (fun H => transport is_true H tt).\n\n(** The predecessor function *)\n\nDefinition pred (n:nat) : nat := match n with\n                                 | O => n\n                                 | S u => u\n                                 end.\nHint Resolve (ap pred): v62.\n\nTheorem pred_Sn : forall n:nat, n = pred (S n).\nProof.\n  simpl; reflexivity.\nDefined.\n\n(** Injectivity of successor *)\n\n(* eq_add_S in Peano.v *)\nDefinition S_inj : forall {n m:nat}, S n = S m -> n = m.\nProof.\n  intros n m p. apply (ap pred p).\nDefined.\nHint Resolve S_inj: core.\n\nDefinition is_succ (n:nat) : Type :=\n  match n with\n  | O => Empty\n  | S p => Unit\n  end.\n\nDefinition is_zero (n:nat) : Type :=\n  match n with\n  | O => Unit\n  | S p => Empty\n  end.\n\n(** Zero is not the successor of a number *)\n\nTheorem O_neq_S {n:nat} : 0 = S n -> Empty.\nProof.\n  intros p. apply (transport is_zero p). constructor.\nDefined.\n\nHint Resolve O_neq_S: core.\n\nTheorem n_Sn : forall n:nat, n = S n -> Empty.\nProof.\n  induction n; auto; apply O_neq_S.\nDefined.\n\nHint Resolve n_Sn: core.\n\n(** Addition *)\n\nFixpoint plus (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\n\nwhere \"n + m\" := (plus n m) : nat_scope.\n\nHint Resolve (ap10 o (ap plus)): v62.\n\nLemma plus_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n; simpl; auto.\nDefined.\nHint Resolve plus_n_O: core.\n\nLemma plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  auto.\nDefined.\n\nLemma plus_n_Sm : forall n m:nat, S (n + m) = n + S m.\nProof.\n  intros n m; induction n; simpl; auto.\nDefined.\nHint Resolve plus_n_Sm: core.\n\nLemma plus_Sn_m : forall n m:nat, S n + m = S (n + m).\nProof.\n  auto.\nDefined.\n\n(** Standard associated names *)\n\nNotation plus_0_r_reverse := plus_n_O (compat \"8.2\").\nNotation plus_succ_r_reverse := plus_n_Sm (compat \"8.2\").\n\n(** Multiplication *)\n\nFixpoint mult (n m:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => m + p * m\n  end\n\nwhere \"n * m\" := (mult n m) : nat_scope.\n\nHint Resolve (ap10 o (ap mult)): core.\n\nLemma mult_n_O : forall n:nat, 0 = n * 0.\nProof.\n  induction n; simpl; auto.\nDefined.\nHint Resolve mult_n_O: core.\n\nLemma mult_n_Sm : forall n m:nat, n * m + n = n * S m.\nProof.\n  intros; induction n as [| p H]; simpl; auto.\n  destruct H; rewrite <- plus_n_Sm; apply (ap S).\n  pattern m at 1 3; elim m; simpl; auto.\nDefined.\nHint Resolve mult_n_Sm: core.\n\n(** Standard associated names *)\n\nNotation mult_0_r_reverse := mult_n_O (compat \"8.2\").\nNotation mult_succ_r_reverse := mult_n_Sm (compat \"8.2\").\n\n(** Truncated subtraction: [m-n] is [0] if [n>=m] *)\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O, _ => n\n  | S k, O => n\n  | S k, S l => k - l\n  end\n\nwhere \"n - m\" := (minus n m) : nat_scope.\n\n(** Definition of the usual orders, the basic properties of [le] and [lt]\n    can be found in files Le and Lt *)\n\nInductive le (n:nat) : nat -> Type :=\n  | le_n : n <= n\n  | le_S : forall m:nat, n <= m -> n <= S m\n\nwhere \"n <= m\" := (le n m) : nat_scope.\n\nHint Constructors le: core.\n(*i equivalent to : \"Hints Resolve le_n le_S : core.\" i*)\n\nDefinition lt (n m:nat) := S n <= m.\nHint Unfold lt: core.\n\nInfix \"<\" := lt : nat_scope.\n\nDefinition ge (n m:nat) := m <= n.\nHint Unfold ge: core.\n\nInfix \">=\" := ge : nat_scope.\n\nDefinition gt (n m:nat) := m < n.\nHint Unfold gt: core.\n\nInfix \">\" := gt : nat_scope.\n\n(* Awaiting definition of /\\:\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\nTheorem S_preserves_le : forall n m, n <= m -> (S n) <= (S m).\nProof.\nintros n m H; induction H; auto.\nDefined.\n\n(** le_pred in Peano.v *)\nTheorem pred_preserves_le : forall n m, n <= m -> pred n <= pred m.\nProof.\ninduction 1; auto. destruct m; simpl; auto.\nDefined.\n\n(** le_S_n *)\nTheorem S_reflects_le : forall {n m}, S n <= S m -> n <= m.\nProof.\nintros n m. exact (pred_preserves_le (S n) (S m)).\nDefined.\n\nTheorem O_le_n n : O <= n.\nProof.\n  induction n; auto.\nDefined.\n\nTheorem n_le_O : forall {n:nat}, n <= 0 -> n = 0.\nProof.\n  assert (gen : forall n m, 0 = m -> n <= m -> n = m).\n  intros n. induction n as [ | n' IH].\n    intros; auto.\n    intros m p H. destruct H as [ | m' H'].\n      destruct (O_neq_S p).\n      destruct (O_neq_S p).\n  intros; apply gen; auto.\nDefined.\n\nDefinition le_refl := le_n.\n\nTheorem le_trans : forall {i j k:nat}, i <= j -> j <= k -> i <= k.\nProof.\n  intros i j k Hij Hjk. induction Hjk as [ | k' Hjk' IH].\n    auto.\n    auto.\nDefined.\n\n(** Case analysis *)\n\nTheorem nat_case :\n forall (n:nat) (P:nat -> Type), P 0 -> (forall m:nat, P (S m)) -> P n.\nProof.\n  induction n; auto.\nDefined.\n\n(** Principle of double induction *)\n\nTheorem nat_double_ind :\n forall R:nat -> nat -> Type,\n   (forall n:nat, R 0 n) ->\n   (forall n:nat, R (S n) 0) ->\n   (forall n m:nat, R n m -> R (S n) (S m)) -> forall n m:nat, R n m.\nProof.\n  induction n; auto.\n  destruct m; auto.\nDefined.\n\n(** max and min omitted *)\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_plus :\n  forall (n m:nat) {A} (f:A -> A) (x:A),\n    nat_iter (n + m) f x = nat_iter n f (nat_iter m f x).\nProof.\n  induction n; intros; simpl; rewrite ?IHn; trivial.\nDefined.\n\n(** Preservation of invariants : if [f : A->A] preserves the invariant [Inv],\n    then the iterates of [f] also preserve it. *)\n\nTheorem nat_iter_invariant :\n  forall (n:nat) {A} (f:A -> A) (P : A -> Type),\n    (forall x, P x -> P (f x)) ->\n    forall x, P x -> P (nat_iter n f x).\nProof.\n  induction n; simpl; trivial.\n  intros A f P Hf x Hx. apply Hf, IHn; trivial.\nDefined.\n\n(** Decidability\n\nNote: there are several possible approaches to decidability.\nHere we mix a few of them. *)\n\nFixpoint booleq_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' => booleq_nat n' m'\n      end\n    end.\n\nFixpoint le_bool (n m:nat) : Bool :=\n  match n with\n    | O => true\n    | S n' => match m with\n      | O => false\n      | S m' => le_bool n' m'\n      end\n    end.\n\nDefinition le_bool__le {n m : nat} : (le_bool n m = true) -> n <= m.\nProof.\n  revert m. induction n as [ | n' IHn]; intros [ | m']; simpl.\n    auto.\n    intros; apply O_le_n.\n    intros H. destruct (true_neq_false (H^)).\n    intros H. apply S_preserves_le. apply IHn. assumption.\nDefined.\n\nDefinition le__le_bool {n m : nat} : n <= m -> (le_bool n m = true).\nProof.\n  revert m. induction n as [ | n' IHn]; intros [ | m']; simpl.\n    auto.\n    auto.\n    intros H. destruct (O_neq_S (n_le_O H)^).\n    intros H. apply IHn. apply S_reflects_le. assumption.\nDefined.\n\nDefinition Decide (A:Type) := (A + (A -> Empty))%type.\n\nDefinition eq_dec_nat : forall (n m:nat), Decide (n = m).\nProof.\n  intros n; induction n as [ | n' IHn];\n    intros m; destruct m as [ | m'].\n    (* O = O *) apply inl. auto.\n    (* O = S m' *) apply inr. apply O_neq_S.\n    (* S n' = 0 *) apply inr.\n      intros H. exact (O_neq_S H^).\n    (* Sn' = S m' *)\n      destruct (IHn m') as [ yes | no ].\n      (* yes *) apply inl; auto.\n      (* now *) apply inr.\n        intros H. apply no. apply (S_inj H).\nDefined.\n\nDefinition le_dec : forall (n m:nat), Decide (n <= m).\nProof.\n  intros n; induction n as [ | n' IHn];\n    intros m; destruct m as [ | m'].\n    (* O = O *) apply inl. auto.\n    (* O = S m' *) apply inl. apply O_le_n.\n    (* S n' = 0 *) apply inr.\n      intros H. exact (O_neq_S (n_le_O H)^).\n    (* Sn' = S m' *)\n      destruct (IHn m') as [ yes | no ].\n      (* yes *) apply inl; apply S_preserves_le; auto.\n      (* now *) apply inr.\n        intros H. apply no. apply (S_reflects_le H).\nDefined.\n\nTheorem nat_is_hset : IsHSet nat.\nProof.\n  apply hset_decpaths. unfold DecidablePaths. apply eq_dec_nat.\nDefined.\n\nDefinition nat_HSet : HSet\n  := Build_HSet nat nat_is_hset.\n\n(* TODO (mid): re-enable this as soon as the Canonical Structures issue is fixed.\nCanonical Structure nat_HSet.\n*)\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/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8688267711434708, "lm_q1q2_score": 0.8038645579767563}}
{"text": "Inductive Nat : Type := Zero : Nat  | Succ : Nat -> Nat.\n\nFixpoint plus (n m:Nat) : Nat :=\n    match n with\n    | Zero      => m\n    | Succ n    => Succ (plus n m)\n    end.\n\nInductive Vec : Type -> Nat -> Type :=\n| VNil : forall (a:Type), Vec a Zero\n| VCons: forall (a:Type) (n:Nat) (x:a) (xs:Vec a n), Vec a (Succ n)\n.\n\n\nFixpoint replicate (a:Type) (n:Nat) (x:a) : Vec a n :=\n    match n with\n    | Zero      => VNil a\n    | Succ n    => VCons a n x (replicate a n x)\n    end.\n\nCompute replicate.\n(*\n    = fix Ffix (x : Type) (x0 : Nat) (x1 : x) {struct x0} : Vec x x0 :=\n      match x0 as c return (Vec x c) with\n      | Zero => VNil x\n      | Succ x2 => VCons x x2 x1 (Ffix x x2 x1)\n      end\n      : forall (a : Type) (n : Nat), a -> Vec a n\n*)\n\nArguments replicate {a} _ _.\n\nDefinition replicate' := \n    fix f (a:Type) (n:Nat) (x:a) : Vec a n :=\n        match n as n' return (Vec a n') with\n        | Zero      => VNil a\n        | Succ p    => VCons a p x (f a p x)\n        end.\n\nCheck replicate'.\n\nArguments replicate' {a} _ _.\n\nLemma replicate_correct : forall (a:Type) (n:Nat) (x:a),\n   replicate n x = replicate' n x.\nProof.\n    intros a n x. induction n.\n    - reflexivity.\n    - simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma Vec_Same : forall (a:Type) (n m:Nat), n = m -> Vec a n = Vec a m.\nProof. intros a n m H. rewrite H. reflexivity. Qed.\n\n\nDefinition cast (a b:Type) (p:a = b) (x:a) : b :=\n    match p in _ = T return T with\n    | eq_refl    => x\n    end.\n\nArguments cast {a} {b} _ _.\n\nDefinition toVec (a:Type) (n m:Nat) (p:n = m) (x:Vec a n) : Vec a m :=\n    cast (Vec_Same a n m p) x.\n\nLemma plus_0_n : forall (n:Nat), n = plus Zero n.\nProof. intros n. induction n; reflexivity. Qed.\n\n\nArguments VNil {a}.\nArguments VCons {a} {n} _ _.\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/haskell/dth/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8740772466456688, "lm_q1q2_score": 0.8038386096250746}}
{"text": "From LF Require Export Basics.\nFrom LF Require Export Induction.\nFrom LF Require Export Lists.\n\n(*1 \u0431\u0430\u043b\u043b*)\nTheorem mult_comm : forall n m : nat,\n  n * m = m * n.\nProof.\n  intros. induction n as [|m'].\n  - simpl. rewrite mult_0_r. reflexivity. \n  - simpl. rewrite IHm'. \n    assert (H: forall x y, x + x * y = x * S y).\n    { intros. induction x as [|x']. \n      - reflexivity. \n      - simpl. rewrite <- IHx'. rewrite plus_swap. reflexivity. }\n    rewrite H. reflexivity. \nQed.\n\n(*2 \u0431\u0430\u043b\u043b*)\nTheorem mult_plus_distr_l : forall n m p : nat,\n p* (n + m)  = (p* n) + (p * m).\nProof.\nintros n m p.\ninduction p.\nreflexivity.\nsimpl.\nrewrite IHp.\nrewrite<- plus_assoc.\npattern (m + (p * n + p * m)).\nrewrite plus_assoc.\npattern (m + p * n).\nrewrite plus_comm.\nrewrite plus_assoc.\nrewrite plus_assoc.\nrewrite plus_assoc.\nreflexivity.\nQed.\n\n\n(*3 \u0431\u0430\u043b\u043b\u0430*)\nLemma plusCrazy : forall m n p q : nat,\n                  plus m (plus n (plus p q)) = plus n (plus (plus q m) p).\nProof.\n  intros m n p q.\n  + rewrite plus_swap. replace (m+(p+q)) with (q+m+p). {reflexivity. } rewrite plus_comm.\n    replace (q+m) with (m+q). { rewrite plus_swap. reflexivity. } rewrite plus_comm.\n    reflexivity.\nQed.\n\n(*4 \u0431\u0430\u043b\u043b\u0430*)\nTheorem mult_S_1 : forall n m : nat,   m = S n -> mult m (plus 1 n) = mult m m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity. Qed.\n\n(*\u0414\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e*)\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 nonzeros (l:natlist) : natlist :=\n  match l with\n    | [] => []\n    | h :: t =>\n        match h with\n          | 0 => nonzeros t\n          | nz => nz :: (nonzeros t)\n        end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n  reflexivity. Qed.\n\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/KR1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8036654702137048}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import Coq.Arith.Peano_dec.\n\nCheck eq_nat_dec.\n\nEval compute in eq_nat_dec 1 1.\nEval compute in eq_nat_dec 1 0.\n\nAbout eq_nat_dec.\nCheck eq_nat_dec.\nCheck eq_nat_dec 1 1.\n\nDefinition test_func (n m:nat) : nat :=\n  match eq_nat_dec n m with\n  | left _ => 1\n  | right _ => 0\n  end.\n\nEval compute in test_func 1 1. (* result 1 *)\nEval compute in test_func 1 0. (* result 0 *)\n\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq_ssreflect_practice", "sha": "96e1d440c8c69673209ae0d86046b6b9305f8bab", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice", "path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice/coq_ssreflect_practice-96e1d440c8c69673209ae0d86046b6b9305f8bab/practices/nat_prop_to_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.8036466771755877}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma positive_is_nonzero : forall x, x > 0 -> x <> 0.\n  Proof. intros; lia. Qed.\n#[global]\n  Hint Resolve positive_is_nonzero : zarith.\n\n  Lemma le_lt_trans n m p : n <= m -> m < p -> n < p.\n  Proof. lia. Qed.\n\n  Lemma le_fold_right_max : forall low l x, (forall y, List.In y l -> low <= y) ->\n    List.In x l -> x <= List.fold_right Z.max low l.\n  Proof.\n    induction l as [|a l IHl]; intros ? lower_bound In_list; [cbv [List.In] in *; intuition | ].\n    simpl.\n    destruct (List.in_inv In_list); subst.\n    + apply Z.le_max_l.\n    + etransitivity.\n      - apply IHl; auto; intuition auto with datatypes.\n      - apply Z.le_max_r.\n  Qed.\n\n  Lemma le_fold_right_max_initial : forall low l, low <= List.fold_right Z.max low l.\n  Proof.\n    induction l as [|a l IHl]; intros; try reflexivity.\n    etransitivity; [ apply IHl | apply Z.le_max_r ].\n  Qed.\n\n  Lemma add_compare_mono_r: forall n m p, (n + p ?= m + p) = (n ?= m).\n  Proof.\n    intros n m p.\n    rewrite <-!(Z.add_comm p).\n    apply Z.add_compare_mono_l.\n  Qed.\n\n  Lemma leb_add_same x y : (x <=? y + x) = (0 <=? y).\n  Proof. destruct (x <=? y + x) eqn:?, (0 <=? y) eqn:?; Z.ltb_to_lt; try reflexivity; lia. Qed.\n#[global]\n  Hint Rewrite leb_add_same : zsimplify.\n\n  Lemma ltb_add_same x y : (x <? y + x) = (0 <? y).\n  Proof. destruct (x <? y + x) eqn:?, (0 <? y) eqn:?; Z.ltb_to_lt; try reflexivity; lia. Qed.\n#[global]\n  Hint Rewrite ltb_add_same : zsimplify.\n\n  Lemma geb_add_same x y : (x >=? y + x) = (0 >=? y).\n  Proof. destruct (x >=? y + x) eqn:?, (0 >=? y) eqn:?; Z.ltb_to_lt; try reflexivity; lia. Qed.\n#[global]\n  Hint Rewrite geb_add_same : zsimplify.\n\n  Lemma gtb_add_same x y : (x >? y + x) = (0 >? y).\n  Proof. destruct (x >? y + x) eqn:?, (0 >? y) eqn:?; Z.ltb_to_lt; try reflexivity; lia. Qed.\n#[global]\n  Hint Rewrite gtb_add_same : zsimplify.\n\n  Lemma sub_pos_bound a b X : 0 <= a < X -> 0 <= b < X -> -X < a - b < X.\n  Proof. lia. Qed.\n\n  Lemma le_sub_1_iff x y : x <= y - 1 <-> x < y.\n  Proof. lia. Qed.\n\n  Lemma le_add_1_iff x y : x + 1 <= y <-> x < y.\n  Proof. lia. 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/Le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.8033617455829821}}
{"text": "Require Import Coq.Init.Nat.\n(* N\u00e3o deve ser importado nenhum novo arquivo\ntodas as defini\u00e7\u00f5es devem estar neste arquivo \n*)\n\n(* Teoremas do Induction.v e Basics.v*)\n\nTheorem add_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nTheorem add_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n.\n  - reflexivity.\n  - simpl.\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.\n  - simpl.\n    rewrite add_0_r.\n    reflexivity.\n  - simpl.\n    rewrite <- plus_n_Sm.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem add_shuffle3 : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite add_assoc.\n  assert(H: n + m = m + n). \n    {rewrite add_comm. reflexivity. }\n  rewrite H.\n  rewrite add_assoc.\n  reflexivity.\nQed.\n\nLemma mult_n_Sm:\n  forall m n: nat,\n  n * S m = n + (n * m).\nProof.\n  intros m n.\n  induction n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHn.\n    rewrite add_shuffle3.\n    reflexivity.\nQed.\n\nTheorem mul_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n as [ | n' IHn].\n  - reflexivity.\n  - simpl.\n    rewrite IHn.\n    reflexivity. \nQed.\n\nTheorem mul_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m.\n  - rewrite mul_0_r.\n    reflexivity.\n  - simpl.\n    rewrite mult_n_Sm.\n    rewrite IHm.\n    reflexivity.\nQed.\n\n(*Fim dos Teoremas*)\n\nFixpoint div2 (n:nat) : nat :=\n  match n with\n  | O => O\n  | S O => O \n  | S (S n') => S (div2 n')  \nend.  \n\nFixpoint sum (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n + sum n'\n  end.\n\nTheorem plus_n_1 : forall (n : nat),\n  n + 1 = S (n).\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall (n m:nat),\n  n + S m = S (n + m).\nProof. \n  intros n m.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn.\n    reflexivity.  \nQed.\n\nTheorem mult_2_n_plus : forall (n : nat),\n  n + n = 2 * n.\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite add_0_r.\n    reflexivity.\nQed.\n\nTheorem mul2_div2 : forall n : nat,\n  n = div2 (2 * n).\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - rewrite mult_n_Sm.\n    simpl.\n    rewrite add_0_r.\n    rewrite mult_2_n_plus.\n    rewrite <- IHn.\n    reflexivity.\nQed.\n\nTheorem div2_mult2_plus: forall (n m : nat),\n  n + div2 m = div2 (2 * n + m).\nProof.\n  intros n m.\n  induction n.\n  - reflexivity.\n  - rewrite mult_n_Sm.\n    simpl.\n    rewrite add_0_r.\n    rewrite mult_2_n_plus.\n    rewrite <- IHn.\n    reflexivity.\nQed.\n\nTheorem mult_Sn_m : forall (n m : nat),\n  S n * m = m + n * m.\nProof.\n  intros n m.\n  rewrite mul_comm.\n  rewrite mult_n_Sm.\n  rewrite <- mul_comm.\n  reflexivity.\nQed.\n\nTheorem sum_Sn : forall n : nat,\n  sum (S n) = S n + sum n.\nProof.\n  reflexivity.\nQed.\n\nTheorem sum_n : forall n : nat,\n  sum n = div2 (n * (n + 1)).\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - rewrite plus_n_1.\n    rewrite mult_n_Sm.\n    rewrite mult_Sn_m.\n    rewrite sum_Sn.\n    assert(H: n * S n = S n * n). \n    { rewrite mul_comm. reflexivity. }\n    rewrite H.\n    rewrite mult_Sn_m.\n    rewrite add_assoc.\n    rewrite mult_2_n_plus.\n    rewrite <- div2_mult2_plus.\n    rewrite IHn.\n    rewrite <- mult_n_Sm.\n    rewrite plus_n_1. \n    reflexivity.\nQed.", "meta": {"author": "MiguelANunes", "repo": "MFO", "sha": "07b8a8b9ad9e3891499985db59b17dcce7c15dbe", "save_path": "github-repos/coq/MiguelANunes-MFO", "path": "github-repos/coq/MiguelANunes-MFO/MFO-07b8a8b9ad9e3891499985db59b17dcce7c15dbe/Listas/Lista1/ListaExe1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8033523538214798}}
{"text": "(* A sorting example : \n   (C) Yves Bertot, Pierre Casteran \n*)\n\n(**\nThis version uses some new features of Coq : Type Classes and User Defined Relations.\n\nThe function called \"aux\" in the book has been renamed to \"insert\" and \"equiv\" has \nbeen renamed to \"permutation\".\n*)\n\n\nRequire Import List  ZArith RelationClasses Morphisms\n               Extraction.\nOpen Scope Z_scope.\n\nInductive sorted : list Z -> Prop :=\n  | sorted0 : sorted nil\n  | sorted1 : forall z:Z, sorted (z :: nil)\n  | sorted2 :\n      forall (z1 z2:Z) (l:list Z),\n        z1 <= z2 ->\n        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\n#[export] Hint Constructors sorted :  sort.\n\nLemma sort_2357 :\n sorted (2 :: 3 :: 5 :: 7 :: nil).\nProof.\n auto with sort zarith.\nQed.\n\n(**\n  inversion lemma \n*)\n  \nTheorem sorted_inv :\n forall (z:Z) (l:list Z), sorted (z :: l) -> sorted l.\nProof.\n intros z l H; inversion H; auto with sort.\nQed.\n\n(*  Number of occurrences of z in l *)\n\nFixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat\n  | (z' :: l') =>\n      match Z.eq_dec z z' with\n      | left _ => S (nb_occ z l')\n      | right _ => nb_occ z l'\n      end\n  end.\n\nExample ex0 : nb_occ 3 (3 :: 7 :: 3 :: nil) = 2%nat.\nProof. reflexivity. Qed.\n\n(* list l' is a permutation of list l *)\n\nDefinition permutation (l l':list Z) : Prop := \n    forall z:Z, nb_occ z l = nb_occ z l'.\n\n(* permutation is an equivalence ! *)\n\nInstance permutation_refl : Reflexive permutation.\nProof.\n intro x; red; trivial.\nQed.\n\nInstance  permutation_sym : Symmetric permutation.\nProof.\n intros x y Hxy ; unfold permutation; auto.\nQed.\n\nInstance permutation_trans : Transitive permutation.\nProof.\n intros l l' l'' H H0 z; rewrite H; now apply H0.\nQed.\n\n\nLemma permutation_cons :\n forall (z:Z) (l l':list Z), permutation l l' -> \n                             permutation (z :: l) (z :: l').\nProof.\n intros z l l' H z'; simpl; case (Z.eq_dec z' z); auto. \nQed.\n\n\nInstance cons_proper : Proper (eq ==> permutation ==> permutation) (@cons Z).\nProof.\n intros x y Hxy l l' Hll'; subst y; now apply permutation_cons.\nQed.\n\nLemma permutation_transpose :\n forall (a b:Z) (l l':list Z),\n   permutation l l' -> \n   permutation (a :: b :: l) (b :: a :: l').\nProof.\n intros a b l l' H z; simpl.\n case (Z.eq_dec z a); case (Z.eq_dec z b); \n  simpl; case (H z); auto.\nQed.\n\n#[export] Hint Resolve permutation_cons permutation_refl permutation_transpose : sort.\n\n\n(* insertion of z into l at the right place \n   (assuming l is sorted) \n*)\n\nFixpoint insert (z:Z) (l:list Z)  : list Z :=\n  match l with\n  | nil => z :: nil\n  | cons a l' =>\n      match Z_le_gt_dec z a with\n      | left _ =>  z :: a :: l'\n      | right _ => a :: (insert z l')\n      end\n  end.\n   \n\nLemma insert_permutation : forall (l:list Z) (x:Z), \n                  permutation (x :: l) (insert x l).\nProof.\n induction l as [|a l0 H]; simpl ; auto with sort.\n -  intros x; case (Z_le_gt_dec x a);\n      simpl; auto with sort.\n    +  intro H0; apply permutation_trans with (a :: x :: l0); \n       auto with sort.\nQed.\n\n\nLemma insert_sorted :\n forall (l:list Z) (x:Z), sorted l -> sorted (insert x l).\nProof.\n intros l x H; induction  H; simpl; auto with sort.\n -  case (Z_le_gt_dec x z); simpl;  auto with sort zarith.\n -   revert H H0 IHsorted; simpl; \n     case (Z_le_gt_dec x z2) ,  (Z_le_gt_dec x z1); \n       simpl; auto with sort zarith.\nQed.\n\n(* the sorting function *)\n\nDefinition sort :\n  forall l:list Z, {l' : list Z | permutation l l' /\\ sorted l'}.\n induction l as [| a l IHl]. \n -  exists (nil (A:=Z)); split; auto with sort.\n -  case IHl; intros l' [H0 H1].\n    exists (insert a l'); split.\n    + transitivity (a::l').\n      * now  rewrite H0. \n      * apply insert_permutation.\n    +  now apply insert_sorted. \nDefined.\n\nExtraction \"insert-sort\" insert sort.\n\n\n", "meta": {"author": "haoyang9804", "repo": "coq-Art", "sha": "52204f59312510c678a7dd9f4e60f15d44af9226", "save_path": "github-repos/coq/haoyang9804-coq-Art", "path": "github-repos/coq/haoyang9804-coq-Art/coq-Art-52204f59312510c678a7dd9f4e60f15d44af9226/ch1_overview/SRC/chap1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8652240808393983, "lm_q1q2_score": 0.8032816528176642}}
{"text": "(** Here is an inductively defined proposition describing whether a\n    natural number is even. *)\nInductive even : nat -> Prop :=\n| even_O : even O\n| even_SS : forall n, even n -> even (S (S n)).\n\nLemma even_4 : even 4.\nProof.\n  apply even_SS.\n  Show Proof.\n  apply even_SS.\n  Show Proof.\n  apply even_O.\nQed.\n\nPrint even_4.\n\n(** Provide a proof term (not a script) for the following propositions. *)\nDefinition even_8 : even 8\n. (* Proof term here *) Admitted.\n\nDefinition even_4plusn : forall n, even n -> even (4 + n)\n. (* Proof term here *) Admitted.\n\n(* Recall the definition of the inductive types corresponding to\n   logical connectives. *)\nPrint and.\n\nPrint or.\n\n(* For the following propositions, provide a proof term. Do not use\n   the proof mode and tactics. *)\n\nDefinition and_comm : forall P Q, P /\\ Q -> Q /\\ P\n. (* Proof term here *) Admitted.\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P\n. (* Proof term here *) Admitted.\n\n(* The type of false proposition is the empty type, meaning that there\n   is no constructor to build such a proposition. *)\nPrint False.\n\n(* Use patter-matching over this empty type to define the principle of\n   explosion. *)\nDefinition ex_falso : forall P, False -> P\n. (* Proof term here *) Admitted.\n\n(* Inductive proofs correspond to recursive functions. *)\n\n(* Let us first prove the base case and inductive step separately. *)\nDefinition base_case : 0 = 0 + 0\n. (* Proof term here *) Admitted.\n\n(* This proof can be difficult to write, as often with equality-based\n   proofs.  Hint: It can be done using only [eq_rect]. *)\nDefinition inductive_step : forall n, n = n + 0 -> S n = S n + 0\n. (* Proof term here *) Admitted.\n\n(** Combine the two lemmas into an inductive proof/recursive\n    function. Use [fix] to define the recursion (see presentation), or\n    alternatively replace <<Definition>> by <<Fixpoint>>. *)\nDefinition add_0 : forall n, n = n + 0\n. (* Proof term here *) Admitted.\n\n(** Use tactics to define addition over natural numbers, instead of\n    writing the term directly. Use the keyword <<Defined>> instead of\n    the usual <<Qed>> at the end of your script: This ensures that the\n    proof term that you created is transparent (not opaque as proofs\n    usually are). *)\nDefinition add' : nat -> nat -> nat.\nAdmitted.\n\n(* If your definition is correct, the following lemmas should be\n   proved as given. *)\nExample ex1 : add' 0 3 = 3.\nProof.\n  reflexivity.\nQed.\n\nExample ex2 : add' 2 4 = 6.\nProof.\n  reflexivity.\nQed.\n\nExample ex3 : add' 3 8 = 11.\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "vlopezj", "repo": "coq-course", "sha": "b7f3c44d73859ddad49a6edbfd3430283bcc251f", "save_path": "github-repos/coq/vlopezj-coq-course", "path": "github-repos/coq/vlopezj-coq-course/coq-course-b7f3c44d73859ddad49a6edbfd3430283bcc251f/exercises/3/Ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.8032816462640612}}
{"text": "(***********************************************************************)\n(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\n(*                                                                     *)\n(***********************************************************************)\n(***********************************************************************)\n(*                                                                     *)\n(*  Definition of cyclic group                                         *)\n(*                                                                     *)\n(***********************************************************************)\n(***********************************************************************)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat.\nRequire Import seq fintype div prime.\nRequire Import finset groups morphisms automorphism normal group_perm zp fp.\n\n(* Require Import paths connect bigops. *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection Phi.\n\n(***********************************************************************)\n(*                                                                     *)\n(*  Euler phi function                                                 *)\n(*                                                                     *)\n(***********************************************************************)\n\nDefinition phi n := #|([eta coprime n] : pred 'I_n)|.\n\nLemma cardphi : forall p, #|fp_mul_finGroupType p| = (phi p).\nProof.  by move=> p; rewrite card_sub. Qed.\n\nLemma phi0 : phi 0 = 0.\nProof.\nby rewrite /phi eq_card0 //; case; case=> [|n]; case/negP; rewrite ltn0.\nQed.\n\nLemma phi_mult: forall m n,\n  coprime m n -> phi (m * n) = phi m * phi n.\nProof.\nmove=> m n Hcop.\ncase: (posnP m) => [-> | mpos]; first by rewrite mul0n phi0 mul0n.\ncase: (posnP n) => [-> | npos]; first by rewrite muln0 phi0 muln0.\nhave:= @rho_isom (PosNat mpos) (PosNat npos) Hcop.\nby move/isom_card; rewrite !cardsT card_prod !cardphi.\nQed.\n\nLemma phi_prime_k: forall p k (H:prime p),\n  phi (p ^ k.+1) = (p ^ (k.+1)) - (p ^ k).\nProof.\nmove => p k Hp; have Hp0: (0 < p) by exact: (ltn_0prime Hp).\napply: (canRL (addnK _)); rewrite /phi /= {7}expnS.\nhave Hf: forall x : fzp (p ^ k), p * x < p * (p ^ k).\n  by move => [n1 /= Hn1]; rewrite /= ltn_pmul2l.\npose f (x : fzp (p ^ k)) := Ordinal (Hf x).\nhave injF: injective f.\n  move=> [x Hx] [y Hy] [Hxy]; apply: val_inj => /=.\n  by apply/eqP; rewrite -(@eqn_pmul2l p) // Hxy.\nrewrite -{1}(card_ord (p ^ k)) -(card_image injF ).\nrewrite -{5}(card_ord (p * p ^ k)) addnC.\nset a := image _ _; apply: etrans (cardC a); congr addn.\napply: eq_card => [[x Hx]] /=.\nrewrite [_ \\in _]coprime_pexpl // prime_coprime //=.\nsuff: p %| x = ~~ predC a (Ordinal Hx) by move=> ->; apply/negPn/idP.\napply/idP/idP.\n  move/dvdnP=> [y Dx]; have Hy := Hx.\n  rewrite Dx mulnC ltn_pmul2l /= in Hy => //.\n  apply/negPn; apply/imageP.\n  exists (Ordinal Hy) => //.\n  by rewrite /f /=; apply: val_inj; rewrite /= mulnC.\nmove/negPn; move/imageP=> [y Hy]; rewrite/f; move/eqP=> /= HH.\nby apply/dvdnP; exists (nat_of_ord y); rewrite mulnC; apply/eqP.\nQed.\n\nEnd Phi.\n\n(***********************************************************************)\n(*                                                                     *)\n(*  Cyclic group                                                       *)\n(*                                                                     *)\n(***********************************************************************)\n\nImport GroupScope.\n\nSection Cyclic.\n\nVariable gT : finGroupType.\nImplicit Types a x y : gT.\nImplicit Types A B : {set gT}.\nImplicit Types G H : {group gT}.\n\nDefinition cyclic A := existsb x, A == <[x]>.\n\nLemma cyclicP : forall A, reflect (exists x, A = <[x]>) (cyclic A).\nProof. move=> A; apply: (iffP existsP) => [] [x]; exists x; exact/eqP. Qed.\n\nLemma cycle_cyclic : forall x, cyclic <[x]>.\nProof. by move=> x; apply/cyclicP; exists x. Qed.\n\nLemma cycle1 : <[1]> = 1 :> {set gT}.\nProof. by apply/eqP; rewrite eqEsubset gen_subG !sub1G. Qed.\n\nLemma cycle_id : forall a, a \\in <[a]>.\nProof. by move=> a; rewrite mem_gen // set11. Qed.\n\nLemma cycle_subG : forall a H, (<[a]> \\subset H) = (a \\in H).\nProof. by move=> a H; rewrite gen_subG sub1set. Qed.\n\nLemma mem_cycle : forall a m, a ^+ m \\in <[a]>.\nProof. by move=> a m; rewrite groupX // cycle_id. Qed.\n\nDefinition zp_to_cycle n a (i : 'I_n) := a ^+ i.\n\nLemma zp_to_cycleM : forall (n : pos_nat) a, a ^+ n = 1 ->\n  {in setT &, {morph @zp_to_cycle n a : x y / x * y}}.\nProof.\nrewrite /zp_to_cycle => n a an_1 [i _] [j _] _ _ /=; rewrite -expgn_add.\nby rewrite {2}(divn_eq (i + j) n) expgn_add mulnC expgn_mul an_1 exp1gn mul1g.\nQed.\n\nLemma order1 : #[1 : gT] = 1%N.\nProof. by rewrite /order cycle1 cards1. Qed.\n\nLemma order_inf : forall a n, a ^+ n.+1 == 1 -> #[a] <= n.+1.\nProof.\nmove=> a [|n]; move/eqP; first by rewrite expg1 => ->; rewrite order1.\nmove/zp_to_cycleM=> zpM; rewrite -[n.+2]card_ord -cardsT.\napply: leq_trans (subset_leq_card _) (leq_imset_card (Morphism zpM) _).\nrewrite -morphimEdom gen_subG sub1set /= morphimEdom /=.\napply/imsetP; exists (inord 1 : 'I_n.+2); first exact: in_setT.\nby rewrite /zp_to_cycle inordK // expg1.\nQed.\n\nLemma zp_to_cycle_inj : forall a, injective (@zp_to_cycle #[a] a).\nProof.\nmove=> a i j; wlog ltij : i j / i < j.\n  by case (ltngtP i j); [|symmetry|move/val_inj]; auto.\nmove/eqP; rewrite eq_mulVg1 /zp_to_cycle -(subnK ltij) addSnnS expgn_add mulKg.\nmove/order_inf; rewrite -leq_subS // subSS leqNgt; case/negP.\nexact: leq_ltn_trans (leq_subr i j) _.\nQed.\n\nLemma zp_to_cycle_imset :  forall a, @zp_to_cycle #[a] a @: setT = <[a]>.\nProof.\nmove=> a; apply/eqP; rewrite eqEcard andbC.\nrewrite (card_imset _ (@zp_to_cycle_inj a)) cardsT card_ord leqnn.\nby apply/subsetP=> x; case/imsetP=> i _ ->; rewrite mem_cycle.\nQed.\n\nLemma cyclePmin : forall a b,\n  reflect (exists2 m, m < #[a] & a ^+ m = b) (b \\in <[a]>).\nProof.\nmove=> a b; rewrite -zp_to_cycle_imset.\napply: (iffP imsetP) => [[m] | [m ltma <-]]; first by exists (m : nat).\nby exists (Ordinal ltma); rewrite ?inE.\nQed.\n\nLemma cycleP : forall a b, reflect (exists n, a ^+ n = b) (b \\in <[a]>).\nProof.\nmove=> a b; apply: (iffP idP) => [|[n <-]]; last exact: mem_cycle.\nby case/cyclePmin=> n; exists n.\nQed.\n\nLemma order_expn1 : forall a, a ^+ #[a] = 1.\nProof.\nmove=> a; have: a^-1 \\in <[a]> by rewrite groupV cycle_id.\ncase/cyclePmin=> i; rewrite leq_eqVlt=> ltia a_i.\nhave{a_i} a_i1: a ^+ i.+1 = 1 by rewrite expgS a_i mulgV.\ncase/predU1P: ltia => [<- //| lti1a].\nby have:= @zp_to_cycle_inj a (Ordinal lti1a) ord0 a_i1.\nQed.\n\nCanonical Structure zp_to_cycle_morphism a :=\n  Morphism (zp_to_cycleM (order_expn1 a)).\n\nLemma zp_to_cycle_injm : forall a, 'injm (@zp_to_cycle #[a] a).\nProof.\nby move=>a; apply/injmP; move=> x y _ _; apply:zp_to_cycle_inj.\nQed.\n\nLemma cycle_isom : forall a, isom setT  <[a]> (@zp_to_cycle #[a] a).\nProof.\nmove=> a; apply/isomP; split; last by rewrite morphimEdom zp_to_cycle_imset.\napply/injmP; apply: in2W; exact: zp_to_cycle_inj.\nQed.\n\nLemma cycle_decomp : forall a b,\n  b \\in <[a]> -> {m : nat | m < #[a] & a ^+ m = b}.\nProof.\nmove=> a b Cab; have ex_i: exists i, a ^+ i == b.\n  by case/cycleP: Cab => i <-; exists i.\nexists (ex_minn ex_i); case: ex_minnP => i a_i min_i; last exact/eqP.\ncase/cyclePmin: Cab => j ltja a_j; apply: leq_ltn_trans ltja.\nby rewrite min_i // a_j.\nQed.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Order Properties (1/2)                                       *)\n(*                                                                     *)\n(***********************************************************************)\n\nLemma cycleJ : forall a b, <[a ^ b]> = <[a]> :^ b.\nProof. by move=> a b; rewrite -genJ conjg_set1. Qed.\n\nLemma orderJ : forall a b, #[a ^ b] = #[a].\nProof. by move=> a b; rewrite /order cycleJ cardJg. Qed.\n\nLemma expg_mod_order : forall a k, a ^+ k = a ^+ (k %% #[a]).\nProof.\nmove=> a k; rewrite {1}(divn_eq k #[a]) expgn_add mulnC expgn_mul.\nby rewrite order_expn1 exp1gn mul1g.\nQed.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Commutativity Properties                                     *)\n(*                                                                     *)\n(***********************************************************************)\n\n\nLemma commute_cycle_com : forall a b : gT,\n  commute a b -> {in <[a]>, centralised <[b]>}.\nProof.\nmove=> a b Hcom x; case/cycleP=> kx <-{x} y; case/cycleP=> ky <- {y}.\nexact: commuteX2.\nQed.\n\nLemma commute_cycle_normal : forall a b : gT,\n  commute a b -> <[a * b]> \\subset 'N(<[a]>).\nProof.\nmove=> a b Hcom; apply: cents_norm.\napply/centsP; apply: commute_cycle_com.\napply: commute_sym; exact: commuteM.\nQed.\n\nLemma commute_cycle_sub : forall a b : gT,\n  commute a b -> coprime #[a] #[b] -> <[a]> \\subset <[a * b]>.\nProof.\nmove=> a b c_ab; move/eqnP=> co_ab; apply/subsetP=> x; case/cycleP=> k <-{x}.\ncase: (egcdnP #[a] (ltn_0order b))=> kb ka Heq Hineq.\napply/cycleP; exists (kb * #[b] * k)%N.\nrewrite (expMgn _ c_ab) {2}(mulnC kb) -(mulnA #[b]).\nrewrite (expgn_mul b #[b]) order_expn1 exp1gn mulg1.\nrewrite Heq gcdnC co_ab muln_addl mul1n expgn_add -(mulnC #[a]).\nby rewrite -(mulnA #[a]) expgn_mul order_expn1 exp1gn mul1g.\nQed.\n\nLemma cycle_mul : forall (a b : gT),\n  commute a b -> coprime #[a] #[b] -> <[a * b]> = <[a]> * <[b]>.\nProof.\nmove=> a b c_ab co_ab; apply/eqP; rewrite eqEcard coprime_cardMg //.\nhave ->: <[a * b]> \\subset <[a]> * <[b]>.\n  have CaCb := cent_mulgenEl (introT centsP (commute_cycle_com c_ab)).\n  by rewrite -CaCb gen_subG sub1set /= CaCb mem_mulg ?cycle_id.\nrewrite dvdn_leq ?ltn_0order // gauss_inv //=.\nby rewrite {2}c_ab !cardSg // commute_cycle_sub // coprime_sym.\nQed.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Bijection with Zp                                            *)\n(*                                                                     *)\n(***********************************************************************)\n\nLemma decomp_irr : forall a b (x y : {m | (m < #[a]) && (a ^+ m == b)}),\n  x = y.\nProof.\nmove=> a b x y; apply: val_inj; wlog: x y / val x < val y.\n  by move=> IH; case: (ltngtP (val x) (val y)) => // *; last symmetry; auto.\ncase: x => m /=; case/andP=> _; case: y => n /=; case/andP=> lt_n_oa.\nmove/eqP <-; rewrite eq_mulVg1 => eq1 ltmn; move: eq1.\nrewrite -{1}(subnK ltmn) addSnnS expgn_add mulKg; move/order_inf.\nby rewrite leqNgt (leq_trans _ lt_n_oa) // -leq_subS // ltnS subSS leq_subr.\nQed.\n\nLemma decomp_order_unicity :  forall a m (lt_m_oa : m < #[a]) n,\n  (n < #[a]) && (a ^+ n == a ^+ m) -> m = n.\nProof.\nmove=> a m; rewrite -[m < _]andbT -(eqxx (a ^+ m)) => def_m n def_n.\nby case: (decomp_irr (Sub m def_m) (Sub n def_n)).\nQed.\n\nLemma imset_zp_to_cycle : forall a, <[a]> \\subset (zp_to_cycle a @* setT).\nProof. by move=> a; rewrite -zp_to_cycle_imset morphimEdom. Qed.\n\nDefinition cycle_to_zp (a: gT) :=\n  restrm (imset_zp_to_cycle a) (invm (zp_to_cycle_injm a)).\n\nLemma cycle_to_zp_id : forall a n,\n   n %% #[a] = cycle_to_zp a (a ^+ n).\nProof.\nmove=> a n; move :(ltn_0order a); rewrite expg_mod_order -(ltn_mod n #[a]) => H.\nrewrite -/(nat_of_ord (Ordinal H)).\nby rewrite -{1}(invmE (zp_to_cycle_injm a) (in_setT (Ordinal H))).\nQed.\n\nLemma cycle_to_zp_corr : forall a b,\n  b \\in <[a]> -> a ^+ (cycle_to_zp a b) == b.\nProof.\nmove=> a b; rewrite -zp_to_cycle_imset; move/imsetP => [n Hn ->].\nby rewrite -{2}(invmE (zp_to_cycle_injm a) Hn).\nQed.\n\nLemma zp_inj : forall a, 'injm ([morphism of cycle_to_zp a]).\nProof. by move=> a /=; apply: (injm_restrm _ (injm_invm _)). Qed.\n\nLemma zp_isom : forall a, isom <[a]> setT ([morphism of cycle_to_zp a]).\nProof.\nmove=> a; apply/isomP; split; first exact: zp_inj.\nby rewrite /= morphim_restrm setIid -zp_to_cycle_imset -morphimEdom invm_dom.\nQed.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Order properties  (2/2)                                      *)\n(*                                                                     *)\n(***********************************************************************)\n\nLemma order_dvd : forall a n, (#[a] %| n) = (a ^+ n == 1).\nProof.\nmove=> a n; rewrite expg_mod_order /dvdn; apply/idP/idP.\n  by move/eqP->; rewrite expg0.\nrewrite -(expg0 a); move : (ltn_0order a); rewrite -(ltn_mod n)=> H.\nby move/(conj H); move/andP; move/(decomp_order_unicity (ltn_0order a))=> <-.\nQed.\n\nLemma order_eq1 : forall a, (#[a] == 1%N) = (a == 1).\nProof. by move=> a; rewrite -dvdn1 order_dvd expg1. Qed.\n\nLemma cycle_eq1 : forall a, (<[a]> == 1) = (a == 1).\nProof. by move=> a; rewrite -order_eq1 trivg_card1. Qed.\n\nLemma order_dvd_g : forall (H : {group gT}) a, a \\in H -> #[a] %| #|H|.\nProof. by move=> H a Ha; apply: cardSg; rewrite cycle_subG. Qed.\n\nLemma order_gexp_dvd : forall a n, #[a ^+ n] %| #[a].\nProof. move=> a n; apply: order_dvd_g; exact: mem_cycle. Qed.\n\nLemma order_gcd : forall a n, 0 < n -> #[a ^+ n] = #[a] %/ gcdn #[a] n.\nProof.\nmove => a n H.\napply/eqP; rewrite eqn_dvd; apply/andP; split.\n  rewrite order_dvd -expgn_mul -gcdn_divnC //.\n  by rewrite expgn_mul order_expn1 exp1gn.\nsuff: #[a] %| #[a ^+ n] * gcdn #[a] n.\n  move: (dvdn_gcdl #[a] n) (divn_eq #[a] (gcdn #[a] n)).\n  rewrite {1}/dvdn; move/eqP=> H1; rewrite {1}H1 addn0=> {H1} H1.\n  by rewrite {1}H1 dvdn_pmul2r // ltn_0gcd H orbT.\nrewrite order_dvd mulnC expgn_mul -[a ^+ _]mulg1.\ncase: (egcdnP #[a] H)=> z2 z1 H1 H2.\nrewrite -{1}(@exp1gn _ z1) -{1}(order_expn1 a) -expgn_mul.\nrewrite mulnC -expgn_add addnC gcdnC -H1 -expgn_mul -mulnA mulnC.\nby rewrite 2!expgn_mul order_expn1 exp1gn.\nQed.\n\nLemma order_mul : forall a b : gT,\n  commute a b -> coprime #[a] #[b] -> #[a * b] = (#[a] * #[b])%N.\nProof.\nby move=> a b Hcom Hcop; rewrite -coprime_cardMg -?cycle_mul.\nQed.\n\nLemma eq_expg_mod_order : forall x m n,\n  (x ^+ m == x ^+ n) = (m == n %[mod #[x]]).\nProof.\nmove=> x m n; wlog le_nm: m n / n <= m.\n  by move=> IH; case/orP: (leq_total m n); move/IH; rewrite // eq_sym => ->.\nrewrite eqn_mod_dvd // -{1}(subnK le_nm) expgn_add.\nby rewrite (can2_eq (mulKg _) (mulKVg _)) mulVg order_dvd.\nQed.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Generator                                                    *)\n(*                                                                     *)\n(***********************************************************************)\n\nDefinition generator (A : {set gT}) a := A == <[a]>.\n\nLemma generator_cycle : forall a, generator <[a]> a.\nProof. by move=> a; exact: eqxx. Qed.\n\nLemma cycle_generator : forall a x, generator <[a]> x -> x \\in <[a]>.\nProof. move=> a x; move/(<[a]> =P _)->; exact: cycle_id. Qed.\n\nLemma generator_order : forall a b,\n  generator <[a]> b -> #[a] = #[b].\nProof. by rewrite /order => a b; move/(<[a]> =P _)->. Qed.\n\nLemma cycle_subset : forall a n, <[a ^+ n]> \\subset <[a]>.\nProof. move=> a n; rewrite cycle_subG; exact: mem_cycle. Qed.\n\nLemma cycleV : forall a, <[a^-1]> = <[a]>.\nProof.\nmove=> a; symmetry; apply/eqP; rewrite eqEsubset.\nby rewrite !cycle_subG // -2!groupV invgK !cycle_id.\nQed.\n\nLemma orderV : forall x, #[x^-1] = #[x].\nProof. by move=> x; rewrite /order cycleV. Qed.\n\nEnd Cyclic.\n\nSection CyclicSubGroup.\n\nVariable gT : finGroupType.\n\n(*  G. 1.3.1 (i) *)\n\nLemma cycle_sub_group : forall (a : gT) m, m %| #[a] ->\n  [set H : {group gT} | (H \\subset <[a]>) && (#|H| == m)]\n     = [set <[a ^+ (#[a] %/ m)]>%G].\nProof.\nmove=> a m Hdiv.\nhave Hpos: 0 < m by apply (ltn_0dvd (ltn_0order a) Hdiv).\nhave Hcardm: #|<[a ^+ (#[a] %/ m)]>| == m.\n  have Hdivpos: 0 < #[a] %/ m by\n    rewrite -(ltn_pmul2r Hpos) mul0n (divnK Hdiv) ltn_0order.\n  rewrite [card ( _)](order_gcd _ Hdivpos).\n  rewrite {2}(divn_eq #[a] m) mulnC; move:{+}Hdiv; rewrite /dvdn.\n  move/eqP->; rewrite gcdnC gcdn_addl_mul gcdn0.\n  rewrite -{2}(@mulKn m (#[a] %/ m)) ?Hdivpos //=.\n  by rewrite (divnK Hdiv) eqxx.\napply/eqP; rewrite eqEsubset sub1set inE /= cycle_subset Hcardm !andbT.\napply/subsetP=> X; rewrite in_set1 inE -val_eqE /= eqEcard (eqP Hcardm).\ncase/andP=> sXa; move/eqP=> oX; rewrite oX leqnn andbT.\napply/subsetP=> x Xx; case/cycleP: (subsetP sXa _ Xx) => k def_x.\nhave: (x ^+ m == 1)%g by rewrite -oX -order_dvd cardSg // gen_subG sub1set.\nrewrite -def_x -expgn_mul -order_dvd -[#[a]](LaGrange sXa) -oX mulnC.\nrewrite dvdn_pmul2r // mulnK //; case/dvdnP=> i ->{def_x k}.\nby rewrite mulnC expgn_mul groupX // cycle_id.\nQed.\n\nLemma cycle_subgroup_char : forall a (H : {group gT}),\n  H \\subset <[a]> -> H \\char <[a]>.\nProof.\nmove=> a H sHa; apply: lone_subgroup_char => // J sJa isoJH.\nhave dvHa: #|H| %| #[a] by exact: cardSg.\nhave{dvHa} Huniq := esym (cycle_sub_group dvHa).\nmove/setP: Huniq => Huniq; move: (Huniq H) (Huniq J); rewrite !inE /=.\nby rewrite sHa sJa (isog_card isoJH) eqxx; do 2!move/eqP <-.\nQed.\n\nEnd CyclicSubGroup.\n\nSection MorphicImage.\n\nVariables aT rT : finGroupType.\nVariables (D : {group aT}) (f : {morphism D >-> rT}) (x : aT).\nHypothesis Dx : x \\in D.\n\nLemma morphim_cycle : f @* <[x]> = <[f x]>.\nProof. by rewrite morphim_gen (sub1set, morphim_set1). Qed.\n\nLemma morph_order : #[f x] %| #[x].\nProof. by rewrite order_dvd -morphX // order_expn1 morph1. Qed.\n\nEnd MorphicImage.\n\nSection CyclicProps.\n\nVariables gT : finGroupType.\nImplicit Types G H K : {group gT}.\nImplicit Type rT : finGroupType.\n\nLemma cyclicS : forall G H, H \\subset G -> cyclic G -> cyclic H.\nProof.\nmove=> G H HsubG; case/cyclicP=> x gex; apply/cyclicP.\nexists (x ^+ (#[x] %/ #|H|)); apply: congr_group; apply/set1P.\nby rewrite -cycle_sub_group /order -gex ?cardSg // inE HsubG eqxx.\nQed.\n\nLemma cyclicJ:  forall (G : {group gT}) x, cyclic (G :^ x) = cyclic G.\nProof.\nmove=> G x; apply/cyclicP/cyclicP=> [[y] | [y ->]].\n  by move/(canRL (conjsgK x)); rewrite -cycleJ; exists (y ^ x^-1).\nby exists (y ^ x); rewrite cycleJ.\nQed.\n\nLemma cyclic_morphim :  forall rT G H (f : {morphism G >-> rT}),\n  cyclic H -> cyclic (f @* H).\nProof.\nmove=> rT G H f cH; wlog sHG: H cH / H \\subset G.\n  by rewrite -morphimIdom; apply; rewrite (cyclicS _ cH, subsetIl) ?subsetIr.\ncase/cyclicP: cH sHG => x ->; rewrite gen_subG sub1set => Gx.\nby apply/cyclicP; exists (f x); rewrite morphim_cycle.\nQed.\n\nLemma isog_cyclic :\n  forall rT G (H : {group rT}), G \\isog H -> cyclic G -> cyclic H.\nProof.\nmove=> rT G H; move/isog_symr; case/isogP=> f injf <- Cf.\nby rewrite -(morphim_invm injf (subxx _)) cyclic_morphim.\nQed.\n\nLemma isog_cyclic_card : forall  rT G (H : {group rT}),\n  cyclic G -> isog G H = cyclic H && (#|H| == #|G|).\nProof.\nmove=> rT G H cG; apply/idP/idP=> [isoHG | ].\n  by rewrite (isog_card isoHG) eqxx (isog_cyclic isoHG).\ncase/cyclicP: cG => x ->{G}; case/andP; case/cyclicP=> y ->{H}; move/eqP=> oy.\napply: isog_trans (isog_symr _) (isom_isog _ (subxx _) (cycle_isom y)).\nmove/(@val_inj _ _ pos_nat_subType): (oy : #[y] = #[x])->.\nexact: (isom_isog _ (subxx _) (cycle_isom x)).\nQed.\n\nLemma quotient_cycle : forall x H, x \\in 'N(H) -> <[x]> / H = <[coset H x]>.\nProof. move=> x H; exact: morphim_cycle. Qed.\n\nLemma quotient_cyclic : forall G H, cyclic G -> cyclic (G / H).\nProof. move=> G H; exact: cyclic_morphim. Qed.\n\nLemma cyclic_prime: forall G, prime #|G| -> cyclic G.\nProof.\nmove=> G pG; case: (pickP (mem G^#)) => [x Hx| Hx]; last first.\n  by move: pG; rewrite (cardsD1 1 G) group1 (eq_card0 Hx).\nmove: (Hx); rewrite /= in_setD1; case/andP => xD1; rewrite -cycle_subG=> xIG.\ncase/primeP: pG => _; move/(_ _ (cardSg xIG)); case/orP;  move/eqP.\n  by rewrite (cardsD1 1) (cardsD1 x) group1 in_setD1 xD1 cycle_id.\nmove=> CxG; apply/cyclicP; exists x.\nby apply/eqP; rewrite eq_sym eqEcard // CxG leqnn andbT.\nQed.\n\nEnd CyclicProps.\n\n(***********************************************************************)\n(*                                                                     *)\n(*       Automorphisms of cyclic groups                                *)\n(*                                                                     *)\n(***********************************************************************)\n\nSection CyclicAutomorphism.\n\nVariables gT1 gT2 : finGroupType.\n\nVariable f : {perm gT1}.\n\nLemma cycle_aut_stable : forall x, f \\in Aut <[x]> -> f @: <[x]> = <[f x]>.\nProof.\nmove=> x autf; rewrite -(autmE autf) -morphimEdom morphim_cycle //.\nexact: cycle_id.\nQed.\n\nLemma order_aut_stable : forall x, f \\in Aut <[x]> -> #[x]  = #[f x].\nProof.\nmove=> x autf; rewrite /order -cycle_aut_stable ?card_imset //.\nexact: perm_inj.\nQed.\n\n(* From the multiplicative group to automorphisms *)\n\nLemma cycle_gexpn_clos : forall (x : gT1) k,\n  (expgn^~ k) @: <[x]> \\subset <[x]>.\nProof.\nmove=> x k; apply/subsetP=> a; case/imsetP=> y; case/cycleP=> n <- -> {a y}.\nby rewrite -expgn_mul mem_cycle.\nQed.\n\nLemma cycle_dcan_gexpn : forall (a : gT1) k, coprime #[a] k ->\n  exists g, {in <[a]>, cancel (expgn^~ k) g}.\nProof.\nmove=> a k; case Hpos: (0 < k) => Hcop; last first.\n  move: Hcop; move/idPn: Hpos; rewrite -eqn0Ngt; move/eqP->.\n  rewrite coprime_sym /coprime gcd0n /order => Hcard.\n  have Heq: (1%g : {set gT1}) =i <[a]>.\n    apply/subset_cardP; last by rewrite sub1set; apply:group1.\n    by move/eqP:Hcard->; rewrite cardsE card1.\n  by exists (@id gT1) => x; rewrite expg0 //= -(Heq x); move/set1P=> <-.\ncase: (bezoutl #[a] Hpos); move=> x xinf.\nrewrite coprime_sym /coprime in Hcop; move/eqP: Hcop->; move/dvdnP=> [k0 Hk0].\nexists (fun z:gT1 => z ^+ k0)%g; move=> x0 Hx0 //=.\nrewrite -expgn_mul mulnC -Hk0 expgn_add mulnC; case/cycleP: Hx0 => i <-.\nby rewrite expg1 -!expgn_mul mulnCA expgn_mul order_expn1 exp1gn mulg1.\nQed.\n\nLemma inj_gexpn : forall (a : gT1) k,\n  coprime #[a] k -> {in <[a]> &, injective (expgn^~ k)}.\nProof.\nmove=> k a Hcop; move: (cycle_dcan_gexpn Hcop)=> [g dcan].\nby apply (can_in_inj dcan).\nQed.\n\nDefinition cycle_expgm of gT1 := fun k x => x ^+ k : gT1.\n\nLemma cycle_expgm_morphM : forall a k,\n  {in <[a]> &, {morph cycle_expgm a k : x y / x * y}}.\nProof.\nmove=> a k x y cax cay; apply: expMgn; exact: commute_cycle_com cay.\nQed.\n\nCanonical Structure cycle_expgm_morphism a k :=\n  Morphism (@cycle_expgm_morphM a k).\n\nLemma cycle_expgm_inj : forall a k, coprime #[a] k -> 'injm (cycle_expgm a k).\nProof. move=> a k coak; apply/injmP; exact: inj_gexpn. Qed.\n\nLemma cycle_expgm_on : forall a k, coprime #[a] k ->\n  cycle_expgm a k @* <[a]> = <[a]>.\nProof.\nmove=> a k coak; apply/morphim_fixP=> //; first exact: cycle_expgm_inj.\nby rewrite morphimEdom cycle_gexpn_clos.\nQed.\n\nDefinition cycle_aut a k (coak : coprime #[a] k) :=\n  aut (cycle_expgm_inj coak) (cycle_expgm_on coak).\n\nEnd CyclicAutomorphism.\n\n(***********************************************************************)\n(*                                                                     *)\n(*        Bijection with Fp                                            *)\n(*                                                                     *)\n(***********************************************************************)\n\nSection FpAut.\n\nVariable gT:finGroupType.\n\nDefinition fp_to_cycle (x : gT) :=\n  fun (D : fp_mul #[x]) => cycle_aut (valP D).\n\nLemma fp_to_cycleM : forall x:gT,\n  {in setT &, {morph @fp_to_cycle x : n m / n * m}}.\nProof.\nmove=> x n m Hn Hm; apply/permP.\nmove=> z; rewrite permM !permE; case e:(z \\in <[x]>%G); last by rewrite e.\nmove/cyclePmin : e =>[k Hk <-]; rewrite /= /cycle_expgm -!expgn_mul mem_cycle.\nby apply/eqP; rewrite eq_expg_mod_order -modn_mulml modn_mulmr modn_mulml mulnA.\nQed.\n\nCanonical Structure fp_to_cycle_morphism x :=\n  Morphism (@fp_to_cycleM x).\n\nLemma fp_to_cycle_injm : forall x:gT, 'injm (@fp_to_cycle x).\nProof.\nmove=> x; apply/injmP=> y1 y2 _ _; move/permP; move/(_ x); move/eqP.\nrewrite /=  !autE ?cycle_id //=; move/(conj (valP (sval y1))); move/andP.\nmove/(decomp_order_unicity (valP (sval y2)))=> /= Heq.\nby apply:val_inj; apply:val_inj => /=; rewrite Heq.\nQed.\n\nLemma cycle_to_fp_loc_corr : forall (f : {perm gT}) (x : gT),\n  f \\in Aut <[x]> -> coprime #[x] (cycle_to_zp x (f x)).\nProof.\nmove=> f x autf /=; set n := cycle_to_zp x (f x).\nhave Hfx: f x \\in <[x]>.\n  by rewrite -[<[x]>](autm_dom autf) mem_imset // setIid cycle_id.\nhave:= cycle_to_zp_corr Hfx; rewrite eq_sym -/n.\ncase: (posnP n) => [-> {n} | npos Hn].\n  rewrite -{3}(permK f x); move/eqP->.\n  by rewrite -groupV in autf; rewrite -(autmE autf) morph1 order1.\nhave: gcdn #[x] n <= 1.\n  rewrite leqNgt; apply/negP=> Hgcd; have:= ltn_Pdiv Hgcd (ltn_0order x).\n  rewrite ltn_neqAle; move: (order_gcd x npos); rewrite -(eqP Hn).\n  move/eqP; rewrite -(order_aut_stable autf); move/eqP=> Hg.\n  by rewrite {3}Hg eqxx andFb.\nby rewrite leq_eqVlt orbC ltnNge ltn_0gcd npos ltn_0group.\nQed.\n\nLemma cycle_to_fp_loc_repr : forall (f : {perm gT}) x,\n  f \\in Aut <[x]> ->\n (forall z, z \\in <[x]> -> f z = z ^+ (cycle_to_zp x (f x)))%g.\nProof.\nmove=> f x autf; have Cxx := cycle_id x.\nmove=> z; case/cycleP=> n <- {z}; rewrite -{1}(autmE autf) morphX //=.\nhave Cfx: f x \\in <[x]>.\n  by rewrite -[<[x]>](autm_dom autf) mem_imset // setIid.\nby rewrite -expgn_mul mulnC expgn_mul (eqP (cycle_to_zp_corr Cfx)).\nQed.\n\nLemma fp_to_cycle_imset : forall x:gT, ((@fp_to_cycle x) @* setT) = (Aut <[x]>).\nProof.\nmove=> x; apply/eqP; rewrite eqEsubset; apply/andP; split.\n  by apply/subsetP=> /= k; move/morphimP=> [[k0 Hk0] _ _ ->]; apply: Aut_aut.\napply/subsetP=> f Haut.\napply/morphimP.\npose kk : fp_mul #[x] := (Sub (cycle_to_zp x (f x)) (cycle_to_fp_loc_corr Haut)).\nexists kk; rewrite ?in_setT //=; apply/permP=> z; rewrite permE.\ncase eax : (z \\in <[x]>); first by rewrite (cycle_to_fp_loc_repr Haut eax).\nby clear kk; move: Haut; rewrite inE; case/andP; move/out_perm->; rewrite ?eax.\nQed.\n\nLemma imset_fp_to_cycle : forall a,Aut <[a]> \\subset ( (@fp_to_cycle a) @* setT).\nProof.\nby move=> a; rewrite -fp_to_cycle_imset morphimEdom.\nQed.\n\nDefinition cycle_to_fp (a: gT) :=\n  restrm (imset_fp_to_cycle a) (invm (fp_to_cycle_injm a)).\n\nLemma fp_inj : forall x : gT, 'injm [morphism of cycle_to_fp x].\nProof.\nmove=> x; move: (injm_invm (fp_to_cycle_injm x)); rewrite /=.\nby rewrite /ker /morphpre; rewrite {1}(fp_to_cycle_imset x); apply.\nQed.\n\nLemma fp_isom : forall a : gT, isom (Aut <[a]>) setT (cycle_to_fp a).\nProof.\nmove=> a; apply/isomP; split; first exact: fp_inj.\napply/setP=> x; rewrite inE morphimEdom.\napply/imsetP; exists (fp_to_cycle x); first exact: Aut_aut.\nby rewrite /= /restrm invmE ?in_setT.\nQed.\n\nEnd FpAut.\n\n(***********************************************************************)\n(*                                                                     *)\n(*       Automorphism with Zp, consequences on generators              *)\n(*                                                                     *)\n(***********************************************************************)\n\nSection GenAut.\n\nVariables aT rT : finGroupType.\n\nLemma generator_bij : forall (G H : {group aT}) (f : {morphism G >-> rT}) a,\n   'injm f -> H \\subset G -> a \\in G ->\n    generator H a = generator (f @* H) (f a).\nProof.\nmove=> G H f a injf sHG Ga.\nrewrite /generator -morphim_cycle // !eqEsubset.\nby rewrite !morphimSGK //= ?(subset_trans injf, sub1G, cycle_subG).\nQed.\n\nEnd GenAut.\n\nSection ZpAut.\n\nVariable gT : finGroupType.\nVariable a : gT.\n\nLemma expgn_muln : forall k (n : pos_nat) p (H : p < n),\n  Ordinal H ^+ k = Ordinal (ltn_pmod (p * k) (valP n)).\nProof.\nelim=> [|k IH] n p H; apply: val_inj=> //=; first by rewrite muln0 modn_small.\nby rewrite expgS IH //= modn_addmr -{1}(muln1 p) -muln_addr add1n.\nQed.\n\nLemma zp_group_cycle : forall (n : pos_nat) k (lt_k_n : k < n),\n  coprime k n -> setT = <[Ordinal lt_k_n]>.\nProof.\nmove=> n k H Hcop; symmetry; apply/setP; apply/subset_eqP; apply/andP.\nsplit; first by apply/subsetP=> x //= Hx ; rewrite inE.\napply/subsetP; move=> x _ /=; apply/cycleP; move: k H Hcop x.\ncase=> [|k] H Hcop /= x0.\n  rewrite /coprime gcd0n in Hcop; exists 1%N; move: (valP x0).\n  move/eqP:Hcop=> Hn; rewrite {3}Hn !ltnS !leqn0; move/eqP => H0.\n  by apply: val_inj; rewrite /= addn0 /= H0 modn_small.\ncase: (egcdnP n (ltn0Sn k))=> kk kn Heq Hineq.\nexists (kk * x0)%N; rewrite /= expgn_muln; apply: val_inj => /=.\nrewrite mulnA (mulnC (k.+1)) Heq muln_addl -(mulnA kn) (mulnC n) mulnA.\nmove: Hcop; rewrite modn_addl_mul /coprime; move/eqP->.\nby rewrite mul1n modn_small.\nQed.\n\nLemma zp_ord : forall (n : pos_nat) (i : zp_group n),\n  i = Ordinal (valP (i : 'I_n)).\nProof. by move=> n i; apply: val_inj. Qed.\n\nLemma zp_gen : forall (n : pos_nat) (i : 'I_n),\n  generator setT i = coprime i n.\nProof.\nmove=> n i; apply/idP/idP; last first.\n  move=> Hcop; apply/eqP.\n  apply:zp_group_cycle=> /=; by [apply: (valP (i : 'I_n)) | apply: Hcop].\nmove/(setT =P _)=> Hcop.\ncase e: (0 < (i : 'I_n)).\n  apply:modn_coprime; first exact: (idP e).\n  have H1: (1 < n) by apply: leq_ltn_trans (valP (i : 'I_n)); apply:(idP e).\n  have: Ordinal H1 \\in <[i]> by rewrite -Hcop inE.\n  by case/cycleP=> n1; rewrite (zp_ord i) expgn_muln /=; case; exists n1.\nmove/negbT:e; rewrite lt0n negbK; move/eqP=> i0.\nhave i1 : i = 1 by exact: val_inj.\nby rewrite i0 -(card_ord n) -cardsT Hcop i1 cycle1 cards1.\nQed.\n\nLemma generator_coprime : forall m,\n  coprime m #[a] = generator <[a]> (a ^+ m).\nProof.\nmove=> m; rewrite (generator_bij (zp_inj a));\nrewrite /= ?morphimEdom ?zp_to_cycle_imset ?mem_cycle //=.\nmove: (zp_isom a); case/isomP => _ /=.\nrewrite -morphimEdom => ->; rewrite /coprime -gcdn_modl.\nhave Hmod: m %% #[a] < #[a] by rewrite ltn_mod (ltn_0order a).\nhave:= @zp_gen [is #[a] : _ <: pos_nat] (Ordinal Hmod).\nrewrite /= /coprime => <-; congr generator; apply: val_inj=> /=.\nby rewrite cycle_to_zp_id.\nQed.\n\nLemma phi_gen : phi #[a] = #|[pred x | generator <[a]> x]|.\nProof.\nrewrite /phi /=; set n := #[a].\nhave: [pred x : 'I_n | coprime n x] =i\n      [pred x : 'I_n | generator <[a]> (a ^+ x)].\n  by move=> x /=; rewrite !inE /= -generator_coprime coprime_sym.\nmove/eq_card=> ->.\nsuff: (image (cycle_to_zp a) (generator <[a]>)) =i\n        [pred x : 'I_n | generator <[a]> (a ^+ x)].\n  move/eq_card <-; apply: card_dimage; move/injmP: (zp_inj a).\n  apply:sub_in2; exact: cycle_generator.\nmove=> /= x; apply/imageP/idP; rewrite inE /=.\n  move=> [x0 Hx0 ->]; move: (cycle_generator Hx0); move/cycle_to_zp_corr.\n  by move/eqP; rewrite /cycle_to_zp /= => ->.\nmove=> Hgen; exists (a ^+ x)%g; first by trivial.\napply: val_inj; rewrite /cycle_to_zp /=.\nmove: (cycle_to_zp_corr (cycle_generator Hgen)); rewrite eq_sym.\nmove/(conj (valP x))=> /=; move/andP; move/decomp_order_unicity=> /=.\nby rewrite ltn_ord; move/(_ is_true_true).\nQed.\n\nEnd ZpAut.\n\nSection CyclicAutomorphism_Abelian.\n\n(* G. 1.3.10 *)\n\nVariable gT : finGroupType.\n\nLemma aut_cycle_commute : forall x : gT, abelian (Aut <[x]>).\nProof.\nmove=> x.\nhave:= isom_isog  [morphism of (cycle_to_fp x)] (subxx _) (fp_isom x).\nrewrite isog_sym.\ncase/isogP=> f _ /= <-; apply: morphim_cents.\nby apply/centsP=> m _ n _; do 2!apply: val_inj => /=; rewrite mulnC.\nQed.\n\nEnd CyclicAutomorphism_Abelian.\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/cyclic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8032656514587859}}
{"text": "(* Hand is defined inductively. *)\nInductive Hand : Set := Gu | Tyoki | Pa.\n\n(* Check type of Hand. *)\nCheck Hand.\n\n(* Show definitions. *)\nPrint Hand.\nPrint Hand_ind.\n\n(* Function definition *)\nInductive win : Hand -> Hand -> Prop :=\n| gu_win_tyoki : win Gu Tyoki\n| tyoki_win_pa : win Tyoki Pa\n| pa_win_gu : win Pa Gu.\n\nHint Constructors win.\n(* Winning hand *)\nDefinition winning_hand(s:Hand) : { a | win a s }.\nProof.\ninduction s.\n exists Pa. apply pa_win_gu.\n exists Gu. auto.\n exists Tyoki; auto.\nDefined.\n\n(* Result = hand & proof *)\nEval compute in (winning_hand Gu).\n(* Hand *)\nEval compute in (proj1_sig (winning_hand Gu)).\n(* Proof *)\nEval compute in (proj2_sig (winning_hand Gu)).\n(* Extract as OCaml program *)\nExtraction winning_hand.\n\n(* Winning hand is unique. *)\nTheorem winning_hand_unique : forall a b c, \n  win a c -> win b c -> a = b.\nProof.\nintros a b c Hac Hbc. induction c.\n inversion Hac. inversion Hbc. reflexivity.\n inversion Hac. inversion Hbc. auto.\n inversion Hac; inversion Hbc; auto.\nQed.\n\n(* Import List module *)\nRequire Import List.\n\n(* Show definition of list type *)\nPrint list.\n\n(* Sample of list *)\nCheck (1::2::nil).\n\nCheck list_ind.\n\n(* Define append function *)\nFixpoint append{A:Type}(xs ys:list A):=\nmatch xs with\n| nil => ys\n| x::xs' => x::(append xs' ys)\nend.\n\n(* Evaluation *)\nEval compute in (append (1::2::nil) (3::4::nil)).\n\n(* Definition of nat *)\nPrint nat.\nPrint plus.\n\n(* Write your length function *)\nFixpoint len{A:Type}(xs:list A):nat :=\nmatch xs with\n| nil => ??????\n| x::xs' => ???????\nend.\n\n(* Should be 3 *)\nEval compute in (len (1::2::3::nil)).\n\nTheorem len_append: forall (A:Type)(xs ys:list A),\n  len (append xs ys) = plus (len xs) (len ys).  \nProof.\nintro A.\ninduction xs.\n simpl.\n intro ys. auto.\n\n intro ys. simpl.\n erewrite IHxs.\n auto.\nQed.\n\nFixpoint reverse{A:Type}(xs:list A):list A :=\nmatch xs with\n| nil => nil\n| x::xs' => append (reverse xs') (x::nil)\nend.\n\n(* Evaluate *)\nEval compute in (reverse (1::2::3::nil)).\n(* reverse twice *)\nEval compute in (reverse (reverse (1::2::3::nil))).\n\nLemma append_right_nil: forall (A:Type)(xs:list A),\n  append xs nil = xs.\nProof.\n????\nQed.\n\nLemma append_append : forall (A:Type)(xs ys zs:list A),\n  append (append xs ys) zs = append xs (append ys zs).\nProof.\n????\nQed. \n\nLemma reverse_append : forall (A:Type)(xs ys:list A),\n  reverse (append xs ys) = append (reverse ys) (reverse xs).\nProof.\n????\nQed.\n\nTheorem reverse_reverse: forall (A:Type)(xs:list A),\n  reverse (reverse xs) = xs.\nProof.\n????\nQed.\n\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20130817/coqart_20130817.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8032557579755494}}
{"text": "From LF Require Export Logic.\nRequire Coq.omega.Omega.\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n\nCheck ev_0.\nCheck ev_SS.\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros. induction n.\n  - apply ev_0.\n  - simpl. apply ev_SS. assumption.\n  Qed.\n\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion  E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  inversion H.\n  inversion H1.\n  assumption.\n  Qed.\n\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *)\n  intros. inversion H. inversion H1. inversion H3.\n  Qed.\n\nLemma ev_even_firsttry : forall n,\n  ev 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 *)\n\nAdmitted.\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  (* FILL IN HERE *)\n  intros.\n  induction H.\n  - assumption.\n  - simpl. apply ev_SS. assumption.\n  Qed.\n\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n (* FILL IN HERE *)\n split.\n - intros. induction H.\n   + constructor.\n   + constructor. constructor.\n   + apply ev_sum. assumption. assumption.\n - intros. induction H.\n   + constructor.\n   + apply (ev'_sum 2 n).\n     constructor.\n     assumption.\n Qed.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  induction H0.\n  - assumption.\n  - simpl in H. apply IHev. apply evSS_ev. assumption.\n  Qed.\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *)\n  intros.\n  assert (ev ((n + m) + (n + p))).\n  {\n    apply ev_sum. assumption. assumption.\n  }\n  rewrite (plus_assoc) in H1.\n  rewrite <- (plus_assoc n m n) in H1.\n  rewrite (plus_comm m n) in H1.\n  rewrite (plus_assoc) in H1.\n  rewrite <- double_plus in H1.\n  rewrite <- plus_assoc in H1.\n  apply (ev_ev__ev (double n) (m+p) H1).\n  apply ev_double.\n  Qed.\n\n\nTheorem ex_mid_ev:\n  forall n, ev n \\/ ~ ev n.\n\nProof.\n  intros.\n  assert (ev n <-> evenb n = true).\n  {\n    rewrite ev_even_iff. rewrite even_bool_prop. reflexivity.\n  }\n  apply restricted_excluded_middle with (evenb n).\n  assumption.\n  Qed.\n\nTheorem ev_n_not_ev_Sn:\n  forall n,\n  ev n -> ~ ev (S n).\n\nProof.\n  unfold not. \n  - intros. induction H.\n    + inversion H0.\n    + inversion H0. apply IHev. assumption.\n  Qed.\n\n\n\nModule Playground.\n\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\nInductive total_relation: nat -> nat -> Prop :=\n  | totrel: forall n m, total_relation n m.\n\nExample tot_rel_example:\n  total_relation 3 5.\n\nProof. constructor. Qed.\n\n\nInductive empty_relation: nat -> nat -> Prop :=.\n\nTheorem not_exist_in_empty_rel:\n  ~ (exists n m, empty_relation n m).\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  inversion H0.\n  inversion H1.\n  Qed.\n\n\nLemma Sn_le_m__n_le_m:\n  forall n m,\n  S n <= m -> n <= m.\n\nProof.\n  intros.\n  induction H.\n  - constructor. constructor.\n  - constructor. assumption.\n  Qed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  induction H.\n  - assumption.\n  - apply IHle. apply Sn_le_m__n_le_m.\n    assumption.\n  Qed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *)\n  induction n.\n  - constructor.\n  - constructor. assumption.\n  Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  induction H.\n  - constructor.\n  - constructor. assumption.\n  Qed.\n\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) \n  intros. inversion H.\n  - constructor.\n  - apply Sn_le_m__n_le_m. assumption.\n  Qed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* FILL IN HERE *)\n  induction a.\n  - simpl. apply O_le_n.\n  - intros. simpl. apply n_le_m__Sn_le_Sm. \n    apply IHa.\n  Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* FILL IN HERE *)\n intros.\n induction H.\n - split.\n   + apply n_le_m__Sn_le_Sm. apply le_plus_l.\n   + apply n_le_m__Sn_le_Sm. rewrite plus_comm. apply le_plus_l.\n - destruct IHle. split.\n   + constructor. assumption.\n   + constructor. assumption.\n Qed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *)\n  unfold lt.\n  intros. constructor. assumption.\n  Qed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *)\n  induction n.\n  - intros. apply O_le_n.\n  - intros. simpl in H. destruct m.\n    + inversion H.\n    + apply n_le_m__Sn_le_Sm.\n      apply IHn. apply H.\n  Qed.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  generalize dependent n.\n  induction m.\n  - intros. inversion H. reflexivity.\n  - intros. inversion H.\n    + rewrite <- leb_refl. reflexivity.\n    + destruct n.\n      * reflexivity.\n      * simpl. apply IHm. apply Sn_le_Sm__n_le_m. assumption.\n  Qed.\n\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  intros.\n  split. apply leb_complete. apply leb_correct.\n  Qed.\n\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  (* FILL IN HERE *)\n  intros.\n  rewrite leb_iff in H.\n  rewrite leb_iff in H0.\n  rewrite leb_iff.\n  apply le_trans with m.\n  assumption.\n  assumption.\n  Qed.\n\n\n\n(*New Session*)\n\nInductive reg_exp {T : Type} : Type :=\n| EmptySet : reg_exp\n| EmptyStr : reg_exp\n| Char : T -> reg_exp\n| App : reg_exp -> reg_exp -> reg_exp\n| Union : reg_exp -> reg_exp -> reg_exp\n| Star : reg_exp -> reg_exp.\n\n\nInductive exp_match {T} : list T -> @reg_exp T -> Prop :=\n| MEmpty : exp_match [] EmptyStr\n| MChar : forall (x: T), exp_match [x] (Char x)\n| MApp : forall s1 re1 s2 re2,\n           exp_match s1 re1 ->\n           exp_match s2 re2 ->\n           exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL : forall s1 re1 re2,\n              exp_match s1 re1 ->\n              exp_match s1 (Union re1 re2)\n| MUnionR : forall re1 s2 re2,\n              exp_match s2 re2 ->\n              exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n               exp_match s1 re ->\n               exp_match s2 (Star re) ->\n               exp_match (s1 ++ s2) (Star re).\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\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\nCompute reg_exp_of_list [1;2;3].\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. Check app_nil_r.\n  rewrite <- (app_nil_r _ s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n(*Exercise 1*)\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros t s H. inversion H.\nQed.\n\n(*Exercise 2*)\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 [match1 | match2].\n  - constructor. assumption.\n  - apply MUnionR. assumption.\nQed.\n\n(*Exercise 3*)\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 as [| a t IH].\n    - simpl. apply MStar0.\n    - simpl. apply MStarApp.\n    apply H. simpl. left. reflexivity.\n    apply IH. intros. apply H. simpl. right. assumption.\nQed.\n\n(*Exercise 4*)\n\nLemma Helper: forall S (x:S) y, [x]++y = x::y.\n      Proof.\n  intros S x y. simpl. reflexivity. \nQed. \n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  intros T s1 s2.\n  generalize dependent s1.\n  induction s2 as [|h t].\n    split. \n    + intros H. simpl in H. inversion H. reflexivity.\n    + intros H. simpl. rewrite H. apply MEmpty.\n    + intros s1. split. \n     intros H. simpl in H. inversion H. \n      inversion H3. simpl. \n      rewrite (IHt s2) in H4. rewrite H4. reflexivity.\n     intros H. simpl. rewrite H.\n      rewrite <- Helper. apply MApp.\n      * apply MChar.\n      * apply IHt. 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\nCompute re_chars (Union (Char 5) (App (Char 3) (EmptyStr))). (* 5 + 3\\epsilon *)\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    inversion Hin.\n  - (* MChar *)\n    inversion Hin. simpl. left. assumption.\n    inversion H.\n  - (*MApp*) simpl. Check In_app_iff.\n    rewrite In_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      left. apply (IH1 Hin).\n    + (* In x s2 *)\n      right. apply IH2. apply 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      simpl in IH2.\n      apply (IH2 Hin).\nQed.\n\n\n\nLemma star_app: forall T (s1 s2 : list T) (re : @reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  generalize dependent s2.\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n  - (* MEmpty *)\n    simpl. intros. apply H.\n\n  - simpl. intros. (* MChar. Stuck... *)\nAbort.\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),\n  re' = Star re ->\n  s1 =~ re' ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n\nProof. intros. induction H0.\nAbort.\n\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\n(** The [Heqre'] is contradictory in most cases, which allows us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)   inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n  - (* MStar0 *)\n    inversion Heqre'. intros s H. apply H.\n  - (* MStarApp *)\n    inversion Heqre'. (*rewrite H0 in IH2, Hmatch1.*)\n    intros s2 H1. Check app_assoc.\n    rewrite <- app_assoc.\n    apply MStarApp.\n    + rewrite H0 in Hmatch1. apply Hmatch1. \n    + rewrite H0 in IH2. apply IH2.\n      * reflexivity.\n      * apply H1.\nQed.\n\nLemma beq_nat_true_iff : forall x y, eqb x y = true <-> x=y.\nProof. split. apply eqb_true. intros; subst; symmetry; apply eqb_refl. Qed.\n\n\nTheorem filter_not_empty_In : forall n l,\n  filter (eqb n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (eqb n m) eqn:H.\n    + (* beq_nat n m = true *)\n      intros _. Check beq_nat_true_iff.\n      rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + (* beq_nat n m = false *)\n      intros H'. right. apply (IHl' H').\nQed.\n\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\nTheorem iff_reflect : forall P b, (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. unfold not. intros. apply H in H0. inversion H0.\nQed.\n\n(*Exercise 5*)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  intros. destruct H as [HP | HNP].\n  - split. intros. reflexivity. intros. apply HP.\n  - split. intros. destruct (HNP H). intros. discriminate.\nQed. \n\n\nLemma beq_natP : forall n m, reflect (n = m) (eqb n m).\nProof.\n  intros n m. apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (eqb n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_natP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(*Exercise 6: Use beq_natP in the proof.*)\nFixpoint count n l :=\n  match l with\n  | [] => 0\n  | m :: l' => (if eqb n m then 1 else 0) + count n l'\n  end.\n\nTheorem beq_natP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros n l.\n  induction l as [| a t IH].\n  - simpl. intros _ f. destruct f.\n  - simpl. destruct (beq_natP n a) as [H | H].\n    + intros H'. discriminate.\n    + simpl. intros H1 [H2 | H3].\n      * apply H. rewrite H2. reflexivity.\n      * apply IH. apply H1. apply H3.\nQed.\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/CA18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.9086178963141964, "lm_q1q2_score": 0.8032539124391939}}
{"text": "Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nEval compute in (fst (pair 3 5)).\n(* ===> 3 *)\n\nNotation \"( x , y )\" := (pair x y).\n\nEval compute in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\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\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. destruct p as [n m]. simpl. reflexivity.\nQed.\n\n(** \u2610\nExercise: 1 star, optional (fst_swap_is_snd)  \nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.  *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nNotation \"x + y\" := (plus x y)  \n                    (at level 50, left associativity). \n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil \n  | 0 :: t => nonzeros t\n  | h :: t => h :: nonzeros t\n  end.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match oddb h with\n  | true => h :: oddmembers t\n  | false => oddmembers t\n  end\n  end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  match l with\n  | nil => 0\n  | h :: t => match oddb h with\n  | true => 1 + (countoddmembers t)\n  | false => (countoddmembers t)\n  end\n  end.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match beq_nat v h with\n  | true => 1 + (count v t)\n  | false => (count v t)\n  end\n  end.\n\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  negb (beq_nat (count v s) 0).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** Exercise: 3 stars (bag_theorem)  *)\nFixpoint total (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => h + (total t)\n  end.\n\nExample test_total1: total [1;2;3;4;5] = 15.\nProof. reflexivity. Qed.\nExample test_total2: total [ ] = 0.\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    reflexivity. Qed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* 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\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n  match l with\n  | nil => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem rev_length_firsttry : 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\nTheorem length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l. induction l as [| n' l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> length_snoc.\n    rewrite -> IHl'. reflexivity. Qed.\n\n(* SearchAbout rev. *)\n\n(** Exercise: 3 stars (list_exercises)\nMore practice with lists.  *)\n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons\". simpl. rewrite -> IHl. reflexivity.\nQed.\n\nLemma reverse : forall n : nat, forall l : natlist,\n  rev (snoc l n) = n :: rev l.\nProof.\n  intros. induction l as [| n' l'].\n  Case \"l = nil\". simpl. reflexivity.\n  Case \"l = cons\". simpl. rewrite -> IHl'. simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons\". simpl. rewrite -> reverse. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros. rewrite -> app_assoc. rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros. induction l as [| l'].\n  Case \"l = nil\". simpl. reflexivity.\n  Case \"l = cons\". simpl. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros. induction l1 as [| l1'].\n  Case \"l1 = nil\". simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = cons\". simpl. rewrite -> snoc_append. rewrite -> IHl1. \n  rewrite -> snoc_append. rewrite -> app_assoc. reflexivity.\nQed.\n \n(** An exercise about your implementation of nonzeros:  *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros. induction l1 as [| l2' l1'].\n  Case \"l1 = nil\". simpl. reflexivity.\n  Case \"l1 = cons\".\n    induction l2' as [| l2'']. \n    SCase \"L2 = nil\". simpl. rewrite -> IHl1'. reflexivity.\n    SCase \"L2 = cons\". simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with \n  | nil, nil => true\n  | _, nil => false\n  | nil, _ => false\n  | h :: t, h' :: t' => andb (beq_nat h h') (beq_natlist t t') \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\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros. induction l as [| l'].\n  Case \"l = nil\". simpl. reflexivity.\n  Case \"l = cons\". simpl. rewrite -> IHl. admit.\nQed.\n\n(** Exercise: 2 stars (list_design)  *)\n\nSearchAbout cons.\nSearchAbout snoc.\nSearchAbout app.\n\n(** Theorem cons_snoc_app :  *)\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\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\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | h :: t => Some h\nend.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n\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\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros. simpl. admit.\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. simpl. rewrite -> H. reflexivity. \nQed.\n\nEnd Dictionary.\n\nEnd NatList.", "meta": {"author": "JayMazur", "repo": "CS-4593-and-6463", "sha": "852c940444fde2aa8770a9f20039f3e38ee69488", "save_path": "github-repos/coq/JayMazur-CS-4593-and-6463", "path": "github-repos/coq/JayMazur-CS-4593-and-6463/CS-4593-and-6463-852c940444fde2aa8770a9f20039f3e38ee69488/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.9086178913651383, "lm_q1q2_score": 0.8032539108399962}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom COC Require Export Tactics.\n\n(** We have seen many examples of factual claims (_propositions_)\n    and ways of presenting evidence of their truth (_proofs_).  In\n    particular, we have worked extensively with _equality\n    propositions_ ([e1 = e2]), implications ([P -> Q]), and quantified\n    propositions ([forall x, P]).  In this chapter, we will see how\n    Coq can be used to carry out other familiar forms of logical\n    reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3 : Prop.\n\nCheck forall n m : nat, n + m = m + n : Prop.\n\n(** Note that _all_ syntactically well-formed propositions have type\n    [Prop] in Coq, regardless of whether they are true. *)\n\n(** Simply _being_ a proposition is one thing; being _provable_ is\n    something else! *)\n\nCheck 2 = 2 : Prop.\n\nCheck 3 = 2 : Prop.\n\nCheck forall n : nat, n = 2 : Prop.\n\n(** Indeed, propositions not only have types: they are\n    _first-class_ entities that can be manipulated in all the same\n    ways as any of the other things in Coq's world. *)\n\n(** So far, we've seen one primary place that propositions can appear:\n    in [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have given names to other kinds of expressions. *)\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : Prop.\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_claim_is_true :\n  plus_claim.\nProof. reflexivity.  Qed.\n\n(** We can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. *)\n\n(** For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three : nat -> Prop.\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments. For instance, here's a\n    (polymorphic) property defining the familiar notion of an\n    _injective function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1. apply H1.\nQed.\n\n\n(** The equality operator [=] is also a function that returns a\n    [Prop].\n\n    The expression [n = m] is syntactic sugar for [eq n m] (defined in\n    Coq's standard library using the [Notation] mechanism). Because\n    [eq] can be used with elements of any type, it is also\n    polymorphic: *)\n\nCheck @eq : forall A : Type, A -> A -> Prop.\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type\n    argument [A] to [eq] is declared as implicit, and we need to turn\n    off the inference of this implicit argument to see the full type\n    of [eq].) *)\n\n(* ################################################################# *)\n(** * Logical Connectives *)\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** The _conjunction_, or _logical and_, of propositions [A] and [B]\n    is written [A /\\ B], representing the claim that both [A] and [B]\n    are true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  It will generate\n    two subgoals, one for each part of the statement: *)\n\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 * 2 = 4 *) reflexivity.\nQed.\n\n(** For any propositions [A] and [B], if we assume that [A] is true\n    and that [B] is true, we can conclude that [A /\\ B] is also\n    true. *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 \n    -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  apply and_intro.\n  - (* n = 0 *) induction n as [| n'].\n    + reflexivity.\n    + discriminate H.\n  - (* m = 0 *) induction m as [| m'].\n    + reflexivity.\n    + rewrite plus_comm in H. discriminate H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite -> Hn. rewrite -> Hm. simpl.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] right when we introduce it,\n    instead of introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** For this specific theorem, both formulations are fine.  But\n    it's important to understand how to work with conjunctive\n    hypotheses because conjunctions often arise from intermediate\n    steps in proofs, especially in larger developments.  Here's a\n    simple example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  apply and_exercise in H.\n  destruct H as [Hn Hm].\n  rewrite -> Hn. simpl. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know\n    [A /\\ B] but in some context we need just [A] or just [B].\n    In such cases we can do a [destruct] (possibly as part of\n    an [intros]) and use an underscore pattern [_] to indicate\n    that the unneeded conjunct should just be thrown away. *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  (** destruct HPQ as [_ HQ]. to return Q instead of P **)\n  apply HP.\nQed.\n\n(** **** Exercise: 1 star, standard, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [_ HQ].\n  apply HQ.\nQed.\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of multi-way conjunctions.  The following\n    commutativity and associativity theorems are handy in such\n    cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.\nQed.\n\n(** **** Exercise: 2 stars, standard (and_assoc) \n\n    (In the following proof of associativity, notice how the _nested_\n    [intros] pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split.\n  - (* inner *) split.\n    + apply HP.\n    + apply HQ.\n  - (* outer *) apply HR.\nQed.\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and : Prop -> Prop -> Prop.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_,\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (This infix notation stands for [or A B], where [or : Prop ->\n    Prop -> Prop].) *)\n\n(** To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis (which, as with other data types like [nat], can be done\n    explicitly with [destruct] or implicitly with an [intros]\n    pattern): *)\n\nLemma eq_mult_0 :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     [n = 0 \\/ m = 0] *)\n  intros n m [Hn | Hm].\n  - (* Here, [n = 0] *)\n    rewrite -> Hn. reflexivity.\n  - (* Here, [m = 0] *)\n    rewrite -> Hm. rewrite -> mult_n_O. reflexivity.\nQed.\n\n(** Conversely, to show that a disjunction holds, it suffices to show\n    that one of its sides holds. This is done via two tactics, [left]\n    and [right].  As their names imply, the first one requires proving\n    the left side of the disjunction, while the second requires\n    proving its right side.  Here is a trivial use... *)\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and here is a slightly more interesting example requiring both\n    [left] and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  (* WORKED IN CLASS *)\n  intros n. induction n as [|n'].\n  - (* left *)\n  left. reflexivity.\n  - (* right *)\n  right. simpl. reflexivity.\nQed.\n\nSearch ( _ * _ = _ ).\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 : forall n m,\n    n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n. induction n as [|n'].\n  - (* n = O *)\n  intros m H. rewrite mult_O_1 in H. left. apply H.\n  - (* n = S n' *) intros m. induction m as [| m].\n    + intros H. simpl in H. rewrite mult_n_O in H. right. apply H.\n    + intros H. discriminate H.\nQed.\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [HP|HQ].\n  - right. apply HP.\n  - left. apply HQ.\nQed.\n\n(* ================================================================= *)\n(** ** Falsehood and Negation\n\n    So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    negative results, demonstrating that some given proposition is\n    _not_ true. Such statements are expressed with the logical\n    negation operator [~]. *)\n\n(** To see how negation works, recall the _principle of explosion_\n    from the [Tactics] chapter, which asserts that, if we assume a\n    contradiction, then any other proposition can be derived. \n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].\n\n    Coq actually makes a slightly different (but equivalent) choice,\n    defining [~ P] as [P -> False], where [False] is a specific\n    contradictory proposition defined in the standard library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not : Prop -> Prop.\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can use [destruct] on it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (not_implies_our_not) \n\n    Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P HPnot Q HP.\n  contradiction.\nQed.\n\n(** Inequality is a frequent enough example of negated statement\n    that there is a special notation for it, [x <> y]: **)\n\nNotation \"x <> y\" := (~(x = y)).\n\n(** We can use [not] to state that [0] and [1] are different elements\n    of [nat]: *)\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  (** The proposition [0 <> 1] is exactly the same as\n      [~(0 = 1)], that is [not (0 = 1)], which unfolds to\n      [(0 = 1) -> False]. (We use [unfold not] explicitly here\n      to illustrate that point, but generally it can be omitted.) *)\n  unfold not.\n  (** To prove an inequality, we may assume the opposite\n      equality... *)\n  intros contra.\n  (** ... and deduce a contradiction from it. Here, the\n      equality [O = S O] contradicts the disjointness of\n      constructors [O] and [S], so [discriminate] takes care\n      of it. *)\n  discriminate contra.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    make Coq understand it!  Here are proofs of a few familiar facts\n    to get you warmed up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.\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\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H HQnot.\n  unfold not. unfold not in HQnot. intros P'. apply HQnot. apply H. apply P'.\nQed.\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. intros [HP HPnot].\n  apply HPnot. apply HP.\nQed.\n\n(** Since inequality involves a negation, it also requires a little\n    practice to be able to work with it fluently.  Here is one useful\n    trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn:HE.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.          (* note implicit [destruct b] here *)\n  - (* b = true *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see examples later on. *)\n\n(* ================================================================= *)\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is simply the conjunction\n    of two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB.\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 iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P. split.\n  - (* -> *) intros P'. apply P'.\n  - (* <- *) intros P'. apply P'.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [HPQ HQP] [HQR HRQ]. split.\n  - (* -> *) intros P'. apply HPQ in P'. apply HQR in P'. apply P'.\n  - (* <- *) intros R'. apply HRQ in R'. apply HQP in R'. apply R'.\nQed.\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - (* -> *) intros H. inversion H.\n    + split.\n      { left. apply H0. }\n      { left. apply H0. }\n    + split.\n      { apply proj1 in H0. right. apply H0. }\n      { apply proj2 in H0. right. apply H0. }\n  - (* <- *) intros H. inversion H.\n    + destruct H1.\n      { left. apply H1. }\n      { destruct H0.\n        { left. apply H0. }\n        { right. split.\n          { apply H0. }\n          { apply H1. } } }\nQed.\n\n(* ================================================================= *)\n(** ** Setoids and Logical Equivalence *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we have\n    to import the Coq library that supports it: *)\n\nFrom Coq Require Import Setoids.Setoid.\n\n(** A \"setoid\" is a set equipped with an equivalence relation,\n    that is, a relation that is reflexive, symmetric, and transitive.\n    When two elements of a set are equivalent according to the\n    relation, [rewrite] can be used to replace one element with the\n    other. We've seen that already with the equality relation [=] in\n    Coq: when [x = y], we can use [rewrite] to replace [x] with [y],\n    or vice-versa.\n\n    Similarly, the logical equivalence relation [<->] is reflexive,\n    symmetric, and transitive, so we can use it to replace one part of\n    a proposition with another: if [P <-> Q], then we can use\n    [rewrite] to replace [P] with [Q], or vice-versa. *)\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences. *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - (* -> *) apply mult_eq_0.\n  - (* <- *) apply eq_mult_0.\nQed.\n\nTheorem or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - (* -> *) intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - (* <- *) intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\n(** We can now use these facts with [rewrite] and [reflexivity]\n    to give smooth proofs of statements involving equivalences.  For\n    example, here is a ternary version of the previous [mult_0]\n    result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite -> mult_0. rewrite -> mult_0. rewrite -> or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which direction of\n    the equivalence will be useful. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** Another important logical connective is _existential\n    quantification_.  To say that there is some [x] of type [T] such\n    that some property [P] holds of [x], we write [exists x : T,\n    P]. As with [forall], the type annotation [: T] can be omitted if\n    Coq is able to infer from the context what the type of [x] should\n    be. *)\n\n(** To prove a statement of the form [exists x, P], we must show that\n    [P] holds for some specific choice of value for [x], known as the\n    _witness_ of the existential.  This is done in two steps: First,\n    we explicitly tell Coq which witness [t] we have in mind by\n    invoking the tactic [exists t].  Then we prove that [P] holds after\n    all occurrences of [x] are replaced by [t]. *)\n\nDefinition even x := exists n : nat, x = double n.\n\nLemma four_is_even : even 4.\nProof.\n  (* witness_ of the existential is given as 2 in this context *)\n  unfold even. exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n    the context, we can destruct it to obtain a witness [x] and a\n    hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  (* WORKED IN CLASS *)\n  intros n [m Hm]. (* note implicit [destruct] here *)\n  exists (2 + m).\n  apply Hm.\nQed.\n\n(** **** Exercise: 1 star, standard, especially useful (dist_not_exists) \n\n    Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\"  (Hint: [destruct H as [x E]] works on\n    existential assumptions!)  *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros X P Hall Hexist.\n  destruct Hexist as [x HPnot].\n  unfold not in HPnot. apply HPnot. apply Hall.\nQed.\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros X P Q. split.\n  - (* -> *) intros H. destruct H as [X' H]. destruct H as [HP | HQ].\n    + left. exists X'. apply HP.\n    + right. exists X'. apply HQ.      \n  - (* <- *) intros H. destruct H as [HP | HQ].\n    + destruct HP as [X' HP]. exists X'. left. apply HP.\n    + destruct HQ as [X' HQ]. exists X'. right. apply HQ.\nQed.\n\n\n(* ################################################################# *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure:\n\n       - If [l] is the empty list, then [x] cannot occur in it, so the\n         property \"[x] appears in [l]\" is simply false.\n\n       - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n         occurs in [l] if either it is equal to [x'] or it occurs in\n         [l']. *)\n\n(** We can translate this directly into a straightforward recursive\n    function taking an element and a list and returning a proposition (!): *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested disjunctions. *)\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* WORKED IN CLASS *)\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n\n    Note, in the first, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions recursively, though convenient\n    in some cases, also has some drawbacks.  In particular, it is\n    subject to Coq's usual restrictions regarding the definition of\n    recursive functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\n  - (* -> *) intros H. induction l as [| x' l' IHl'].\n    + (* l = [] *)\n      simpl in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl in H. destruct H as [H1 | H2].\n      { exists x'. split.\n        - apply H1.\n        - simpl. left. reflexivity. }\n      { apply IHl' in H2. destruct H2 as [x2 H2]. exists x2. split.\n        - apply proj1 in H2. apply H2.\n        - simpl. right. apply proj2 in H2. apply H2. }\n  - (* <- *) intros H. induction l as [| x' l' IHl'].\n    + (* l = [] *)\n      simpl in H. destruct H as [x' H]. apply proj2 in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl. simpl in H. destruct H as [x'' H]. inversion H. destruct H1 as [H2 | H3].\n      { left. rewrite H2. apply H0. }\n      { right. apply IHl'. exists x''. split.\n        - apply H0.\n        - apply H3. }\nQed.\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' x. split.\n  - intros H. induction l.\n    + simpl. simpl in H. right. apply H.\n    + simpl. simpl in H. destruct H.\n      { left. left. apply H. }\n      { apply IHl in H. apply or_assoc. right. apply H. }\n  - intros H. induction l.\n    + simpl. simpl in H. destruct H.\n      { contradiction. }\n      { apply H. }\n    + simpl. simpl in H. apply or_assoc in H. destruct H as [H1 | [H2 | H3]].\n      { left. apply H1. }\n      { right. apply IHl. left. apply H2. }\n      { right. apply IHl. right. apply H3. }\nQed.\n\n(** **** Exercise: 3 stars (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | [] => True\n  | h :: t => P h /\\ All P t\n  end.\n\nLemma All_In : forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  intros T P l. split.\n  - (* -> *) intros H. induction l as [| n l' IHl'].\n    + (* l = nil *) simpl. auto.\n    + (* l = n :: l' *) simpl. split.\n      (* left *) { apply H. simpl. left. reflexivity. }\n      (* right *) { apply IHl'. intros x0 H0. apply H. simpl. right. apply H0. }\n  - (* <- *) intros H. induction l.\n    + (* l = nil *) simpl. intros x0 H0. contradiction.\n    + (* l = cons n l' *) simpl. intros x0 H0. destruct H0 as [|H1 H2].\n      (* left *) { simpl in H. apply proj1 in H. rewrite H0 in H. apply H. }\n      (* right *) { simpl in H. apply proj2 in H. apply IHl with x0 in H. apply H. apply H1. }\nQed.\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun (n : nat) => if oddb n then Podd n else Peven n.\n\n(** To test your definition, prove the following facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n Hodd Heven.\n  unfold combine_odd_even. destruct (oddb n) eqn: H.\n  - apply Hodd. reflexivity.\n  - apply Heven. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros Podd Peven n Hcomb Hodd.\n  unfold combine_odd_even in Hcomb.\n  rewrite Hodd in Hcomb. assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n Hcomb Heven.\n  unfold combine_odd_even in Hcomb.\n  rewrite Heven in Hcomb. assumption.\nQed.\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature that distinguishes Coq from some other popular\n    proof assistants (e.g., ACL2 and Isabelle) is that it treats\n    _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it all in detail in order to use Coq.\n    This section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use [Check] to ask Coq to print the type\n    of an expression.  We can also use it to ask what theorem a\n    particular identifier refers to. *)\n\nCheck plus_comm.\n\n(** Coq checks the _statement_ of the [plus_comm] theorem (or prints\n    it for us, if we leave off the part beginning with the colon) in\n    the same way that it checks the _type_ of any term that we ask it\n    to [Check]. Why? *)\n\n(** The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_, which represents a logical derivation establishing\n    of the truth of the statement [forall n m : nat, n + m = m + n].  The\n    type of this object is the proposition which it is a proof of. *)\n\n(** Intuitively, this makes sense because the statement of a\n    theorem tells us what we can use that theorem for, just as the\n    type of a \"computational\" object tells us what we can do with that\n    object -- e.g., if we have a term of type [nat -> nat -> nat], we\n    can give it two [nat]s as arguments and get a [nat] back. \n    Similarly, if we have an object of type [n = m -> n + n = m + m]\n    and we provide it an \"argument\" of type [n = m], we can derive\n    [n + n = m + m]. *)\n\n(** Operationally, this analogy goes even further: by applying a\n    theorem as if it were a function, i.e., applying it to hypotheses\n    with matching types, we can specialize its result without having\n    to resort to intermediate assertions.  For example, suppose we\n    wanted to prove the following result: *)\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  (* WORKED IN CLASS *)\n  intros x y z.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\nAbort.\n\n(** We saw similar problems back in Chapter [Induction], and saw one\n    way to work around them by using [assert] to derive a specialized\n    version of [plus_comm] that can be used to rewrite exactly where\n    we want. *)\n\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n(** A more elegant alternative is to apply [plus_comm] directly\n    to the arguments we want to instantiate it with, in much the same\n    way as we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite <- (plus_comm y z).\n  reflexivity.\nQed.\n\n(** Let's see another example of using a theorem like a\n    function. The following theorem says: any list [l]\n    containing some element must be nonempty. *)\n\nTheorem in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl.\n  rewrite Hl in H.\n  simpl in H.\n  apply H.\nQed.\n\n(** What makes this interesting is that one quantified variable\n    ([x]) does not appear in the conclusion ([l <> []]). *)\n\n(** We should be able to use this theorem to prove the special case\n    where [x] is [42]. However, naively, the tactic [apply in_not_nil]\n    will fail because it cannot infer the value of [x]. *)\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  Fail apply in_not_nil.\nAbort.\n\n(** There are several ways to work around this: *)\n\n(** Use [apply ... with ...] *)\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\n(** Use [apply ... in ...] *)\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\n(** Explicitly apply the lemma to the value for [x]. *)\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\n(** Explicitly apply the lemma to a hypothesis. *)\nLemma in_not_nil_42_take5 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. (The details of how this proof\n    works are not critical -- the goal here is just to illustrate what\n    can be done.) *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite -> mult_n_O in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples in later chapters. *)\n\n(* ================================================================= *)\n(** ** Functional Extensionality *)\n\n(** The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But,\n    since Coq's equality operator is polymorphic, we can use it at\n    _any_ type -- in particular, we can write propositions claiming\n    that two _functions_ are equal to each other: *)\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same output on every input:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_. *)\n\n(** Informally, an \"extensional property\" is one that pertains to an\n    object's observable behavior.  Thus, functional extensionality\n    simply means that a function's identity is completely determined\n    by what we can observe from it -- i.e., the results we obtain\n    after applying it. *)\n\n(** However, functional extensionality is not part of Coq's built-in\n    logic.  This means that some apparently \"obvious\" propositions are\n    not provable. *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\n(** However, we can add functional extensionality to Coq's core using\n    the [Axiom] command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Defining something as an [Axiom] has the same effect as stating a\n    theorem and skipping its proof using [Admitted], but it alerts the\n    reader that this isn't just something we're going to come back and\n    fill in later! *)\n\n(** We can now invoke functional extensionality in proofs: *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as this can render it _inconsistent_ -- that is, it may\n    become possible to prove every proposition, including [False],\n    [2+2=5], etc.!\n\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe to add: hard work by highly trained mathematicians is\n    often required to establish the consistency of any particular\n    combination of axioms.\n\n    Fortunately, it is known that adding functional extensionality, in\n    particular, _is_ consistent. *)\n\n(** To check whether a particular proof relies on any additional\n    axioms, use the [Print Assumptions] command.  *)\n\nPrint Assumptions function_equality_ex2.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\nPrint Assumptions functional_extensionality.\n\n(* recursion with acumulation *)\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(** This version of [rev] is said to be _tail-recursive_, because the\n    recursive call to the function is the last operation that needs to\n    be performed (i.e., we don't have to execute [++] after the\n    recursive call); a decent compiler will generate very efficient\n    code in this case.\n\n    Prove that the two definitions are indeed equivalent. *)\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(* ================================================================= *)\n(** ** Propositions vs. Booleans *)\n\n(** We've seen two different ways of expressing logical claims in Coq:\n    with _booleans_ (of type [bool]), and with _propositions_ (of type\n    [Prop]).\n\n    For instance, to claim that a number [n] is even, we can say\n    either... *)\n\n(** ... that [evenb n] evaluates to [true]... *)\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\n\n(** ... or that there exists some [k] such that [n = double k]. *)\nExample even_42_prop : even 42.\nProof. unfold even. exists 21. reflexivity. Qed.\n\n(** Of course, it would be pretty strange if these two\n    characterizations of evenness did not describe the same set of\n    natural numbers!  Fortunately, we can prove that they do... *)\n\n(** We first need two helper lemmas. *)\nLemma evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.  Qed.\n\nPrint evenb_S.\n\n(** **** Exercise: 3 stars, standard (evenb_double_conv)  *)\nLemma evenb_double_conv : forall n, exists k,\n  n = if evenb n then double k else S (double k).\nProof.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. exists 0. reflexivity.\n  - (* n = S n' *) destruct (evenb n') eqn: Heq.\n    + (* evenb n' = true *) rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists n''. rewrite IHn'. reflexivity.\n    + (* evenb n' = false *) rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists (n''+1). rewrite IHn'. rewrite double_plus. rewrite double_plus.\n      rewrite plus_n_Sm. rewrite <- plus_1_l. rewrite <- plus_n_Sm. rewrite <- (plus_1_l (n'' + n'')).\n      rewrite plus_comm. rewrite plus_assoc.  rewrite (plus_comm 1).\n      rewrite plus_assoc. reflexivity.\nQed.\n\n(** Now the main theorem: *)\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> even n.\nProof.\n  intros n. split.\n  - (* -> *)intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite -> Hk. rewrite H. exists k. reflexivity.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** In view of this theorem, we say that the boolean computation\n    [evenb n] is _reflected_ in the truth of the proposition\n    [exists k, n = double k]. *)\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either\n      - (1) that [n =? m] returns [true], or\n      - (2) that [n = m].\n    Again, these two notions are equivalent. *)\n\nPrint eqb_refl.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n  n1 =? n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - (* -> *) apply eqb_true.\n  - (* <- *) intros H. rewrite -> H. rewrite <- eqb_refl. reflexivity.\nQed.\n\n(** However, even when the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, they are\n    often not equivalent from the point of view of convenience for\n    some specific purpose. *)\n\n(** In the case of even numbers above, when proving the\n    backwards direction of [even_bool_prop] (i.e., [evenb_double],\n    going from the propositional to the boolean claim), we used a\n    simple induction on [k].  On the other hand, the converse (the\n    [evenb_double_conv] exercise) required a clever generalization,\n    since we can't directly prove [(evenb n = true) -> even n]. *)\n\n(** For these examples, the propositional claims are more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail\nDefinition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects\n    an element of [bool] (or some other inductive type with two\n    elements).  The reason has to do with the _computational_ nature\n    of Coq's core language, which is designed so that every function\n    it can express is computable and total.  One reason for this is to\n    allow the extraction of executable programs from Coq developments.\n    As a consequence, [Prop] in Coq does _not_ have a universal case\n    analysis operation telling whether any given proposition is true\n    or false, since such an operation would allow us to write\n    non-computable functions.\n\n    Beyond the fact that non-computable properties are impossible in\n    general to phrase as boolean computations, even many _computable_\n    properties are easier to express using [Prop] than [bool], since\n    recursive function definitions in Coq are subject to significant\n    restrictions.  For instance, the next chapter shows how to define\n    the property that a regular expression matches a given string\n    using [Prop].  Doing the same with [bool] would amount to writing\n    a regular expression matching algorithm, which would be more\n    complicated, harder to understand, and harder to reason about than\n    a simple (non-algorithmic) definition of this property.\n\n    Conversely, an important side benefit of stating facts using\n    booleans is enabling some proof automation through computation\n    with Coq terms, a technique known as _proof by reflection_.\n\n    Consider the following statement: *)\n\nExample even_1000 : even 1000.\n\n\n(** The most direct way to prove this is to give the value of [k]\n    explicitly. *)\n\nProof. unfold even. exists 500. reflexivity. Qed.\n\n(** The proof of the corresponding boolean statement is even\n    simpler (because we don't have to invent the witness: Coq's\n    computation mechanism does it for us!). \n    \n    In this case the witness is the nat term with value 500 *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** What is interesting is that, since the two notions are equivalent,\n    we can use the boolean formulation to prove the other one without\n    mentioning the value 500 explicitly: *)\n\nExample even_1000'' : even 1000.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n\n(** Although we haven't gained much in terms of proof-script\n    size in this case, larger proofs can often be made considerably\n    simpler by the use of reflection.  As an extreme example, a famous\n    Coq proof of the even more famous _4-color theorem_ uses\n    reflection to reduce the analysis of hundreds of different cases\n    to a boolean computation. *)\n\n(** Another notable difference is that the negation of a \"boolean\n    fact\" is straightforward to state and prove: simply flip the\n    expected boolean result. *)\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  (* WORKED IN CLASS *)\n  reflexivity.\nQed.\n\n(** In contrast, propositional negation can be more difficult\n    to work with directly. *)\n\nExample not_even_1001' : ~(even 1001).\nProof.\n  (* WORKED IN CLASS *)\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intro H.\n  discriminate H.\nQed.\n\n(** Equality provides a complementary example, where it is sometimes\n    easier to work in the propositional world. Knowing that\n    [n =? m = true] is generally of little direct help in the middle of a\n    proof involving [n] and [m]; however, if we convert the statement\n    to the equivalent form [n = m], we can rewrite with it. *)\n\nLemma plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m p H.\n  rewrite eqb_eq in H.\n  rewrite -> H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  - (* -> *) intros H. split.\n    + (* b1 = true *) rewrite andb_commutative in H. apply andb_true_elim2 in H. apply H.\n    + (* b2 = true *) apply andb_true_elim2 in H. apply H.\n  - (* <- *) intros H. inversion H. rewrite H0. rewrite H1. reflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - (* -> *) intros H. destruct H. destruct b1.\n    + simpl. left. reflexivity.\n    + simpl. right. reflexivity.\n  - (* -> *) intros H. destruct H as [H1 | H2].\n    + rewrite H1. simpl. reflexivity.\n    + rewrite H2. destruct b1.\n      { reflexivity. }\n      { reflexivity. }\nQed.\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\n\nTheorem eqb_nat_false_iff : forall x y : nat,\n  eqb x y = false <-> x <> y.\nProof.\n  intros x y. unfold not. split.\n  - (* -> *) intros H0 H1. apply eqb_eq in H1. rewrite H1 in H0. inversion H0.\n  - (* <- *) intros H. induction x as [| x'].\n    + induction y as [| y'].\n      { exfalso. apply H. reflexivity. }\n      { generalize dependent y'. auto. }\n    + induction y as [| y'].\n      { generalize dependent x'. auto. }\n      { simpl. destruct (eqb x' y') eqn:Heq.\n        - exfalso. apply H. apply f_equal. apply eqb_eq. apply Heq.\n        - reflexivity. }\nQed.\n\n\n(** **** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint eqb_list {A} (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 => if(eqb h1 h2) then eqb_list eqb t1 t2 else false\n  end.\n  \nLemma beq_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 l2. split.\n  - (* -> *) generalize dependent l2. induction l1 as [| h1 l1' IHl1'].\n    + induction l2 as [| h2 l2' IHl2'].\n      { reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (eqb h1 h2) eqn:Heq.\n        + apply H in Heq. rewrite <- Heq.\n          assert (l1' = l2' -> h1 :: l1' = h1 :: l2') as H2.\n          { intros H3. rewrite H3. reflexivity. } apply H2. apply IHl1'. apply H1.\n        + inversion H1. }\n  - (* <- *) generalize dependent l2. induction l1 as [| h1 l1' IHl1'].\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (eqb h1 h2) eqn:Heq.\n        + apply IHl1'. apply H in Heq. rewrite Heq in H1.\n          assert (h1 :: l1' = h1 :: l2' -> l1' = l2') as H2.\n          { intros H3. inversion H1. reflexivity. } apply H2. rewrite Heq. apply H1.\n        + inversion H1. apply H in H2. rewrite H2 in Heq. symmetry. apply Heq. }\nQed.\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  intros. split.\n  - (* -> *) intros. induction l.\n    + simpl. auto.\n    + simpl. split.\n      { unfold forallb in H. rewrite andb_true_iff in H. apply proj1 in H. assumption. }\n      { apply IHl. inversion H. rewrite andb_true_iff in H1. destruct H1 as [H2 H3]. rewrite H2.\n        rewrite H3. auto. }\n  - (* <- *) intros. induction l.\n    + reflexivity.\n    + simpl. rewrite andb_true_iff. split.\n      { simpl in H. apply proj1 in H. assumption. }\n      { simpl in H. apply proj2 in H. apply IHl in H. assumption. }\nQed.\n\n\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8947894632969136, "lm_q1q2_score": 0.8032482861798609}}
{"text": "Require Import Nat.\nRequire Import Arith.\n\n\n(*\n  The \"Tm\" type and the previously defined typing relation.\n*)\n\nInductive Tm : Set :=\n  | num (n : nat)\n  | plus (t t' : Tm)\n  | isZero (t : Tm)\n  | true\n  | false\n  | ifThenElse (t t' t'' : Tm)\n.\n\n\nNotation \"t + t'\" := (plus t t') : term_scope.\nNotation\n  \"'If' t 'then' t' 'else' t''\" :=\n  (ifThenElse t t' t'')\n  (at level 100)\n  : term_scope\n.\n\nDelimit Scope term_scope with term.\n(* Bind Scope term_scope with Tm. *)\nOpen Scope term_scope.\n\n\n(* The set of Ty and the inductive typing relation. *)\n\nInductive Ty : Set := Nat | Bool.\n\nInductive TypeJudgement : Tm -> Ty -> Prop :=\n  | TJ_num {n : nat} : (num n) :: Nat\n  | TJ_plus {t t' : Tm} (j : t :: Nat) (j' : t' :: Nat) : (t + t') :: Nat\n  | TJ_isZero {t : Tm} (j : t :: Nat) : (isZero t) :: Bool\n  | TJ_true : true :: Bool\n  | TJ_false : false :: Bool\n\n  | TJ_ifThenElse\n    {t t' t'' : Tm} {A : Ty}\n    (j : t :: Bool) (j' : t' :: A) (j'' : t'' :: A)\n    : (If t then t' else t'') :: A\n\nwhere \"tm :: ty\" := (TypeJudgement tm ty) : term_scope.\n\n\n(*\n  2.3. Oper\u00e1ci\u00f3s szemantika\n*)\n\n(* val : 2.9. - 2.11. *)\n\nReserved Notation \"t 'val'\" (at level 1).\n\n(*\n  Value judgements.\n*)\n\nInductive ValueJudgement : Tm -> Prop :=\n  | VJ_num {n : nat} : (num n) val\n  | VJ_true          : true val\n  | VJ_false         : false val\nwhere \"t 'val'\" := (ValueJudgement t).\n\n\n\n\n(* |-> : 2.14. - 2.22. *)\n\nReserved Notation \"t |-> t'\" (at level 100).\n\n(*\n  One Step Transition judgements.\n*)\n\nInductive OneStepTransitionJudgement : Tm -> Tm -> Prop :=\n  | OSTJ_plus {n n1 n2 : 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 {t1 t2 : Tm} : \n    If true then t1 else t2 |-> t1\n  \n  | OSTJ_ifThenElse_false {t1 t2 : Tm} : \n    If false then t1 else t2 |-> t2\n    \n  | OSTJ_plus_left {t1 t2 t1' : Tm} : \n    (t1 |-> t1') -> \n    (t1 + t2 |-> t1' + t2)\n    \n  | OSTJ_plus_right {t1 t2 t2' : Tm} : \n    t1 val -> \n    (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 \"t |-> t'\" := (OneStepTransitionJudgement t t').\n\n\n\n\n(* |->* : 2.12. - 2.13. *)\n\nReserved Notation \"t |->* t'\" (at level 100).\n\n(*\n  Any Step Transition judgements.\n*)\n\nInductive AnyStepTransitionJudegement : Tm -> Tm -> Prop :=\n  | ASTJ_refl  {e : Tm} : \n    (e |->* e)\n     \n  | ASTJ_trans {e e' e'' : Tm} : \n    (e  |->  e') -> \n    (e' |->* e'') -> \n    (e  |->* e'')\nwhere \"t |->* t'\" := (AnyStepTransitionJudegement t t').\n\n\n\nLemma p :\n  (num 1 + num 2) + (num 3 + num 4) |-> num 3 + (num 3 + num 4).\nProof.\n  apply OSTJ_plus_left.\n  apply OSTJ_plus.\n  trivial.\nQed.\n\nLemma q :\n  num 3 + (num 3 + num 4) |-> num 3 + num 7.\nProof.\n  apply OSTJ_plus_right.\n  + apply VJ_num.\n  + apply OSTJ_plus. trivial.\nQed.\n\nLemma r :\n  num 3 + num 7 |-> num 10.\nProof.\n  apply OSTJ_plus.\n  trivial.\nQed.\n\nLemma TransitionTest1 :\n  (num 1 + num 2) + (num 3 + num 4) |->* num 10.\nProof.\n  eapply ASTJ_trans.\n  + eapply OSTJ_plus_left. eapply OSTJ_plus. reflexivity.\n  + eapply ASTJ_trans. \n    - simpl. eapply OSTJ_plus_right.\n      * exact VJ_num.\n      * eapply OSTJ_plus. reflexivity.\n    - simpl. eapply ASTJ_trans.\n      * eapply OSTJ_plus. reflexivity.\n      * simpl. apply ASTJ_refl. \nQed.\n\n\nLemma TransitionTest2 :\n  If isZero (num 1 + num 2) then num 1 else (num 3 + num 1) |->* num 4.\nProof.\n  eapply ASTJ_trans.\n  + eapply OSTJ_ifThenElse. eapply OSTJ_isZero. eapply OSTJ_plus. reflexivity.\n  + eapply ASTJ_trans. \n    - eapply OSTJ_ifThenElse. eapply OSTJ_isZero_false. auto.\n    - eapply ASTJ_trans.\n      * eapply OSTJ_ifThenElse_false.\n      * eapply ASTJ_trans.\n        ** eapply OSTJ_plus. reflexivity.\n        ** simpl. eapply ASTJ_refl.\nQed.\n\n\n(*\n  2.19. Lemma.\n  No transition exists from val.\n*)\n\n\n\n(*\n  2.20. Lemma.\n  Deterministicity.\n*)\n\n\n\n\n(*\n  2.27. T\u00e9tel.\n  Theorem of type preservation.\n*)\n\n\n\n(*\n  2.29. Lemma\n*)\n\n\n\n(*\n  2.28. T\u00e9tel.\n  Theorem of progress.\n*)\n\n", "meta": {"author": "Anabra", "repo": "type-systems", "sha": "36565e1bc477f6d47f726c22b90e909c189c4fb5", "save_path": "github-repos/coq/Anabra-type-systems", "path": "github-repos/coq/Anabra-type-systems/type-systems-36565e1bc477f6d47f726c22b90e909c189c4fb5/operational_semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.8031384592936947}}
{"text": "(*\n\n  _   _    ___    __  __   _____  __        __   ___    ____    _  __    ____\n | | | |  / _ \\  |  \\/  | | ____| \\ \\      / /  / _ \\  |  _ \\  | |/ /   |___ \\\n | |_| | | | | | | |\\/| | |  _|    \\ \\ /\\ / /  | | | | | |_) | | ' /      __) |\n |  _  | | |_| | | |  | | | |___    \\ V  V /   | |_| | |  _ <  | . \\     / __/\n |_| |_|  \\___/  |_|  |_| |_____|    \\_/\\_/     \\___/  |_| \\_\\ |_|\\_\\   |_____|\n\n\nHowdy folks! In this homework assignment we'll explore more Coq programming\nand proving and get some practice with interpreters.\n\nThere are 21 problems worth a total of 120 core points and\n30 challenge points.\n\n*)\n\n\nRequire Import Arith Lia List String.\nImport ListNotations.\nOpen Scope string.\n\n(*\n               ____                  _     _                     _\n              / ___|    ___    ___  | |_  (_)   ___    _ __     / |\n              \\___ \\   / _ \\  / __| | __| | |  / _ \\  | '_ \\    | |\n               ___) | |  __/ | (__  | |_  | | | (_) | | | | |   | |\n              |____/   \\___|  \\___|  \\__| |_|  \\___/  |_| |_|   |_|\n\n                          SECTION 1 : More Coq Practice\n*)\n\n(*\n * In this part of the homework, we get some practice with lists and other\n * data structures.\n *\n * Step through this file with VSCode (or another IDE for Coq), and complete the\n * problems. Search for \"PROBLEM\" to be sure you find them all---not all\n * problems correspond to Coq code!\n *\n * Throughout, we include the approximate lines of code (LOC) or number of\n * tactics for each of our solutions to these problems.  These are rough\n * guidelines to help you figure out if you are getting off track.\n *\n * There is no penalty for writing a shorter or longer solution! However, if\n * you find yourself writing a much longer solution, you might save yourself\n * some time by taking a step back and seeing if you can find a simpler way.\n *\n *)\n\n(* --- More arithmetic --- *)\n\n(* This module creates a namespace where we can travel back in time to\n * Homework 1. Later in this homework we will be using the Coq standard library\n * version of nat, so we hide our own definitions in this namespace so we can\n * close it later.\n *)\nModule Homework1_TimeTravel. (* get in the DeLorean *)\nSet Implicit Arguments.\n\n(*\n * Here are some definitions again from Homework 1.\n *)\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nFixpoint add (n1 : nat) (n2 : nat) : nat :=\n  match n1 with\n  | O => n2\n  | S m1 => S (add m1 n2)\n  end.\n\n(*\n * PROBLEM 1 [0 points, ~4 tactics]\n *\n * You'll need this, which you proved in Homework 1. Feel free to copy/paste\n * your solution.\n *)\nLemma add_n_S :\n  forall n1 n2,\n    add n1 (S n2) = S (add n1 n2).\nProof.\ninduction n1 as [| p IHp]; intros; simpl.\n- reflexivity.\n- rewrite IHp. reflexivity.\nQed. (* Change to Qed when done *)\n\n(* We can define multiplication recursively as repeated addition. *)\n\nFixpoint mult (n1 : nat) (n2 : nat) : nat :=\n  match n1 with\n  | O => O\n  | S m1 => add n2 (mult m1 n2)\n  end.\n\n(*\n * PROBLEM 2 [8 points, ~35 tactics]\n *\n * Prove that multiplication is commutative, as stated by the lemma below.\n *\n * Hint: Proceed by induction.\n *\n * Hint: Don't use more than one induction inside a single proof.  Instead,\n * figure out lemmas that might be useful, and then prove those separately\n * (by induction, probably). See the style guide for more information.\n *\n * Hint: It might be useful to review all the lemmas about `add` in Homework 1.\n * Feel free to copy them over if you need to use them. You might need to\n * state and prove some analogous lemmas about `mult`.\n *\n * Hint: In order to prove your helpers about `mult`, you might need 1 or 2\n * additional facts about `add`.  Try to keep these simple, based on facts\n * you know from math, and prove them by induction.\n *)\n\n Lemma add_n_O :\n  forall n,\n  add n O = n.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\n  Qed.\n\nLemma mult_n_O :\n forall n,\n   mult n O = O.\nProof.\n induction n; auto.\nQed.\n\nLemma add_comm :\n  forall n1 n2,\n    add n1 n2 = add n2 n1.\nProof.\n  induction n1.\n  intros.\n  - simpl. rewrite -> add_n_O. reflexivity.\n  - simpl. intro n2. symmetry. rewrite add_n_S.\n    rewrite IHn1. auto.\nQed.\n\nLemma add_assoc :\n  forall n1 n2 n3,\n    add n1 (add n2 n3) = add (add n1 n2) n3.\nProof.\n  intros.\n  induction n1.\n  - simpl. reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma mult_n_Sm : \n  forall n m : nat,\n    mult n (S m) =  add n (mult n m).\nProof.\n  induction n; simpl; intros.\n  - reflexivity.\n  - rewrite IHn. f_equal.\n    rewrite -> add_assoc.\n    replace (add m n) with (add n m) by apply add_comm.\n    rewrite <- add_assoc.\n    reflexivity.\nQed.\n\n\nLemma mult_comm :\n  forall n m : nat,\n    mult n m = mult m n.\nProof.\n  induction n; simpl; intros.\n  - symmetry. apply mult_n_O.\n  - rewrite IHn. rewrite mult_n_Sm. reflexivity. \nQed. \n\n\nLemma add_swap:\n  forall n1 n2 n3,\n    add n1 (add n2 n3) = add n2 (add n1 n3).\nProof.\n  intros.\n  induction n1 as [| p IHp].\n  - simpl. reflexivity.\n  - simpl. rewrite IHp. rewrite <- add_n_S. reflexivity.\nQed.\n\nLemma mult_distributive:\n  forall n1 n2 n3,\n    mult (add n1 n2) n3 = add (mult n1 n3) (mult n2 n3).\nProof.\n  intros.\n  induction n1 as [| m1 IHm1].\n  - simpl. reflexivity.\n  - simpl. rewrite <- add_assoc. rewrite IHm1. reflexivity.\nQed.\n(*\n * PROBLEM 3 [10 points, ~25 tactics]\n *\n * State and prove that the `mult` function is associative.\n *\n * Hint: You'll probably need ~2 more lemmas about mult and/or add.\n *)\n(* YOUR LEMMA STATEMENT AND PROOF HERE *)\nLemma mult_assoc : \n  forall n1 n2 n3,\n    mult n1 (mult n2 n3) = mult (mult n1 n2) n3.\nProof.\n  intros.\n  induction n1 as [| p IHp].\n  - simpl. reflexivity.\n  - simpl. rewrite IHp. rewrite <- mult_distributive. reflexivity.\nQed.\n\n(* Here's the definition of `le` from lecture (and the standard library). *)\nInductive le (n : nat) : nat -> Prop :=\n| le_n : le n n\n| le_S : forall m, le n m -> le n (S m).\n\n(*\n * PROBLEM 4 [10 points, ~9 tactics]\n *\n * State and prove the following:\n * If a <= b then a + c <= b + c\n *\n * Hint: Proceed by induction.\n *)\nLemma a_le_b_add_c_le_b_add_c : \n  forall a b c: nat,\n    le a b -> le (add a c) (add b c).\n  Proof.\n    intros.\n    induction H.\n    - simpl. apply le_n.\n    - simpl. apply le_S. assumption.\nQed.\n\nEnd Homework1_TimeTravel. (* return to the present *)\n\n(*\n * Now that you've seen how nat, add, and mult are defined under the hood,\n * from now on we'll use the versions in Coq's standard library. These come\n * with nice notations like `1 + 3 * 4`, and with lots of free lemmas.\n *\n * There are also some useful tactics for working with arithmetic.\n *\n * Here are some automated proofs that the Coq standard library versions\n * of add and mult are commutative. (These lemmas are also in the standard\n * library, but we prove them from scratch just to demonstrate the tactics.)\n *)\n\nLemma add_comm_again :\n  forall a b, a + b = b + a.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma mult_comm_again :\n  forall a b, a * b = b * a.\nProof.\n  intros.\n  ring.\nQed.\n\n(*\n * PROBLEM 5 [4 points, ~5 tactics]\n *\n * Prove this simple fact about and.\n *\n * Hint: Review tactics that are useful for taking apart hypotheses.\n *\n * Hint: Review tactics that are useful for decomposing goals.\n *\n * Hint: Our solution uses little automation. If you feel like it, you can solve\n * it with ~1 tactic as well, using automation.\n *)\nLemma and_comm :\n  forall (A B : Prop),\n    A /\\ B ->\n    B /\\ A.\nProof.\n  intros.\n  destruct H as [Ha Hb].\n  split. (* works because we're proving a conjunction.*)\n  - assumption. \n  - assumption. \nQed. \n\n(*\n * PROBLEM 6 [4 points, ~7 tactics]\n *\n * Prove this simple fact about or.\n *\n * Hint: Review tactics that are useful for taking apart hypotheses.\n *\n * Hint: Review tactics that are useful for decomposing goals.\n *\n * Hint: Our solution uses little automation. If you feel like it, you can solve\n * it with ~1 tactic as well, using automation.\n *)\nLemma or_comm :\n  forall (A B : Prop),\n    A \\/ B ->\n    B \\/ A.\nProof.\n  intros.\n  destruct H as [Ha | Hb].\n  - right. exact Ha. (* can't split here because not a conjunction - have to extract each side *)\n  - left. exact Hb.\nQed.\n\n(* Here is an inductive definition of evenness for natural numbers. *)\nInductive even : nat -> Prop :=\n| even_O : even O\n| even_SS : forall n, even n -> even (S (S n)).\n\n(*\n * There are two constructors that can prove even. 0 is even. And a number of\n * the form S (S n) is even if n is even.\n *)\n\n(*\n * PROBLEM 7 [9 points, ~3 sentences]\n *\n * Write a comment answering the following questions.\n *\n * (a) If n is a nat in Coq, how many constructors of the type nat (O or S) is\n *     it built with? How many of those are S constructors and how many are O?\n *\n * (b) If n is a nat in Coq, and pf is a proof of even n, how many constructors\n *     of the proposition even is pf built with? How many are even_O and how\n *     many are even_SS?\n *\n * (c) If n is a nat in Coq, and n is odd, explain intuitively why your answer\n *     to part (b) implies that there is no proof of \"even n\".\n *\n * Hint: Your answer to part (a) should be three quantities: how many\n * constructors total, how many are O, and how many are S? Each quantity should\n * be expressed in terms of n. For example, one (wrong) answer would be \"There\n * are n / 3 + 7 constructors total, n / 3 are O, and 7 are S.\"\n *\n * Hint: Your answer to part (b) should be of a similar \"shape\" to part (a):\n * three quantities expressed in terms of n.\n *)\n(*\n * (a) Each nat is built with n + 1 constructors, where n is the number of S () and + 1 O constuctor.\n * (b) Each even n is built with n/2 even_SS constructors and one even_O constructor.\n * (c) There's isn't one! The construcors described in #2 are predicated on the recursive nature of even numbers.\n       As there isn't a constructor for False in Coq, so there is no proof of even n if n is odd.\n *)\n\n(* Here is a function that returns twice its argument. *)\nFixpoint double (n : nat) : nat :=\n  match n with\n  | O => O\n  | S m => S (S (double m))\n  end.\n\n(*\n * PROBLEM 8 [4 points, ~5 tactics]\n *\n * Prove that double always returns an even number.\n *\n * Hint: Proceed by induction.\n *)\nLemma double_even :\n  forall n,\n    even (double n).\nProof.\n  intros.\n  induction n.\n  simpl.\n  - exact even_O.\n  - simpl. apply even_SS. assumption. \nQed.\n\n(*\n * PROBLEM 9 [4 points, ~2 sentences]\n *\n * Consider the following lemma, which says that every even number is the output\n * of double on some input.\n *\n * Attempt to prove this lemma by induction on n. No need to turn in your\n * partial proof.\n *\n * Explain in a comment where you get stuck.\n *)\n\nLemma even_double :\n  forall n,\n    even n ->\n    exists k,\n      n = double k.\nProof.\n  induction n.\n  - intros. exists 0. reflexivity.\n  - intros. destruct IHn as [k Hk]. \n    contradict H. exfalso. (* I could have stopped before the destruct, but going this deep proves that the approach truly is broken,\n                              because the first goal is \"False\" and the only element above the line is \"n: nat\" *) \nAbort.\n(* We don't know enough about the computation of even n, or double k so the proof breaks down almost immediately. Immediately after\nproving the base case, n = 0, the proof assistant poses us with even S( n ) which is, of course, false. But we don't have enough\ninformation to demonstrate that. Instead, if we were to induct on the derivation of even n we can prove that, for all cases\nwhere n is even, the implication holds. *)\n\n(*\n * PROBLEM 10 [5 points, ~9 tactics]\n *\n * Now prove the lemma by induction on the derivation of even n.\n *)\nLemma even_double :\n  forall n,\n    even n ->\n    exists k,\n      n = double k.\nProof.\n  intros.\n  induction H.\n  - exists O. reflexivity.\n  - destruct IHeven as [d1 d2].\n    + exists (S d1). simpl in *. lia. \nQed.\n\n(*\n * PROBLEM 11 [5 points, ~6 tactics]\n *\n * Prove that the sum of two even numbers is even.\n *\n * Hint: What should you induct on?\n *)\nLemma plus_even :\n  forall x y,\n    even x ->\n    even y ->\n    even (x + y).\nProof.\n  intros. induction H.\n  - simpl. assumption.\n  - simpl. constructor. assumption.  \nQed.\n\n(*\n * PROBLEM 12 [5 points, ~4 tactics]\n *\n * Prove that 3 is not even.\n *\n * Hint: No need for induction. \"Call Coq's bluff\".\n *)\nLemma three_not_even :\n  even 3 -> False.\nProof.\n  intro Ht.\n  inversion Ht. (* \"I'll prove false for all cases which could have proved this true\"*)\n  inversion H0. (* even 1 is totally impossible to prove, so we're done *)\nQed. \n\nModule Data_Structures.\nSet Implicit Arguments.\n\n(* --- List practice --- *)\n\n(* Here are some definitions copied from the Coq standard library. *)\nInductive list (A : Type) : Type :=\n| nil\n| cons (hd : A) (tl : list A).\n\nArguments nil {A}.\nInfix \"::\" := cons.\nNotation \"[ ]\" := nil.\nNotation \"[ x1 ; .. ; xN ]\" := (cons x1 (.. (cons xN nil) ..)).\n\nFixpoint length {A} (ls : list A) : nat :=\n  match ls with\n  | nil => 0\n  | _ :: ls' => 1 + length ls'\n  end.\n\nFixpoint app {A} (ls1 ls2 : list A) : list A :=\n  match ls1 with\n  | nil => ls2\n  | x :: ls1' => x :: app ls1' ls2\n  end.\nInfix \"++\" := app.\n\nFixpoint rev {A} (ls : list A) : list A :=\n  match ls with\n  | nil => nil\n  | x :: ls' => rev ls' ++ [x]\n  end.\n\n(*\n * PROBLEM 13 [12 points, ~15 tactics]\n *\n * Prove the following theorem about the length of a reversed list.\n *\n * Hint: Proceed by induction on l.\n *\n * Hint: You'll need a helper lemma!\n *)\n\n Lemma len_1_S : \n  forall A (l: list A),\n    length l + 1 = S (length l).\n Proof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. reflexivity.\n Qed.\n\n Lemma length_comp:\n  forall A (l1 l2 : list A),\n    length (l1 ++ l2) = length l1 + length l2.\nProof.\n  induction l1; auto.\n  - simpl. intros. rewrite IHl1. reflexivity.\nQed.\n\nLemma length_rev :\n  forall A (l : list A),\n    length (rev l) = length l.\nProof.\n  induction l.\n  - auto.\n  - simpl. rewrite length_comp. simpl. rewrite IHl. apply len_1_S. \nQed.\n\n(*\n * Here is a function that adds up all the elements of a list of nats.\n *)\nFixpoint sum_list (l : list nat) : nat :=\n  match l with\n  | [] => 0\n  | x :: xs => x + sum_list xs\n  end.\n\n(*\n * And here are two functions that computes the same result with tail recursion.\n *)\nFixpoint sum_list_tr (l : list nat) (acc : nat) : nat :=\n  match l with\n  | [] => acc\n  | x :: xs => sum_list_tr xs (x + acc)\n  end.\n\nDefinition sum_list_tailrec (l : list nat) : nat :=\n  sum_list_tr l 0.\n\n(*\n * PROBLEM 14 [5 points, ~1 sentences]\n *\n * Consider the following theorem about the two ways of summing a list. You will\n * be asked to prove it in the next problem. For now, make a proof attempt that\n * proceeds directly by induction on `l`, without any nested inductions or\n * extra lemmas. At some point, you should get stuck.\n *\n * Write a sentence or two explaining why your proof attempt fails. Focus on the\n * induction hypothesis and whether it gives you enough information to complete\n * the proof.\n *\n * There is no need to turn in your proof attempt. Just turn in your\n * explanation.\n *\n * Hint: The base case should be provable.\n *\n * Hint: You might be able to make slightly more progress if you use the\n * `unfold` tactic to see inside the definition of `sum_list_tailrec`.\n *)\nTheorem sum_list_tailrec_ok : forall l,\n  sum_list_tailrec l = sum_list l.\nProof.\n  induction l.\n  - auto.\n  - simpl. rewrite <- IHl. unfold sum_list_tailrec. simpl. \nAbort.\n  (* The remaining goal of the proof when we left off above is: \"sum_list_tr l (hd + 0) = hd + sum_list_tr l 0\" and the inductive\n  hypothesis is \"sum_list_tailrec l = sum_list l\". The inductive hypothesis here is helpful if we\n  have a reference to sum_list_tailrec or sum_list in our remaining goal, but that's not the case *)\n\n(*\n * PROBLEM 15 [8 points, ~15 tactics]\n *\n * Now fix your broken proof by backing up and stating and proving a more\n * general helper lemma. Then use your helper lemma to finish the proof.\n *\n * Hint: Since `sum_list_tailrec` is defined in terms of the recursive function\n * `sum_list_tr`, it makes sense for your lemma to be about `sum_list_tr`.\n *\n * Hint: Your lemma should be proved by induction.\n *\n * Hint: Your fixed proof of `sum_list_tailrec_ok` should *not* use induction.\n *)\n\n Lemma sum_list_tr_sum_list_pl_acc : forall l acc,\n sum_list_tr l acc = sum_list l + acc.\nProof.\n induction l.\n - auto.\n - simpl. intros. rewrite -> IHl. lia.\nQed.\n\nTheorem sum_list_tailrec_ok : forall l,\n  sum_list_tailrec l = sum_list l.\nProof.\n  intros. unfold sum_list_tailrec.\n  replace (sum_list l) with (sum_list l + 0) by lia. apply sum_list_tr_sum_list_pl_acc.\nQed.\n\n(* --- Binary Tree practice --- *)\n\nInductive tree (A : Type) : Type :=\n| Leaf\n| Node : tree A -> A -> tree A -> tree A.\nArguments Leaf {A}.\n\nFixpoint reverse {A} (t : tree A) : tree A :=\n  match t with\n  | Leaf => Leaf\n  | Node l n r => Node (reverse r) n (reverse l)\n  end.\n\n(*\n * PROBLEM 16 [5 points, ~5 LOC]\n *\n * Define a function that adds up all the elements of a tree of nats.\n *)\nFixpoint sum_tree (t : tree nat) : nat :=\n  match t with\n  | Leaf => 0\n  | Node l d r => d + sum_tree l + sum_tree r\n  end.\n\n(*\n * PROBLEM 17 [5 points, ~5 tactics]\n *\n * Prove that `reverse` has no effect on the sum of the elements in a tree.\n *)\nLemma sum_tree_reverse :\n  forall t,\n    sum_tree (reverse t) = sum_tree t.\nProof.\n  induction t.\n  - auto.\n  - simpl. rewrite IHt1. rewrite IHt2. lia. \nQed.\n\n(*\n * PROBLEM 18 [12 points, ~20 tactics]\n *\n * Prove the following similar lemma about `sum_list` and `rev`.\n *\n * Hint: Proceed by induction on l.\n *\n * Hint: You'll need a helper lemma about sum_list.\n *)\n\nLemma sum_list_app_eq_sum_list_split :\n  forall l1 l2,\n    sum_list (l1 ++ l2) = sum_list l1 + sum_list l2. \nProof.\n  induction l1.\n  - auto.\n  - simpl. intros. rewrite IHl1. lia.\nQed.\n\n(* sum_list_nat is mostly just for reorganizing a goal and I couldn't\n   figure out another way to do that *)\nLemma sum_list_nat :\n  forall (hd : nat) (l1: list nat),\n     hd = sum_list [hd].\n  Proof.\n    intros. simpl. lia. \nQed.\n\nLemma sum_list_rev :\n  forall l,\n    sum_list (rev l) = sum_list l.\nProof.\n  induction l.\n  - auto.\n  - simpl. rewrite <- IHl. simpl. rewrite (sum_list_nat hd) at 2.\n    rewrite sum_list_app_eq_sum_list_split. lia. auto.\nQed.\n\nEnd Data_Structures.\n\n(*\n * PROBLEM 19 [5 points, ~3 sentences]\n *\n * Please take a moment to let us know how the homework went for you by\n * answering the following three questions:\n *    1. How long did the homework take you?\n *    2. Which parts were most interesting or helpful for you?\n *    3. Which parts were especially frustrating, confusing, or tedious?\n *       What should we do better next time?\n *\n * It's fine if your answers are short if you don't have much to say!\n *)\n\n(* \n* answers to the questions above:\n *    1. probably 15 or so hours, but I got stuck for a long time on the\n  *       first few. Office hours with Zach was really helpful!\n *    2. Everything was interesting, but I enjoyed the data structures\n  *       section the most. It's cool that there is a (truly challenging)\n  *       challenges section.\n *    3. Everything made sense eventually. I would definitely benefit from \n         seeing the instructors work through more proofs with more tactics.\n         Office hours was a game-changer for me mostly because I was able to \n        see how Zach thought through a few lemmas. \n *)\n\n\n\n(* --- End of Core Points --- *)\n\n(*\n * This is the end of the core points available for Homework 2. See below for\n * challenge points.\n *\n * To submit your homework, please follow the instructions at the end of the\n * README.md file in this directory.\n *\n * Please also see the README.md file to read about how we will grade this\n * homework assignment.\n *)\n\n(*\n             ____                  _     _                     ____\n            / ___|    ___    ___  | |_  (_)   ___    _ __     |___ \\\n            \\___ \\   / _ \\  / __| | __| | |  / _ \\  | '_ \\      __) |\n             ___) | |  __/ | (__  | |_  | | | (_) | | | | |    / __/\n            |____/   \\___|  \\___|  \\__| |_|  \\___/  |_| |_|   |_____|\n\n                          SECTION 2 : Challenge Problem\n*)\n\n(*\n * CHALLENGE 20 [10 points, ~20 tactics]\n *\n * Give an alternative characterization of evenness as follows.\n *)\n\n\n Lemma even_double_nat :\n forall n, n + n = double n .\nProof.\n  intros.\n  induction n.\n  - auto.\n  - simpl. lia.\nQed.\n\nLemma even_n_add_n :\n forall n, even (n + n).\nProof.\n  intros.\n  induction n.\n  - simpl. constructor.\n  - rewrite even_double_nat. apply double_even.\nQed.\n\nLemma even_iff_exists_half :\n  forall n,\n    even n <-> exists k, n = 2 * k.\nProof.\n  split.\n  intros.\n  induction H.\n  - exists 0. auto.\n  - destruct IHeven.\n    + exists (S x). lia.\n  - simpl in *. (* exists k, n = 2 * k. is NOT recursive so we shouldn't need induction. *)\n    intros.\n    destruct H.\n    rewrite H.\n    replace (x + (x + 0)) with (x + x) by lia.\n    apply even_n_add_n.\nQed.\n\n(* CHALLENGE 21 [20 points, ~8 tactics]\n *\n * In class we saw a proof that Peirce's law implies the law of excluded middle.\n * Now prove the reverse direction\n *\n * Hint: This way should be easier than the proof from lecture.\n *)\nLemma lem_implies_peirce :\n  (forall P : Prop, P \\/ ~P) -> forall P Q : Prop, ((P -> Q) -> P) -> P.\nProof.\n   simpl. intros.\n    destruct (H P) as [P1 | P2]. (* P1 = P, P2 = ~P - comment in here because I became *very* confused*)\n    - apply P1.\n    - apply H0. intros. contradict H1. apply P2.\n  Qed.\n", "meta": {"author": "SharmaAjay19", "repo": "CSEP-505", "sha": "0a27b36dccac1f0308c1860303e6a2f8a61d3c8a", "save_path": "github-repos/coq/SharmaAjay19-CSEP-505", "path": "github-repos/coq/SharmaAjay19-CSEP-505/CSEP-505-0a27b36dccac1f0308c1860303e6a2f8a61d3c8a/Homeworks/hw2/HW2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.9019206738932333, "lm_q1q2_score": 0.802974773637866}}
{"text": "Inductive bool : Type :=\n| true : bool\n| false : bool.\n\nDefinition negb (x : bool) : bool :=\nmatch x with\n| true => false\n| false => true\nend.\n\nCheck negb.\n\nLemma L1 : negb true = false.\nProof.\nsimpl.\nreflexivity.\nQed.\n\nLemma negb_negb (x:bool) : negb (negb x) = x.\nProof.\ndestruct x.\nreflexivity.\nreflexivity.\nQed.\n\nDefinition andb (x y : bool) : bool :=\nmatch x with\n| true => y\n| false => false\nend.\n\nLemma andb_com x y : andb x y = andb y x.\nProof.\ndestruct x.\ndestruct y.\nreflexivity.\nreflexivity.\ndestruct y.\nreflexivity.\nreflexivity.\nDefined.\n\nDefinition orb (x y : bool) : bool :=\nmatch x with\n| true => true\n| false => y\nend.\n\nCheck orb.\n\nLemma orb_com x y : orb x y = orb y x.\nProof.\ndestruct x.\ndestruct y.\nreflexivity.\nreflexivity.\ndestruct y.\nreflexivity.\nreflexivity.\nQed.\n\nLemma demorgan x y : negb (orb x y) = andb (negb x) (negb y).\nProof.\ndestruct x.\ndestruct y.\nreflexivity.\nreflexivity.\ndestruct y.\nreflexivity.\nreflexivity.\nQed.\n\nCheck fun x : bool => x.\n\nCompute (fun x : bool => x) true.\n\nCheck andb true.\n\nCompute andb true.\n\nDefinition andb' : bool -> bool -> bool :=\n fun x : bool =>\n   fun y : bool =>\n     match x with\n      | true => y\n      | false => false\nend.\n\nPrint negb.\n\nPrint andb.\nPrint andb'.\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_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569265, "lm_q2_score": 0.890294223211224, "lm_q1q2_score": 0.8029747634148311}}
{"text": "Require Import List.\n\nSet Implicit Arguments.\n\nPrint List.\n\nFixpoint sum (l : list nat) : nat :=\nmatch l with\n  | nil => 0\n  | cons h tail => \n    let n:= sum tail in h + n\nend.\n\n\nEval compute in sum(cons 5 (cons 5 (cons 5 nil))).\n\nPrint \"++\".\nPrint rev.\nPrint length.\nPrint map.\n\nLemma ex3_1 : forall (l1 : list nat) (l2 : list nat), sum (l1 ++ l2) = sum l1 + sum l2.\nProof.\n  induction l1.\n  - intro. simpl. reflexivity.\n  - simpl. intro. rewrite IHl1. rewrite PeanoNat.Nat.add_assoc. reflexivity.\nQed.\n\nLemma ex3_2 : forall (A:Type) (l:list A), length (rev l) = length l.\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite app_length. simpl. rewrite IHl. rewrite PeanoNat.Nat.add_comm. reflexivity.\nQed.\n\nLemma ex3_3 : forall (A B:Type) (f:A->B) (l1 l2:list A), (map f l1)++(map f l2) = map f (l1++l2).\nProof.\n  induction l1.\n  - induction l2.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - induction l2.\n    + simpl. rewrite <- IHl1. simpl. reflexivity.\n    + simpl. rewrite <- IHl1. simpl. reflexivity.\nQed.\n\nLemma ex3_4 : forall (A B:Type) (f:A->B) (l:list A), rev (map f l) = map f (rev l).\nProof.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. rewrite map_app. simpl. reflexivity.\nQed.\n\n\n\nPrint In.\n\nInductive In (A:Type) (y:A) : list A -> Prop :=\n| InHead : forall xs:list A, In y (cons y xs)\n| InTail : forall (x:A) (xs:list A), In y xs -> In y (cons x xs).\n\nPrint In.\n\nLemma ex4_1_aux : forall (A:Type) (x:A) (l1 l2: list A), (In x l1 \\/ In x l2) -> In x (l1 ++ l2).\nProof.\n  intros.\n  destruct H as [H|H].\n  - induction H.\n    + rewrite <- app_comm_cons. apply InHead.\n    + rewrite <- app_comm_cons. apply InTail. assumption.\n  - induction l1.\n    + simpl. assumption.\n    + rewrite <- app_comm_cons. apply InTail. assumption.\nQed.\n\nLemma ex4_1 : forall (A:Type) (x:A) (l:list A), In x l -> In x (rev l).\nProof.\n  intros.\n  induction H.\n  - simpl.\n    apply ex4_1_aux.\n    right.\n    apply InHead.\n  - simpl.\n    apply ex4_1_aux.\n    left.\n    assumption.\nQed.\n\nLemma ex4_2 : forall (A B:Type) (y:B) (f:A->B) (l:list A), In y (map f l) -> exists x, In x l /\\ y = f x.\nProof.\n  intros.\n  induction l.\n  - simpl in H. inversion H.\n  - simpl in H. inversion H.\n    * exists a. split.\n      + apply InHead.\n      + reflexivity.\n    * cut (exists x:A, In x l /\\ y = f x).\n      + intro. destruct H3. exists x0. destruct H3 as [H3 H4]; split.\n        -- constructor; assumption.\n        -- assumption.\n      + exact (IHl H1).\nQed.\n\nLemma ex4_3 : forall (A:Type) (x:A) (l :list A), In x l -> exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  intros.\n  induction H.\n  + exists nil. exists xs. simpl. reflexivity.\n  + destruct IHIn as [I1 H1]. destruct H1 as [I2 H1]. exists (x0::I1). exists I2. rewrite <-app_comm_cons. rewrite H1; reflexivity.\nQed.\n\n\nInductive Prefix (A:Type) : list A -> list A -> Prop :=\n| PreNil : forall l:list A, Prefix nil l\n| PreCons : forall (x:A) (l1 l2:list A), Prefix l1 l2 -> Prefix (x::l1) (x::l2).\n\nLemma ex5_1 : forall (A:Type) (l1 l2:list A), Prefix l1 l2 -> length l1 <= length l2.\nProof.\n  intros.\n  induction H.\n  - simpl. intuition.\n  - simpl. rewrite <- PeanoNat.Nat.succ_le_mono. assumption.\nQed.\n\nLemma ex5_2 : forall l1 l2, Prefix l1 l2 -> sum l1 <= sum l2.\nProof.\n  intros.\n  induction H.\n  - simpl; intuition.\n  - simpl. apply Plus.plus_le_compat_l. assumption.\nQed.\n\nLemma ex5_3 : forall (A:Type) (l1 l2:list A) (x:A), (In x l1) /\\ (Prefix l1 l2) -> In x l2.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  induction H2.\n  + induction l.\n    - assumption.\n    - apply InTail. assumption.\n  + inversion H1.\n    - constructor.\n    - constructor. apply IHPrefix. assumption.\nQed.\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\nLemma ex6_1 : forall (A:Type)(l1 l2 l3 l4:list A), SubList l1 l2 -> SubList l3 l4 -> SubList (l1++l3) (l2++l4).\nProof.\n  intros.\n  induction H.\n  - simpl. induction l.\n    + simpl; assumption.\n    + rewrite <- app_comm_cons. constructor. assumption.\n  - rewrite <- app_comm_cons; constructor; assumption.\n  - rewrite <- app_comm_cons; constructor; assumption.\nQed.\n\nLemma ex6_2 : forall (A:Type) (l1 l2:list A), SubList l1 l2 -> SubList (rev l1) (rev l2).\nProof.\nAdmitted.\n\nLemma ex6_3 : forall (A:Type) (x:A) (l1 l2:list A), Prefix l1 l2 -> SubList l1 l2.\nProof.\n  intros.\n  induction H.\n  - apply SLnil.\n  - apply SLcons1. assumption.\nQed.\n\nLemma ex6_4 : forall (A:Type) (x:A) (l1 l2:list A), SubList l1 l2 -> In x l1 -> In x l2.\nProof.\n  intros.\n  induction H.\n  - induction l.\n    + assumption.\n    + apply InTail. assumption.\n  - inversion H0. \n    + apply InHead. \n    + apply InTail. apply IHSubList. assumption.\n  - apply InTail. apply IHSubList; assumption.\nQed.", "meta": {"author": "JaK0be", "repo": "VF", "sha": "4d886d958200df476b3ece5c2194ee5ff1f149d5", "save_path": "github-repos/coq/JaK0be-VF", "path": "github-repos/coq/JaK0be-VF/VF-4d886d958200df476b3ece5c2194ee5ff1f149d5/TPC5/ficha2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.924141827813457, "lm_q1q2_score": 0.8029191556295533}}
{"text": "From mathcomp\n     Require Import ssreflect ssrnat.\n\nSection naturalNumber.\n\nLemma addOnEqn (n : nat) : 0 + n = n.\nProof. by []. Qed.\n\nLemma addn3Eq2n1 (n : nat) : n + 3 = 2 + n + 1.\nProof.\nrewrite addn1.\nrewrite add2n.\nrewrite addnC.\nby [].\nQed.\n\nFixpoint sum n := if n is m.+1 then (sum m) + n else 0.\n\nLemma sumGauss (n : nat) : (sum n) * 2 = (n + 1) * n.\nProof.\nelim: n.\nby [].\nmove=> n IHn.\nrewrite mulnC.\nrewrite (_ : sum (n.+1) = n.+1 + (sum n)); last first.\nrewrite /=.\nby rewrite addnC.\n\nrewrite mulnDr.\nrewrite mulnC in IHn.\nrewrite IHn.\nrewrite 2!addn1.\nrewrite [_ * n] mulnC.\nrewrite -mulnDl.\nby [].\nQed.\n\nEnd naturalNumber.", "meta": {"author": "hajifkd", "repo": "coq_book", "sha": "5bc7ff0c2234034d61ab1aed441fc6d0efa03344", "save_path": "github-repos/coq/hajifkd-coq_book", "path": "github-repos/coq/hajifkd-coq_book/coq_book-5bc7ff0c2234034d61ab1aed441fc6d0efa03344/ch2/NaturalNumber.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8028903350759415}}
{"text": "Require Import  Arith.\nSet Implicit Arguments.\n\n(** Similar to Vector_Def library, with different names \n*)\n\nSection Vector_definitions.\n\nVariable A : Type.\n\nInductive vector : nat -> Type :=\n| vnil : vector 0\n| vcons (h:A)(n:nat)(v: vector n) : vector (S n).\n\n\nAbout vector_rect.\n\n(**\n vector_rect :\nforall P : forall n : nat, vector n -> Type,\nP 0 vnil ->\n(forall (n : nat) (v : vector n), P n v -> P (S n) (vcons h v)) ->\nforall (n : nat) (v : vector n), P n v\n*)\n\n(** Arguments for the recursor vector_rect *)\n\nLet P_head (n:nat)(v: vector n) := n<>0 -> A.\nLet P_tail (n:nat)(v: vector n) := n<>0 -> vector (pred n).\n\n\nDefinition  P_head_0 : P_head  vnil.\nProof.\n  intro H. now destruct H.\nDefined.\n\n\nDefinition  P_tail_0 : P_tail  vnil.\nProof.\n  intro H; now destruct H.\nDefined.\n\n\nDefinition P_head_S :\n forall (h : A) (n : nat) (v : vector n), P_head  v ->\n                                       P_head  (vcons  h  v) .\nProof.\n intros h n v X _; exact h.\nDefined. \n\nDefinition P_tail_S :\n forall (h : A) (n : nat) (v : vector n), P_tail  v ->\n                                          P_tail  (vcons  h  v) .\nProof.\n intros h n v X _;  exact v.\nDefined. \n \n\n\nDefinition v_head_aux := vector_rect P_head P_head_0 P_head_S.\nCheck v_head_aux.\n\nDefinition v_tail_aux := vector_rect  P_tail P_tail_0 P_tail_S.\n\n\nDefinition v_head (n:nat)(v: vector (S n)) : A :=\n  v_head_aux  v (Nat.neq_succ_0 n).\n\nDefinition v_tail (n:nat)(v: vector (S n)) : vector n:=\n $( refine (v_tail_aux v _); auto)$.\n\n\nDefinition v_Id  : forall n, vector n -> vector n :=\nfun n => match n with \n| 0 => fun v => vnil\n|S p => fun v => vcons (v_head v) (v_tail v)\nend. \n\n\nCompute fun v : vector 0 => v_Id v.\n\n(*\nDefinition v_Id  : forall n, vector n -> vector n .\n destruct n; intro v.\n - exact vnil.\n - exact (vcons (v_head v) (v_tail v)).   \nQed.\n*)\n\n\nLemma v_Id_eq : forall n (v:vector n), v = v_Id v.\n intros n v; pattern n ,v;apply vector_rect.\n- reflexivity.\n- intros.  reflexivity. \nQed. \n\n\nLemma vector_0 : forall v: vector 0, v = vnil.\nintro v. \n  change  vnil with (v_Id v).\n apply v_Id_eq.\nQed.\n\n\nLemma vector_S : forall n (v:vector (S n)),\n    v = vcons (v_head v) (v_tail v).\nProof.\n  intros n v; change (vcons (v_head v) (v_tail v)) with (v_Id v).\n  apply v_Id_eq.\nQed.\n\n\n  End Vector_definitions.\n\nArguments vnil {A}.\n\nLemma test1 : v_head  (vcons  42  vnil) =  42.\nProof. reflexivity. Qed.\n\nLemma test : v_tail  (vcons  42  (vcons 22 vnil)) =  vcons 22 vnil . \nProof. reflexivity. Qed.\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch6_inductive_data/SRC/recursor_for_vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.8028043409164027}}
{"text": "(**\n\nThis exposes all the operators on bitvector which is used to give\nsemantics.\n\n *)\nRequire Export Bvector.\nRequire Import BinNat.\nRequire Import Arith.\nRequire Import NArith.\nRequire Import ZArith.\nRequire Import Nat.\nRequire Import SetoidClass.\n\n\nDeclare Scope bitvector_scope.\nDelimit Scope bitvector_scope with bitvector.\n\nArguments Bv2N [n].\n\n(** computes 2^m *)\nDefinition twopower m : N := Nat.iter m N.double 1%N.\nDefinition twopower_nat (m:nat) : nat := Nat.iter m Nat.double 1.\nDefinition twopower_N   (m:N) : N := N.iter m N.double 1%N.\nDefinition arithm (func : N -> N -> N) sz : Bvector sz -> Bvector sz -> Bvector sz\n  := fun x y => N2Bv_sized sz (func (@Bv2N _ x) (@Bv2N _ y)).\n\nDefinition BVN_size {sz} (vec : Bvector sz) := N.size (Bv2N vec).\nDefinition BVN_size_nat {sz} (vec : Bvector sz) := N.size_nat (Bv2N vec).\n\nDefinition BVplus      := arithm N.add.\nDefinition BVnegative sz (vec : Bvector sz) := N2Bv_sized sz (2^(N.of_nat sz) - Bv2N vec).\nDefinition BVminus sz  := arithm (fun x y => x + 2^(N.of_nat sz) - y)%N sz.\n\nDefinition BVmul       := arithm N.mul.\nDefinition BVquot      := arithm N.div.\nDefinition BVrem       := arithm N.modulo.\n\nDefinition BVones : forall sz, Bvector sz\n  := Bvect_true.\nDefinition BVzeros : forall sz, Bvector sz\n  := Bvect_false.\n\n\nCheck BVand. (* Comes directly from Bvector *)\nCheck BVor.  (* Comes directly from Bvector *)\nCheck BVxor. (* Comes directly from Bvector *)\n\nDefinition BVcomp   := Bneg. (* renaming for better naming convention *)\n\nDefinition BVshiftL1 sz : Bvector sz -> Bvector sz :=\n  match sz with\n  | 0 => @id (Bvector 0)\n  | S sz0 => fun vec => BshiftL sz0 vec false\n  end.\n\nDefinition BVshiftL sz (n : nat) : Bvector sz -> Bvector sz\n  := Nat.iter n (BVshiftL1 sz).\n\nDefinition BVshiftR1 sz : Bvector sz -> Bvector sz :=\n  match sz with\n  | 0 => @id (Bvector 0)\n  | S sz0 => fun vec => BshiftRl sz0 vec false\n  end.\n\nDefinition BVshiftR sz (n : nat) : Bvector sz -> Bvector sz\n  := Nat.iter n (BVshiftR1 sz).\n\nDefinition rotTowardsLSB sz (vec : Bvector sz) :=\n  match vec with\n  | [] => []\n  | (x :: xs) => Vector.shiftin x xs\n  end.\n\n(** This is what shiftout should have been not sure why it was not defined this way *)\nDefinition popout {A} : forall n, Vector.t A (S n) -> (Vector.t A n * A) :=\n  @Vector.rectS _ (fun n _ => (Vector.t A n * A)%type)\n           (fun a => ([], a))\n           (fun h _ _ H => let (xs, x) := H in (h :: xs, x)).\n\nArguments popout [A n].\n\nDefinition rotTowardsMSB sz (vec : Bvector sz) :=\n  match vec with\n  | [] => []\n  | xs => let (xsp, x) := popout xs in (x :: xsp)\n  end.\n\nDefinition BVrotR sz n\n  := Nat.iter n (rotTowardsLSB sz).\n\nDefinition BVrotL sz n\n  := Nat.iter n (rotTowardsMSB sz).\n\n(** Generates a bit vector with n-lsb bits set *)\nDefinition lower_ones sz n : Bvector sz\n  := N2Bv_sized sz (N.ones (N.of_nat n)).\n\n(** Generate a bit vector with n-msb bits set *)\nDefinition upper_ones sz n : Bvector sz\n  := BVcomp sz (lower_ones sz (sz - n)).\n\n(** Generate a bit vector with 1 in all bits between m and n\n    (inclusive) and zero otherwise. Used to select a particular range\n    of values.\n\n*)\n\nDefinition onesAt sz (pos : nat) (len : nat): Bvector sz\n  := BVxor sz (lower_ones sz (len+pos)) (lower_ones sz pos).\n\n(* begin hide *)\nArguments BVplus   [sz].\nArguments BVminus  [sz].\nArguments BVmul    [sz].\nArguments BVquot   [sz].\nArguments BVrem    [sz].\nArguments BVnegative [sz].\nArguments BVand    [_].\nArguments BVor     [_].\nArguments BVxor    [_].\nArguments BVcomp   [_].\nArguments BVshiftL [sz].\nArguments BVshiftL1 [sz].\nArguments BVshiftR [sz].\nArguments BVshiftR1 [sz].\nArguments BVrotR   [sz].\nArguments BVrotL   [sz].\n\nArguments lower_ones [sz].\nArguments upper_ones [sz].\nArguments onesAt     [sz].\nArguments BVzeros {sz}.\nArguments BVones  {sz}.\n(* end hide *)\n\n(** * Bitwise functions\n\nThis function essentially give the semantics of some of the bitwise\nmacros that we have in the library. Facts about them will help dealing\nwith semantics.\n\n*)\nDefinition selectLower {sz} n (vec : Bvector sz) := BVand vec (lower_ones n).\nDefinition selectUpper {sz} n (vec : Bvector sz) := BVand vec (upper_ones n).\nDefinition clearUpper {sz}  n  := @selectLower sz (sz -n).\nDefinition clearLower {sz}  n  := @selectUpper sz (sz - n).\n\n(** Some efficient arithmetic functions using bitwise operations. **)\n\n\nDefinition div2power_nat    {sz} n := @BVshiftR sz n.\nDefinition modulo2power_nat {sz} n := @selectLower sz n.\nDefinition of_N {sz}   : N -> Bvector sz := N2Bv_sized sz.\nDefinition to_N {sz}   : Bvector sz -> N := @Bv2N sz.\n(*\nDefinition of_nat {sz} : nat -> Bvector sz :=  fun n => N2Bv_sized sz (N.of_nat n).\nDefinition to_nat {sz} : Bvector sz -> nat := fun vec => N.to_nat (to_N vec).\n *)\n\nDefinition bveq {sz}(v1 v2 : Bvector sz) := BVeq sz sz v1 v2.\n\n\n\n\n(** * Notations for bitvector operations\n\nWe define instances for Algebraic syntax for bitvector. This gives\npretty arithmetic operations for bitvectors.\n\nThe bitwise operations are given unicode syntax and are used primarily\nso that the proof obligations turn out to readable. They are not meant\nfor input.\n\nTODO: Note that we have hidden the notation that uses unicode so that\ncoqdoc's pdf generation does not get stuck.\n\n*)\n\n(* begin hide *)\nRequire Export setoid_ring.Algebra_syntax.\n\nInstance zero_Bvector sz : Zero (Bvector sz)     := N2Bv_sized sz 0.\nInstance one_Bvector sz  : One (Bvector sz)      := N2Bv_sized sz 1.\nInstance add_Bvector sz  : Addition (Bvector sz) := @BVplus sz.\nInstance mul_Bvector sz  : Multiplication  := @BVmul sz.\nInstance sub_Bvector sz  : Subtraction (Bvector sz) := @BVminus sz.\nInstance opp_Bvector sz  : Opposite (Bvector sz)   := (@BVnegative sz).\n\nInstance setoid_bvector sz : Setoid (Bvector sz) := {| SetoidClass.equiv := eq |}.\n\n(* end hide *)\nDefinition of_Z {sz} (z :  Z) : Bvector sz:=\n  match z with\n  | Z0 => zero\n  | Zpos zp => of_N (Npos zp)\n  | Zneg zp => BVnegative (of_N (Npos zp))\n  end.\n\nDefinition to_Z {sz}(bv : Bvector sz) := Z.of_N (to_N bv).\n\nFixpoint pow {sz}(eta : Bvector sz)(n : nat) : Bvector sz :=\n  match n with\n  | 0   => 1\n  | S m => (eta  * (pow eta m))\n  end.\n\nInstance bitvector_power_nat (sz : nat) : Power := @pow sz.\n\nInfix \"=?\" := (bveq) (at level 70): bitvector_scope.\n(* begin hide *)\n\nDeclare Custom Entry bits.\n\nNotation \"[bits| e |]\" := e (e custom bits).\nNotation \"( x )\" := x  (in custom bits at level 0).\nNotation \"` x `\" := x  (in custom bits at level 0, x constr, format \"` x `\").\n\nInfix \"*\"           := BVmul            (in custom bits at level 40, left associativity).\n\nInfix \"/\"           := BVquot           (in custom bits at level 40, left associativity).\nInfix \"%\"           := BVrem            (in custom bits at level 40, left associativity).\n\nInfix \"+\"           := BVplus           (in custom bits at level 50, left associativity).\nInfix \"-\"           := BVminus          (in custom bits at level 50, left associativity).\n\n\nNotation \"~ E\"      := (BVcomp E)  (in custom bits at level 30, right associativity).\nInfix \"&\"         := BVand         (in custom bits at level 56, left associativity).\nInfix \"\u2295\"         := BVxor         (in custom bits at level 57, left associativity).\nInfix \"|\"         := BVor          (in custom bits at level 59, left associativity).\nNotation \"A \u226b m\" := (BVshiftR m A) (in custom bits at level 54, left associativity).\nNotation \"A \u226a m\" := (BVshiftL m A) (in custom bits at level 54, left associativity).\nNotation \"A \u22d8 m\" := (BVrotL m A)   (in custom bits at level 54, left associativity).\nNotation \"A \u22d9 m\" := (BVrotR m A)   (in custom bits at level 54, left associativity).\nNotation \"\u27e6 A \u27e7\"  := (@Bv2N _ A)   (in custom bits).\n(* end hide *)\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/BitVector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8026834601544466}}
{"text": "(* Pr\u00e1ctica 6 *)\n(* Gabina Luz Bianchi *)\n\n(* Ejercicio 3 *)\n\nDefinition Value := bool.\n\nInductive BoolExpr : Set :=\n| bbool : bool -> BoolExpr\n| band : BoolExpr -> BoolExpr -> BoolExpr\n| bnot : BoolExpr -> BoolExpr.\n\nInductive BEval : BoolExpr -> Value -> Prop :=\n| ebool : forall b : bool, BEval (bbool b) (b:Value)\n| eandl : forall e1 e2 : BoolExpr, BEval e1 false -> BEval (band e1 e2) false\n| eandr : forall e1 e2 : BoolExpr, BEval e2 false -> BEval (band e1 e2) false\n| eandrl : forall e1 e2 : BoolExpr, BEval e1 true -> BEval e2 true -> BEval (band e1 e2) true\n| enott : forall e : BoolExpr, BEval e true -> BEval (bnot e) false\n| enotf : forall e : BoolExpr, BEval e false -> BEval (bnot e) true.\n\n\nFixpoint beval1 (e : BoolExpr) : Value :=\nmatch e with\n| bbool b => b\n| band e1 e2 =>\n               match beval1 e1, beval1 e2 with\n               | true, true => true\n               | _, _ => false\n               end\n| bnot e1 => if beval1 e1 then false else true\nend.\n\nFixpoint beval2 (e : BoolExpr) : Value :=\nmatch e with\n| bbool b => b\n| band e1 e2 => \n               match beval2 e1 with\n               | false => false\n               | _ => beval2 e2\n               end\n| bnot e1 => if beval2 e1 then false else true\nend.\n\nLemma beval1cor: forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval1 e).\ninduction e.\n   * unfold beval1.\n     constructor.\n   * simpl.\n     case_eq (beval1 e1);intros.\n        + case_eq (beval1 e2);intros.\n           - constructor.\n              rewrite H in IHe1.\n              assumption.\n              rewrite H0 in IHe2.\n              assumption.\n           - apply eandr.\n             rewrite H0 in IHe2.\n             assumption.\n        + constructor.\n          rewrite H in IHe1.\n          auto.\n    * simpl.\n     case_eq (beval1 e); intros.\n        + rewrite H in IHe.\n          constructor.\n          auto.\n       + rewrite H in IHe.\n         constructor.\n         auto.\nQed.\n\nLemma beval2cor: forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval2 e).\ninduction e.\n   * unfold beval2.\n     constructor.\n   * simpl.\n     case_eq (beval2 e1);intros.\n        + case_eq (beval2 e2);intros.\n           - constructor.\n              rewrite H in IHe1.\n              assumption.\n              rewrite H0 in IHe2.\n              assumption.\n           - apply eandr.\n             rewrite H0 in IHe2.\n             assumption.\n        + constructor.\n          rewrite H in IHe1.\n          auto.\n    * simpl.\n     case_eq (beval2 e); intros.\n        + rewrite H in IHe.\n          constructor.\n          auto.\n       + rewrite H in IHe.\n         constructor.\n         auto.\nQed.\n\nHint Constructors BEval.\nHint Constructors BoolExpr.\n\n\nLemma beval1cor2: forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\n  intro; exists (beval1 e).\n  induction e.\n    auto.\n\n    simpl; destruct (beval1 e1); destruct (beval1 e2); auto.\n\n    simpl; destruct (beval1 e); auto.\nQed.\n\n\nLemma beval2cor2: forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\n  intro; exists (beval2 e).\n  induction e.\n    auto.\n\n    simpl; destruct (beval2 e1); destruct (beval2 e2); auto.\n\n    simpl; destruct (beval2 e); auto.\nQed.\n\nExtraction Language Haskell.\nExtraction \"beval1\" beval1cor2.\nExtraction \"beval2\" beval2cor2.\n\nExtract Inductive bool => \"Bool\" [ \"true\" \"false\" ].\nExtraction \"beval12\" beval1cor.\nExtraction \"beval22\" beval2cor.\n\n\n(* Ejercicio 5 *)\n\n\nInductive Le: nat -> nat -> Prop :=\n| le0 : forall n:nat, Le 0 n\n| leS : forall n m : nat, Le n m -> Le (S n) (S m).\n\nInductive Gt: nat -> nat -> Prop :=\n| gt0 : forall n:nat, (n <> 0) -> Gt n 0\n| gtS : forall n m : nat, Gt n m -> Gt (S n) (S m).\n\nFunction leBool (n m : nat) : bool :=\nmatch n with\n| 0 => true\n| S k => match m with\n         | 0 => false\n         | S p => leBool k p\n         end\nend.\n\nHint Constructors Le.\nHint Constructors Gt.\nRequire Import Omega.\n\nLemma Le_Gt_dec: forall n m:nat, {(Le n m)}+{(Gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m).\n   +left.\n    auto.\n  +right.\n   constructor.\n   discriminate.\n  + elim IHb; intros.\n     - left.\n       auto.\n     - right.\n       auto.\nQed.\n\nLemma le_gt_dec: forall n m:nat, {(le n m)}+{(gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m).\n   + left.\n     omega.\n   + right.\n     omega.\n   + elim IHb; intros.\n        - left.\n          omega.\n        - right.\n          omega.\nQed.\n\n(* Ejercicio 6 *)\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\nRequire Import Omega.\nRequire Import DecBool.\nRequire Import Compare_dec.\nRequire Import Plus.\nRequire Import Mult. \nRequire Import Coq.Arith.Compare_dec.\n\n\nDefinition nat_div_mod :\n forall a b:nat, not(b=0) -> {qr:nat*nat | spec_res_nat_div_mod a b qr}. \nProof.\nintros.\ndestruct b; intros.\n   - omega.\n   - induction a.\n        + exists (0, 0).\n          unfold spec_res_nat_div_mod.\n          omega.\n        + elim IHa.\n          intros.\n          destruct x.\n          case_eq (le_lt_dec b n0); intros.\n             * exists (S n,0).\n               unfold spec_res_nat_div_mod.\n               split; intros.\n               rewrite -> plus_0_r.\n               unfold spec_res_nat_div_mod in p.\n               elim p; intros.\n               rewrite -> H1.\n               simpl.\n               assert (n0 = b).\n                  omega.\n               rewrite -> H3.\n               assert (b * n + b = b * S n).\n                  assert ( S n = n + 1).\n                  omega.\n               rewrite -> H4.\n               rewrite -> mult_plus_distr_l.\n               omega.\n               symmetry in H4.\n               rewrite -> H4.\n               omega.\n               omega.\n             * exists (n, S n0).\n               unfold spec_res_nat_div_mod.\n               split; intros.\n               unfold spec_res_nat_div_mod in p.\n               elim p; intros.\n               rewrite -> H1.\n               omega.\n               omega.\nQed.\n\nExtraction \"divmod\" nat_div_mod. \n\n(* Ejercicio 7 *)\n\nInductive tree (A:Set) : Set :=\n| leaf : tree A\n| node : A -> tree A -> tree A -> tree A.\n\nInductive tree_sub (A:Set) (t:tree A) : tree A -> Prop :=\n| tree_sub1 : forall (t':tree A) (x:A), tree_sub A t (node A x t t')\n| tree_sub2 : forall (t':tree A) (x:A), tree_sub A t (node A x t' t).\n\nTheorem well_founded_tree_sub : forall A:Set, well_founded (tree_sub A).\nProof.\nintros.\nunfold well_founded.\nintros.\ninduction a.\n   + apply (Acc_intro).\n     intros.\n     inversion H.\n   + apply (Acc_intro).\n     intros.\n     inversion H; assumption.\nQed.\n\n(* Ejercicio 8 *)\n\nFixpoint size (be : BoolExpr) :=\nmatch be with\n | bbool b => 0\n | band b1 b2 => 2 + size b1 + size b2\n | bnot b =>  1 + size b\nend.\n\nDefinition elt (e1 e2 : BoolExpr) := size e1 < size e2. \n\nTheorem well_founded_elt : well_founded (elt).\nProof.\napply well_founded_ltof. \nQed.", "meta": {"author": "gabina", "repo": "coq", "sha": "b9e5fc6a43d0ac670816ecb57ed441863ff8e5c0", "save_path": "github-repos/coq/gabina-coq", "path": "github-repos/coq/gabina-coq/coq-b9e5fc6a43d0ac670816ecb57ed441863ff8e5c0/tp6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.8026226494149585}}
{"text": "From MyCoq.Lib Require Export Nat.\nFrom MyCoq.Lib Require Export Poly.\n\nCheck 3 = 3.\nCheck forall n m : nat, n + m = m + n.\n\nDefinition plus_claim : Prop := N 2 + N 2 = N 4.\n\nTheorem plus_claim_is_true: plus_claim.\nProof.\n  unfold plus_claim.\n  reflexivity.\nQed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = N 3.\nCheck is_three.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj: injective S.\nProof.\n  unfold injective.\n  intros x y H.\n  injection H as H'.\n  apply H'.\nQed.\n\nLocate eq.\nCheck @eq.\n\n\n(* \u903b\u8f91\u8054\u7ed3\u8bcd *)\nExample and_example: (N 3 + N 4 = N 7) /\\ (N 2 * N 2 = N 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 H1 H2.\n  split.\n  - apply H1.\n  - apply H2.\nQed.\n\nExample and_exercise:\n  forall n m : nat, n + m = O -> n = O /\\ m = O.\nProof.\n  intros n m H.\n  assert (H1: n = O).\n  {\n    destruct n as [| n'].\n    - reflexivity.\n    - discriminate H.\n  }\n  assert (H2: m = O).\n  {\n    destruct m as [| m'].\n    - reflexivity.\n    - rewrite plus_comm in H.\n      discriminate H.\n  }\n  split.\n  - apply H1.\n  - apply H2.\nQed.\n\nLemma and_example2:\n  forall n m : nat, n = O /\\ m = O -> n + m = O.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm] eqn : HE.\n  rewrite Hn.\n  rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2':\n  forall n m : nat, n = O /\\ m = O -> n + m = O.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn.\n  rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3:\n  forall n m : nat, n + m = O -> n * m = O.\nProof.\n  intros n m H.\n  assert (H': n = O /\\ m = O).\n  {\n    apply and_exercise.\n    apply H. \n  }\n  destruct H' as [Hn Hm].\n  rewrite Hn.\n  reflexivity.\nQed.\n\nLemma proj1: forall P Q : Prop, P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  apply HP.\nQed.\n\nLemma proj2: forall P Q : Prop, P /\\ Q -> Q.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [_ HQ].\n  apply HQ.\nQed.\n\nTheorem and_commut: forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP.\nQed.\n\nTheorem and_assoc: forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split.\n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR.\nQed.\n\nLemma eq_mult_O:\n  forall n m : nat, n = O \\/ m = O -> n * m = O.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn.\n    reflexivity.\n  - rewrite Hm.\n    rewrite -> mult_n_O.\n    reflexivity.\nQed.\n\nLemma or_intro_l: forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nModule MyNot.\nDefinition not (P : Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\nEnd MyNot.\n\nTheorem ex_falso_quodlibet: forall P : Prop,\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\nFact not_implies_our_not: forall P : Prop,\n  ~ P -> (forall Q : Prop, P -> Q).\nProof.\n  intros P HNP.\n  unfold not in HNP.\n  intros Q HP.\n  apply HNP in HP.\n  destruct HP.\nQed.\n\nNotation \"x <> y\" := (~ (x = y)).\n\nTheorem zero_not_one: O <> N 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate contra.\nQed.\n\nTheorem not_False:\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything: forall P Q : Prop,\n  (P /\\ ~ P) -> Q.\nProof.\n  intros P Q [HP HNA].\n  unfold not in HNA.\n  apply HNA in HP.\n  destruct HP.\nQed.\n\nTheorem double_neg: forall P : Prop,\n  P -> ~ ~ P.\nProof.\n  intros P H.\n  unfold not.\n  intros G.\n  apply G.\n  apply H.\nQed.\n\nTheorem contrapositive: forall (P Q : Prop),\n  (P -> Q) -> (~ Q -> ~P).\nProof.\n  intros P Q H HNQ.\n  unfold not in HNQ.\n  unfold not.\n  intros HP.\n  apply H in HP.\n  apply HNQ in HP.\n  apply HP.\nQed.\n\nTheorem not_both_true_and_false: forall P : Prop,\n  ~ (P /\\ ~ P).\nProof.\n  intros P.\n  unfold not.\n  intros [HP HNP].\n  apply HNP in HP.\n  apply HP.\nQed.\n\nTheorem not_true_is_false: forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn : HE.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H.\n    reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\nTheorem not_true_is_false': forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    exfalso. (* <=== *)\n    apply H.\n    reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\nCheck I.\n\nLemma True_is_true: True.\nProof.\n  apply I.\nQed.\n\nModule MyIff.\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\nEnd MyIff.\n\nTheorem iff_sym: forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) \n    apply HBA.\n  - (* <- *)\n    apply HAB.\nQed.\n\nLemma not_true_iff_false: forall b,\n  b <> true <-> b = false.\nProof.\n  intros b.\n  split.\n  - (* -> *) \n    apply not_true_is_false.\n  - (* <- *)\n    intros H.\n    rewrite H.\n    intros H'.\n    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.\n        apply H1.\n      * left.\n        apply H1.\n    + destruct H2 as [H21 H22].\n      split.\n      * right.\n        apply H21.\n      * right.\n        apply H22.\n  - intros [H1 H2].\n    destruct H1 as [H11 | H12].\n    + left.\n      apply H11.\n    + destruct H2 as [H21 | H22].\n      * left.\n        apply H21.\n      * right.\n        split.\n        -- apply H12.\n        -- apply H22.\nQed.\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_eq_O: forall n m, n * m = O -> n = O \\/ m = O.\nProof.\n  intros n m H.\n  destruct n as [| n'].\n  - left.\n    reflexivity.\n  - destruct m as [| m'].\n    + right.\n      reflexivity.\n    + discriminate H.\nQed.\n\nLemma mult_O: forall n m, n * m = O <-> n = O \\/ m = O.\nProof.\n  split.\n  - apply mult_eq_O.\n  - apply eq_mult_O.\nQed.\n\nLemma or_assoc:\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R.\n  split.\n  - intros [H | [H | H]].\n    + left.\n      left.\n      apply H.\n    + left.\n      right.\n      apply H.\n    + right.\n      apply H.\n  - intros [[H | H] | H].\n    + left.\n      apply H.\n    + right.\n      left.\n      apply H.\n    + right.\n      right.\n      apply H.\nQed.\n\nLemma mult_O_3:\n  forall n m p, n * m * p = O <-> n = O \\/ m = O \\/ p = O.\nProof.\n  intros n m p.\n  rewrite mult_O.\n  rewrite mult_O.\n  rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma apply_iff_example:\n  forall n m : nat, n * m = O -> n = O \\/ m = O.\nProof.\n  intros n m H.\n  apply mult_O.\n  apply H.\nQed.\n\nDefinition even x := exists n : nat, x = double n.\n\nLemma four_is_even: even (N 4).\nProof.\n  unfold even.\n  exists (N 2).\n  reflexivity.\nQed.\n\nTheorem exists_example_2: forall n,\n  (exists m, n = (N 4) + m) ->\n  (exists o, n = (N 2) + o).\nProof.\n  intros n [m Hm].\n  exists ((N 2) + m).\n  apply Hm.\nQed.\n\nTheorem dist_not_exists: forall (X : Type) (P : X -> Prop),\n  (forall x, P x) -> not (exists x, not (P x)).\nProof.\n  intros X P.\n  intros H1 H2.\n  destruct H2 as [x H2'].\n  unfold not in H2'.\n  apply H2'.\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 [x [H1 | H2]].\n    + left.\n      exists x. \n      apply H1.\n    + right.\n      exists x.\n      apply H2.\n  - intros [[x H1] | [x H2]].\n    + exists x.\n      left.\n      apply H1.\n    + exists x.\n      right.\n      apply H2.\nQed.\n\n\n(* \u4f7f\u7528\u547d\u9898\u7f16\u7a0b *)\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1: In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2:\n  forall n, In n [N 2; N 4] ->\n  exists n', n = (N 2) * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists (N 1).\n    rewrite <- H.\n    reflexivity.\n  - exists (N 2).\n    rewrite <- H.\n    reflexivity.\nQed.\n\nLemma In_map:\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n  In x l -> In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - simpl.\n    intros [].\n  - simpl.\n    intros [H | H].\n    + rewrite H.\n      left.\n      reflexivity.\n    + right.\n      apply IHl'.\n      apply H.\nQed.\n\nLemma In_map_iff:\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n  In y (map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y.\n  split.\n  - induction l as [| x' l' IHl'].\n    + simpl.\n      intros [].\n    + simpl.\n      intros [H1 | H2].\n      * exists x'.\n        split.\n        ** apply H1.\n        ** left.\n           reflexivity.\n      * apply IHl' in H2.\n        destruct H2 as [x [H21 H22]].\n        exists x.\n        split.\n        ** apply H21.\n        ** right.\n           apply H22.\n  - induction l as [| x' l' IHl'].\n    + simpl.\n      intros [x [H1 H2]].\n      apply H2.\n    + simpl.\n      intros [x [H1 H2]].\n      destruct H2 as [H21 | H22].\n      * rewrite <- H21 in H1.\n        left.\n        apply H1.\n      * right.\n        apply IHl'.\n        exists x.\n        split.\n        ** apply H1.\n        ** apply H22.\nQed.\n\nLemma In_app_iff: forall A l1 l2 (a : A),\n  In a (l1 ++ l2) <-> In a l1 \\/ In a l2.\nProof.\n  intros A l1 l2.\n  split.\n  induction l1 as [|x' l' IHl'].\n  - simpl.\n    right.\n    apply H.\n  - simpl.\n    intros [H1 | H2].\n    + left.\n      left.\n      apply H1.\n    + apply IHl' in H2.\n      destruct H2 as [H21 | H22].\n      * left.\n        right.\n        apply H21.\n      * right.\n        apply H22.\n  - induction l1 as [|x' l' IHl'].\n    + simpl.\n      intros [[] | H2].\n      apply H2.\n    + simpl.\n      intros [[H1 | H2] | H3].\n      * left.\n        apply H1.\n      * right.\n        apply IHl'.\n        left.\n        apply H2.\n      * right.\n        apply IHl'.\n        right.\n        apply H3.\nQed.  \n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n    | [] => True\n    | x :: y => P x /\\ All P y\n  end.\n\nLemma All_In:\n  forall T (P : T -> Prop) (l : list T),\n  (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l.\n  split.\n  - induction l as [| x' l' IHl'].\n    + reflexivity.\n    + simpl.\n      intro H.\n      split.\n      * apply H.\n        left.\n        reflexivity.\n      * apply IHl'.\n        intros x H1.\n        apply H.\n        right.\n        apply H1.\n  - induction l as [| x' l' IHl'].\n    + simpl.\n      intros H x [].\n    + simpl.\n      intros [H11 H12] x.\n      intros [H21 | H22].\n      * rewrite <- H21.\n        apply H11.\n      * apply IHl'.\n       ** apply H12.\n       ** apply H22.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n =>\n    match oddb n with\n      | true => Podd n\n      | false => Peven n\n    end.\n\nTheorem combine_odd_even_intro:\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n H1 H2.\n  unfold combine_odd_even. \n  destruct (oddb n).\n  - apply H1.\n    reflexivity.\n  - apply H2.\n    reflexivity.\nQed. \n\nTheorem combine_odd_even_elim_odd:\n  forall (Podd Peven : nat -> Prop) (n : nat),\n  combine_odd_even Podd Peven n ->\n  oddb n = true ->\n  Podd n.\nProof.\n  intros Podd Peven n.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - intros.\n    apply H.\n  - intros.\n    discriminate H0.\nQed.\n\nTheorem combine_odd_even_elim_even:\n  forall (Podd Peven : nat -> Prop) (n : nat),\n  combine_odd_even Podd Peven n ->\n  oddb n = false ->\n  Peven n.\nProof.\n  intros Podd Peven n.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - intros.\n    discriminate H0.\n  - intros.\n    apply H.\nQed.\n\n\n(* \u5bf9\u53c2\u6570\u5e94\u7528\u5b9a\u7406 *)\nCheck plus_comm.\n\nLemma plus_comm3:\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  Check (plus_comm y z).\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nTheorem in_not_nil:\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H.\n  unfold not.\n  intro Hl.\n  destruct l eqn : HE.\n  - simpl in H.\n    destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42:\n  forall l : list nat, In (N 42) l -> l <> [].\nProof.\n  intros l H.\n  (* apply in_not_nil with (x := N 42). *)\n  apply (in_not_nil nat (N 42)).\n  apply 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 * (N 0)) ns) -> n = N 0.\nProof.\n  intros n ns H.\n  Check (proj1 _ _ (In_map_iff _ _ _ _ _) H).\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H) as [m [Hm _]].\n  rewrite mult_comm in Hm.\n  rewrite mult_O_n in Hm.\n  rewrite <- Hm.\n  reflexivity.\nQed.\n", "meta": {"author": "GanZiheng", "repo": "learn-coq", "sha": "6d915f299e0b483ba53a8184c9ec13ac275aeca6", "save_path": "github-repos/coq/GanZiheng-learn-coq", "path": "github-repos/coq/GanZiheng-learn-coq/learn-coq-6d915f299e0b483ba53a8184c9ec13ac275aeca6/Src/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.8026226447719854}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export Tactics.\n\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions ([forall\n    x, P]).  In this chapter, we will see how Coq can be used to carry\n    out other familiar forms of logical reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** Note that all well-formed propositions have type [Prop] in Coq,\n    regardless of whether they are true or not. Simply _being_ a\n    proposition is one thing; being _provable_ is something else! *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** Indeed, propositions don't just have types: they are _first-class\n    objects_ that can be manipulated in the same ways as the other\n    entities in Coq's world.  So far, we've seen one primary place\n    that propositions can appear: in [Theorem] (and [Lemma] and\n    [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have given names to expressions of other sorts. *)\n\nDefinition plus_fact : Prop  :=  2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\n(** We can later use this name in any situation where a proposition is\n    expected -- for example, as the claim in a [Theorem] declaration. *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\n(** We can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments.  For instance, here's a\n    polymorphic property defining the familiar notion of an _injective\n    function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** The equality operator [=] that we have been using so far is also\n    just a function that returns a [Prop]. The expression [n = m] is\n    just syntactic sugar for [eq n m], defined using Coq's [Notation]\n    mechanism. Because [=] can be used with elements of any type, it\n    is also polymorphic: *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type argument [A]\n    to [eq] is declared as implicit, so we need to turn off implicit\n    arguments to see the full type of [eq].) *)\n\n(* #################################################################### *)\n(** * Logical Connectives *)\n\n(** ** Conjunction *)\n\n(** The _conjunction_ or _logical and_ of propositions [A] and [B] is\n    written [A /\\ B], denoting the claim that both [A] and [B] are\n    true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  Its effect is to\n    generate two subgoals, one for each part of the statement: *)\n\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** More generally, the following principle works for any two\n    propositions [A] and [B]: *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** A logical statement with multiple arrows is just a theorem that\n    has several hypotheses.  Here, [and_intro] says that, for any\n    propositions [A] and [B], if we assume that [A] is true and we\n    assume that [B] is true, then [A /\\ B] is also true.\n\n    Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can, apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\nRequire Peano.\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  induction n, m.\n  - simpl. intros. split. reflexivity. reflexivity.\n  - simpl. intros. split. reflexivity. assumption.\n  - intros. split. inversion H. reflexivity.\n  - intros. inversion H.\nQed.\n\n\n(** [] *)\n\n(** So much for proving conjunctive statements.  To go in the other\n    direction -- i.e., to _use_ a conjunctive hypothesis to prove\n    something else -- we employ the [destruct] tactic.\n\n    If the proof context contains a hypothesis [H] of the form [A /\\\n    B], writing [destruct H as [HA HB]] will remove [H] from the\n    context and add two new hypotheses: [HA], stating that [A] is\n    true, and [HB], stating that [B] is true.  For instance: *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] when we introduce it instead of\n    introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** In this case, there is not much difference between the two\n    theorems.  But it is often necessary to explicitly decompose\n    conjunctions that arise from intermediate steps in proofs,\n    especially in bigger developments.  Here's a simplified\n    example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know [A /\\\n    B] but in some context we need just [A] (or just [B]).  The\n    following lemmas are useful in such cases: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros. destruct H. assumption.\nQed.\n(** [] *)\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of conjuncts in multi-way conjunctions.  The\n    following commutativity and associativity theorems come in handy\n    in such cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.\nQed.\n\n(** **** Exercise: 2 stars (and_assoc)  *)\n(** (In the following proof of associativity, notice how the _nested_\n    intro pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split. split.  assumption. assumption. assumption.\nQed.\n\n(** [] *)\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (Alternatively, we can write [or A B], where [or : Prop ->\n    Prop -> Prop].)\n\n    To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis, which, as for [nat] or other data types, can be done\n    with [destruct] or [intros].  Here is an example: *)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     [n = 0 \\/ m = 0] *)\n  intros n m [Hn | Hm].\n  - (* Here, [n = 0] *)\n    rewrite Hn. reflexivity.\n  - (* Here, [m = 0] *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n(** We can see in this example that, when we perform case analysis on\n    a disjunction [A \\/ B], we must satisfy two proof obligations,\n    each showing that the conclusion holds under a different\n    assumption -- [A] in the first subgoal and [B] in the second.\n    Note that the case analysis pattern ([Hn | Hm]) allows us to name\n    the hypothesis that is generated in each subgoal.\n\n    Conversely, to show that a disjunction holds, we need to show that\n    one of its sides does. This is done via two tactics, [left] and\n    [right].  As their names imply, the first one requires proving the\n    left side of the disjunction, while the second requires proving\n    its right side.  Here is a trivial use... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and a slightly more interesting example requiring the use of\n    both [left] and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  induction n, m.\n  - simpl. intros. left. reflexivity.\n  - intros. left. reflexivity.\n  - intros. right. reflexivity.\n  - intros.   left. inversion H.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros. destruct H. right. assumption. left. assumption.\nQed.\n\n(** [] *)\n\n(** ** Falsehood and Negation *)\n\n(** So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    _negative_ results, showing that certain propositions are _not_\n    true. In Coq, such negative statements are expressed with the\n    negation operator [~].\n\n    To see how negation works, recall the discussion of the _principle\n    of explosion_ from the [Tactics] chapter; it asserts that, if we\n    assume a contradiction, then any other proposition can be derived.\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].  Coq actually makes a slightly different\n    choice, defining [~ P] as [P -> False], where [False] is a\n    _particular_ contradictory proposition defined in the standard\n    library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can [destruct] it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.\nQed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\n(** Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros. destruct H. assumption.\nQed.\n\n(** [] *)\n\n(** This is how we use [not] to state that [0] and [1] are different\n    elements of [nat]: *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** Such inequality statements are frequent enough to warrant a\n    special notation, [x <> y]: *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    get things into the right configuration so that Coq can understand\n    it!  Here are proofs of a few familiar facts to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.\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\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not. intros. apply H in H1. destruct H0. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros. unfold not. intros. destruct H. apply H0. assumption.\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\n(** Similarly, since inequality involves a negation, it requires a\n    little practice to be able to work with it fluently.  Here is one\n    useful trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see some examples such uses of [True] later on. *)\n\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HAB HBA].\n  split.\n  - (* -> *) apply HBA.\n  - (* <- *) apply HAB.\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'. inversion H'.\nQed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros. split. intros. assumption. intros. assumption.\nQed.\n\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [H11 H12] [H21 H22]. split. intros.  apply H21. apply H11. assumption.\n  intros. apply H12. apply H22. assumption.\nQed.\n  (** [] *)\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros. split.\n  -  intros. destruct H. split. left. assumption. left. assumption. destruct H. split.\n     right. assumption.  right. assumption.\n  - intros. destruct H.  destruct H. left. assumption. destruct H0. left. assumption. right. split. assumption.  assumption.\nQed.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we need\n    to import a special Coq library that allows rewriting with other\n    formulas besides equality: *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences: *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [H | [H | H]].\n    + left. left. apply H.\n    + left. right. apply H.\n    + right. apply H.\n  - intros [[H | H] | H].\n    + left. apply H.\n    + right. left. apply H.\n    + right. right. apply H.\nQed.\n\n(** We can now use these facts with [rewrite] and [reflexivity] to\n    give smooth proofs of statements involving equivalences.  Here is\n    a ternary version of the previous [mult_0] result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which side of\n    the equivalence to use. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n(* ############################################################ *)\n(** ** Existential Quantification *)\n\n(** Another important logical connective is _existential\n    quantification_.  To say that there is some [x] of type [T] such\n    that some property [P] holds of [x], we write [exists x : T,\n    P]. As with [forall], the type annotation [: T] can be omitted if\n    Coq is able to infer from the context what the type of [x] should\n    be.\n\n    To prove a statement of the form [exists x, P], we must show that\n    [P] holds for some specific choice of value for [x], known as the\n    _witness_ of the existential.  This is done in two steps: First,\n    we explicitly tell Coq which witness [t] we have in mind by\n    invoking the tactic [exists t]; then we prove that [P] holds after\n    all occurrences of [x] are replaced by [t].  Here is an example: *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n    the context, we can destruct it to obtain a witness [x] and a\n    hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.\nQed.\n\n(** **** Exercise: 1 star (dist_not_exists)  *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros X P h1 h2.  elim h2.  intros x h3. elim h3. apply h1.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros. split.\n  - intros. destruct H. destruct H. left. exists x. assumption. right. exists x. assumption.\n  - intros [H1 | H2]. destruct H1. exists x. left. assumption.  destruct H2. exists x. right. assumption.\nQed.\n\nPrint dist_exists_or.\n(** [] *)\n\n(* #################################################################### *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure:\n\n    - If [l] is the empty list, then [x] cannot occur on it, so the\n      property \"[x] appears in [l]\" is simply false.\n\n    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n      occurs in [l] if either it is equal to [x'] or it occurs in\n      [l']. *)\n\n(** We can translate this directly into a straightforward Coq\n    function, [In].  (It can also be found in the Coq standard\n    library.) *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | nil => False\n  | h::t => h = x \\/ In x t\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested conjunctions. *)\n\nExample In_example_1 : In 4 [3; 4; 5].\nProof.\n  simpl. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions, though convenient in some\n    cases, also has some drawbacks.  In particular, it is subject to\n    Coq's usual restrictions regarding the definition of recursive\n    functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros. split.\n  - intros. induction l.\n    + simpl in H. destruct H.\n    + simpl in H. destruct H. exists x. split. assumption. simpl. left. reflexivity.\n      apply IHl in H. destruct H.  exists x0. destruct H.  split. assumption. simpl. right. assumption.\n  - intros. destruct H. destruct H. rewrite <- H.  induction l.\n    + simpl. destruct H0.\n    + destruct H0. rewrite <- H0.   unfold map.  simpl.  left.  reflexivity. simpl. right. apply IHl. apply H0.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros. split.\n  - intros. induction l,  l'.\n    + simpl in H. destruct H.\n    + simpl in H. destruct H. right. rewrite <- H. simpl. left. reflexivity. right. simpl. right. assumption.\n    + simpl in H.    rewrite app_nil_r in H. rewrite app_nil_r in IHl. left. simpl. assumption.\n    + simpl in H.  destruct H. left.  rewrite H. simpl. left. reflexivity. destruct IHl. assumption. left. simpl. right. assumption. destruct H0. right. rewrite H0. simpl. left. reflexivity.\n      right. simpl. right. assumption.\n  - intros [H1 | H2].\n    + induction l. destruct H1. simpl. destruct H1. left. assumption. apply IHl in H. right.  apply H.\n    + induction l. simpl. assumption. simpl. right. assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T: Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | [] => True\n  | x' :: l' => (P x') /\\ All P l'\n  end.\n\n\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  intros. split.\n  + intros. induction l.\n    - simpl. reflexivity.\n    - simpl. split. apply H. simpl. left. reflexivity. apply IHl. intros. apply H. simpl. right. apply H0.\n  + intros.  induction l.\n    -  destruct H0.\n    -  destruct H0. simpl in H. destruct H. rewrite <- H0.  assumption.  apply IHl. simpl in H. destruct H. assumption. assumption.\nQed.\n\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun (n: nat) => match (oddb n) with\n                  | true  =>  (Podd n)\n                  | false => (Peven n)\n                  end.\n\n\nPrint oddb.\nPrint evenb.\n\n(** To test your definition, prove the following facts: *)\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros P Q n h1 h2. unfold combine_odd_even. destruct (oddb n).\n  + apply h1. reflexivity.\n  + apply h2. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros. unfold combine_odd_even in H. destruct (oddb n).\n  assumption. exfalso. inversion H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros. unfold combine_odd_even in H. destruct (oddb n).\n  + inversion H0.\n  + assumption.\nQed.\n\n(** [] *)\n\n(* #################################################################### *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from many other proof\n    assistants is that it treats _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it in detail in order to use Coq.  This\n    section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use the [Check] command to ask Coq to\n    print the type of an expression.  We can also use [Check] to ask\n    what theorem a particular identifier refers to. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** Coq prints the _statement_ of the [plus_comm] theorem in the same\n    way that it prints the _type_ of any term that we ask it to\n    [Check].  Why?\n\n    The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_ -- a data structure that represents a logical\n    derivation establishing of the truth of the statement [forall n m\n    : nat, n + m = m + n].  The type of this object _is_ the statement\n    of the theorem that it is a proof of.\n\n    Intuitively, this makes sense because the statement of a theorem\n    tells us what we can use that theorem for, just as the type of a\n    computational object tells us what we can do with that object --\n    e.g., if we have a term of type [nat -> nat -> nat], we can give\n    it two [nat]s as arguments and get a [nat] back.  Similarly, if we\n    have an object of type [n = m -> n + n = m + m] and we provide it\n    an \"argument\" of type [n = m], we can derive [n + n = m + m].\n\n    Operationally, this analogy goes even further: by applying a\n    theorem, as if it were a function, to hypotheses with matching\n    types, we can specialize its result without having to resort to\n    intermediate assertions.  For example, suppose we wanted to prove\n    the following result: *)\n\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\n\n(** One simple way of fixing this problem, using only tools that we\n    already know, is to use [assert] to derive a specialized version\n    of [plus_comm] that can be used to rewrite exactly where we\n    want. *)\n\n  rewrite plus_comm.\n  assert (H : m + p = p + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n\n\n(** A more elegant alternative is to apply [plus_comm] directly to the\n    arguments we want to instantiate it with, in much the same way as\n    we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take2 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\nCheck plus_comm3_take2.\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples of the idioms from this section in\n    later chapters. *)\n\n(* #################################################################### *)\n(** * Coq vs. Set Theory *)\n\n(** Coq's logical core, the _Calculus of Inductive Constructions_,\n    differs in some important ways from other formal systems that are\n    used by mathematicians for writing down precise and rigorous\n    proofs.  For example, in the most popular foundation for\n    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set\n    Theory (ZFC), a mathematical object can potentially be a member of\n    many different sets; a term in Coq's logic, on the other hand, is\n    a member of at most one type.  This difference often leads to\n    slightly different ways of capturing informal mathematical\n    concepts, though these are by and large quite natural and easy to\n    work with.  For example, instead of saying that a natural number\n    [n] belongs to the set of even numbers, we would say in Coq that\n    [ev n] holds, where [ev : nat -> Prop] is a property describing\n    even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be either cumbersome or\n    sometimes even impossible, unless we enrich the core logic with\n    additional axioms.  We conclude this chapter with a brief\n    discussion of some of the most significant differences between the\n    two worlds. *)\n\n(** ** Functional Extensionality\n\n    The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But\n    since Coq's equality operator is polymorphic, these are not the\n    only possibilities -- in particular, we can write propositions\n    claiming that two _functions_ are equal to each other: *)\n\nExample function_equality_ex : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same outputs:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_.\n\n    Informally speaking, an \"extensional property\" is one that\n    pertains to an object's observable behavior.  Thus, functional\n    extensionality simply means that a function's identity is\n    completely determined by what we can observe from it -- i.e., in\n    Coq terms, the results we obtain after applying it.\n\n    Functional extensionality is not part of Coq's basic axioms: the\n    only way to show that two functions are equal is by\n    simplification (as we did in the proof of [function_equality_ex]).\n    But we can add it to Coq's core logic using the [Axiom]\n    command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Using [Axiom] has the same effect as stating a theorem and\n    skipping its proof using [Admitted], but it alerts the reader that\n    this isn't just something we're going to come back and fill in\n    later!\n\n    We can now invoke functional extensionality in proofs: *)\n\nPrint functional_extensionality.\n\nLemma plus_comm_ext : plus = fun n m => m + n.\nProof.\n  apply functional_extensionality. intros n.\n  apply functional_extensionality. intros m.\n  apply plus_comm.\nQed.\n\nCheck plus_comm_ext.\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as they may render it inconsistent -- that is, it may\n    become possible to prove every proposition, including [False]!\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe: hard work is generally required to establish the\n    consistency of any particular combination of axioms.  Fortunately,\n    it is known that adding functional extensionality, in particular,\n    _is_ consistent.\n\n    Note that it is possible to check whether a particular proof\n    relies on any additional axioms, using the [Print Assumptions]\n    command. For instance, if we run it on [plus_comm_ext], we see\n    that it uses [functional_extensionality]: *)\n\nPrint Assumptions plus_comm_ext.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 5 stars (tr_rev)  *)\n(** One problem with the definition of the list-reversing function\n    [rev] that we have is that it performs a call to [app] on each\n    step; running [app] takes time asymptotically linear in the size\n    of the list, which means that [rev] has quadratic running time.\n    We can improve this with the following definition: *)\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: l1' => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n(** This version is said to be _tail-recursive_, because the recursive\n    call to the function is the last operation that needs to be\n    performed (i.e., we don't have to execute [++] after the recursive\n    call); a decent compiler will generate very efficient code in this\n    case.  Prove that both definitions are indeed equivalent. *)\n\nCheck tr_rev.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** ** Propositions and Booleans *)\n\n(** We've seen that Coq has two different ways of encoding logical\n    facts: with _booleans_ (of type [bool]), and with\n    _propositions_ (of type [Prop]). For instance, to claim that a\n    number [n] is even, we can say either (1) that [evenb n] returns\n    [true] or (2) that there exists some [k] such that [n = double k].\n    Indeed, these two notions of evenness are equivalent, as can\n    easily be shown with a couple of auxiliary lemmas (one of which is\n    left as an exercise).\n\n    We often say that the boolean [evenb n] _reflects_ the proposition\n    [exists k, n = double k].  *)\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n(** **** Exercise: 3 stars (evenb_double_conv)  *)\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  intros. induction n.\n  + simpl. exists 0. reflexivity.\n  +  rewrite evenb_S. destruct (evenb n).\n  - simpl. destruct IHn as [x IHn]. rewrite  IHn. exists x.   reflexivity.\n  - simpl. destruct IHn as [x IHn]. rewrite IHn.  exists (S x).  simpl. reflexivity.\nQed.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either (1) that [beq_nat n m] returns [true] or (2) that [n =\n    m].  These two notions are equivalent. *)\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** However, while the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, we have\n    also seen that they need not be equivalent _operationally_.\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little help in the middle of a proof\n    involving [n] and [m]; however, if we convert the statement to the\n    equivalent form [n = m], we can rewrite with it.\n\n    The case of even numbers is also interesting.  Recall that, when\n    proving the backwards direction of\n    [even_bool_prop] ([evenb_double], going from the propositional to\n    the boolean claim), we used a simple induction on [k]).  On the\n    other hand, the converse (the [evenb_double_conv] exercise)\n    required a clever generalization, since we can't directly prove\n    [(exists k, n = double k) -> evenb n = true].\n\n    For these examples, the propositional claims were more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects an\n    elements of [bool] (or some other inductive type with two\n    elements).  The reason for this error message has to do with the\n    _computational_ nature of Coq's core language, which is designed\n    so that every function that it can express is computable and\n    total.  One reason for this is to allow the extraction of\n    executable programs from Coq developments.  As a consequence,\n    [Prop] in Coq does _not_ have a universal case analysis operation\n    telling whether any given proposition is true or false, since such\n    an operation would allow us to write non-computable functions.\n\n    Although general non-computable properties cannot be phrased as\n    boolean computations, it is worth noting that even many\n    _computable_ properties are easier to express using [Prop] than\n    [bool], since recursive function definitions are subject to\n    significant restrictions in Coq.  For instance, the next chapter\n    shows how to define the property that a regular expression matches\n    a given string using [Prop].  Doing the same with [bool] would\n    amount to writing a regular expression matcher, which would be\n    more complicated, harder to understand, and harder to reason\n    about.\n\n    Conversely, an important side benefit of stating facts using\n    booleans is enabling some proof automation through computation\n    with Coq terms, a technique known as _proof by\n    reflection_. Consider the following statement: *)\n\nExample even_1000 : exists k, 1000 = double k.\n\n(** The most direct proof of this fact is to give the value of [k]\n    explicitly. *)\n\n Proof. exists 500. reflexivity. Qed.\n\n(** On the other hand, the proof of the corresponding boolean\n    statement is even simpler: *)\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\n(** What is interesting is that, since the two notions are equivalent,\n    we can use the boolean formulation to prove the other one without\n    mentioning 500 explicitly: *)\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** Although we haven't gained much in terms of proof size in this\n    case, larger proofs can often be made considerably simpler by the\n    use of reflection.  As an extreme example, the Coq proof of the\n    famous _4-color theorem_ uses reflection to reduce the analysis of\n    hundreds of different cases to a boolean computation.  We won't\n    cover reflection in great detail, but it serves as a good example\n    showing the complementary strengths of booleans and general\n    propositions. *)\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros. split.\n  intros.\n  + split. destruct b1. reflexivity. destruct H. reflexivity.\n    destruct b1. destruct H. simpl.  reflexivity.  simpl in H. inversion H.\n  + intros. destruct H. rewrite H. rewrite H0. reflexivity.\nQed.\n\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros. split. destruct b1.\n  +  simpl. intros. left. reflexivity.\n  + intros.  destruct b2.\n    - right. reflexivity.\n    - destruct H.  simpl.  left.  reflexivity.\n      + intros. destruct H. rewrite H. simpl. reflexivity. rewrite H. simpl. destruct b1.  simpl. reflexivity. simpl. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  intros. split.\n  + intros h1 h2.\n    rewrite h2 in h1. rewrite <- beq_nat_refl in h1. inversion h1.\n  + intros h1. destruct (beq_nat x y) eqn:x_eq_y.\n    - apply beq_nat_true in x_eq_y. elim h1. assumption.\n    - reflexivity.\nQed.\n\n(** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A} (beq : A -> A -> bool)\n(l1 l2 : list A) : bool :=\n    match l1 with\n    | nil => match l2  with\n             | nil => true\n             | t2::l2 => false\n             end\n    | h1 :: t1 =>\n      match l2 with\n      | nil => false\n      | h2 :: t2 => (beq h1 h2) && (beq_list beq t1 t2)\n      end\n    end.\n\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq h1.\n  induction l1 as [|a l1].\n  + induction l2 as [|b l2].\n    - split; reflexivity.\n    - split;  intros h2; inversion h2.\n  + induction l2 as [|b l2].\n    - split; inversion 1.\n    - simpl; split.\n      * intros h2.\n        apply andb_true_iff in h2.\n        destruct h2 as [h2 h3].\n        apply h1 in h2.\n        apply IHl1 in h3.\n        rewrite h2; rewrite h3; reflexivity.\n      * intros h2.\n        apply andb_true_iff.\n        injection h2 as h3 h4.\n        split. rewrite h1. assumption.\n        rewrite -> IHl1.  assumption.\nQed.\n        (**\n  intros. induction l1.\n  + induction l2.\n    - simpl. split;  intros; reflexivity.\n    - simpl. split; intros; inversion H0.\n  + induction l2 as [|b l2].\n    - split. inversion 1.  intros; inversion H0.\n    - simpl. split.\n      * intros. apply andb_true_iff in H0.  destruct H0.  apply H in H0. rewrite H0.\n    * intros. inversion H0.\n  + induction l2. split; split.\n    - intros. inversion H0.\n    - intros. inversion H0.\n    - split.\n      * intros. inversion H0. apply andb_true_iff in H2. destruct H2. apply H in H1. rewrite H1.\n        destruct H0. injuection H2.\n\n    reflexivity.     intros. induction l1.\n    - induction l2.\n      *  reflexivity.\n      * inversion H0.\n    - induction l2.\n      * inversion 1.  destruct H0. inversion H0.\n    - inversion H0.\n    - inversion H0. rewrite andb_true_iff in H2.  destruct H2.  apply H in H1. rewrite H1.\n\n      destruct H2.\n*)\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\n\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  intros. split.\n  + intros.  induction l.\n    - simpl. reflexivity.\n    - simpl.  simpl in H. rewrite  andb_true_iff in H. destruct H.  split. assumption.  apply IHl.  assumption.\n  + intros. induction l.\n    - reflexivity.\n    - simpl.  simpl in H. rewrite andb_true_iff. destruct H. split. assumption. apply IHl. assumption.\nQed.\n\n(** Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** ** Classical vs. Constructive Logic *)\n\n(** We have seen that it is not possible to test whether or not a\n    proposition [P] holds while defining a Coq function.  You may be\n    surprised to learn that a similar restriction applies to _proofs_!\n    In other words, the following intuitive reasoning principle is not\n    derivable in Coq: *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\n(** To understand operationally why this is the case, recall that, to\n    prove a statement of the form [P \\/ Q], we use the [left] and\n    [right] tactics, which effectively require knowing which side of\n    the disjunction holds.  However, the universally quantified [P] in\n    [excluded_middle] is an _arbitrary_ proposition, which we know\n    nothing about.  We don't have enough information to choose which\n    of [left] or [right] to apply, just as Coq doesn't have enough\n    information to mechanically decide whether [P] holds or not inside\n    a function.  On the other hand, if we happen to know that [P] is\n    reflected in some boolean term [b], then knowing whether it holds\n    or not is trivial: we just have to check the value of [b].  This\n    leads to the following theorem: *)\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m].\n\n    You may find it strange that the general excluded middle is not\n    available by default in Coq; after all, any given claim must be\n    either true or false.  Nonetheless, there is an advantage in not\n    assuming the excluded middle: statements in Coq can make stronger\n    claims than the analogous statements in standard mathematics.\n    Notably, if there is a Coq proof of [exists x, P x], it is\n    possible to explicitly exhibit a value of [x] for which we can\n    prove [P x] -- in other words, every proof of existence is\n    necessarily _constructive_.  Because of this, logics like Coq's,\n    which do not assume the excluded middle, are referred to as\n    _constructive logics_.  More conventional logical systems such as\n    ZFC, in which the excluded middle does hold for arbitrary\n    propositions, are referred to as _classical_.\n\n    The following example illustrates why assuming the excluded middle\n    may lead to non-constructive proofs: *)\n\n(** _Claim_: There exist irrational numbers [a] and [b] such that [a ^\n    b] is rational.\n\n    _Proof_: It is not difficult to show that [sqrt 2] is irrational.\n    If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =\n    sqrt 2] and we are done.  Otherwise, [sqrt 2 ^ sqrt 2] is\n    irrational.  In this case, we can take [a = sqrt 2 ^ sqrt 2] and\n    [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^\n    2 = 2].  []\n\n    Do you see what happened here?  We used the excluded middle to\n    consider separately the cases where [sqrt 2 ^ sqrt 2] is rational\n    and where it is not, without knowing which one actually holds!\n    Because of that, we wind up knowing that such [a] and [b] exist\n    but we cannot determine what their actual values are (at least,\n    using this line of argument).\n\n    As useful as constructive logic is, it does have its limitations:\n    There are many statements that can easily be proven in classical\n    logic but that have much more complicated constructive proofs, and\n    there are some that are known to have no constructive proof at\n    all!  Fortunately, like functional extensionality, the excluded\n    middle is known to be compatible with Coq's logic, allowing us to\n    add it safely as an axiom.  However, we will not need to do so in\n    this book: the results that we cover can be developed entirely\n    within constructive logic at negligible extra cost.\n\n    It takes some practice to understand which proof techniques must\n    be avoided in constructive reasoning, but arguments by\n    contradiction, in particular, are infamous for leading to\n    non-constructive proofs.  Here's a typical example: suppose that\n    we want to show that there exists [x] with some property [P],\n    i.e., such that [P x].  We start by assuming that our conclusion\n    is false; that is, [~ exists x, P x]. From this premise, it is not\n    hard to derive [forall x, ~ P x].  If we manage to show that this\n    intermediate fact results in a contradiction, we arrive at an\n    existence proof without ever exhibiting a value of [x] for which\n    [P x] holds!\n\n    The technical flaw here, from a constructive standpoint, is that\n    we claimed to prove [exists x, P x] using a proof of [~ ~ exists\n    x, P x]. However, allowing ourselves to remove double negations\n    from arbitrary statements is equivalent to assuming the excluded\n    middle, as shown in one of the exercises below.  Thus, this line\n    of reasoning cannot be encoded in Coq without assuming additional\n    axioms. *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** The consistency of Coq with the general excluded middle axiom\n    requires complicated reasoning that cannot be carried out within\n    Coq itself.  However, the following theorem implies that it is\n    always safe to assume a decidability axiom (i.e., an instance of\n    excluded middle) for any _particular_ Prop [P].  Why? Because we\n    cannot prove the negation of such an axiom; if we could, we would\n    have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not.\n  intros. apply H. right. intros. apply H. left. assumption.\nQed.\n  (** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist)  *)\n(** It is a theorem of classical logic that the following two\n    assertions are equivalent:\n\n    ~ (exists x, ~ P x)\n    forall x, P x\n\n    The [dist_not_exists] theorem above proves one side of this\n    equivalence. Interestingly, the other direction cannot be proved\n    in constructive logic. Your job is to show that it is implied by\n    the excluded middle. *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  cbv. intros em X P h2 x. destruct  (em (P x)). assumption. elim h2.\n  exists x.  assumption.\nQed.\n\nCheck not_exists_dist.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\nCheck implies_to_or.\nTheorem peirce_double_neg_elim : peirce -> double_negation_elimination.\nProof.\n  cbv. intros. specialize (H P False). apply H. intros. contradiction.\nQed.\n\n\nTheorem double_negation_elimination_de_morgan_not_and_not: double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  intros dne P Q H.  red in dne.\n   apply dne.  intro H2. apply H.\n   split. intro H3. apply H2. left. assumption.  intro H3.   apply H2. right. assumption.\nQed.\n\nCheck double_negation_elimination_de_morgan_not_and_not.\n\nTheorem de_morgan_not_and_not_implies_to_or:\n  de_morgan_not_and_not -> implies_to_or.\nProof.\n  intros dm P Q H. red in dm. apply dm.  hnf.  intros [nnp nq].\n  apply nnp. intro H2. apply H in H2.  contradiction.\nQed.\n\nTheorem implies_to_or_excluded_middle: implies_to_or -> excluded_middle.\nProof.\n  intros.  red. intros. red in H. specialize (H (P) P).\n  rewrite or_comm.\n  apply H.  intros. assumption.\nQed.\n\nCheck implies_to_or_excluded_middle.\n\nTheorem excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n  cbv. intros em P Q H.  destruct (em P) as [p|np].\n  assumption. apply H. intros. contradiction.\nQed.\n\nCheck excluded_middle_peirce.\n(** [] *)\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "perng", "repo": "proof", "sha": "bf181860d43bffdc67f7cd52269518f5fcaf27f1", "save_path": "github-repos/coq/perng-proof", "path": "github-repos/coq/perng-proof/proof-bf181860d43bffdc67f7cd52269518f5fcaf27f1/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.8026101213393638}}
{"text": "\nRequire Import List.\nOpen Scope list_scope.\n\nSection BooleanValuedFunction.\n  \n  (* a \u2208 l *)\n  Definition elem {A : Type} (eqb : A -> A -> bool) (l : list A) (a : A) :=\n    fold_left orb (map (eqb a) l) false.\n\n  Goal forall (l : list bool), fold_left orb (true :: l) false = true.\n  Proof.\n    induction l.\n    - reflexivity.\n    - simpl in IHl.\n      simpl.\n      now rewrite IHl.\n  Qed.\n\n  Check filter.\n  (* l1 \u2229 l2 *)\n  Fixpoint intersection {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A) :=\n     filter (elem eqb l2) l1.\n  \n  Compute intersection Nat.eqb (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil) (3 :: 6 :: 9 :: nil).\n\n  Definition not_elem {A : Type} (eqb : A -> A -> bool) (l : list A) (a : A) :=\n    negb (elem eqb l a).\n\n  (* l1 \\ l2 *)\n  Fixpoint sub {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A) :=\n    filter (not_elem eqb l2) l1.\n  \n  Compute sub Nat.eqb (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil) (2 :: 4 :: 5 :: nil).\nEnd BooleanValuedFunction.\n  \nRequire Import Extraction.\nExtraction Language Haskell.\nExtract Inductive list => \"([])\" [\"[]\" \"(:)\"].\nExtract Inductive bool => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\nExtraction \"difflist2.hs\" intersection sub.\n", "meta": {"author": "morita-hm", "repo": "diff_list", "sha": "976f778a27fe8c81539f03c12a77b63362479c3e", "save_path": "github-repos/coq/morita-hm-diff_list", "path": "github-repos/coq/morita-hm-diff_list/diff_list-976f778a27fe8c81539f03c12a77b63362479c3e/DiffList2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.8025644168945661}}
{"text": "(** * Introduction *)\n(** ** Booleans *)\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\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(** **** 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\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. reflexivity. Qed.\nExample test_nandb2:               (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3:               (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4:               (nandb true true) = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 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(** ** Numbers *)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool   :=   negb (evenb n).\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\n(** **** Exercise: 1 star (factorial) *)\n(** 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 => 1\n    | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\n(** **** Exercise: 2 stars (blt_nat) *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined function.\n\n    Note: If you have trouble with the [simpl] tactic, try using\n    [compute], which is like [simpl] on steroids.  However, there is a\n    simple, elegant solution for which [simpl] suffices. *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  match n with\n    | O => ble_nat (S O) m\n    | n' => ble_nat (S n') m\n  end.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(** * Proof by Simplification *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.  Qed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.  Qed.\n\n(** * Proof by Rewriting *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\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(** **** Exercise: 1 star (plus_id_exercise) *)\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H1.\n  rewrite -> H1.\n  intros H2.\n  rewrite -> H2.\n  reflexivity. Qed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  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 -> H.\n  reflexivity. Qed.\n\n(** * Proof by Case Analysis *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n    reflexivity.\n    reflexivity.  Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n    reflexivity.\n    reflexivity.  Qed.\n\n(** **** 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.\n  reflexivity.  Qed.\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.\n  rewrite -> H.\n  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 = negb x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros.\n  rewrite -> H.\n  rewrite -> H.\n  rewrite -> negb_involutive.\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. Alternatively, remember that you do\n    not have to introduce all hypotheses at the same time.) *)\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros b c. destruct b. destruct c.\n  simpl. reflexivity.\n  simpl. intros H. rewrite -> H.\n  reflexivity.\n  simpl. intros H. rewrite -> H.\n  reflexivity.\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    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(* TODO *)\n\n(** * Optional Material *)\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(* TODO See https://github.com/etosch/software_foundations/blob/master/lesson1_Basics.v *)", "meta": {"author": "kmiya", "repo": "software_foundations", "sha": "af69f496f643ce93b1dc90a8f69b8c61b4a0b88f", "save_path": "github-repos/coq/kmiya-software_foundations", "path": "github-repos/coq/kmiya-software_foundations/software_foundations-af69f496f643ce93b1dc90a8f69b8c61b4a0b88f/ex_Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.8025644146866288}}
{"text": "Require Import Arith Omega.\n\nTheorem complete_ind : forall P, (forall n, (forall i, i < n -> P i) -> P n) -> forall n, P n.\nProof.\n  intros ? IH m.\n  assert (H : forall i, i <= m -> P i).\n  - induction m; intros i ?.\n    + apply IH.\n      intros.\n      omega.\n    + destruct (eq_nat_dec i m);\n        [| apply IH; intros ];\n        apply IHm;\n        omega.\n  - apply H.\n    omega.\nQed.\n", "meta": {"author": "fetburner", "repo": "Misc", "sha": "c48f9166e922dee111c98157d6da45b77cda5ea6", "save_path": "github-repos/coq/fetburner-Misc", "path": "github-repos/coq/fetburner-Misc/Misc-c48f9166e922dee111c98157d6da45b77cda5ea6/complete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.8024913824962701}}
{"text": "\n(***************************** LIFLF - TPA ************************************)\n(************* Evaluation pratique en temps limit\u00e9 : 30' **********************)\n(******************************************************************************)\n\nRequire Import Arith.\nRequire Import List.\nExport ListNotations.\n\n\n(* Partie 1. Exercices sur les listes d'entiers *)\n(* -------------------------------------------- *)\n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"lgr\" qui calcule la longueur d'une liste de nat (et donc de type list nat) *)\nFixpoint lgr (l : list nat) : nat :=\nmatch l with\n|[] => 0\n|n::l' => 1 + lgr l'\nend.\n\n\nExample ex_lgr : (lgr (1::2::3::4::5::[])) = 5.\nProof. cbv. reflexivity. Qed.\n\n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"mir\" qui calcule le miroir d'une liste de nat *)\nFixpoint mir (l : list nat) : list nat :=\n  match l with\n  |[] => []\n  |n::l' => (mir l')++(n::[])\nend.\n\nExample ex_mir : (mir (1::2::3::4::5::[])) = 5::4::3::2::1::[].\nProof. cbv. reflexivity. Qed.\n\n\n(* EXERCICE *)\n(* Exprimer et prouver que le miroir d'une liste \u00e0 laquelle on a ajout\u00e9 un \u00e9l\u00e9ment en t\u00eate\n   est le miroir de la liste concat\u00e9n\u00e9 \u00e0 la liste constitu\u00e9e de juste cet \u00e9l\u00e9ment *)\nTheorem miroirEtConcat (l : list nat) (n : nat) : mir (n::l) = (mir l)++(n::[]).\nProof.\ninduction l as [ | n'].\n-simpl.\nreflexivity.\n-simpl.\nreflexivity.\nQed.\n(* Partie 2. Exercices sur les arbres binaires *)\n(* ------------------------------------------- *)\n\n\n(* On donne le type \"btree\" des arbres binaires avec valeurs de type nat stock\u00e9es dans les feuilles *)\nInductive btree : Type :=\n| F : nat -> btree\n| N : btree -> btree -> btree\n.\n\n(* exemples *)\n(* L'arbre \"ab1\" :  o    et \"ab2\" :    o\n                   / \\                / \\\n                  o   2              1   o\n                 / \\                    / \\\n                1   o                  o   5\n                   / \\                / \\\n                  o   3              2   o\n                 / \\                    / \\\n                4   5                  3   4\n*)\n(* On donne l'arbre \"ab1\" : *)\nDefinition ab1 := N (N (F 1) (N (N (F 4) (F 5)) (F 3))) (F 2).\n\n(* EXERCICE *)\n(* D\u00e9finir l'arbre \"ab2\" correspondant \u00e0 l'exemple ci-dessus *)\nDefinition ab2 := N (F 1) (N (N (F 2) (N (F 3) (F 4))) (F 5)). \n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"bnbf\" qui calcule le nombre de feuilles d'un tel arbre *)\nFixpoint bnbf (ab : btree) : nat :=\nmatch ab with\n|F n => 1\n|N abG abD => bnbf abG + bnbf abD\nend.\n\n\nExample ex_bnbf_ab1 : (bnbf ab1) = 5.\nProof. cbv. reflexivity. Qed.\n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"bnbn\" qui calcule le nombre de noeuds d'un tel arbre *)\nFixpoint bnbn (ab : btree) : nat :=\nmatch ab with\n|F n => 0\n|N abG abD => 1 + bnbn abG + bnbn abD\nend.\n\n\nExample ex_bnbn_ab1 : (bnbn ab1) = 4.\nProof. cbv. reflexivity. Qed.\n\n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"bsumval\" qui calcule la somme des valeurs contenues dans l'arbre *)\nFixpoint bsumval (ab : btree) : nat :=\nmatch ab with\n|F n => n\n|N abG abD => bsumval abG + bsumval abD\nend.\n\n\n\nExample ex_bsumval_ab1 : (bsumval ab1) = 15.\nProof. cbv. reflexivity. Qed.\n\n\n\n(* EXERCICE *)\n(* \u00c9crire la fonction \"bajout\" qui ajoute un \u00e9l\u00e9ment dans un arbre *)\nFixpoint bajout (x : nat)(ab : btree): btree :=\nmatch ab with\n|F n => N (F n) (F x)\n|N abG abD => N abG (bajout x abD)\nend.\n\n\nExample ex_bajout_ab1 : bnbf (bajout 10 ab1) = 1 + bnbf ab1.\nProof. cbv. reflexivity. Qed.\n\n\n", "meta": {"author": "MartinLeocmach", "repo": "LIFLF", "sha": "effa54ad070752ed08ebec09fb6066b4e68f35d2", "save_path": "github-repos/coq/MartinLeocmach-LIFLF", "path": "github-repos/coq/MartinLeocmach-LIFLF/LIFLF-effa54ad070752ed08ebec09fb6066b4e68f35d2/liflf_TPN_A_2019.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.8023770517317571}}
{"text": "Require Import bool.\nRequire Import nat.\nRequire Import list.\nRequire Import fmap.\nRequire Import In.\nRequire Import induction.\n\nExample test_In1 : In 4 [3,4,5].\nProof. simpl. right. left. reflexivity. Qed.\n\n\nExample test_In2 : forall n, \n    In n [2,4] -> exists m, n = 2 * m.\nProof.\n    simpl. intros n [H|[H|H]].\n    - exists 1. symmetry in H. apply H.\n    - exists 2. symmetry in H. apply H.\n    - inversion H.\nQed.\n\nDefinition combine_odd_even (Po Pe:nat -> Prop) (n:nat) : Prop :=\n    if oddb n then Po n else Pe n.\n\n\nTheorem combine_odd_even_intro : forall (Po Pe:nat -> Prop) (n:nat),\n    (oddb n = true -> Po n)  -> \n    (oddb n = false -> Pe n) -> \n    combine_odd_even Po Pe n.\nProof.\n    intros Po Pe n Ho He. destruct (oddb n) eqn:H.\n    - unfold combine_odd_even. rewrite H. apply Ho. reflexivity.\n    - unfold combine_odd_even. rewrite H. apply He. reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd : forall (Po Pe:nat -> Prop) (n:nat),\n    combine_odd_even Po Pe n -> oddb n = true -> Po n.\nProof.\n    intros Po Pe n H H'. unfold combine_odd_even in H. rewrite H' in H. exact H.\nQed.\n\nTheorem combine_odd_even_elim_even : forall (Po Pe:nat -> Prop) (n:nat),\n    combine_odd_even Po Pe n -> oddb n = false -> Pe n.\nProof.\n    intros Po Pe n H H'. unfold combine_odd_even in H. rewrite H' in H. exact H.\nQed.\n\n\nExample lemma_application_ex1 : forall (n:nat) (ns:list nat),\n    In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n    intros n ns. induction ns as [|x xs H].\n    - intros H. inversion H.\n    - simpl. intros [H'|H'].\n        + rewrite mult_n_0 in H'. symmetry. exact H'.\n        + apply H. 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/sf/test_In.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8023730972486416}}
{"text": "Section Group.\n  Variable G : Set.\n  Variable op : G -> G -> G.\n  Variable e : G.\n  Notation \"x * y\" := (op x y).\n  (* Axioms for the Group *)\n  Definition Identity (g : G) := forall x:G, x * g = x /\\ g * x = x.\n  Axiom G1: Identity e.\n  Axiom G2: forall x y z:G, (x * y) * z = x * (y * z).\n  Axiom G3: forall x:G, exists y:G, x * y = e.\n  Theorem IdentityUniqueness : forall (x : G) (y : G), (Identity x /\\ Identity y) -> (x = y).\n    Proof.\n      intros.\n      destruct H.\n      assert (x = x * y).\n      unfold Identity in H0.\n      destruct (H0 x).\n      symmetry.\n      assumption.\n      assert (x * y = y).\n      unfold Identity in H.\n      destruct (H y).\n      assumption.\n      transitivity (x * y).\n      assumption.\n      assumption.\n  Qed.\nPrint IdentityUniqueness.\nEnd Group", "meta": {"author": "MichaelBurge", "repo": "matroids", "sha": "a9e42e2f93af300caf408ad9b25712431a2f79fe", "save_path": "github-repos/coq/MichaelBurge-matroids", "path": "github-repos/coq/MichaelBurge-matroids/matroids-a9e42e2f93af300caf408ad9b25712431a2f79fe/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.8023659347228477}}
{"text": "Require Export Induction.\nModule NatList.\n\nInductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nDefinition fst (p: natprod) : nat :=\n  match p with\n  | pair x _ => x\n  end.\n\nDefinition snd (p: natprod) : nat :=\n  match p with\n  | pair _ y => y\n  end.\n\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (snd (4, 7)).\n\nDefinition swap_pair (p: natprod) : natprod :=\n  match p with\n  | (x, y) => (y, x)\n  end.\n\nTheorem surjective_pairing: forall p:natprod,\n  p = (fst p, snd p).\nProof.\n  intros.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p: natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\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  | [] => O\n  | _ :: l' => S (length l')\n  end.\n\nFixpoint app (l1 l2: natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | x :: xs => x :: (app xs l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (def:nat) (l:natlist) : nat :=\n  match l with\n  | nil => def\n  | h :: _ => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | _ :: t => t\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | h :: t => h :: nonzeros t\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => if (evenb h) then oddmembers t\n                           else h :: oddmembers t\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed. \n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | [], r2 => r2\n  | r1, [] => r1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n  end.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | [] => 0\n  | h :: t => (if beq_nat h v then 1 else 0) + (count v t)\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. 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. simpl. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  blt_nat 0 (count v s).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | [] => []\n  | h :: t => if beq_nat v h then t else h :: remove_one v t\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | [] => []\n  | h :: t => if beq_nat v h then remove_all v t else h :: remove_all v t\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | [] => true\n  | h :: t => (member h s2) && (subset t (remove_one h s2))\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\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.\n  destruct l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros.\n  induction l1 as [| h1 t1 IH1'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IH1'. reflexivity.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | [] => []\n  | h :: t => (rev t) ++ [h]\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem app_length: forall l1 l2: natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros.\n  induction l1 as [| n l1' IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem rev_length: forall l:natlist,\n  length (rev l) = length l.\nProof.\n  intros.\n  induction l as [| h l' IHl'].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> app_length, plus_comm.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1 as [| h1 t1 IH].\n  - simpl. destruct l2 as [| h2 t2].\n    + simpl. reflexivity.\n    + simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. destruct l2 as [| h2 t2].\n    + simpl. rewrite -> app_nil_r. reflexivity.\n    + rewrite -> IH. simpl. rewrite -> app_assoc. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n    simpl. rewrite -> IH.\n    reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros.\n  induction l1 as [| h t IH].\n  - simpl. reflexivity.\n  - simpl.\n    destruct h as [| h'].\n    + simpl. rewrite -> IH. reflexivity.\n    + simpl. rewrite -> IH. reflexivity.\nQed.\n\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | [], [] => true\n  | [], _ => false\n  | _, [] => true\n  | h1 :: t1, h2 :: t2 => (beq_nat h1 h2) && (beq_natlist t1 t2)\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. induction h as [| h' IH'].\n    + simpl. rewrite <- IH. reflexivity.\n    + simpl. rewrite <- IH'. reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros.\n  destruct s as [| h t].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n\nTheorem leb_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros.\n  induction n as [| n' IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros. \n  induction s as [| h t IH].\n  - simpl. reflexivity.\n  - destruct h as [| h'].\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IH. reflexivity.\nQed.\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 as [| h1 t1 IH].\n  - simpl. reflexivity.\n  - destruct h1 as [| h1'].\n    + simpl. rewrite -> IH. reflexivity.\n    + simpl. rewrite -> IH. reflexivity.\nQed.\n\n\nTheorem rev_injective: forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\n\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | [] => None\n  | x :: l' => match n with\n               | O => Some x\n               | S n' => nth_error l' n'\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n\nDefinition option_elim (def : nat) (o : natoption) : nat :=\n  match o with\n  | None => def\n  | Some x => x\n  end.\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | [] => None\n  | h :: _ => Some h\n  end.\n\nExample test_hd_error1 : hd_error [] = None.\nProof. reflexivity. Qed.\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  intros.\n  destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nEnd NatList.\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (i j: id) :=\n  match i, j with\n  | Id x, Id y => beq_nat x y\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intros.\n  destruct x as [x'].\n  simpl. rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d:partial_map) (x:id) (val:nat) :=\n  record x val d.\n\nFixpoint find (x:id) (d:partial_map) : natoption :=\n  match d with\n  | empty => None\n  | record k v d' => if beq_id x k then Some v\n                                    else find x d'\n  end.\n\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros.\n  simpl. rewrite <- beq_id_refl. reflexivity.\nQed.\n\n\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros.\n  simpl. rewrite -> H. reflexivity.\nQed.\n\nEnd PartialMap.\n\n", "meta": {"author": "atungare", "repo": "coq-software-foundations", "sha": "49bf005d87f530a54274ce9de06b6bce99c1e8aa", "save_path": "github-repos/coq/atungare-coq-software-foundations", "path": "github-repos/coq/atungare-coq-software-foundations/coq-software-foundations-49bf005d87f530a54274ce9de06b6bce99c1e8aa/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8021653073221146}}
{"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 the type [ord] of tree ordinals.\n   This formalisation of tree ordinals is based on notes by Peter Hancock:\n     (Ordinal-theoretic) Proof Theory.\n     Course notes from Midlands Graduate School, 2008.\n     % \\url{http://personal.cis.strath.ac.uk/~ph/} %\n     # <a href=\"http://personal.cis.strath.ac.uk/~ph/\">http://personal.cis.strath.ac.uk/~ph/</a> #\n     % http://events.cs.bham.ac.uk/mgs2008/notes/proofTheory.pdf %\n     # <a href=\"http://events.cs.bham.ac.uk/mgs2008/notes/proofTheory.pdf\">http://events.cs.bham.ac.uk/mgs2008/notes/proofTheory.pdf</a> #\n  See also the formalisation in Isabelle by Michael Compton:\n  % http://www4.informatik.tu-muenchen.de/~isabelle/html-data/library/HOL/Induct/Tree.html %\n  # <a href=\"http://www4.informatik.tu-muenchen.de/~isabelle/html-data/library/HOL/Induct/Tree.html\">http://www4.informatik.tu-muenchen.de/~isabelle/html-data/library/HOL/Induct/Tree.html</a> #\n*)\n\n\nSet Implicit Arguments.\n\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Logic.Classical.\n\nDelimit Scope ord_scope with ord.\nOpen Scope ord_scope.\n\n\n(** Inductive type for tree ordinals. *)\nInductive ord : Set :=\n  | Zero  : ord\n  | Succ  : ord -> ord\n  | Limit : (nat -> ord) -> ord.\n\n(** The intuition is that the [Limit] constructor represents the least\n   upper bound of its argument sequence.\n   We might like to exclude sequences such as (4,4,4,...), since they would\n   not necessarily represent a limit ordinal. A way to do this is by\n   imposing a monotonicity property on the [Limit] arguments. We first\n   define an ordering on [ord] and, using that, define a subset of [ord]\n   where the [Limit] arguments are monotone (in library [WfOrdinal]). *)\n\n(** Type of predecessor indices of an ordinal. *)\nFixpoint pd_type (alpha : ord) : Set :=\n  match alpha with\n  | Zero       => False\n  | Succ alpha => (unit + pd_type alpha) % type\n  | Limit f    => { n : nat & pd_type (f n) }\n  end.\n\nReserved Notation \"alpha [ i ]\" (at level 60).\n\n(** Predecessor indices of an ordinal are essentially the paths on its tree\n   structure starting from the root that cross at least one [Succ]\n   constructor. *)\n\n(** Predecessor of an ordinal for a given predecessor index. *)\nFixpoint pd (alpha : ord) : pd_type alpha -> ord :=\n  match alpha with\n  | Zero       => False_rect _\n  | Succ alpha => fun i => match i with\n                           | inl tt => alpha\n                           | inr t  => alpha[t]\n                           end\n  | Limit f    => fun i => match i with\n                           | existT _ n t => (f n)[t]\n                           end\n  end\nwhere \"alpha [ i ]\" := (pd alpha i) : ord_scope.\n\n(** [pd_type] and [pd] can be seen as defining a 'subtree' partial order on\n   [ord]. We use it to define an extensional non-strict order on [ord]. *)\n\n(** Non-strict order on [ord]. *)\nInductive ord_le : ord -> ord -> Prop :=\n  | Ord_le_Zero  : forall beta,\n                      Zero <= beta\n  | Ord_le_Succ  : forall alpha beta i,\n                      alpha <= beta[i] ->\n                      Succ alpha <= beta\n  | Ord_le_Limit : forall f beta,\n                      (forall n, f n <= beta) ->\n                      Limit f <= beta\nwhere \"alpha <= beta\" := (ord_le alpha beta) : ord_scope.\n\n(** Strict order on [ord]. *)\nDefinition ord_lt (alpha beta : ord) := exists i, alpha <= beta[i].\nInfix \" < \" := ord_lt : ord_scope.\n\n(** Equality on [ord]. *)\nDefinition ord_eq alpha beta := alpha <= beta /\\ beta <= alpha.\nInfix \" == \" := ord_eq (no associativity, at level 75) : ord_scope.\n\n(** We proceed with some useful lemmas about these relations. *)\n\n(** First predecessor of a successor is the original ordinal. *)\nLemma first_pd_after_succ_id :\n  forall alpha, alpha = Succ alpha [inl (pd_type alpha) tt].\nProof.\ntrivial.\nQed.\n\n\n(** No successor ordinal <= zero. *)\nLemma ord_le_not_succ_zero :\n  forall alpha, ~ Succ alpha <= Zero.\nProof.\nintros alpha H.\ninversion_clear H.\ndestruct i.\nQed.\n\n\nLemma ord_lt_not_zero : \n  forall alpha, ~ (alpha < Zero)%ord.\nProof.\n  intros.\n  intro H.\n  destruct H.\n  destruct x.\nQed.\n\n\n(** No double successor <= 1. *)\nLemma ord_le_not_succ_succ_one :\n  forall alpha, ~ Succ (Succ alpha) <= Succ Zero.\nProof.\nintros alpha H.\ninversion_clear H.\ndestruct i.\ndestruct u.\napply (@ord_le_not_succ_zero alpha).\nassumption.\nassumption.\nQed.\n\n(** If alpha <= zero, alpha <= any ordinal. *)\nLemma ord_le_zero_right :\n  forall alpha beta,\n    alpha <= Zero ->\n    alpha <= beta.\nProof.\ninduction alpha as [| alpha _ | f IH]; intros beta H.\nconstructor.\ninversion_clear H.\ndestruct i.\ninversion_clear H.\nconstructor.\nintro n.\napply IH.\ntrivial.\nQed.\n\n(** If alpha <= a predecessor of beta, alpha <= beta. *)\nLemma ord_le_pd_right :\n  forall alpha beta (i : pd_type beta),\n    alpha <= beta[i] ->\n    alpha <= beta.\nProof.\ninduction alpha as [| alpha IH | f IH]; intros beta i H.\nconstructor.\napply Ord_le_Succ with i.\ninversion H as [| a b j |].\napply IH with j.\nassumption.\nconstructor.\nintro n.\ninversion_clear H.\napply IH with i.\ntrivial.\nQed.\n\n(** If alpha <= beta, all predecessors of alpha <= beta. *)\nLemma ord_le_pd_left :\n  forall alpha beta (i : pd_type alpha),\n    alpha <= beta ->\n    alpha[i] <= beta.\nProof.\nintros alpha beta i H.\ninduction H as [| alpha beta j H IH | f beta H IH].\ndestruct i.\ndestruct i as [[] | i']; apply ord_le_pd_right with j.\napply H.\napply IH.\ndestruct i.\napply IH.\nQed.\n\n(** If alpha <= beta, alpha <= the successor of beta. *)\nLemma ord_le_succ_right :\n  forall alpha beta,\n    alpha <= beta ->\n    alpha <= Succ beta.\nProof.\ninduction alpha as [| alpha _ | f IH]; intros beta H.\nconstructor.\ninversion_clear H.\napply Ord_le_Succ with (inr unit i).\nassumption.\nconstructor.\nintro n.\napply IH.\ninversion_clear H.\ntrivial.\nQed.\n\n(** If the successor of alpha <= beta, alpha <= beta. *)\nLemma ord_le_succ_left :\n  forall alpha beta,\n    Succ alpha <= beta ->\n    alpha <= beta.\nProof.\nintros alpha beta H.\nrewrite (first_pd_after_succ_id alpha).\napply ord_le_pd_left.\nassumption.\nQed.\n\n(** If the successor of alpha <= the successor of beta, alpha <= beta. *)\nLemma ord_le_succ_elim :\n  forall alpha beta,\n    Succ alpha <= Succ beta ->\n    alpha <= beta.\nProof.\ninversion_clear 1.\ndestruct i as [[] |]; [| apply ord_le_pd_right with p]; assumption.\nQed.\n\n(** If the alpha <= beta, the successor of alpha <= the successor of beta. *)\nLemma ord_le_succ_intro :\n  forall alpha beta,\n    alpha <= beta ->\n    Succ alpha <= Succ beta.\nProof.\nintros.\napply Ord_le_Succ with (inl (pd_type beta) tt).\nassumption.\nQed.\n\n(** No successor of alpha is <= alpha. *)\nLemma ord_le_not_succ :\n  forall alpha, ~ Succ alpha <= alpha.\nProof.\ninduction alpha as [| alpha IH | f IH]; intro H.\napply ord_le_not_succ_zero with Zero.\nassumption.\napply IH.\nexact (ord_le_succ_elim H).\ninversion_clear H as [| a b i H' |].\ninversion_clear H' as [| | a b H].\ndestruct i as [n i].\napply IH with n.\napply Ord_le_Succ with i.\napply H.\nQed.\n\n(** If alpha <= a function value, alpha <= the limit of that function.\n   Suggested by Bruno Barras. *)\nLemma ord_le_limit_right :\n  forall alpha f n,\n    alpha <= f n ->\n    alpha <= Limit f.\nProof.\ninduction alpha as [| alpha _ | f IH]; intros g n H.\nconstructor.\ninversion_clear H.\napply Ord_le_Succ with (existT (fun n => pd_type (g n)) n i).\nassumption.\nconstructor.\nintro m.\napply (IH m g n).\ninversion_clear H.\ntrivial.\nQed.\n\n(** If a limit <= alpha, any value value of the function <= alpha. *)\nLemma ord_le_limit_left :\n  forall alpha f n,\n    Limit f <= alpha ->\n    f n <= alpha.\nProof.\nintros alpha f n H.\ninversion_clear H.\ntrivial.\nQed.\n\n(** [<=] is reflexive. *)\nLemma ord_le_refl :\n  forall alpha, alpha <= alpha.\nProof.\ninduction alpha as [| alpha IH | f IH].\nconstructor.\napply Ord_le_Succ with (inl (pd_type alpha) tt).\nassumption.\nconstructor.\nintro n.\napply ord_le_limit_right with n.\napply IH.\nQed.\n\n(* Added *)\nLemma ord_lt_succ_alpha : \n  forall alpha, alpha < Succ alpha.\nProof.\n  intros.\n  exists (inl (pd_type alpha) tt).\n  apply ord_le_refl.\nQed.\n\n(** Added *)\nLemma ord_le_limit_is_bound : \n  forall (f : nat -> ord) (n : nat),\n    f n <= Limit f.\nProof. intros. apply ord_le_limit_left. apply ord_le_refl. Qed.\n\n(** [<=] is transitive. *)\nLemma ord_le_trans :\n  forall alpha beta gamma,\n    alpha <= beta ->\n    beta <= gamma ->\n    alpha <= gamma.\nProof.\nintros alpha beta gamma H1.\nrevert gamma.\ninduction H1 as [| alpha beta i H IH | f beta H IH]; intros gamma H2.\nconstructor.\ninduction H2 as [| beta gamma j H' _ | f gamma H' IH'].\ndestruct i.\napply Ord_le_Succ with j.\napply IH.\ndestruct i as [[] | i']; simpl in * |- *.\nassumption.\napply ord_le_pd_left.\nassumption.\ndestruct i as [n i]; simpl in * |- *.\napply (IH' n i H IH).\nconstructor.\nintro n.\nexact (IH n gamma H2).\nQed.\n\n(** [<=] is antisymmetric (for [==]). *)\nLemma ord_le_antisymm :\n  forall alpha beta,\n    alpha <= beta ->\n    beta <= alpha ->\n    alpha == beta.\nProof.\nintros.\nunfold ord_eq.\nsplit; assumption.\nQed.\n\n\n(* Added *)\n(** [<=] is total *)\nLemma ord_le_ge_cases : \n  forall alpha beta, alpha <= beta \\/ beta <= alpha.\nProof.\n  assert( ord_le_le : forall (A:Type) (R Q : A->Prop),\n    (forall n, R(n) \\/ Q(n)) -> \n    (forall n, R(n)) \\/ exists n, Q(n)). \n  { \n    intros.\n      assert ((forall x, R x) \\/ exists x, ~R x).\n      {\n        case (classic (exists x, ~R x)).\n        - intro. right. apply H0.\n        - intro. left. apply not_ex_not_all. apply H0.\n      }\n      case H0.\n      - intro. left. apply H1.\n      - intro. right. destruct H1.  exists x.\n        case (H x). intro. contradiction H2. trivial.\n  }\n  induction alpha.\n  intro. left. constructor.\n  intro.\n    induction beta.\n    right. constructor.\n    case IHbeta.\n      intro. left. apply ord_le_succ_right. assumption.\n      intro.\n        case (IHalpha beta).\n          intro H0.\n            left.\n            exact (ord_le_succ_intro H0).\n          intro H0.\n            right.\n            exact (ord_le_succ_intro H0).\n    assert ((forall n0 : nat, (o n0 <= Succ alpha)%ord) \\/ (exists n0, (Succ alpha <= o n0)%ord)).\n    {\n      apply ord_le_le. intro.\n      case (H n); intro. right; assumption.\n      left; assumption.\n    }\n    case (H0).\n      intro. right. constructor. assumption.\n      intro. destruct H1. left. apply ord_le_trans with (o x). assumption.\n      apply ord_le_limit_is_bound.\n  intro.\n    assert ((forall (n : nat), (o n <= beta)%ord) \\/ (exists n, (beta <= o n)%ord)). { \n      apply ord_le_le.\n      intro n.\n      apply (H n beta).\n    }\n    case H0.\n      intro. left. constructor. assumption.\n      intro. destruct H1. right. \n      apply ord_le_trans with (o x).\n      assumption.\n      apply ord_le_limit_is_bound.\nQed.\n\n(** [==] is reflexive. *)\nLemma ord_eq_refl :\n  forall alpha, alpha == alpha.\nProof.\nsplit; apply ord_le_refl.\nQed.\n\n(** [==] is symmetric. *)\nLemma ord_eq_symm :\n  forall alpha beta,\n    alpha == beta ->\n    beta == alpha.\nProof.\nsplit; apply H.\nQed.\n\n(** [==] is transitive. *)\nLemma ord_eq_trans :\n  forall alpha beta gamma,\n    alpha == beta ->\n    beta == gamma ->\n    alpha == gamma.\nProof.\ndestruct 1.\ndestruct 1.\nsplit; apply ord_le_trans with beta; assumption.\nQed.\n\n(** Not zero < zero. *)\nLemma ord_lt_zero_zero :\n  ~ Zero < Zero.\nProof.\nintro H.\ndestruct H as [i H].\nelim i.\nQed.\n\n(** If alpha <= beta, not beta <= a predecessor of alpha. *)\nLemma ord_le_not_pd_right :\n  forall alpha beta i,\n    alpha <= beta ->\n    ~ beta <= alpha[i].\nProof.\ninduction alpha as [| alpha IH | f IH]; intros beta i H1 H2.\ndestruct i.\ndestruct i.\ndestruct u.\napply ord_le_not_succ with alpha.\napply ord_le_trans with beta; assumption.\nexact (IH beta p (ord_le_succ_left H1) H2).\ndestruct i.\ninversion_clear H1.\nexact (IH x beta p (H x) H2).\nQed.\n\n(** Not alpha <= a predecessor of alpha. *)\nLemma ord_le_not_pd_right_weak :\n  forall alpha i, ~ alpha <= alpha[i].\nProof.\nintros.\napply ord_le_not_pd_right.\napply ord_le_refl.\nQed.\n\n\n\n(** [<] is transitive. *)\nLemma ord_lt_trans :\n  forall alpha beta gamma,\n    alpha < beta ->\n    beta < gamma ->\n    alpha < gamma.\nProof.\nintros alpha beta gamma.\ndestruct 1 as [i].\ndestruct 1 as [j].\nexists j.\napply ord_le_trans with beta; [apply ord_le_pd_right with i |]; assumption.\nQed.\n\n(** [<] is irreflexive. *)\nLemma ord_lt_irrefl :\n  forall alpha, ~ alpha < alpha.\nProof.\nintros alpha H.\ndestruct H as [i H].\nexact (ord_le_not_pd_right_weak i H).\nQed.\n\n(** [<] is asymmetric. *)\nLemma ord_lt_asymm :\n  forall alpha beta,\n    alpha < beta ->\n    ~ beta < alpha.\nProof.\nintros alpha beta H1 H2.\ndestruct H1 as [i H1].\ndestruct H2 as [j H2].\napply (@ord_le_not_pd_right alpha beta j);\n  [apply ord_le_pd_right with i |]; assumption.\nQed.\n\n(** [pd_type] is closed under transitivity. *)\nLemma pd_trans :\n  forall alpha i j,\n    exists k, pd alpha k = pd (pd alpha i) j.\nProof.\ninduction alpha as [| alpha IH | f IH]; intros.\nelim i.\ndestruct i as [[] | i]; simpl in j |- *.\nexists (inr _ j).\nreflexivity.\ndestruct (IH i j) as [k H].\nexists (inr _ k).\nassumption.\ndestruct i as [n i]; simpl in j |- *.\ndestruct (IH n i j) as [k H].\nexists (existT (fun n => pd_type (f n)) n k).\nassumption.\nQed.\n\n(** If the successor of alpha < beta, alpha < beta. *)\nLemma ord_lt_succ_left :\n  forall alpha beta,\n    Succ alpha < beta ->\n    alpha < beta.\nProof.\nintros alpha beta.\ndestruct 1 as [i H].\nexists i.\napply ord_le_succ_left.\nassumption.\nQed.\n\n(** If alpha < beta, alpha < the successor of beta. *)\nLemma ord_lt_succ_right :\n  forall alpha beta,\n    alpha < beta ->\n    alpha < Succ beta.\nProof.\nintros alpha beta.\ndestruct 1 as [i H].\nexists (inl (pd_type beta) tt).\napply ord_le_pd_right with i.\nassumption.\nQed.\n\n(** Added *)\nLemma ord_lt_le_succ_right : \n  forall alpha beta, \n    alpha < beta -> \n    Succ alpha <= beta.\nProof.\n    intros alpha beta H.\n    destruct H as [i H].\n    apply Ord_le_Succ with i.\n    assumption.\nQed.\n\n(** Added *)\nLemma ord_lt_limit_left :\n  forall alpha f n,\n    Limit f < alpha ->\n    f n < alpha.\nProof.\nintros alpha ff n H1.\ndestruct H1.\nexists x.\napply ord_le_limit_left. trivial.\nQed.\n\n(** If alpha < beta, alpha <= beta. *)\nLemma ord_lt_ord_le :\n  forall alpha beta, alpha < beta -> alpha <= beta.\nProof.\nintros alpha beta.\ndestruct 1 as [i H].\napply ord_le_pd_right with i.\nassumption.\nQed.\n\n(** If alpha < beta, the successor of alpha <= beta. *)\nLemma ord_lt_ord_le_succ :\n  forall alpha beta,\n    alpha < beta ->\n    Succ alpha <= beta.\nProof.\nintros alpha beta.\ndestruct 1 as [i H].\napply Ord_le_Succ with i.\nassumption.\nQed.\n\n(** If alpha < beta, not beta <= alpha. *)\nLemma ord_lt_not_ord_le :\n  forall alpha beta,\n    alpha < beta ->\n    ~ beta <= alpha.\nProof.\nintros alpha beta H1 H2.\ndestruct H1 as [i H1].\napply (@ord_le_not_pd_right beta alpha i); assumption.\nQed.\n\n(** If alpha <= a predecessor of the successor of beta, alpha <= beta. *)\nLemma ord_le_succ_pd_right :\n  forall alpha beta i,\n    alpha <= Succ beta [i] ->\n    alpha <= beta.\nProof.\n(* This is a messy proof *)\ninduction alpha; intros.\nsimpl in H.\ndestruct i.\ndestruct u.\nassumption.\napply Ord_le_Zero.\ndestruct beta.\ndestruct i.\ndestruct u.\ndestruct (ord_le_not_succ_zero H).\ndestruct p.\napply Ord_le_Succ with (inl (pd_type beta) tt).\nsimpl.\nsimpl in H.\ndestruct i.\ndestruct u.\napply ord_le_succ_elim.\nassumption.\ndestruct p.\napply ord_le_succ_left.\ndestruct u.\nassumption.\napply ord_le_succ_left.\napply ord_le_pd_right with p.\nassumption.\nsimpl in H.\ndestruct i.\ndestruct u.\nassumption.\ndestruct p.\napply ord_le_limit_right with x.\napply ord_le_pd_right with p.\nassumption.\napply Ord_le_Limit.\nintro.\ninversion_clear H0.\napply H with i.\napply H1.\nQed.\n\n(** Added *)\nLemma ord_le_lt_trans : forall alpha beta gamma, \n      alpha <= beta  ->\n      beta < gamma ->\n      alpha < gamma.\nProof.\nintros alpha beta gamma.\nintros H1 H2.\ndestruct H2 as [i H3].\nexists i.\napply ord_le_trans with (beta) ; assumption.\nQed.\n\n(** Added *)\nLemma ord_lt_le_trans : forall alpha beta gamma, \n      alpha < beta  ->\n      beta <= gamma ->\n      alpha < gamma.\nProof.\nintros alpha beta gamma H1 H2.\ninduction H2.\n- destruct H1. destruct x.\n- exists i. apply ord_le_trans with (alpha0). destruct H1. \n  apply ord_le_succ_pd_right with (x); assumption. assumption.\n- destruct H1. destruct x. apply H0 with (n:=x). exists p. apply H1.\nQed.\n\n(** Added *)\nLemma ord_lt_limit_right :\n  forall alpha f n,\n    alpha < f n ->\n    alpha < Limit f.\nProof.\nintros.\napply ord_lt_le_trans with (beta:=(f n)).\nassumption.\napply ord_le_limit_is_bound.\nQed.\n\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\n\n\nInstance ord_eq_wd : Equivalence (ord_eq).\nsplit.\n  - unfold Reflexive. apply ord_eq_refl.\n  - unfold Symmetric. apply ord_eq_symm.\n  - unfold Transitive. apply ord_eq_trans.\nQed.\n\nInstance ord_le_wd : Proper (ord_eq==>ord_eq==>iff) ord_le.\nProof.\nreduce. \nsplit.\n- intro H2. apply ord_le_trans with (x). apply H.\n  apply ord_le_trans with (x0). apply H2. apply H0.\n- intro H2. apply ord_le_trans with (y). apply H.\n  apply ord_le_trans with (y0). apply H2. apply H0.\nQed.\n\nInstance ord_lt_wd : Proper (ord_eq==>ord_eq==>iff) ord_lt.\nProof.\nreduce.\ndestruct H. destruct H0.\nsplit.\n- intro. apply ord_lt_le_trans with (x0); try apply ord_le_lt_trans with (x); assumption.\n- intro. apply ord_lt_le_trans with (y0); try apply ord_le_lt_trans with (y); assumption.\nQed.\n\n\n(** Ordinal arithmetic. *)\n\nFixpoint add (alpha beta : ord) : ord :=\n  match beta with\n  | Zero      => alpha\n  | Succ beta => Succ (add alpha beta)\n  | Limit f   => Limit (fun o => add alpha (f o))\n  end.\n\nFixpoint mul (alpha beta : ord) : ord :=\n  match beta with\n  | Zero      => Zero\n  | Succ beta => add (mul alpha beta) alpha\n  | Limit f   => Limit (fun o => mul alpha (f o))\n  end.\n\nFixpoint exp (alpha beta : ord) : ord :=\n  match beta with\n  | Zero      => Succ Zero\n  | Succ beta => mul (exp alpha beta) alpha\n  | Limit f   => Limit (fun o => exp alpha (f o))\n  end.\n\nLemma ord_le_add_right :\n  forall alpha beta,\n    alpha <= add alpha beta.\nProof.\nintros alpha beta.\ninduction beta as [| beta IH | f IH].\napply ord_le_refl.\napply ord_le_succ_right.\nexact IH.\napply ord_le_limit_right with 0.\napply IH.\nQed.\n\nLemma ord_le_add :\n  forall alpha beta gamma,\n    beta <= gamma ->\n    add alpha beta <= add alpha gamma.\nProof.\nintros alpha beta gamma H.\ninduction H as [gamma | beta gamma i H IH | f gamma H IH].\napply ord_le_add_right.\ninduction gamma as [| gamma IHg | f IHg]; simpl.\nelim i.\ndestruct i as [[] | i].\napply Ord_le_Succ with (inl (pd_type (add alpha gamma)) tt).\napply IH.\napply ord_le_succ_right.\napply IHg with i; assumption.\ndestruct i as [n i].\napply ord_le_limit_right with n.\napply IHg with i; assumption.\nconstructor.\nintro n.\napply IH.\nQed.\n\nLemma ord_lt_add :\n  forall alpha beta gamma,\n    beta < gamma ->\n    add alpha beta < add alpha gamma.\nProof.\nintros alpha beta gamma H.\nunfold ord_lt; destruct H as [i H].\ninduction gamma as [| gamma _ | f IH]; simpl.\ndestruct i.\nexists (inl _ tt); simpl.\napply ord_le_add.\ndestruct i as [[] | i].\nassumption.\napply ord_le_pd_right with i.\nassumption.\ndestruct i as [n i].\nspecialize IH with n i.\ndestruct IH as [j IH].\nassumption.\nexists (existT (fun n => pd_type (add alpha (f n))) n j).\nassumption.\nQed.\n\n(** The natural numbers can be coerced into finite ordinals. *)\n\nFixpoint nat_as_ord (n : nat) : ord :=\n  match n with\n  | O   => Zero\n  | S n => Succ (nat_as_ord n)\n  end.\n\nCoercion nat_as_ord : nat >-> ord.\n\n(** The smallest infinite ordinal is the limit of the natural numbers. *)\nDefinition omega := Limit (fun n => n).\n\n(** We show that [<=] and [<] on ordinals are the same as [<=] and [<] on\n   natural numbers. *)\n\nRequire Import Le.\n\nLemma le_implies_ord_le : forall n m, (n <= m)%nat -> n <= m.\nProof.\ninduction n as [| n IH]; intros m H.\nconstructor.\ndestruct m as [| m].\ncontradiction le_Sn_0 with n.\napply ord_le_succ_intro.\napply IH.\napply le_S_n.\nassumption.\nQed.\n\nLemma ord_le_implies_le : forall (n m : nat), n <= m -> (n <= m)%nat.\nProof.\ninduction n as [| n IH]; intros m H.\napply le_0_n.\ndestruct m as [| m].\ncontradiction ord_le_not_succ_zero with n.\napply le_n_S.\napply IH.\napply ord_le_succ_elim.\nassumption.\nQed.\n\nLemma ord_le_le : forall n m, (n <= m)%nat <-> n <= m.\nProof.\nsplit.\napply le_implies_ord_le.\napply ord_le_implies_le.\nQed.\n\nRequire Import Lt.\n\nLemma lt_implies_ord_lt : forall n m, (n < m)%nat -> n < m.\nProof.\ninduction n as [| n IH]; intros m H.\ndestruct H; exists (inl _ tt); constructor.\ndestruct m as [| m].\ncontradiction lt_n_O with (S n).\nexists (inl _ tt).\napply ord_lt_ord_le_succ; simpl.\napply IH.\napply lt_S_n.\nassumption.\nQed.\n\nLemma ord_lt_implies_lt : forall (n m : nat), n < m -> (n < m)%nat.\nProof.\ninduction n as [| n IH]; intros m H.\ndestruct H as [i H].\ndestruct m as [| m].\nelim i.\napply lt_0_Sn.\ndestruct H as [i H].\ndestruct m as [| m].\nelim i.\napply lt_n_S.\napply IH.\n(* this can be cleaned up *)\ndestruct m as [| m].\ndestruct i as [[] | []].\ncontradiction ord_le_not_succ_zero with n.\nexists (inl _ tt).\ndestruct i as [[] | [[] | i]].\napply ord_le_succ_elim.\nassumption.\napply ord_le_succ_left.\nassumption.\napply ord_le_succ_left.\napply ord_le_pd_right with i.\nassumption.\nQed.\n\nLemma ord_lt_lt : forall n m, (n < m)%nat <-> n < m.\nProof.\nsplit.\napply lt_implies_ord_lt.\napply ord_lt_implies_lt.\nQed.\n\n(** We now prove two simple facts about our equality [==] containing\n   different representations of omega. *)\n\nLemma fact_a :\n  Limit (fun n => S n) == omega.\nProof.\nsplit; constructor; intro n.\napply Ord_le_Succ with (existT (fun n:nat => pd_type n) (S n) (inl _ tt)).\napply ord_le_refl.\ndestruct n as [| n].\nconstructor.\napply Ord_le_Succ with (existT (fun n:nat => pd_type (S n)) n (inl _ tt)).\napply ord_le_refl.\nQed.\n\nLemma fact_b :\n  Limit (fun n => n * 2) == omega.\nProof.\nsplit; constructor; intro n.\ndestruct n as [| n]; simpl.\nconstructor.\napply Ord_le_Succ with (existT (fun n:nat => pd_type n) (S (S (n * 2))) (inl _ tt)).\napply ord_le_refl.\ndestruct n as [| n].\nconstructor.\napply Ord_le_Succ with (existT (fun n:nat => pd_type (n * 2)) (S n) (inl _ tt)).\nsimpl.\ninduction n as [| n IH]; simpl.\nconstructor.\napply ord_le_succ_right.\napply ord_le_succ_intro.\nexact IH.\nQed.\n\n(** A weak inversion property of ordinals equal to omega. *)\nLemma ord_eq_omega_discriminate :\n  forall alpha,\n    alpha == omega ->\n    exists f, alpha = Limit f.\nProof.\nintros [| alpha | f] [H1 H2].\ninversion_clear H2.\ncontradict (ord_le_not_succ_zero (H 1)).\ninversion_clear H1.\ninversion_clear H2.\ndestruct i as [n i].\ncontradict (ord_le_not_pd_right i (ord_le_succ_elim (H0 (S n))) H).\nexists f; reflexivity.\nQed.\n\nClose Scope ord_scope.", "meta": {"author": "acharal", "repo": "lexicographic-lattice-structures", "sha": "f14027ba99863d8164f41545ae9aa0d785a451d9", "save_path": "github-repos/coq/acharal-lexicographic-lattice-structures", "path": "github-repos/coq/acharal-lexicographic-lattice-structures/lexicographic-lattice-structures-f14027ba99863d8164f41545ae9aa0d785a451d9/Ordinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8021129318293484}}
{"text": "Require Export Induction.\nModule NatList.\n\n  Inductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\n  Check pair 3 5.\n\n  Definition 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(* ===> 3 *)\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\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  (*simpl.*)\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\n(*Exercise: 1 star (snd_fst_is_swap)*)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(**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  intro p.\n  destruct p as [m n].\n  simpl.\n  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)\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\nCompute length mylist1.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\nExample test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof.  reflexivity. Qed.\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n(**Exercise: 2 stars, recommended (list_funs)\nComplete the definitions of nonzeros, oddmembers and countoddmembers below. Have a look at the tests to understand what these functions should do.*)\nFixpoint nonzeros (l:natlist) : natlist  :=\n  match l with\n  | nil => nil\n  | h :: t => match h with\n              | O => nonzeros t\n              | S n => [h] ++ nonzeros t\n               end\n  end.\n              \n              \nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  simpl.\n  reflexivity.\nQed.\n\nCompute oddb 4. (*Tests whether a number is odd*)\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].\n  simpl.\n  reflexivity.\nQed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  match oddmembers l with\n  |nil => 0\n  |h :: t => 1 + length t\n  end.\n\nCompute countoddmembers [1;0;3;1;4;5;7;2;2;5].\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  reflexivity.\nQed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nreflexivity.\n  Qed.\n  \nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nreflexivity.\n  Qed.\n\n(**Exercise: 3 stars, advanced (alternate)\nComplete the definition of alternate, which \"zips up\" two lists into one, alternating between elements taken from the first list and elements from the second. See the tests below for more specific examples.\nNote: one natural and elegant way of writing alternate will fail to satisfy Coq's requirement that all Fixpoint definitions be \"obviously terminating.\" If you find yourself in this rut, look for a slightly more verbose solution that considers elements of both lists at the same time. (One possible solution requires defining a new kind of pairs, but this is not the only way.)*)\n\n  Fixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1 with\n    |nil => l2\n    |h :: t => match l2 with\n               | nil => l1\n               | a :: b => [h] ++ [a] ++ alternate t b\n               end\n    end.\n\nCompute alternate [] [20;30].\n  \nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nsimpl.\nreflexivity.\nQed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nsimpl.\nreflexivity.\n  Qed.\n  \nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nsimpl.\nreflexivity.\n  Qed.\n  \nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nsimpl.\nreflexivity.\n  Qed.\n\n  Definition bag := natlist.\n\n  (**Exercise: 3 stars, recommended (bag_functions)\nComplete the following definitions for the functions count, sum, add, and member for bags.*)\n(**Fixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => if beq_nat v h then 1 + count v t else count v t\n  end.*)\n\n  Fixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match beq_nat h v with\n              | true => 1 + count v t\n              | false => count v t\n              end\n  end.\n\nCompute count 1 [1;2;3;1;4;1].\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nsimpl.\nreflexivity.\n  Qed.\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nsimpl.\nreflexivity.\n  Qed.\n\n  Definition sum : bag -> bag -> bag :=\n    app. (*or alternate*)\n\n   Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n   simpl.\n   reflexivity.\n   Qed.\n\n  (**Another way of implementing sum using anonymouys function*)\n(** Definition sum : bag -> bag -> bag :=\n    fun x y =>\n      match x,y with\n      | [], y => y\n      | x, [] => x\n      | x, y => x ++ y\n      end.*)\n\n  Definition add (v:nat) (s:bag) : bag :=\n    match s with\n    | nil => [v]\n    | h :: t => [v] ++ s\n  end.\n\n  Compute add 1 [1;4;1].\n\n  Example test_add1: count 1 (add 1 [1;4;1]) = 3.\n  simpl.\n  reflexivity.\n  Qed.\n\n  Example test_add2: count 5 (add 1 [1;4;1]) = 0.\n  simpl.\n  reflexivity.\n  Qed.\n\n  Definition member (v:nat) (s:bag) : bool :=\n    match count v s with\n    | 0 => false\n    | _ => true\n    end.\n  \n\n  (**Fixpoint member (v:nat) (s:bag) : bool :=\n    match s with\n    | nil => false\n    | h :: t => if beq_nat h v then true else member  v t \n    end.*)\n\n  Example test_member1: member 1 [1;4;1] = true.\n  simpl.\n  reflexivity.\n  Qed.\n  \n  Example test_member2: member 2 [1;4;1] = false.\n  simpl.\n  reflexivity.\n  Qed.\n\n  Fixpoint remove_one (v:nat) (s:bag) : bag :=\n    match s with\n    | nil => nil\n    | h :: t => if beq_nat h v then t else [h] ++ remove_one v t\n    end.\n\n  Compute remove_one 2 [2;3;5;3;2;7].\n\n  Example test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  simpl.\n  reflexivity.\n  Qed.\n  \nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nsimpl.\nreflexivity.\nQed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nsimpl.\nreflexivity.\n  Qed.\n\n  \nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nsimpl.\nreflexivity.\n  Qed.\n\n  Fixpoint remove_all (v:nat) (s:bag) : bag :=\n    match s with\n    | nil => nil\n    | h :: t => if beq_nat h v then remove_all v t else [h] ++ remove_all v t\n    end.\n\n  Compute remove_all 5 [5;5;5;2;7;2;1;5;4;5;1;5;4].\n\n  Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n  simpl.\n  reflexivity.\n  Qed.\n  \n  Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n  simpl.\n  reflexivity.\n  Qed.\n  \nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nsimpl.\nreflexivity.\n  Qed.\n  \nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nsimpl.\n  reflexivity.\n  Qed.\n\n  Fixpoint subset (s1:bag) (s2:bag) : bool :=\n    match s1, s2 with\n    | nil, _ => true (**nil is subset of anything*)\n    | _, nil => false (**nothing is subset of nil*)\n    | h :: t, s2 => if member h s2 then subset t (remove_one h s2) else false   \n    end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nsimpl.\nreflexivity.\n  Qed.\n  \nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nsimpl.\nreflexivity.\n  Qed.\n\n  (**my theorem*)\nTheorem bag_theorem : forall (l: bag) (x: nat), length( add (count x l) l ) = length (add x l).\nProof.\n  intros l x.\n  induction l.\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    reflexivity.\nQed.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. simpl. 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.\n    reflexivity.\n  - (* l = cons n l' *)\n    simpl.\n    reflexivity. Qed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => rev t ++ [h]\n  end.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. simpl. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. simpl. reflexivity. Qed.\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l =  *)\n    simpl.\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  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    simpl.\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nSearch rev.\n\n(**List Exercises, Part 1*)\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| n l' IHl].\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1 as [| n l IHl].\n  -\n    simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  -\n    simpl.\n    rewrite -> IHl.\n    Search app.\n    rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nSearch app.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intro l.\n  induction l as [| n l' IHl].\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    rewrite -> rev_app_distr.\n    simpl.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  induction l1 as [|n l' IHl].\n  -\n    simpl.\n    rewrite -> app_assoc.\n    reflexivity.\n  -\n    simpl.\n    rewrite -> IHl.\n    reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1 as [|n l' IHl].\n  -\n    simpl.\n    reflexivity.\n  -\n    Search nonzeros.\n    induction n.\n    +\n      simpl.\n      rewrite -> IHl.\n      reflexivity.\n    +\n      simpl.\n      rewrite IHl.\n      reflexivity.\nQed.\n\nSearch count.\n\n(**Auxiliar Fixpoint for Definition member_nat*)\nFixpoint count_nat (v:nat) (s:natlist) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => if beq_nat v h then 1 + count_nat v t else count_nat v t\n  end.\n\n(**Auxiliar Definition for Fixpoint beq_natlist*)\nDefinition member_nat (v:nat) (s:natlist) : bool :=\n      match count_nat v s with\n    | 0 => false\n    | _ => true\n    end.\n\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | nil, _ => false\n  | _, nil => false\n  | h::t, d::l =>  if beq_nat h d then beq_natlist t l else false\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nsimpl.\nreflexivity.\n  Qed.\n\n  Example test_beq_natlist2 :\n    beq_natlist [1;2;3] [1;2;3] = true.\n  simpl.\n  reflexivity.\n  Qed.\n\n  Example test_beq_natlist3 :\n    beq_natlist [1;2;3] [1;2;4] = false.\n  simpl.\n  reflexivity.\n  Qed.\n\n  Theorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intro l.\n  induction l as [|n].\n  -\n    simpl.\n    reflexivity.\n  -\n    rewrite -> IHl.\n    induction n.\n    +\n      simpl.\n      reflexivity.\n    +\n      rewrite -> IHn.\n      reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intro l.\n  induction l as [|n IHl].\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    reflexivity.\nQed.\n\n(**The following lemma about leb might help you in the next exercise.*)\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity. Qed.\n\n(**Exercise: 3 stars, advanced (remove_does_not_increase_count)*)\nTheorem remove_does_not_increase_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s.\n  induction s as [|n].\n  -\n    simpl.\n    reflexivity.\n  -\n    rewrite <- IHs.\n    induction n.\n    +\n      simpl.\n      rewrite -> ble_n_Sn.\n      rewrite -> IHs.\n      reflexivity.\n    +\n      simpl.\n      reflexivity.\nQed.\n    \nTheorem bag_count_sum : forall (n : nat) (s : bag), leb (count n s) (count n (sum [n] s)) = true.\nProof.\n  intros n s.\n  induction n.\n  -\n    simpl.\n    rewrite -> ble_n_Sn.\n    reflexivity.\n  -\n    simpl.\n    rewrite <- beq_nat_refl.\n    rewrite -> ble_n_Sn.\n    reflexivity.\nQed.\n\nRequire Import Setoid.\n\n  Theorem rev_injective : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  rewrite <- rev_involutive at 1.\n  rewrite H.\n  rewrite rev_involutive.\n  reflexivity.\nQed.\n  \n\n  Fixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42 (* arbitrary! *)\n  | a :: l' => match beq_nat n O with \n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n  Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n  Fixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat 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\n  \nExample test_hd_error1 : hd_error [] = None.\nsimpl.\nreflexivity.\nQed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nsimpl.\nreflexivity.\nQed.\n\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nsimpl.\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 default.\n  induction l as [|head].\n  -\n    simpl.\n    reflexivity.\n  -\n    simpl.\n    reflexivity.\nQed.\n\nEnd NatList.\n\nInductive id : Type :=\n| Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intro x.\n  induction x.\n  -\n    simpl.\n    induction n.\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite <- IHn.\n      reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> 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 beq_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 x v.\n  induction d.\n  -\n    simpl.\n    rewrite <- beq_id_refl.\n    reflexivity.\n  -\n    simpl.\n    rewrite <- beq_id_refl.\n    reflexivity.\nQed.\n\n\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o.\n  intro Hxy.\n  induction d.\n  -\n    simpl.\n    rewrite -> Hxy.\n    reflexivity.\n  -\n    simpl.\n    rewrite -> Hxy.\n    reflexivity.\nQed.\nEnd PartialMap.\n    ", "meta": {"author": "thalesad", "repo": "coqexercises", "sha": "62f09168bf5267196780146ddb6ab53b4bb458d6", "save_path": "github-repos/coq/thalesad-coqexercises", "path": "github-repos/coq/thalesad-coqexercises/coqexercises-62f09168bf5267196780146ddb6ab53b4bb458d6/ListsThales.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.9073122257466114, "lm_q1q2_score": 0.8020996566843542}}
{"text": "\nTheorem bool_cases : forall b:bool, b = true \\/ b = false.\nProof\n  bool_ind (fun b:bool => b = true \\/ b = false)\n    (or_introl _ (refl_equal true)) (or_intror _ (refl_equal false)).\n\n\nTheorem bool_cases' : forall b:bool, b = true \\/ b = false.\nProof.\n intro b; pattern b; apply bool_ind; [ left | right ]; reflexivity.\nQed. \n\n\n(** version with destruct : \n*)\nTheorem bool_cases'' : forall b:bool, b = true \\/ b = false.\nProof.\n destruct b;[left | right]; reflexivity.\nQed. \n\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch6_inductive_data/SRC/bool_cases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8840392909114835, "lm_q1q2_score": 0.8020996505913202}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* * Shared libraries *)\n\n(* ** Finitary sums and products over monoids *)\n\nRequire Import List Arith ZArith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list binomial.\n\nSet Implicit Arguments.\n\nRecord monoid_theory (X : Type) (m : X -> X -> X) (u : X) := mk_monoid {\n  monoid_unit_l : forall x, m u x = x;\n  monoid_unit_r : forall x, m x u = x;\n  monoid_assoc  : forall x y z, m x (m y z) = m (m x y) z;\n}.\n\nFact Nat_plus_monoid : monoid_theory plus 0.\nProof. exists; intros; ring. Qed.\n\nFact Nat_mult_monoid : monoid_theory mult 1.\nProof. exists; intros; ring. Qed.\n\nFact Zplus_monoid : monoid_theory Zplus 0%Z.\nProof. exists; intros; ring. Qed.\n\nFact Zmult_monoid : monoid_theory Zmult 1%Z.\nProof. exists; intros; ring. Qed.\n\n#[export] Hint Resolve Nat_plus_monoid Nat_mult_monoid\n             Zplus_monoid Zmult_monoid : core.\n\nSection msum.\n\n  Variable (X : Type) (m : X -> X -> X) (u : X).\n\n  Infix \"\u2295\" := m (at level 50, left associativity).\n\n  Fixpoint msum n f := \n    match n with \n      | 0   => u\n      | S n => f 0 \u2295 msum n (fun n => f (S n))\n    end.\n\n  Notation \"\u2211\" := msum.\n\n  Fact msum_fold_map n f : \u2211 n f = fold_right m u (map f (list_an 0 n)).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; f_equal; auto.\n    rewrite IHn, <-  map_S_list_an, map_map; auto.\n  Qed.\n\n  Fact msum_0 f : \u2211 0 f = u.\n  Proof. auto. Qed.\n\n  Fact msum_S n f : \u2211 (S n) f = f 0 \u2295 \u2211 n (fun n => f (S n)).\n  Proof. auto. Qed.\n\n  Hypothesis Hmonoid : monoid_theory m u.\n\n  Fact msum_1 f : \u2211 1 f = f 0.\n  Proof.\n    destruct Hmonoid as [ H1 H2 ].\n    rewrite msum_S, msum_0, H2; auto.\n  Qed.\n\n  Fact msum_plus a b f : \u2211 (a+b) f = \u2211 a f \u2295 \u2211 b (fun i => f (a+i)).\n  Proof.\n    destruct Hmonoid as [ H1 _ H3 ].\n    revert f; induction a as [ | a IHa ]; intros f; simpl; auto.\n    rewrite <- H3; f_equal; apply IHa.\n  Qed.\n\n  Fact msum_plus1 n f : \u2211 (S n) f = \u2211 n f \u2295 f n.\n  Proof.\n    destruct Hmonoid as [ _ H2 _ ].\n    replace (S n) with (n+1) by lia.\n    rewrite msum_plus; simpl; f_equal.\n    rewrite H2; f_equal; lia.\n  Qed.\n\n  Fact msum_ext n f g : (forall i, i < n -> f i = g i) -> \u2211 n f = \u2211 n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g Hfg; simpl; f_equal; auto.\n    + apply Hfg; lia.\n    + apply IHn; intros; apply Hfg; lia.\n  Qed.\n\n  Fact msum_unit n : \u2211 n (fun _ => u) = u.\n  Proof.\n    destruct Hmonoid as [ H1 _ _ ].\n    induction n as [ | n IHn ]; simpl; auto.\n    rewrite IHn; auto.\n  Qed.\n\n  Fact msum_comm a n f : (forall i, i < n -> f i \u2295 a = a \u2295 f i) -> \u2211 n f \u2295 a = a \u2295 \u2211 n f.\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f; induction n as [ | n IHn ]; intros f H; simpl; auto.\n    + rewrite H1, H2; auto.\n    + rewrite H3, <- H; try lia.\n      repeat rewrite <- H3; f_equal.\n      apply IHn.\n      intros; apply H; lia.\n  Qed.\n\n  Fact msum_sum n f g : (forall i j, i < j < n -> f j \u2295 g i = g i \u2295 f j) -> \u2211 n (fun i => f i \u2295 g i) = \u2211 n f \u2295 \u2211 n g.\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f g; induction n as [ | n IHn ]; intros f g H; simpl; auto.\n    rewrite IHn.\n    + repeat rewrite <- H3; f_equal.\n      repeat rewrite H3; f_equal.\n      symmetry; apply msum_comm.\n      intros; apply H; lia.\n    + intros; apply H; lia.\n  Qed.\n\n  Fact msum_of_unit n f : (forall i, i < n -> f i = u) -> \u2211 n f = u.\n  Proof.\n    intros H.\n    rewrite <- (msum_unit n).\n    apply msum_ext; auto.\n  Qed.\n\n  Fact msum_only_one n f i : i < n\n                          -> (forall j, j < n -> i <> j -> f j = u)\n                          -> \u2211 n f = f i.\n  Proof.\n    destruct Hmonoid as [ M1 M2 M3 ].\n    intros H1 H2.\n    replace n with (i + 1 + (n-i-1)) by lia.\n    do 2 rewrite msum_plus.\n    rewrite msum_of_unit, msum_1, msum_of_unit, M1, M2.\n    + f_equal; lia.\n    + intros j Hj; destruct (H2 (i+1+j)); auto; lia.\n    + intros j Hj; destruct (H2 j); auto; lia.\n  Qed.\n\n  Fact msum_msum n k f :\n          (forall i1 j1 i2 j2, i1 < n -> j1 < k -> i2 < n -> j2 < k -> f i1 j1 \u2295 f i2 j2 = f i2 j2 \u2295 f i1 j1)\n       -> \u2211 n (fun i => \u2211 k (f i)) = \u2211 k (fun j => \u2211 n (fun i => f i j)).\n  Proof.\n    revert k f; induction n as [ | n IHn ]; intros k f Hf.\n    + rewrite msum_0, msum_of_unit; auto.\n    + rewrite msum_S, IHn.\n      * rewrite <- msum_sum.\n        - apply msum_ext.\n          intros; rewrite msum_S; trivial.\n        - intros; symmetry; apply msum_comm.\n          intros; apply Hf; lia.\n      * intros; apply Hf; lia.\n  Qed.\n\n  Fact msum_ends n f : (forall i, 0 < i <= n -> f i = u) -> \u2211 (n+2) f = f 0 \u2295 f (S n).\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    intros H.\n    replace (n+2) with (1 + n + 1) by lia.\n    do 2 rewrite msum_plus; simpl.\n    rewrite msum_of_unit.\n    + rewrite H2, H2, H2; do 2 f_equal; lia.\n    + intros; apply H; lia.\n  Qed.\n\n  Fact msum_first_two n f : 2 <= n -> (forall i, 2 <= i -> f i = u) -> \u2211 n f = f 0 \u2295 f 1.\n  Proof.\n    destruct Hmonoid as [ _ M2 _ ].\n    intros Hn H1.\n    destruct n as [ | [ | n ] ]; try lia.\n    do 2 rewrite msum_S.\n    rewrite msum_of_unit.\n    + rewrite M2; trivial.\n    + intros; apply H1; lia.\n  Qed.\n\n  Definition mscal n x := msum n (fun _ => x).\n\n  Fact mscal_0 x : mscal 0 x = u.\n  Proof. apply msum_0. Qed.\n\n  Fact mscal_S n x : mscal (S n) x = x \u2295 mscal n x.\n  Proof. apply msum_S. Qed.\n\n  Fact mscal_1 x : mscal 1 x = x.\n  Proof. \n    destruct Hmonoid as [ _ H2 _ ].\n    rewrite mscal_S, mscal_0, H2; trivial.\n  Qed.\n\n  Fact mscal_of_unit n : mscal n u = u.\n  Proof. apply msum_of_unit; auto. Qed.\n\n  Fact mscal_plus a b x : mscal (a+b) x = mscal a x \u2295 mscal b x.\n  Proof. apply msum_plus. Qed.\n\n  Fact mscal_plus1 n x : mscal (S n) x = mscal n x \u2295 x.\n  Proof. apply msum_plus1. Qed.\n\n  Fact mscal_comm n x y : x \u2295 y = y \u2295 x -> mscal n x \u2295 y = y \u2295 mscal n x.\n  Proof. intros H; apply msum_comm; auto. Qed.\n\n  Fact mscal_sum n x y : x \u2295 y = y \u2295 x -> mscal n (x \u2295 y) = mscal n x \u2295 mscal n y.\n  Proof. intro; apply msum_sum; auto. Qed.\n\n  Fact mscal_mult a b x : mscal (a*b) x = mscal a (mscal b x).\n  Proof.\n    induction a as [ | a IHa ]; simpl.\n    + do 2 rewrite mscal_0; auto.\n    + rewrite mscal_plus, IHa, mscal_S; auto.\n  Qed.\n\n  Fact msum_mscal n k f : (forall i j, i < n -> j < n -> f i \u2295 f j = f j \u2295 f i) \n                       -> \u2211 n (fun i => mscal k (f i)) = mscal k (\u2211 n f).\n  Proof. intros H; apply msum_msum; auto. Qed.\n\nEnd msum.\n\nSection msum_morphism.\n\n  Variable (X Y : Type) (m1 : X -> X -> X) (u1 : X) \n                        (m2 : Y -> Y -> Y) (u2 : Y)\n           (H1 : monoid_theory m1 u1)\n           (H2 : monoid_theory m2 u2)\n           (phi : X -> Y)\n           (Hphi1 : phi u1 = u2)\n           (Hphi2 : forall x y, phi (m1 x y) = m2 (phi x) (phi y)).\n\n  Fact msum_morph n f : phi (msum m1 u1 n f) = msum m2 u2 n (fun x => phi (f x)).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; auto.\n    rewrite Hphi2, IHn; trivial.\n  Qed.\n\n  Fact mscal_morph n x : phi (mscal m1 u1 n x) = mscal m2 u2 n (phi x).\n  Proof. apply msum_morph. Qed.\n\nEnd msum_morphism.\n\nSection binomial_Newton.\n\n  Variable (X : Type) (sum times : X -> X -> X) (zero one : X).\n\n  Infix \"\u2295\" := sum (at level 50, left associativity).\n  Infix \"\u2297\" := times (at level 40, left associativity).\n  \n  Notation z := zero.\n  Notation o := one.\n\n  Notation scal := (mscal sum zero).\n  Notation expo := (mscal times one).\n\n  Hypothesis (M_sum : monoid_theory sum zero) \n             (sum_comm : forall x y, x \u2295 y = y \u2295 x)\n             (sum_cancel : forall x u v, x \u2295 u = x \u2295 v -> u = v)\n             (M_times : monoid_theory times one)\n             (distr_l : forall x y z, x \u2297 (y\u2295z) = x\u2297y \u2295 x\u2297z)\n             (distr_r : forall x y z, (y\u2295z) \u2297 x = y\u2297x \u2295 z\u2297x).\n\n  Fact times_zero_l x : z \u2297 x = z.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (z\u2297x).\n    rewrite S2, <- distr_r, S1; trivial.\n  Qed.\n\n  Fact times_zero_r x : x \u2297 z = z.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (x\u2297z).\n    rewrite S2, <- distr_l, S1; trivial.\n  Qed.\n\n  Notation \"\u2211\" := (msum sum zero).\n\n  Fact sum_0n_scal n k f : \u2211 n (fun i => scal k (f i)) = scal k (\u2211 n f).\n  Proof. apply msum_mscal; auto. Qed.\n\n  Fact scal_times k x y : scal k (x\u2297y) = x\u2297scal k y.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, mscal_0, times_zero_r; auto.\n    + rewrite mscal_S, mscal_S, IHk, distr_l; auto.\n  Qed.\n\n  Fact scal_one_comm k x : scal k o \u2297 x = x \u2297 scal k o.\n  Proof.\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, times_zero_l, times_zero_r; auto.\n    + rewrite mscal_S, distr_l, distr_r; f_equal; auto.\n      rewrite T1, T2; auto.\n  Qed.\n\n  Corollary scal_one k x : scal k x = scal k o \u2297 x.\n  Proof. \n    destruct M_times as [ T1 T2 T3 ].\n    rewrite <- (T2 x) at 1.\n    rewrite scal_times.\n    symmetry; apply scal_one_comm.\n  Qed.\n\n  Fact sum_0n_distr_l b n f : \u2211 n (fun i => b\u2297f i) = b\u2297\u2211 n f.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_r; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_l; auto.\n  Qed.\n\n  Fact sum_0n_distr_r b n f : \u2211 n (fun i => f i\u2297b) = \u2211 n f \u2297 b.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_l; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_r; auto.\n  Qed.\n\n  (*   Newton Binomial theorem for (X,\u2295,z,\u2297,o) where\n          1) (X,\u2295,z) is a cancellative commutative monoid\n          2) (X,\u2297,o) is a monoid\n          3) \u2297 distributes over \u2295 on the left and one the right \n\n        cancellative could be weakened into z is left and right\n        absorbing for \u2297, ie a\u2297z = z\u2297a = z \n\n   *)\n\n  Theorem binomial_Newton n a b :\n        a \u2297 b = b \u2297 a\n     -> expo n (a \u2295 b) = \u2211 (S n) (fun i => scal (binomial n i) (expo (n - i) a \u2297 expo i b)).\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    intros Hab; induction n as [ | n IHn ].\n    + rewrite mscal_0, msum_S, msum_0; simpl.\n      rewrite mscal_0, mscal_0, mscal_1; auto.\n      rewrite S2, T1; auto.\n    + rewrite msum_S with (n := S n), binomial_n0, mscal_1; auto.\n      rewrite mscal_0, Nat.sub_0_r; auto.\n      rewrite T2.\n      rewrite msum_ext with (g := fun i => b \u2297 scal (binomial n i) (expo (n-i) a \u2297 expo i b)\n                                         \u2295 a \u2297 scal (binomial n (S i)) (expo (n-S i) a \u2297 expo (S i) b)).\n      2: { intros; rewrite binomial_SS, mscal_plus; auto.\n           replace (S n - S i) with (n-i) by lia; f_equal.\n           * rewrite mscal_S. \n             do 3 rewrite scal_times.\n             do 2 rewrite T3; f_equal.\n             apply mscal_comm; auto.\n           * destruct (le_lt_dec n i).\n             + rewrite binomial_gt; try lia.\n               do 2 rewrite mscal_0.\n               rewrite times_zero_r; auto.\n             + replace (n - i) with (S (n - S i)) by lia.\n               rewrite mscal_S.\n               repeat rewrite scal_times.\n               repeat rewrite T3; auto. }\n      rewrite msum_sum; auto.\n      do 2 rewrite sum_0n_distr_l.\n      rewrite <- IHn.\n      rewrite msum_plus1, binomial_gt; auto.\n      rewrite mscal_0, S2.\n      generalize (msum_S sum z n (fun i => scal (binomial n i) (expo (n-i) a \u2297 expo i b))); intros H.\n      rewrite Nat.sub_0_r, binomial_n0, mscal_1, mscal_0, T2 in H; auto.\n      rewrite S3, (sum_comm (expo _ _)), <- S3.\n      rewrite mscal_S with (x :=a), <- distr_l, <- H, <- IHn.\n      rewrite mscal_S, distr_r.\n      apply sum_comm.\n  Qed.\n\nEnd binomial_Newton.\n\nSection Newton_nat.\n\n  Notation power := (mscal mult 1).\n  Notation \"\u2211\" := (msum plus 0).\n\n  Fact sum_fold_map n f : \u2211 n f = fold_right plus 0 (map f (list_an 0 n)).\n  Proof. apply msum_fold_map. Qed.\n\n  Fact power_0 x : power 0 x = 1.\n  Proof. apply mscal_0. Qed.\n\n  Fact power_S n x : power (S n) x = x * power n x.\n  Proof. apply mscal_S. Qed.\n\n  Fact power_1 x : power 1 x = x.\n  Proof. apply mscal_1, Nat_mult_monoid. Qed.\n\n  Fact power_of_0 n : 0 < n -> power n 0 = 0.\n  Proof. destruct n; try lia; rewrite power_S; auto. Qed.\n\n  Fact power_of_1 n : power n 1 = 1.\n  Proof. rewrite mscal_of_unit; auto. Qed.\n\n  Fact power_plus p a b : power (a+b) p = power a p * power b p.\n  Proof. apply mscal_plus, Nat_mult_monoid. Qed.\n\n  Fact power_mult p a b : power (a*b) p = power a (power b p).\n  Proof. apply mscal_mult; auto. Qed.\n  \n  Fact power_ge_1 k p : p <> 0 -> 1 <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + rewrite power_S.\n      apply (mult_le_compat 1 _ 1); lia.\n  Qed.\n\n  Fact power2_gt_0 n : 0 < power n 2.\n  Proof. apply power_ge_1; discriminate. Qed.\n\n  Fact power_sinc k p : 2 <= p -> power k p < power (S k) p.\n  Proof.\n    intros Hp; rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power k p)) at 1.\n    apply mult_lt_compat_r; try lia.\n    apply power_ge_1; lia.\n  Qed.\n\n  Fact power_ge_n k p : 2 <= p -> k <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + apply le_lt_trans with (2 := power_sinc _ Hp); auto.\n  Qed.\n\n  Fact power_mono_l p q x : 1 <= x -> p <= q -> power p x <= power q x.\n  Proof.\n    intros Hx.\n    induction 1 as [ | q H IH ]; auto.\n    apply le_trans with (1 := IH).\n    rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power _ _)) at 1.\n    apply mult_le_compat; auto.\n  Qed.\n\n  Definition power_mono := power_mono_l.\n  \n  Fact power_smono_l p q x : 2 <= x -> p < q -> power p x < power q x.\n  Proof.\n    intros H1 H2.\n    apply lt_le_trans with (1 := power_sinc _ H1).\n    apply power_mono_l; lia.\n  Qed.\n\n  Fact power_mono_r n p q : p <= q -> power n p <= power n q.\n  Proof.\n    intros H.\n    induction n as [ | n IHn ].\n    + do 2 rewrite power_0; auto.\n    + do 2 rewrite power_S; apply mult_le_compat; auto.\n  Qed. \n\n  Fact power_0_inv p n : power p n = 0 <-> n = 0 /\\ 0 < p.\n  Proof.\n    induction p as [ | p IHp ].\n    + rewrite power_0; lia.\n    + rewrite power_S; split.\n      * intros H.\n        apply mult_is_O in H.\n        rewrite IHp in H; lia.\n      * intros (?&?); subst; simpl; auto.\n  Qed.\n\n  Fact plus_cancel_l : forall a b c, a + b = a + c -> b = c.\n  Proof. intros; lia. Qed.\n\n  Let plus_cancel_l':= plus_cancel_l.\n\n  Fact sum_0n_scal_l n k f : \u2211 n (fun i => k*f i) = k*\u2211 n f.\n  Proof. \n    apply sum_0n_distr_l with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_scal_r n k f : \u2211 n (fun i => (f i)*k) = (\u2211 n f)*k.\n  Proof. \n    apply sum_0n_distr_r with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_mono n f g : (forall i, i < n -> f i <= g i) -> \u2211 n f <= \u2211 n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g H.\n    + do 2 rewrite msum_0; auto.\n    + do 2 rewrite msum_S; apply plus_le_compat.\n      * apply H; lia.\n      * apply IHn; intros; apply H; lia.\n  Qed.\n\n  Fact sum_0n_le_one n f i : i < n -> f i <= \u2211 n f.\n  Proof.\n    revert f i; induction n as [ | n IHn ]; intros f i H.\n    + lia.\n    + rewrite msum_S.\n      destruct i as [ | i ]; try lia.\n      apply lt_S_n, IHn with (f := fun i => f (S i)) in H.\n      lia.\n  Qed.\n\n  Fact sum_power_lt k n f : k <> 0 -> (forall i, i < n -> f i < k) -> \u2211 n (fun i => f i * power i k) < power n k.\n  Proof.\n    intros Hk.\n    revert f; induction n as [ | n IHn ]; intros f Hf.\n    + rewrite msum_0, power_0; lia.\n    + rewrite msum_S, power_S, power_0, Nat.mul_1_r.\n      apply le_trans with (k+ k * (power n k-1)).\n      * apply (@plus_le_compat (S (f 0))).\n        - apply Hf; lia.\n        - rewrite msum_ext with (g := fun i => k*(f (S i)*power i k)).\n          ++ rewrite sum_0n_distr_l with (one := 1); auto; try (intros; ring).\n             apply mult_le_compat_l.\n             apply le_S_n, le_trans with (power n k); try lia.\n             apply IHn; intros; apply Hf; lia.\n          ++ intros; rewrite power_S; ring.\n      * generalize (power_ge_1 n Hk); intros ?.\n        replace (power n k) with (1+(power n k - 1)) at 2 by lia.\n        rewrite Nat.mul_add_distr_l.\n        apply plus_le_compat; lia.\n  Qed. \n\n  Theorem Newton_nat a b n :\n       power n (a + b) = \u2211 (S n) (fun i => binomial n i * power (n - i) a * power i b).\n  Proof.\n    rewrite binomial_Newton with (1 := Nat_plus_monoid) (4 := Nat_mult_monoid); try (intros; ring); auto.\n    apply msum_ext; intros i Hi.\n    rewrite scal_one with (1 := Nat_plus_monoid) (3 := Nat_mult_monoid); auto; try (intros; ring).\n    rewrite <-mult_assoc; f_equal; auto.\n    generalize (binomial n i); intros k.\n    induction k as [ | k IHk ].\n    + rewrite mscal_0; auto.\n    + rewrite mscal_S, IHk; auto; apply plus_cancel_l.\n  Qed.\n\n  Theorem Newton_nat_S a n :\n       power n (1 + a) = \u2211 (S n) (fun i => binomial n i * power i a).\n  Proof.\n    rewrite Newton_nat.\n    apply msum_ext.\n    intros; rewrite power_of_1; ring.\n  Qed.\n\n  Lemma binomial_le_power n i : binomial n i <= power n 2.\n  Proof.\n    destruct (le_lt_dec i n) as [ Hi | Hi ].\n    + change 2 with (1+1).\n      rewrite Newton_nat_S.\n      eapply le_trans.\n      2:{ apply sum_0n_le_one with (f := fun i => binomial n i * power i 1).\n          apply le_n_S, Hi. }\n      rewrite power_of_1; lia.\n    + rewrite binomial_gt; auto; lia.\n  Qed.\n\n  Corollary binomial_lt_power n i : binomial n i < power (S n) 2.\n  Proof.\n    apply le_lt_trans with (1 := binomial_le_power _ _), power_sinc; auto.\n  Qed.\n\nEnd Newton_nat.\n", "meta": {"author": "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/sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.8019611450790388}}
{"text": "(* week_39b_arithmetic_expressions.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Working version, make sure to download\n   the updated version after class.\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool unfold_tactic List.\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\n(* Source syntax: *)\n\nInductive arithmetic_expression : Type :=\n  | Lit : nat -> arithmetic_expression\n  | Plus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n  | Times : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n  | Minus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression.\n\n(* Exercise 0:\n   Write samples of arithmetic expressions.\n*)\n\nCompute (Times (Lit 5) (Plus (Lit 3) (Lit 4))).\nCompute (Plus (Lit 1) (Lit 2)).\nCompute (Times (Lit 1) (Lit 2)).\nCompute (Plus (Lit 1) (Plus (Lit 2) (Plus (Lit 3) (Lit 4)))).\nCompute (Times (Lit 1) (Times (Lit 2) (Times (Lit 3) (Lit 4)))).\n\n(* ********** *)\n\nDefinition specification_of_interpret (interpret : arithmetic_expression -> nat) :=\n  (forall n : nat,\n     interpret (Lit n) = n)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Plus ae1 ae2) = (interpret ae1) + (interpret ae2))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Times ae1 ae2) = (interpret ae1) * (interpret ae2))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Minus ae1 ae2) = (interpret ae1) - (interpret ae2)).\n\n(* Exercise 1:\n   Write unit tests.\n*)\n\n(* TODO: Lav nogle flere *)\nDefinition unit_test_for_interpret (interpret : arithmetic_expression -> nat) :=\n  (interpret (Lit 5) =n= 5)\n  &&\n  (interpret (Times (Lit 1) (Lit 2)) =n= 2)\n  &&\n  (interpret (Plus (Lit 1) (Plus (Lit 2) (Lit 3))) =n= 6)\n  &&\n  (interpret (Times (Plus (Lit 1) (Lit 2)) (Plus (Lit 2) (Lit 3))) =n= 15)\n  && (interpret (Times (Times (Lit 2) (Lit 3)) (Times (Lit 4) (Lit 5))) =n= 120)\n  .\n\n(* Exercise 2:\n   Define an interpreter as a function\n   that satisfies the specification above\n   and verify that it passes the unit tests.\n*)\n\nFixpoint interpreter ( ae : arithmetic_expression) : nat :=\n  match ae with\n    | Lit n => n\n    | Plus ae1 ae2 => (interpreter ae1) + (interpreter ae2)\n    | Times ae1 ae2 => (interpreter ae1) * (interpreter ae2)\n    | Minus ae1 ae2 => (interpreter ae1) - (interpreter ae2)\n  end.\n\nCompute (interpreter (Times (Lit 7) (Plus (Lit 5) (Lit 6)))).\nCompute unit_test_for_interpret interpreter.\n\nLemma unfold_interpreter_lit :\n  forall n : nat,\n    interpreter (Lit n) = n.\nProof.\n  unfold_tactic interpreter.\nQed.\n\nLemma unfold_interpreter_times :\n  forall a b : arithmetic_expression,\n    interpreter (Times a b) = (interpreter a) * (interpreter b).\nProof.\n  unfold_tactic interpreter.\nQed.\n\nLemma unfold_interpreter_plus : \n  forall a b : arithmetic_expression,\n    interpreter (Plus a b) = (interpreter a) + (interpreter b).\nProof.\n  unfold_tactic interpreter.\nQed.\n\nLemma unfold_interpreter_minus :\n  forall a b : arithmetic_expression,\n    interpreter (Minus a b) = (interpreter a) - (interpreter b).\nProof.\n  unfold_tactic interpreter.\nQed.\n\n  \nLemma interpreter_fits_the_specification_of_interpreter :\n  forall exp : arithmetic_expression,\n    specification_of_interpret interpreter.\nProof.\n  unfold specification_of_interpret.\n  split.\n    \n    intro n.\n    apply (unfold_interpreter_lit n).\n\n    split.\n\n      intros ae1 ae2.\n      apply (unfold_interpreter_plus ae1 ae2).\n      \n      split.\n        intros ae1 ae2.\n        apply (unfold_interpreter_times ae1 ae2).\n\n        intros ae1 ae2.\n        apply (unfold_interpreter_minus ae1 ae2).\n\nQed.\n\n\n(* Byte-code instructions: *)\n\nInductive byte_code_instruction : Type :=\n  | PUSH : nat -> byte_code_instruction\n  | ADD : byte_code_instruction\n  | MUL : byte_code_instruction\n  | SUB : byte_code_instruction.\n\n(* ********** *)\n\n(* Byte-code programs: *)\n\nDefinition byte_code_program := list byte_code_instruction.\n\n(* Data stack: *)\n\nDefinition data_stack := list nat.\n\n(* ********** *)\n\n(* Exercise 3:\n   specify a function\n     execute_byte_code_instruction : instr -> data_stack -> data_stack\n   that executes a byte-code instruction, given a data stack\n   and returns this stack after the instruction is executed.\n\n   * Executing (PUSH n) given s has the effect of pushing n on s.\n\n   * Executing ADD given s has the effect of popping two numbers\n     from s and then pushing the result of adding them.\n\n   * Executing MUL given s has the effect of popping two numbers\n     from s and then pushing the result of multiplying them.\n\n   For now, if the stack underflows, just assume it contains zeroes.\n*)\n\n\n(*\n  Also, execute_byte_code_instruction is not recursive, so make sure to define it with Definition, not with Fixpoint.\n*)\n\n(* TODO: Skal vi \u00e6ndre den m\u00e5de x :: stack virker? *)\nDefinition execute_byte_code_instruction (instruction : byte_code_instruction) ( dstack : data_stack) : data_stack :=\n  match instruction with\n    | PUSH n => n :: dstack\n    | ADD => match dstack with\n               | x :: y :: stack => (plus x y) :: stack\n               | x :: stack => x :: stack\n               | nil => 0 :: nil                                    \n             end\n    | MUL => match dstack with\n               | x :: y :: stack => (mult x y) :: stack\n               | x :: stack => x :: stack\n               | nil => 0 :: nil\n             end                                 \n    | SUB => match dstack with\n               | x :: y :: stack => (minus x y) :: stack\n               | x :: stack => x :: stack\n               | nil => 0 :: nil\n             end                                             \n  end. \n\n\nCompute(execute_byte_code_instruction (PUSH 4) (1 :: 2 :: nil)).\nCompute(execute_byte_code_instruction (MUL) (nil)).\nCompute(execute_byte_code_instruction (MUL) (3 :: 2 :: nil)).\nCompute(execute_byte_code_instruction (MUL) (1 :: nil)).\n\n\n\n(* ********** *)\n\n(* Exercise 4:\n   Define a function\n     execute_byte_code_program : byte_code_program -> data_stack -> data_stack\n   that executes a given byte-code program on a given data stack,\n   and returns this stack after the program is executed.\n*)\n\nFixpoint execute_byte_code_program (program : byte_code_program) (dstack : data_stack) : data_stack :=\n  match program with\n    | nil => dstack\n    | p1 :: byte_codes => execute_byte_code_program byte_codes (execute_byte_code_instruction p1 dstack)\n  end.\n\nCompute(execute_byte_code_program ((PUSH 4) :: (PUSH 3) :: (MUL) :: nil) (0 :: nil)).\n\n(* ********** *)\n\n(* Exercise 5:\n   Prove that for all programs p1, p2 and data stacks s,\n   executing (p1 ++ p2) with s\n   gives the same result as\n   (1) executing p1 with s, and then\n   (2) executing p2 with the resulting stack.\n\n  DOING INDUCTION ON P1\n*)\n\nLemma unfold_byte_code_program_bc : \n  forall s : data_stack,\n    execute_byte_code_program nil s = s.\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\nLemma unfold_byte_code_program_ic :\n  forall (p1 : byte_code_instruction) (program : byte_code_program) (s : data_stack),\n    execute_byte_code_program (p1 :: program) s = \n    execute_byte_code_program program (execute_byte_code_instruction p1 s).\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\nTheorem about_list_of_instructions : \n  forall ( p1 p2 : byte_code_program) (s : data_stack),\n    execute_byte_code_program p2 (execute_byte_code_program p1 s) =\n    execute_byte_code_program  (p1 ++ p2) s.\nProof.         \n  intros p1 p2.\n  induction p1 as [ | p1' p1s' IHsp1'].\n\n  intro s.\n  unfold app.\n  rewrite -> unfold_byte_code_program_bc.\n  reflexivity.\n\n  intro s.\n  rewrite -> unfold_byte_code_program_ic.\n  rewrite <- (app_comm_cons).\n  rewrite -> (unfold_byte_code_program_ic).\n  rewrite -> (IHsp1' (execute_byte_code_instruction p1' s)).\n  reflexivity.\nQed.\n  \n\n(* ********** *)\n\nDefinition specification_of_compile (compile : arithmetic_expression -> byte_code_program) :=\n  (forall n : nat,\n     compile (Lit n) = PUSH n :: nil)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Plus ae1 ae2) = (compile ae2) ++ (compile ae1) ++ (ADD :: nil))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Times ae1 ae2) = (compile ae2) ++ (compile ae1)++ (MUL :: nil))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Minus ae1 ae2) = (compile ae2) ++ (compile ae1) ++ (SUB :: nil)).\n\n(* Exercise 6:\n   Define a compiler as a function\n   that satisfies the specification above\n   and uses list concatenation, i.e., ++.\n*)\n\nFixpoint compile_plusplus (ae : arithmetic_expression) : byte_code_program :=\n  match ae with\n    | Lit n => (PUSH n) :: nil\n    | Plus ae1 ae2 => (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (ADD :: nil)\n    | Times ae1 ae2 => (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (MUL :: nil)\n    | Minus ae1 ae2 => (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (SUB :: nil)\n  end.\n\nLemma unfold_compile_plusplus_lit :\n  forall n : nat,\n    compile_plusplus (Lit n) = (PUSH n) :: nil.\nProof.\n  unfold_tactic compile_plusplus.\nQed.\n\nLemma unfold_compile_plusplus_plus :\n  forall ae1 ae2 : arithmetic_expression,\n    compile_plusplus (Plus ae1 ae2) = (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (ADD :: nil).\nProof.\n  unfold_tactic compile_plusplus.\nQed.\n\nLemma unfold_compile_plusplus_times :\n  forall ae1 ae2 : arithmetic_expression,\n    compile_plusplus (Times ae1 ae2) = (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (MUL :: nil).\nProof.\n  unfold_tactic compile_plusplus.\nQed.\n\nLemma unfold_compile_plusplus_minus :\n  forall ae1 ae2 : arithmetic_expression,\n    compile_plusplus (Minus ae1 ae2) = (compile_plusplus ae2) ++ (compile_plusplus ae1) ++ (SUB :: nil).\nProof.\n  unfold_tactic compile_plusplus.\nQed.\n\nTheorem compile_plusplus_fits_the_specification_of_compile :\n  forall ae : arithmetic_expression,\n    specification_of_compile compile_plusplus.\nProof.\n  unfold specification_of_compile.\n  split.\n    intro n.\n    apply (unfold_compile_plusplus_lit).\n    \n    split.\n      intros ae1 ae2.\n      apply (unfold_compile_plusplus_plus).\n\n      split.\n        intros ae1 ae2.\n        apply (unfold_compile_plusplus_times).\n\n        intros ae1 ae2.\n        apply (unfold_compile_plusplus_minus).\nQed.\n\n(* Exercise 7:\n   Write a compiler as a function with an accumulator\n   that does not use ++ but :: instead,\n   and prove it equivalent to the compiler of Exercise 6.\n*)\n\nFixpoint compile_acc (ae : arithmetic_expression) (acc : byte_code_program) : byte_code_program :=\n  match ae with\n    | Lit n => (PUSH n) :: acc\n    | Plus ae1 ae2 => (compile_acc ae2 (compile_acc ae1 (ADD :: acc)))\n    | Times ae1 ae2 => (compile_acc ae2 (compile_acc ae1 (MUL :: acc)))\n    | Minus ae1 ae2 => (compile_acc ae2 (compile_acc ae1 (SUB :: acc)))\n  end.\n\nCompute(compile_acc (Plus (Lit 5) (Lit 3)) nil).\n\nLemma unfold_compile_acc_lit :\n  forall (n : nat) (acc : byte_code_program),\n    compile_acc (Lit n) acc = (PUSH n) :: acc.\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma unfold_compile_acc_plus :\n  forall (ae1 ae2 : arithmetic_expression) (acc : byte_code_program),\n    compile_acc (Plus ae1 ae2) acc = compile_acc ae2 (compile_acc ae1 (ADD :: acc)).\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma unfold_compile_acc_times :\n  forall (ae1 ae2 : arithmetic_expression) (acc : byte_code_program),\n    compile_acc (Times ae1 ae2) acc = compile_acc ae2 (compile_acc ae1 (MUL :: acc)).\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma unfold_compile_acc_minus :\n  forall (ae1 ae2 : arithmetic_expression) (acc : byte_code_program),\n    compile_acc (Minus ae1 ae2) acc = compile_acc ae2 (compile_acc ae1 (SUB :: acc)).\nProof.\n  unfold_tactic compile_acc.\nQed.\n\n\n\nCompute(execute_byte_code_program(compile_plusplus (Minus (Lit 5) (Lit 3))) nil).\n\nCompute(execute_byte_code_program(compile_plusplus (Minus (Lit 3) (Lit 5))) nil).\n\nCompute(execute_byte_code_program(compile_acc (Minus (Lit 5) (Lit 3)) nil) nil).\n\nCompute(execute_byte_code_program(compile_acc (Minus (Lit 3) (Lit 5)) nil) nil).\n\n\n\n(* EUREKA *)\n\nLemma about_compile_acc :\n  forall (ae : arithmetic_expression) (acc bcp : byte_code_program),\n    (compile_acc ae acc) ++ bcp = compile_acc ae (acc ++ bcp).\nProof.\n  intro ae.\n  induction ae as [ n | ae1 IHa1 ae2 IHa2 | ae1' IHa1' ae2' IHa2' | ae1'' IHa1'' ae2'' IHa2'' ].\n\n  intros acc bcp.\n  rewrite ->2 (unfold_compile_acc_lit).\n  Check(app_comm_cons).\n  rewrite <- (app_comm_cons).\n  reflexivity.\n\n  intros acc bcp.\n  rewrite ->2 (unfold_compile_acc_plus).\n  rewrite -> (app_comm_cons).\n  rewrite <- (IHa1 (ADD :: acc) bcp).\n  rewrite <- (IHa2). \n  reflexivity.\n  \n  intros acc bcp.\n  rewrite ->2 (unfold_compile_acc_times).\n  rewrite -> (app_comm_cons).\n  rewrite <- (IHa1' (MUL :: acc) bcp).\n  rewrite <- (IHa2').\n  reflexivity.\n\n  intros acc bcp.\n  rewrite ->2 (unfold_compile_acc_minus).\n  rewrite -> (app_comm_cons).\n  rewrite <- (IHa1'' (SUB :: acc) bcp).\n  rewrite <- (IHa2'').\n  reflexivity.\nQed.\n\nLemma compile_plusplus_fits_compile_acc :\n  forall (ae : arithmetic_expression) (acc : byte_code_program),\n    compile_acc ae acc = (compile_plusplus ae) ++ acc.\nProof.\n  intro ae.\n  induction ae as [ n | ae1 IHa1 ae2 IHa2 | ae1' IHa1' ae2' IHa2' | ae1'' IHa1'' ae2'' IHa2''].\n  intro acc.\n  rewrite -> (unfold_compile_acc_lit).\n  rewrite -> (unfold_compile_plusplus_lit).\n  unfold app.\n  reflexivity.\n\n  intro acc.\n  rewrite -> (unfold_compile_acc_plus).\n  rewrite -> (unfold_compile_plusplus_plus).\n  rewrite <- (IHa1).\n  rewrite <- (IHa2).\n  rewrite ->2 (about_compile_acc).\n  unfold app.\n  reflexivity.\n\n  intro acc.\n  rewrite -> (unfold_compile_acc_times).\n  rewrite -> (unfold_compile_plusplus_times).\n  rewrite <- (IHa1').\n  rewrite <- (IHa2').\n  rewrite ->2 (about_compile_acc).\n  unfold app.\n  reflexivity.\n\n  intro acc.\n  rewrite -> (unfold_compile_acc_minus).\n  rewrite -> (unfold_compile_plusplus_minus).\n  rewrite <- (IHa1'').\n  rewrite <- (IHa2'').\n  rewrite ->2 (about_compile_acc).\n  unfold app.\n  reflexivity.\n\nQed.\n\n\n(* ********** *)\n\n(* Exercise 8:\n   Prove that interpreting an arithmetic expression gives the same result\n   as first compiling it and then executing the compiled program\n   over an empty data stack.\n  INDUCTION ON THE AE\n*)\n\n\n\nDefinition check_stack (stack : data_stack) : nat :=\n  match stack with\n    | x :: nil => x\n    | _ => 0\n  end.\n\nCheck(specification_of_compile).\nCheck(specification_of_interpret).\n\n\n\nLemma executing_compile_is_the_same_as_interpreting :\n  forall (ae : arithmetic_expression),\n    interpreter ae = check_stack ( execute_byte_code_program (compile_acc ae nil) nil).\nProof.\n  intro ae.\n  induction ae as [ a | ae1 IHa1 ae2 IHa2 | ae1' IHa1' ae2' IHa2' | ae1'' IHa1'' ae2'' IHa2''].\n\n  rewrite -> (unfold_interpreter_lit).\n  rewrite -> (unfold_compile_acc_lit).\n  rewrite -> (unfold_byte_code_program_ic).\n  rewrite -> (unfold_byte_code_program_bc).\n  unfold execute_byte_code_instruction.\n  unfold check_stack.\n  reflexivity.\n\n  rewrite -> (unfold_interpreter_plus).\n  rewrite -> (unfold_compile_acc_plus).\n\n  rewrite -> (IHa1).\n  rewrite -> (IHa2).\n  rewrite ->4 (compile_plusplus_fits_compile_acc).\n  rewrite <- (about_list_of_instructions).\n  SearchAbout(app).\n  rewrite -> (app_assoc).\n  rewrite -> (about_list_of_instructions).\n  rewrite <-3 (compile_plusplus_fits_compile_acc).\n\n  rewrite -> (unfold_byte_code_program_ic).\n\n\n(* ********** *)\n\n(* Exercise 9:\n   Write a Magritte-style execution function for a byte-code program\n   that does not operate on natural numbers but on syntactic representations\n   of natural numbers:\n\n   Definition data_stack := list arithmetic_expression.\n\n   * Executing (PUSH n) given s has the effect of pushing (Lit n) on s.\n\n   * Executing ADD given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their addition.\n\n   * Executing MUL given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their multiplication.\n\n   Again, for this week's exercise,\n   assume there are enough arithmetic expressions on the data stack.\n   If that is not the case, just pad it up with syntactic representations\n   of zero.\n\n*)\n\n(* Exercise 10:\n   Prove that the Magrite-style execution function from Exercise 9\n   implements a decompiler that is the left inverse of the compiler\n   of Exercise 6.\n*)\n\n(* ********** *)\n\n(* end of week_39b_arithmetic_expressions.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_39b_arithmetic_expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.80195628821866}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nRequire Import Logic.\nRequire Import Basics.\nRequire Import Lists.List.\n\nImport ListNotations.\n(* ################################################################# *)\n(** * Inductively Defined Propositions *)\n\n(** In the [Logic] chapter we looked at several ways of writing\n    propositions, including conjunction, disjunction, and quantifiers.\n    In this chapter, we bring a new tool into the mix: _inductive\n    definitions_.\n\n    Recall that we have seen two ways of stating that a number [n] is\n    even: We can say (1) [evenb n = true], or (2) [exists k, n =\n    double k].  Yet another possibility is to say that [n] is even if\n    we can establish its evenness from the following rules:\n\n       - Rule [ev_0]: The number [0] is even.\n       - Rule [ev_SS]: If [n] is even, then [S (S n)] is even.\n\n    To illustrate how this new definition of evenness works, let's use\n    its rules to show that [4] is even. By rule [ev_SS], it suffices\n    to show that [2] is even. This, in turn, is again guaranteed by\n    rule [ev_SS], as long as we can show that [0] is even. But this\n    last fact follows directly from the [ev_0] rule. *)\n\n(** We will see many definitions like this one during the rest\n    of the course.  For purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n\n                              ------------                        (ev_0)\n                                 ev 0\n\n                                  ev n\n                             --------------                      (ev_SS)\n                              ev (S (S n))\n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [ev_SS] says that, if [n]\n    satisfies [ev], then [S (S n)] also does.  If a rule has no\n    premises above the line, then its conclusion holds\n    unconditionally.\n\n    We can represent a proof using these rules by combining rule\n    applications into a _proof tree_. Here's how we might transcribe\n    the above proof that [4] is even: *)\n(**\n\n                ------  (ev_0)\n                 ev 0\n                ------ (ev_SS)\n                 ev 2\n                ------ (ev_SS)\n                 ev 4\n*)\n\n(** Why call this a \"tree\" (rather than a \"stack\", for example)?\n    Because, in general, inference rules can have multiple premises.\n    We will see examples of this below. *)\n\n(** Putting all of this together, we can translate the definition of\n    evenness into a formal Coq definition using an [Inductive]\n    declaration, where each constructor corresponds to an inference\n    rule: *)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n(** This definition is different in one crucial respect from\n    previous uses of [Inductive]: its result is not a [Type], but\n    rather a function from [nat] to [Prop] -- that is, a property of\n    numbers.  Note that we've already seen other inductive definitions\n    that result in functions, such as [list], whose type is [Type ->\n    Type].  What is new here is that, because the [nat] argument of\n    [ev] appears _unnamed_, to the _right_ of the colon, it is allowed\n    to take different values in the types of different constructors:\n    [0] in the type of [ev_0] and [S (S n)] in the type of [ev_SS].\n\n    In contrast, the definition of [list] names the [X] parameter\n    _globally_, to the _left_ of the colon, forcing the result of\n    [nil] and [cons] to be the same ([list X]).  Had we tried to bring\n    [nat] to the left in defining [ev], we would have seen an error: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n(** (\"Parameter\" here is Coq jargon for an argument on the left of the\n    colon in an [Inductive] definition; \"index\" is used to refer to\n    arguments on the right of the colon.) *)\n\n(** We can think of the definition of [ev] as defining a Coq property\n    [ev : nat -> Prop], together with theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Such \"constructor\n    theorems\" have the same status as proven theorems.  In particular,\n    we can use Coq's [apply] tactic with the rule names to prove [ev]\n    for particular numbers... *)\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** ... or we can use function application syntax: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** We can also prove theorems that have hypotheses involving [ev]. *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\nDefinition double (n : nat) : nat := n * 2.\n\n(** More generally, we can show that any number multiplied by 2 is even: *)\n\n(** **** Exercise: 1 star (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Using Evidence in Proofs *)\n\n(** Besides _constructing_ evidence that numbers are even, we can also\n    _reason about_ such evidence.\n\n    Introducing [ev] with an [Inductive] declaration tells Coq not\n    only that the constructors [ev_0] and [ev_SS] are valid ways to\n    build evidence that some number is even, but also that these two\n    constructors are the _only_ ways to build evidence that numbers\n    are even (in the sense of [ev]). *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [ev n], then we know that [E] must have one of two shapes:\n\n      - [E] is [ev_0] (and [n] is [O]), or\n      - [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is\n        evidence for [ev n']). *)\n\n(** This suggests that it should be possible to analyze a hypothesis\n    of the form [ev n] much as we do inductively defined data\n    structures; in particular, it should be possible to argue by\n    _induction_ and _case analysis_ on such evidence.  Let's look at a\n    few examples to see what this means in practice. *)\n\n(* ================================================================= *)\n(** ** Inversion on Evidence *)\n\n(** Subtracting two from an even number yields another even number.\n    We can easily prove this claim with the techniques that we've\n    already seen, provided that we phrase it in the right way.  If we\n    state it in terms of [evenb], for instance, we can proceed by a\n    simple case analysis on [n]: *)\n\nTheorem evenb_minus2: forall n,\n  evenb n = true -> evenb (pred (pred n)) = true.\nProof.\n  intros [ | [ | n' ] ].\n  - (* n = 0 *) reflexivity.\n  - (* n = 1; contradiction *) intros H. inversion H.\n  - (* n = n' + 2 *) simpl. intros H. apply H.\nQed.\n\n(** We can state the same claim in terms of [ev], but this quickly\n    leads us to an obstacle: Since [ev] is defined inductively --\n    rather than as a function -- Coq doesn't know how to simplify a\n    goal involving [ev n] after case analysis on [n].  As a\n    consequence, the same proof strategy fails: *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros [ | [ | n' ] ].\n  - (* n = 0 *) simpl. intros _. apply ev_0.\n  - (* n = 1; we're stuck! *) simpl.\nAbort.\n\n(** The solution is to perform case analysis on the evidence that [ev\n    n] _directly_. By the definition of [ev], there are two cases to\n    consider:\n\n    - If that evidence is of the form [ev_0], we know that [n = 0].\n      Therefore, it suffices to show that [ev (pred (pred 0))] holds.\n      By the definition of [pred], this is equivalent to showing that\n      [ev 0] holds, which directly follows from [ev_0].\n\n    - Otherwise, that evidence must have the form [ev_SS n' E'], where\n      [n = S (S n')] and [E'] is evidence for [ev n'].  We must then\n      show that [ev (pred (pred (S (S n'))))] holds, which, after\n      simplification, follows directly from [E']. *)\n\n(** We can invoke this kind of argument in Coq using the [inversion]\n    tactic.  Besides allowing us to reason about equalities involving\n    constructors, [inversion] provides a case-analysis principle for\n    inductively defined propositions.  When used in this way, its\n    syntax is similar to [destruct]: We pass it a list of identifiers\n    separated by [|] characters to name the arguments to each of the\n    possible constructors.  For instance: *)\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** Note that, in this particular case, it is also possible to replace\n    [inversion] by [destruct]: *)\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** The difference between the two forms is that [inversion] is more\n    convenient when used on a hypothesis that consists of an inductive\n    property applied to a complex expression (as opposed to a single\n    variable).  Here's is a concrete example.  Suppose that we wanted\n    to prove the following variation of [ev_minus2]: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\n\n(** Intuitively, we know that evidence for the hypothesis cannot\n    consist just of the [ev_0] constructor, since [O] and [S] are\n    different constructors of the type [nat]; hence, [ev_SS] is the\n    only case that applies.  Unfortunately, [destruct] is not smart\n    enough to realize this, and it still generates two subgoals.  Even\n    worse, in doing so, it keeps the final goal unchanged, failing to\n    provide any useful information for completing the proof.  *)\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n    replacing all occurrences of the property argument by the values\n    that correspond to each constructor.  This is enough in the case\n    of [ev_minus2'] because that argument, [n], is mentioned directly\n    in the final goal. However, it doesn't help in the case of\n    [evSS_ev] since the term that gets replaced ([S (S n)]) is not\n    mentioned anywhere. *)\n\n(** The [inversion] tactic, on the other hand, can detect (1) that the\n    first case does not apply, and (2) that the [n'] that appears on\n    the [ev_SS] case must be the same as [n].  This allows us to\n    complete the proof: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\n(** By using [inversion], we can also apply the principle of explosion\n    to \"obviously contradictory\" hypotheses involving inductive\n    properties. For example: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(** **** Exercise: 1 star (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The way we've used [inversion] here may seem a bit\n    mysterious at first.  Until now, we've only used [inversion] on\n    equality propositions, to utilize injectivity of constructors or\n    to discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence for\n    inductively defined propositions.\n\n    Here's how [inversion] works in general.  Suppose the name [I]\n    refers to an assumption [P] in the current context, where [P] has\n    been defined by an [Inductive] declaration.  Then, for each of the\n    constructors of [P], [inversion I] generates a subgoal in which\n    [I] has been replaced by the exact, specific conditions under\n    which this constructor could have been used to prove [P].  Some of\n    these subgoals will be self-contradictory; [inversion] throws\n    these away.  The ones that are left represent the cases that must\n    be proved to establish the original goal.  For those, [inversion]\n    adds all equations into the proof context that must hold of the\n    arguments given to [P] (e.g., [S (S n') = n] in the proof of\n    [evSS_ev]). *)\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** The [ev_double] exercise above shows that our new notion of\n    evenness is implied by the two earlier ones (since, by\n    [even_bool_prop], we already know that those are equivalent to\n    each other). To show that all three coincide, we just need the\n    following lemma: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n\n(** We could try to proceed by case analysis or induction on [n].  But\n    since [ev] is mentioned in a premise, this strategy would probably\n    lead to a dead end, as in the previous section.  Thus, it seems\n    better to first try inversion on the evidence for [ev].  Indeed,\n    the first case can be solved trivially. *)\n\n  intros n E. inversion E as [| n' E'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    k, S (S n') = double k], but the only available assumption is\n    [E'], which states that [ev n'] holds.  Since this isn't directly\n    useful, it seems that we are stuck and that performing case\n    analysis on [E] was a waste of time.\n\n    If we look more closely at our second goal, however, we can see\n    that something interesting happened: By performing case analysis\n    on [E], we were able to reduce the original result to an similar\n    one that involves a _different_ piece of evidence for [ev]: [E'].\n    More formally, we can finish our proof by showing that\n\n        exists k', n' = double k',\n\n    which is the same as the original statement, but with [n'] instead\n    of [n].  Indeed, it is not difficult to convince Coq that this\n    intermediate result suffices. *)\n\n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k').\n      reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\n\n(** If this looks familiar, it is no coincidence: We've encountered\n    similar problems in the [Induction] chapter, when trying to use\n    case analysis to prove results that required induction.  And once\n    again the solution is... induction!\n\n    The behavior of [induction] on evidence is the same as its\n    behavior on data: It causes Coq to generate one subgoal for each\n    constructor that could have used to build that evidence, while\n    providing an induction hypotheses for each recursive occurrence of\n    the property in question.\n\n    Let's try our current lemma again: *)\n\nAbort.\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds to\n    [E'], the single recursive occurrence of [ev] in its own\n    definition.  Since [E'] mentions [n'], the induction hypothesis\n    talks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n    evenness now follows. *)\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique when studying the semantics of programming\n    languages, where many properties of interest are defined\n    inductively.  The following exercises provide simple examples of\n    this technique, to help you familiarize yourself with it. *)\n\n(** **** Exercise: 2 stars (ev_sum)  *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (ev_alternate)  *)\n(** In general, there may be multiple ways of defining a\n    property inductively.  For example, here's a (slightly contrived)\n    alternative definition for [ev]: *)\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\n(** Prove that this definition is logically equivalent to\n    the old one. *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev)  *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\n(** This exercise just requires applying existing lemmas.  No\n    induction or even case analysis is needed, though some of the\n    rewriting may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [ev])\n    can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] above. We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) ->\n    2+2=5].) *)\n\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars, recommended (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* FILL IN HERE *) Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: This theorem can easily be proved without using [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nModule R.\n\n(** **** Exercise: 3 stars, recommended (R_provability2)  *)\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0\n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** The relation [R] above actually encodes a familiar function.\n    Figure out which function; then state and prove this equivalence\n    in Coq? *)\n\nDefinition fR : nat -> nat -> nat \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n\n      [1;2;3]\n\n    is a subsequence of each of the lists\n\n      [1;2;3]\n      [1;1;1;2;2;3]\n      [1;2;7;3]\n      [5;6;1;9;9;2;7;3;8]\n\n    but it is _not_ a subsequence of any of the lists\n\n      [1;2]\n      [1;3]\n      [5;6;2;1;7;3;8].\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove [subseq_refl] that subsequence is reflexive, that is,\n      any list is a subsequence of itself.\n\n    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n      if [l1] is a subsequence of [l2], then [l1] is also a subsequence\n      of [l2 ++ l3].\n\n    - (Optional, harder) Prove [subseq_trans] that subsequence is\n      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n      is a subsequence of [l3], then [l1] is a subsequence of [l3].\n      Hint: choose your induction carefully! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability)  *)\n(** Suppose we give Coq the following definition:\n\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n\n    Which of the following propositions are provable?\n\n    - [R 2 [1;0]]\n    - [R 1 [1;2;1;0]]\n    - [R 6 [3;2;1;0]]  *)\n\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Case Study: Regular Expressions *)\n\n(** The [ev] property provides a simple example for illustrating\n    inductive definitions and the basic techniques for reasoning about\n    them, but it is not terribly exciting -- after all, it is\n    equivalent to the two non-inductive of evenness that we had\n    already seen, and does not seem to offer any concrete benefit over\n    them.  To give a better sense of the power of inductive\n    definitions, we now show how to use them to model a classic\n    concept in computer science: _regular expressions_. \n\n    Regular expressions are a simple language for describing strings,\n    defined as elements of the following inductive type.  (The names\n    of the constructors should become clear once we explain their\n    meaning below.)  *)\n\nInductive reg_exp (T : Type) : Type :=\n| EmptySet : reg_exp T\n| EmptyStr : reg_exp T\n| Char : T -> reg_exp T\n| App : reg_exp T -> reg_exp T -> reg_exp T\n| Union : reg_exp T -> reg_exp T -> reg_exp T\n| Star : reg_exp T -> reg_exp T.\n\nArguments EmptySet {T}.\nArguments EmptyStr {T}.\nArguments Char {T} _.\nArguments App {T} _ _.\nArguments Union {T} _ _.\nArguments Star {T} _.\n\n(** Note that this definition is _polymorphic_: Regular expressions in\n    [reg_exp T] describe strings with characters drawn from [T] --\n    that is, lists of elements of [T].  (We depart slightly from\n    standard practice in that we do not require the type [T] to be\n    finite.  This results in a somewhat different theory of regular\n    expressions, but the difference is not significant for our\n    purposes.)\n\n    We connect regular expressions and strings via the following\n    rules, which define when a regular expression _matches_ some\n    string:\n\n    - The expression [EmptySet] does not match any string.\n\n    - The expression [EmptyStr] matches the empty string [[]].\n\n    - The expression [Char x] matches the one-character string [[x]].\n\n    - If [re1] matches [s1], and [re2] matches [s2], then [App re1\n      re2] matches [s1 ++ s2].\n\n    - If at least one of [re1] and [re2] matches [s], then [Union re1\n      re2] matches [s].\n\n    - Finally, if we can write some string [s] as the concatenation of\n      a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n      expression [re] matches each one of the strings [s_i], then\n      [Star re] matches [s].  (As a special case, the sequence of\n      strings may be empty, so [Star re] always matches the empty\n      string [[]] no matter what [re] is.) *)\n\n(** We can easily translate this informal definition into an\n    [Inductive] one as follows: *)\n\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n| MEmpty : exp_match nil EmptyStr\n| MChar : forall x, exp_match [x] (Char x)\n| MApp : forall s1 re1 s2 re2,\n           exp_match s1 re1 ->\n           exp_match s2 re2 ->\n           exp_match (s1 ++ s2) (App re1 re2)\n| MUnionL : forall s1 re1 re2,\n              exp_match s1 re1 ->\n              exp_match s1 (Union re1 re2)\n| MUnionR : forall re1 s2 re2,\n              exp_match s2 re2 ->\n              exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n               exp_match s1 re ->\n               exp_match s2 (Star re) ->\n               exp_match (s1 ++ s2) (Star re).\n\n(** Once again, for readability, we can also display this definition\n    using inference-rule notation.  At the same time, let's introduce\n    a more readable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the informal\n    ones that we gave at the beginning of the section.  First, we\n    don't need to include a rule explicitly stating that no string\n    matches [EmptySet]; we just don't happen to include any rule that\n    would have the effect of some string matching\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Furthermore, the informal rules for [Union] and [Star] correspond\n    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n    [MStarApp].  The result is logically equivalent to the original\n    rules, but more convenient to use in Coq, since the recursive\n    occurrences of [exp_match] are given as direct arguments to the\n    constructors, making it easier to perform induction on evidence.\n    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n    to prove that the constructors given in the inductive declaration\n    and the ones that would arise from a more literal transcription of\n    the informal rules are indeed equivalent.) *)\n\n(** Let's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the strings [[1]]\n    and [[2]] directly.  Since the goal mentions [[1; 2]] instead of\n    [[1] ++ [2]], Coq wouldn't be able to figure out how to split the\n    string on its own.)\n\n    Using [inversion], we can also show that certain strings do _not_\n    match a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** We can define helper functions to help write down regular\n    expressions. The [reg_exp_of_list] function constructs a regular\n    expression that matches exactly the list that it receives as an\n    argument: *)\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n  match l with\n  | [] => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  simpl. apply (MApp [1]).\n  { apply MChar. }\n  apply (MApp [2]).\n  { apply MChar. }\n  apply (MApp [3]).\n  { apply MChar. }\n  apply MEmpty.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n    the following lemma shows that every string [s] that matches [re]\n    also matches [Star re]. *)\n\nLemma MStar1 :\n  forall T s (re : reg_exp T) ,\n    s =~ re ->\n    s =~ Star re.\nProof.\n  intros T s re H.\n  rewrite <- (app_nil_r _ s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n(** (Note the use of [app_nil_r] to change the goal of the theorem to\n    exactly the same shape expected by [MStarApp].) *)\n\n(** **** Exercise: 3 stars (exp_match_ex1)  *)\n(** The following lemmas show that the informal matching rules given\n    at the beginning of the chapter can be obtained from the formal\n    inductive definition. *)\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars (reg_exp_of_list)  *)\n(** Prove that [reg_exp_of_list] satisfies the following\n    specification: *)\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n    structure, we might expect that proofs involving regular\n    expressions will often require induction on evidence.  For\n    example, suppose that we wanted to prove the following intuitive\n    result: If a regular expression [re] matches some string [s], then\n    all elements of [s] must occur somewhere in [re].  To state this\n    theorem, we first define a function [re_chars] that lists all\n    characters that occur in a regular expression: *)\n\nFixpoint re_chars {T} (re : reg_exp T) : list T :=\n  match re with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App re1 re2 => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re => re_chars re\n  end.\n\n(** We can then phrase our theorem as follows: *)\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp T) (x : T),\n  s =~ re ->\n  In x s ->\n  In x (re_chars re).\nProof.\n  intros T s re x Hmatch Hin.\n  induction Hmatch\n    as [\n        |x'\n        |s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2 re2 Hmatch IH\n        |re|s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. rewrite in_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      left. apply (IH1 Hin).\n    + (* In x s2 *)\n      right. apply (IH2 Hin).\n  - (* MUnionL *)\n    simpl. rewrite in_app_iff.\n    left. apply (IH Hin).\n  - (* MUnionR *)\n    simpl. rewrite in_app_iff.\n    right. apply (IH Hin).\n  - (* MStar0 *)\n    destruct Hin.\n\n(** Something interesting happens in the [MStarApp] case.  We obtain\n    _two_ induction hypotheses: One that applies when [x] occurs in\n    [s1] (which matches [re]), and a second one that applies when [x]\n    occurs in [s2] (which matches [Star re]).  This is a good\n    illustration of why we need induction on evidence for [exp_match],\n    as opposed to [re]: The latter would only provide an induction\n    hypothesis for strings that match [re], which would not allow us\n    to reason about the case [In x s2]. *)\n\n  - (* MStarApp *)\n    simpl. rewrite in_app_iff in Hin.\n    destruct Hin as [Hin | Hin].\n    + (* In x s1 *)\n      apply (IH1 Hin).\n    + (* In x s2 *)\n      apply (IH2 Hin).\nQed.\n\n(** **** Exercise: 4 stars (re_not_empty)  *)\n(** Write a recursive function [re_not_empty] that tests whether a\n    regular expression matches some string. Prove that your function\n    is correct. *)\n\nFixpoint re_not_empty {T} (re : reg_exp T) : bool \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n    that it happily lets you try to set up an induction over a term\n    that isn't sufficiently general.  The net effect of this will be\n    to lose information (much as [destruct] can do), and leave you\n    unable to complete the proof. Here's an example: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n\n(** Just doing an [inversion] on [H1] won't get us very far in the\n    recursive cases. (Try it!). So we need induction. Here is a naive\n    first attempt: *)\n\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** But now, although we get seven cases (as we would expect from the\n    definition of [exp_match]), we lost a very important bit of\n    information from [H1]: the fact that [s1] matched something of the\n    form [Star re].  This means that we have to give proofs for _all_\n    seven constructors of this definition, even though all but two of\n    them ([MStar0] and [MStarApp]) are contradictory.  We can still\n    get the proof to go through for a few constructors, such as\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros H. apply H.\n\n(** ... but most of them get stuck.  For [MChar], for instance, we\n    must show that\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    which is clearly impossible. *)\n\n  - (* MChar. Stuck... *)\n\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n    properly with hypotheses that are completely general, i.e., ones\n    in which all the arguments are variables, as opposed to more\n    complex expressions, such as [Star re].  In this respect it\n    behaves more like [destruct] than like [inversion].\n\n    We can solve this problem by generalizing over the problematic\n    expressions with an explicit equality: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp T),\n  s1 =~ re' ->\n  re' = Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n    because the argument to the first hypothesis is sufficiently\n    general, which means that we can discharge most cases by inverting\n    the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a tactic to\n    automatically generate such equations for us, avoiding thus the\n    need for changing the statements of our theorems.  Calling\n    [remember e as x] causes Coq to (1) replace all occurrences of the\n    expression [e] by the variable [x], and (2) add an equation [x =\n    e] to the context.  Here's how we can use it to show the above\n    result: *)\n\nAbort.\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp T),\n  s1 =~ Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\nProof.\n  intros T s1 s2 re H1.\n  remember (Star re) as re'.\n\n(** We now have [Heqre' : re' = Star re]. *)\n\n  (*generalize dependent s2.*)\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** The [Heqre'] is contradictory in most cases, which allows us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)   inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n\n(** In the interesting cases (those that correspond to [Star]), we can\n    proceed as usual.  Note that the induction hypothesis [IH2] on the\n    [MStarApp] case mentions an additional premise [Star re'' = Star\n    re'], which results from the equality generated by [remember]. *)\n\n  - (* MStar0 *)\n    inversion Heqre'. intros H. apply H.\n  - (* MStarApp *)\n    inversion Heqre'. rewrite H0 in IH2, Hmatch1.\n    intros H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * reflexivity.\n      * apply H1.\nQed.\n\n(** **** Exercise: 4 stars (exp_match_ex2)  *)\n\n(** The [MStar''] lemma below (combined with its converse, the\n    [MStar'] exercise above), shows that our definition of [exp_match]\n    for [Star] is equivalent to the informal one given previously. *)\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp T),\n  s =~ Star re ->\n  exists ss : list (list T),\n    s = fold app ss []\n    /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (pumping)  *)\n(** One of the first interesting theorems in the theory of regular\n    expressions is the so-called _pumping lemma_, which states,\n    informally, that any sufficiently long string [s] matching a\n    regular expression [re] can be \"pumped\" by repeating some middle\n    section of [s] an arbitrary number of times to produce a new\n    string also matching [re]. \n\n    To begin, we need to define \"sufficiently long.\"  Since we are\n    working in a constructive logic, we actually need to be able to\n    calculate, for each regular expression [re], the minimum length\n    for strings [s] to guarantee \"pumpability.\" *)\n\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\n(** Next, it is useful to define an auxiliary function that repeats a\n    string (appends it to itself) some number of times. *)\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\n  end.\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\n  napp (n + m) l = napp n l ++ napp m l.\nProof.\n  intros T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n(** Now, the pumping lemma itself says that, if [s =~ re] and if the\n    length of [s] is at least the pumping constant of [re], then [s]\n    can be split into three substrings [s1 ++ s2 ++ s3] in such a way\n    that [s2] can be repeated any number of times and the result, when\n    combined with [s1] and [s3] will still match [re].  Since [s2] is\n    also guaranteed not to be the empty string, this gives us\n    a (constructive!) way to generate strings matching [re] that are\n    as long as we like. *)\n\nLemma pumping : forall T (re : reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** To streamline the proof (which you are to fill in), the [omega]\n    tactic, which is enabled by the following [Require], is helpful in\n    several places for automatically completing tedious low-level\n    arguments involving equalities or inequalities over natural\n    numbers.  We'll return to [omega] in a later chapter, but feel\n    free to experiment with it now if you like.  The first case of the\n    induction gives an example of how it is used. *)\n\nRequire Import Coq.omega.Omega.\n\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - (* MEmpty *)\n    simpl. omega.\n  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].\n    Unfortunately, performing this conversion by hand can result in\n    tedious proof scripts.  Consider the proof of the following\n    theorem: *)\n\nTheorem filter_not_empty_In : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_nat n m) eqn:H.\n    + (* beq_nat n m = true *)\n      intros _. rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + (* beq_nat n m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly\n    apply the [beq_nat_true_iff] lemma to the equation generated by\n    destructing [beq_nat n m], to convert the assumption [beq_nat n m\n    = true] into the assumption [n = m], which is what we need to\n    complete this case.\n\n    We can streamline this proof by defining an inductive proposition\n    that yields a better case-analysis principle for [beq_nat n\n    m].  Instead of generating an equation such as [beq_nat n m =\n    true], which is not directly useful, this principle gives us right\n    away the assumption we need: [n = m].  We'll actually define\n    something a bit more general, which can be used with arbitrary\n    properties (and not just equalities): *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\n(** The [reflect] property takes two arguments: a proposition\n    [P] and a boolean [b].  Intuitively, it states that the property\n    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: [P]\n    holds if and only if [b = true].  To see this, notice that, by\n    definition, the only way we can produce evidence that [reflect P\n    true] holds is by showing that [P] is true and using the\n    [ReflectT] constructor.  If we invert this statement, this means\n    that it should be possible to extract evidence for [P] from a\n    proof of [reflect P true].  Conversely, the only way to show\n    [reflect P false] is by combining evidence for [~ P] with the\n    [ReflectF] constructor.\n\n    It is easy to formalize this intuition and show that the two\n    statements are indeed equivalent: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros P [] H.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Exercise: 2 stars, recommended (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n    connective is that, by destructing a hypothesis or lemma of the\n    form [reflect P b], we can perform case analysis on [b] while at\n    the same time generating appropriate hypothesis in the two\n    branches ([P] in the first subgoal and [~ P] in the second).\n\n    To use [reflect] to produce a better proof of\n    [filter_not_empty_In], we begin by recasting the\n    [beq_nat_iff_true] lemma into a more convenient form in terms of\n    [reflect]: *)\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m.\n  apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\n(** The new proof of [filter_not_empty_In] now goes as follows.\n    Notice how the calls to [destruct] and [apply] are combined into a\n    single call to [destruct].  (To see this clearly, look at the two\n    proofs of [filter_not_empty_In] in your Coq browser and observe\n    the differences in proof state at the beginning of the first case\n    of the [destruct].) *)\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_natP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** Although this technique arguably gives us only a small gain\n    in convenience for this particular proof, using [reflect]\n    consistently often leads to shorter and clearer proofs. We'll see\n    many more examples where [reflect] comes in handy in later\n    chapters.\n\n    The use of the [reflect] property was popularized by _SSReflect_,\n    a Coq library that has been used to formalize important results in\n    mathematics, including as the 4-color theorem and the\n    Feit-Thompson theorem.  The name SSReflect stands for _small-scale\n    reflection_, i.e., the pervasive use of reflection to simplify\n    small proof steps with boolean computations. *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars, recommended (palindromes)  *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n\n        c : forall l, l = rev l -> pal l\n\n      may seem obvious, but will not work very well.)\n\n    - Prove ([pal_app_rev]) that\n\n       forall l, pal (l ++ rev l).\n\n    - Prove ([pal_rev] that)\n\n       forall l, pal l -> l = rev l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Again, the converse direction is significantly more difficult, due\n    to the lack of evidence.  Using your definition of [pal] from the\n    previous exercise, prove that\n\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge)  *)\n(** Let's prove that our definition of [filter] from the [Poly]\n    chapter matches an abstract specification.  Here is the\n    specification, written out informally in English:\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example,\n\n    [1;4;6;2;3]\n\n    is an in-order merge of\n\n    [1;6;2]\n\n    and\n\n    [4;3].\n\n    Now, suppose we have a set [X], a function [test: X->bool], and a\n    list [l] of type [list X].  Suppose further that [l] is an\n    in-order merge of two lists, [l1] and [l2], such that every item\n    in [l1] satisfies [test] and no item in [l2] satisfies test.  Then\n    [filter test l = l1].\n\n    Translate this specification into a Coq theorem and prove\n    it.  (You'll need to begin by defining what it means for one list\n    to be a merge of two others.  Do this with an inductive relation,\n    not a [Fixpoint].)  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2)  *)\n(** A different way to characterize the behavior of [filter] goes like\n    this: Among all subsequences of [l] with the property that [test]\n    evaluates to [true] on all their members, [filter test l] is the\n    longest.  Formalize this claim and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (NoDup)  *)\n(** Recall the definition of the [In] property from the [Logic]\n    chapter, which asserts that a value [x] appears at least once in a\n    list [l]: *)\n\n(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=\n   match l with\n   | [] => False\n   | x' :: l' => x' = x \\/ In A x l'\n   end *)\n\n(** Your first task is to use [In] to define a proposition [disjoint X\n    l1 l2], which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in\n    common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [In] to define an inductive proposition [NoDup X\n    l], which should be provable exactly when [l] is a list (with\n    elements of type [X]) where every member is different from every\n    other.  For example, [NoDup nat [1;2;3;4]] and [NoDup\n    bool []] should be provable, while [NoDup nat [1;2;1]] and\n    [NoDup bool [true;true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (nostutter)  *)\n(** Formulating inductive definitions of properties is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all.\n\n    We say that a list \"stutters\" if it repeats the same element\n    consecutively.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n (* FILL IN HERE *)\n.\n(** Make sure each of these tests succeeds, but feel free to change\n    the suggested proof (in comments) if the given one doesn't work\n    for you.  Your definition might be different from ours and still\n    be correct, in which case the examples might need a different\n    proof.  (You'll notice that the suggested proofs use a number of\n    tactics we haven't talked about, to make them more robust to\n    different possible ways of defining [nostutter].  You can probably\n    just uncomment and use them as-is, but you can also prove each\n    example with more basic tactics.)  *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle)  *)\n(** The _pigeonhole principle_ states a basic fact about counting: if\n   we distribute more than [n] items into [n] pigeonholes, some\n   pigeonhole must contain at least two items.  As often happens, this\n   apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First prove an easy useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a property [repeats] such that [repeats X l] asserts\n    that [l] contains at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now, here's a way to formalize the pigeonhole principle.  Suppose\n    list [l2] represents a list of pigeonhole labels, and list [l1]\n    represents the labels assigned to a list of items.  If there are\n    more items than labels, at least two items must have the same\n    label -- i.e., list [l1] must contain repeats.\n\n    This proof is much easier if you use the [excluded_middle]\n    hypothesis to show that [In] is decidable, i.e., [forall x l, (In x\n    l) \\/ ~ (In x l)].  However, it is also possible to make the proof\n    go through _without_ assuming that [In] is decidable; if you\n    manage to do this, you will not need the [excluded_middle]\n    hypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\n   excluded_middle ->\n   (forall x, In x l1 -> In x l2) ->\n   length l2 < length l1 ->\n   repeats l1.\nProof.\n   intros X l1. induction l1 as [|x l1' IHl1'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8962513627417531, "lm_q1q2_score": 0.8019562758468207}}
{"text": "(* week_37b_lists.v *)\n(* dIFP 2014-2015, Q1, Week 37 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* New tactics:\n   - assert (to declare a new hypothesis)\n   - clear (to garbage collect the hypotheses).\n*)\n\nRequire Import unfold_tactic.\n\nRequire Import Arith Bool List.\n\n(* The goal of this file is to study lists:\n   Infix :: is cons, and nil is the empty list.\n*)\n\nCompute 3 :: 2 :: 1 :: nil.\n(*\n     = 3 :: 2 :: 1 :: nil\n     : list nat\n*)\n\n(* ********** *)\n\nLemma f_equal_S :\n  forall x y : nat,\n    x = y -> S x = S y.\nProof.\n  intros x y.\n  intro H_xy.\n  rewrite -> H_xy.\n  reflexivity.\nQed.\n\nLemma unfold_plus_bc :\n  forall y : nat,\n    0 + y = y.\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall x' y : nat,\n    (S x') + y = S (x' + y).\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma plus_1_l :\n  forall n : nat,\n    1 + n = S n.\nProof.\n  intro n.\n  rewrite -> (unfold_plus_ic 0 n).\n  rewrite -> (unfold_plus_bc n).\n  reflexivity.\nQed.\n\nLemma plus_1_r :\n  forall n : nat,\n    n + 1 = S n.\nProof.\n  intro n.\n  rewrite -> (plus_comm n 1).\n  apply (plus_1_l n).\nQed.\n\nLemma Sn_1_plus_n :\n  forall n : nat,\n    S n = 1 + n.\nProof.\n  intro n.\n  symmetry.\n  apply (plus_1_l n).\nQed.\n\n(* ********** *)\n\n(* The length of a list: *)\n\nNotation \"A === B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_tests_for_length_nat (length : list nat -> nat) :=\n  (length nil === 0)\n  &&\n  (length (1 :: nil) === 1)\n  &&\n  (length (2 :: 1 :: nil) === 2)\n  &&\n  (length (3 :: 2 :: 1 :: nil) === 3)\n  .\n\nDefinition unit_tests_for_length_bool (length : list bool -> nat) :=\n  (length nil === 0)\n  &&\n  (length (true :: nil) === 1)\n  &&\n  (length (true :: true :: nil) === 2)\n  &&\n  (length (true :: true :: true :: nil) === 3)\n  .\n\nDefinition specification_of_length (T : Type) (length : list T -> nat) :=\n  (length nil = 0)\n  /\\\n  (forall (x : T) (xs' : list T),\n     length (x :: xs') = S (length xs')).\n\nTheorem there_is_only_one_length :\n  forall (T : Type) (length_1 length_2 : list T -> nat),\n    specification_of_length T length_1 ->\n    specification_of_length T length_2 ->\n    forall xs : list T,\n      length_1 xs = length_2 xs.\nProof.\n  intros T length_1 length_2.\n\n  unfold specification_of_length.\n  intros [Hbc1 Hic1] [Hbc2 Hic2].\n\n  intro xs.\n  induction xs as [ | x xs' IHxs'].\n\n  rewrite -> Hbc1.\n  rewrite -> Hbc2.\n  reflexivity.\n\n  rewrite (Hic1 x xs').\n  rewrite (Hic2 x xs').\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* A first implementation of length: *)\n\nFixpoint length_ds (T : Type) (xs : list T) : nat :=\n  match xs with\n    | nil => 0\n    | x :: xs' => S (length_ds T xs')\n  end.\n\nDefinition length_v1 (T : Type) (xs : list T) : nat :=\n  length_ds T xs.\n\nCompute unit_tests_for_length_nat (length_v1 nat).\n(*\n     = true\n     : bool\n*)\n\nCompute unit_tests_for_length_bool (length_v1 bool).\n(*\n     = true\n     : bool\n*)\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_length_ds_base_case :\n  forall T : Type,\n    length_ds T nil = 0.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic length_ds.\nQed.\n\nLemma unfold_length_ds_induction_case :\n  forall (T : Type) (x : T) (xs' : list T),\n    length_ds T (x :: xs') = S (length_ds T xs').\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic length_v1.\nQed.\n\nProposition length_v1_fits_the_specification_of_length :\n  forall T : Type,\n    specification_of_length T (length_v1 T).\nProof.\n  intro T.\n  unfold specification_of_length.\n  split.\n\n  unfold length_v1.\n  apply (unfold_length_ds_base_case T).\n  \n  unfold length_v1.\n  apply (unfold_length_ds_induction_case T).\nQed.\n\n(* ***** *)\n\n(* A second implementation of length: *)\n\nFixpoint length_acc (T : Type) (xs : list T) (a : nat) : nat :=\n  match xs with\n    | nil => a\n    | x :: xs' => length_acc T xs' (S a)\n  end.\n\nDefinition length_v2 (T : Type) (xs : list T) : nat :=\n  length_acc T xs 0.\n\nCompute unit_tests_for_length_nat (length_v2 nat).\n(*\n     = true\n     : bool\n*)\n\nCompute unit_tests_for_length_bool (length_v2 bool).\n(*\n     = true\n     : bool\n*)\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_length_acc_base_case :\n  forall (T : Type) (a : nat),\n    length_acc T nil a = a.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic length_acc.\nQed.\n\nLemma unfold_length_acc_induction_case :\n  forall (T : Type) (x : T) (xs' : list T) (a : nat),\n    length_acc T (x :: xs') a = length_acc T xs' (S a).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic length_acc.\nQed.\n\n(* A useful lemma (Eureka): *)\n\nLemma about_length_acc :\n  forall (T : Type) (xs : list T) (a : nat),\n    length_acc T xs a = (length_acc T xs 0) + a.\nProof.\n  intros T xs.\n\n  induction xs as [| x xs IHxs].\n\n  intro a.\n  rewrite -> (unfold_length_acc_base_case T 0).\n  rewrite -> (unfold_length_acc_base_case T a).\n  rewrite -> (plus_0_l a).\n\n  reflexivity.\n\n  intro a.\n  rewrite -> (unfold_length_acc_induction_case T x xs).\n  rewrite -> (unfold_length_acc_induction_case).\n\n  rewrite -> (Sn_1_plus_n).\n  rewrite -> (IHxs (1 + a)).\n  rewrite -> (IHxs 1).\n  rewrite -> (plus_assoc (length_acc T xs 0) 1 a).\n\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nProposition length_v2_fits_the_specification_of_length :\n  forall T : Type,\n    specification_of_length T (length_v2 T).\nProof.\n  intros T.\n  unfold specification_of_length.\n\n  split.\n  unfold length_v2.\n\n  rewrite -> (unfold_length_acc_base_case T 0).\n  reflexivity.\n\n  intros x xs.\n  unfold length_v2.\n\n  rewrite -> (unfold_length_acc_induction_case T x xs 0).\n  rewrite -> (Sn_1_plus_n (length_acc T xs 0)).\n  rewrite -> (about_length_acc T xs 1).\n\n  rewrite -> (plus_1_r).\n  rewrite -> (plus_1_l (length_acc T xs 0)).\n\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\nFixpoint equal_list_nat (xs ys : list nat) :=\n  match xs with\n    | nil =>\n      match ys with\n        | nil => true\n        | y :: ys' => false\n      end\n    | x :: xs' =>\n      match ys with\n        | nil => false\n        | y :: ys' => (beq_nat x y) && (equal_list_nat xs' ys')\n      end\n  end.\n\n(* ********** *)\n\n(* Concatenating two lists: *)\n\nDefinition unit_tests_for_append_nat (append : list nat -> list nat -> list nat) :=\n  (equal_list_nat (append nil\n                          nil)\n                  nil)\n  &&\n  (equal_list_nat (append (1 :: nil)\n                          nil)\n                  (1 :: nil))\n  &&\n  (equal_list_nat (append nil\n                          (1 :: nil))\n                  (1 :: nil))\n  &&\n  (equal_list_nat (append (1 :: 2 :: nil)\n                          (3 :: 4 :: 5 :: nil))\n                  (1 :: 2 :: 3 :: 4 :: 5 :: nil))\n  .\n\nDefinition specification_of_append (T : Type) (append : list T -> list T -> list T) :=\n  (forall ys : list T,\n     append nil ys = ys)\n  /\\\n  (forall (x : T) (xs' ys : list T),\n     append (x :: xs') ys = x :: (append xs' ys)).\n\nTheorem there_is_only_one_append :\n  forall (T : Type) (append_1 append_2 : list T -> list T -> list T),\n    specification_of_append T append_1 ->\n    specification_of_append T append_2 ->\n    forall xs ys : list T,\n      append_1 xs ys = append_2 xs ys.\nProof.\n  intros T append_1 append_2.\n  unfold specification_of_append.\n  intros [Hbc1 Hic1] [Hbc2 Hic2].\n\n  intro xs.\n  induction xs as [ | x xs' IHxs'].\n\n  intro ys.\n  rewrite -> (Hbc1 ys).\n  rewrite -> (Hbc2 ys).\n  reflexivity.\n\n  intro ys.\n  rewrite (Hic1 x xs').\n  rewrite (Hic2 x xs').\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nFixpoint append_ds (T : Type) (xs ys : list T) : list T :=\n  match xs with\n    | nil => ys\n    | x :: xs' => x :: append_ds T xs' ys\n  end.\n\nDefinition append_v1 (T : Type) (xs ys : list T) : list T :=\n  append_ds T xs ys.\n\nCompute unit_tests_for_append_nat (append_v1 nat).\n\nLemma unfold_append_v1_base_case :\n  forall (T : Type) (ys : list T),\n    append_ds T nil ys = ys.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic append_ds.\nQed.\n\nLemma unfold_append_v1_induction_case :\n  forall (T : Type) (x : T) (xs' ys : list T),\n    append_ds T (x :: xs') ys = x :: append_ds T xs' ys.\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic append_ds.\nQed.\n\nProposition append_v1_fits_the_specification_of_append :\n  forall T : Type,\n    specification_of_append T (append_v1 T).\nProof.\n  intro T.\n  unfold specification_of_append.\n  split.\n\n  apply (unfold_append_v1_base_case T).\n\n  apply (unfold_append_v1_induction_case T).\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Properties:\n     for all ys, append nil ys = ys\n     for all xs, append xs nil = xs\n     for all xs ys zs,\n       append (append xs ys) zs = append xs (append ys zs)\n     for all xs ys,\n       length (append xs ys) = (length xs) + (length ys)\n*)\n\nDefinition unit_tests_for_append_nat_properties (append : list nat -> list nat -> list nat) :=\n  (equal_list_nat (append nil (0 :: nil))\n                  (0 :: nil))\n  &&\n  (equal_list_nat (append (0 :: nil) nil)\n                  (0 :: nil))\n  &&\n  (equal_list_nat (append (append (0 :: nil) (1 :: nil)) (2 :: nil))\n                  (append (0 :: nil) (append (1 :: nil) (2 :: nil))))\n  &&\n  (length (append (1 :: 2 :: nil) (3 :: 4 :: 5 :: nil))\n          === (length (1 :: 2 :: nil)) + (length (3 :: 4 :: 5 :: nil)))\n  .\n\nCompute unit_tests_for_append_nat_properties (append_v1 nat).\n\n(* Exercise: write a unit test that validates these properties. *)\n\nLemma nil_is_neutral_for_append_on_the_left :\n  forall (T : Type)\n         (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    forall ys : list T,\n      append nil ys = ys.\nProof.\n  intros T append.\n  unfold specification_of_append.\n  intros [Hbc Hic].\n  intro ys.\n  apply (Hbc ys).\nQed.\n\nLemma nil_is_neutral_for_append_on_the_right :\n  forall (T : Type)\n         (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    forall xs : list T,\n      append xs nil = xs.\nProof.\n  intros T append.\n\n  unfold specification_of_append.\n  intros [Hbc Hic].\n\n  intro xs.\n  induction xs as [ | x xs' IHxs'].\n\n  apply (Hbc nil).\n\n  rewrite -> (Hic x xs' nil).\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n\nLemma append_is_associative :\n  forall (T : Type)\n         (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    forall xs ys zs: list T,\n      append (append xs ys) zs = append xs (append ys zs).\nProof.\n  intros T append.\n\n  unfold specification_of_append.\n  intros [Hbc Hic].\n\n  intros xs.\n  induction xs as [ | x xs' IHxs'].\n\n  intros ys zs.\n  rewrite -> (Hbc ys).\n  rewrite -> (Hbc (append ys zs)).\n  reflexivity.\n\n  intros ys zs.\n  rewrite -> (Hic x xs' ys).\n  rewrite -> (Hic x (append xs' ys)).\n  rewrite -> (Hic x xs' (append ys zs)).\n  rewrite -> (IHxs' ys zs).\n  reflexivity.\nQed.\n\n(* ********** *)\n\nProposition append_preserves_length :\n  forall (T : Type)\n         (length : list T -> nat)\n         (append : list T -> list T -> list T),\n    specification_of_length T length ->\n    specification_of_append T append ->\n    forall xs ys : list T,\n      length (append xs ys) = (length xs) + (length ys).\nProof.\n  intros T length append.\n\n  unfold specification_of_length.\n  intros [H_length_bc H_length_ic].\n\n  unfold specification_of_append.\n  intros [H_append_bc H_append_ic].\n\n  intro xs.\n  induction xs as [ | x xs' IHxs'].\n\n  intro ys.\n  rewrite -> (H_append_bc ys).\n  rewrite -> H_length_bc.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  intro ys.\n  rewrite -> (H_append_ic x xs' ys).\n  rewrite -> (H_length_ic x (append xs' ys)).\n  rewrite -> (IHxs' ys).\n  rewrite -> (H_length_ic x xs').\n  symmetry.\n  apply plus_Sn_m.\nQed.\n\n(* ********** *)\n\n(* Reversing a list: *)\n\nDefinition unit_tests_for_reverse_nat (reverse : list nat -> list nat) :=\n  (equal_list_nat (reverse nil)\n                  nil)\n  &&\n  (equal_list_nat (reverse (1 :: nil))\n                  (1 :: nil))\n  &&\n  (equal_list_nat (reverse (1 :: 2 :: nil))\n                  (2 :: 1 :: nil))\n  &&\n  (equal_list_nat (reverse (1 :: 2 :: 3 :: nil))\n                  (3 :: 2 :: 1 :: nil))\n  .\n\nDefinition specification_of_reverse (T : Type) (reverse : list T -> list T) :=\n  forall (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    (reverse nil = nil)\n    /\\\n    (forall (x : T) (xs' : list T),\n       reverse (x :: xs') = append (reverse xs') (x :: nil)).\n\nTheorem there_is_only_one_reverse :\n  forall (T : Type)\n         (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    forall reverse_1 reverse_2 : list T -> list T,\n      specification_of_reverse T reverse_1 ->\n      specification_of_reverse T reverse_2 ->\n      forall xs : list T,\n        reverse_1 xs = reverse_2 xs.\nProof.\n  intros T append S_append.\n  intros reverse_1 reverse_2.\n  intros S_rev1 S_rev2.\n\n  unfold specification_of_reverse in S_rev1.\n  unfold specification_of_reverse in S_rev2.\n  destruct (S_rev1 append S_append) as [H_rev1_bc H_rev1_ic].\n  destruct (S_rev2 append S_append) as [H_rev2_bc H_rev2_ic].\n  clear S_rev1 S_rev2.\n\n  unfold specification_of_append in S_append.\n  destruct S_append as [H_append_bc H_append_ic].\n\n  intro xs.\n  induction xs as [| x' xs' IHxs'].\n\n  rewrite -> H_rev1_bc.\n  rewrite -> H_rev2_bc.\n  reflexivity.\n\n  rewrite -> (H_rev1_ic x' xs').\n  rewrite -> (H_rev2_ic x' xs').\n  rewrite -> (IHxs').\n\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* An implementation of reverse: *)\n\nFixpoint reverse_ds (T : Type) (xs : list T) : list T :=\n  match xs with\n    | nil => nil\n    | x :: xs' => append_v1 T (reverse_ds T xs') (x :: nil)\n  end.\n\nDefinition reverse_v1 (T : Type) (xs : list T) : list T :=\n  reverse_ds T xs.\n\nCompute unit_tests_for_reverse_nat (reverse_v1 nat).\n\nLemma unfold_reverse_ds_base_case :\n  forall (T : Type),\n    reverse_ds T nil = nil.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic reverse_ds.\nQed.\n\nLemma unfold_reverse_ds_induction_case :\n  forall (T : Type)\n         (x : T)\n         (xs' : list T),\n    reverse_ds T (x :: xs') =\n    append_v1 T (reverse_ds T xs') (x :: nil).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic reverse_ds.\nQed.\n\nProposition reverse_v1_fits_the_specification_of_reverse :\n  forall T : Type,\n    specification_of_reverse T (reverse_v1 T).\nProof.\n  intro T.\n  unfold specification_of_reverse.\n\n  intros append S_append.\n\n  split.\n\n  apply unfold_reverse_ds_base_case.\n\n  intros x xs'.\n  unfold reverse_v1.\n  rewrite -> (unfold_reverse_ds_induction_case T x xs').\n\n  rewrite -> (there_is_only_one_append T append (append_v1 T) S_append\n                                       (append_v1_fits_the_specification_of_append T)\n                                       (reverse_ds T xs') (x :: nil)).\n  reflexivity.\nQed.\n\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* A second implementation of reverse, with an accumulator : *)\n\nFixpoint reverse_acc (T : Type) (xs a : list T) : list T :=\n  match xs with\n    | nil => a\n    | x :: xs' => reverse_acc T xs' (x :: a)\n  end.\n\nDefinition reverse_v2 (T : Type) (xs : list T) :=\n  reverse_acc T xs nil.\n\nCompute unit_tests_for_reverse_nat (reverse_v2 nat).\n\n(* A useful lemma (Eureka): *)\n\nLemma unfold_reverse_acc_base_case :\n  forall (T : Type) (a : list T),\n    reverse_acc T nil a = a.\nProof.\n  unfold_tactic reverse_acc.\nQed.\n\nLemma unfold_reverse_acc_induction_case :\n  forall (T : Type) (x : T) (xs' a : list T),\n    reverse_acc T (x :: xs') a = reverse_acc T xs' (x :: a).\nProof.\n  unfold_tactic reverse_acc.\nQed.\n\nLemma about_reverse_acc :\n  forall (T : Type)\n         (append : list T -> list T -> list T),\n    specification_of_append T append ->\n    forall xs a : list T,\n      reverse_acc T xs a = append (reverse_acc T xs nil) a.\nProof.\n  intros T append S_append.\n  intros xs.\n\n  assert (S_append_ := S_append).\n  destruct S_append as [H_append_bc H_append_ic].\n\n  induction xs as [|x' xs' IHxs'].\n\n  intro a.\n\n  rewrite -> (unfold_reverse_acc_base_case T a).\n  rewrite -> (unfold_reverse_acc_base_case T nil).\n  rewrite -> (H_append_bc a).\n  reflexivity.\n\n  intro a.\n  rewrite -> (unfold_reverse_acc_induction_case T x' xs' a).\n  rewrite -> (unfold_reverse_acc_induction_case T x' xs' nil).\n  rewrite -> (IHxs' (x' :: a)).\n  \n  rewrite -> (IHxs' (x' :: nil)).\n  rewrite -> (append_is_associative T append S_append_ (reverse_acc T xs' nil) (x' :: nil) a).\n  rewrite -> (H_append_ic x' nil a).\n  rewrite -> (H_append_bc a).\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nProposition reverse_v2_fits_the_specification_of_reverse :\n  forall T : Type,\n    specification_of_reverse T (reverse_v2 T).\nProof.\n  intro T.\n  unfold specification_of_reverse.\n\n  intro append.\n  intro S_append.\n\n  split.\n\n  apply (unfold_reverse_acc_base_case T nil).\n\n  intros x xs.\n  unfold reverse_v2.\n  rewrite -> (unfold_reverse_acc_induction_case T x xs nil).\n\n  rewrite -> (about_reverse_acc T append S_append xs (x :: nil)).\n\n  reflexivity.\nQed.\n\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Properties:\n     for all xs,\n       length xs = length (reverse xs)\n     forall xs ys,\n       reverse (append xs ys) = append (reverse ys) (reverse xs)\nw     forall xs,\n       reverse (reverse xs) = xs\n*)\n\nDefinition unit_tests_for_reverse_nat_properties\n           (reverse : list nat -> list nat)\n           (append : list nat -> list nat -> list nat) :=\n  (length (0 :: 1 :: nil) === length (reverse (0 :: 1 :: nil)))\n  &&\n  (equal_list_nat (reverse (append (0 :: 1 :: nil) (2 :: 3 :: nil)))\n                  (append (reverse (2 :: 3 :: nil)) (reverse (0 :: 1 :: nil))))\n  &&\n  (equal_list_nat (reverse (reverse (0 :: 1 :: nil))) (0 :: 1 :: nil))\n  .\n\nCompute unit_tests_for_reverse_nat_properties (reverse_v2 nat) (append_v1 nat).\n\n(* Exercise: write a unit test that validates these properties. *)\n\nProposition reverse_preserves_length :\n  forall (T : Type)\n         (length : list T -> nat)\n         (append : list T -> list T -> list T)\n         (reverse : list T -> list T),\n    specification_of_length T length ->\n    specification_of_append T append ->\n    specification_of_reverse T reverse ->\n    forall xs : list T,\n      length xs = length (reverse xs).\nProof.\n  intro T.\n  intros length append reverse.\n  intros S_length S_append S_reverse.\n\n  destruct (S_reverse append S_append) as [H_reverse_bc H_reverse_ic].\n  assert (S_append_ := S_append).\n  assert (S_length_ := S_length).\n  destruct S_length as [H_length_bc H_length_ic].\n  destruct S_append as [H_append_bc H_append_ic].\n\n  intro xs.\n  induction xs as [| x xs IHxs].\n\n  rewrite -> H_length_bc.\n  rewrite -> H_reverse_bc.\n  rewrite -> H_length_bc.\n  reflexivity.\n\n  rewrite -> H_length_ic.\n  rewrite -> H_reverse_ic.\n  rewrite -> (append_preserves_length T length append S_length_ S_append_ (reverse xs) (x :: nil)).\n  rewrite -> (H_length_ic x nil).\n  rewrite -> H_length_bc.\n  rewrite -> (plus_1_r (length (reverse xs))).\n  rewrite <- IHxs.\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nProposition reverse_preserves_append_sort_of :\n  forall (T : Type)\n         (append : list T -> list T -> list T)\n         (reverse : list T -> list T),\n    specification_of_append T append ->\n    specification_of_reverse T reverse ->\n    forall xs ys : list T,\n      reverse (append xs ys) = append (reverse ys) (reverse xs).\nProof.\n  intros T append reverse.\n  intros S_append S_reverse.\n  intro xs.\n\n  assert (S_append_ := S_append).\n  destruct S_append as [H_append_bc H_append_ic].\n  destruct (S_reverse append S_append_) as [H_reverse_bc H_reverse_ic].\n\n  induction xs as [| x xs IHxs].\n\n  intro ys.\n  rewrite -> (H_append_bc ys).\n  rewrite -> H_reverse_bc.\n  rewrite -> (nil_is_neutral_for_append_on_the_right T append S_append_ (reverse ys)).\n  reflexivity.\n\n  intro ys.\n  rewrite -> (H_append_ic x xs ys).\n  rewrite -> (H_reverse_ic x (append xs ys)).\n  rewrite -> (IHxs ys).\n  rewrite -> (append_is_associative T append S_append_ (reverse ys) (reverse xs) (x :: nil)).\n  rewrite -> (H_reverse_ic x xs).\n  reflexivity.\nQed.\n\n(* Replace \"Abort.\" with a proof. *)\n\nProposition reverse_is_involutive :\n  forall (T : Type)\n         (append : list T -> list T -> list T)\n         (reverse : list T -> list T),\n    specification_of_append T append ->\n    specification_of_reverse T reverse ->\n    forall xs : list T,\n      reverse (reverse xs) = xs.\nProof.\n  intros T append reverse.\n  intros S_append S_reverse.\n\n  assert (S_append_ := S_append).\n  destruct (S_reverse append S_append) as [H_reverse_bc H_reverse_ic].\n  destruct S_append as [H_append_bc H_append_ic].\n\n  intro xs.\n  induction xs as [| x xs IHxs].\n\n  rewrite -> H_reverse_bc.\n  rewrite -> H_reverse_bc.\n  reflexivity.\n\n  rewrite -> (H_reverse_ic x xs).\n  rewrite -> (reverse_preserves_append_sort_of T append reverse S_append_ S_reverse (reverse xs) (x :: nil)).\n  rewrite -> (H_reverse_ic x nil).\n  rewrite -> H_reverse_bc.\n  rewrite -> (H_append_bc (x :: nil)).\n  rewrite -> (IHxs).\n  rewrite -> (H_append_ic x nil xs).\n  rewrite -> (H_append_bc xs).\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Mapping a function over the elements of a list: *)\n\nDefinition unit_tests_for_map_nat (map : (nat -> nat) -> list nat -> list nat) :=\n  (equal_list_nat (map (fun n => n) \n                       nil)\n                  nil)\n  &&\n  (equal_list_nat (map (fun n => n)\n                       (1 :: nil))\n                  (1 :: nil))\n  &&\n  (equal_list_nat (map (fun n => n)\n                       (1 :: 2 :: 3 :: nil))\n                  (1 :: 2 :: 3 :: nil))\n  &&\n  (equal_list_nat (map (fun n => S n)\n                       nil)\n                  nil)\n  &&\n  (equal_list_nat (map (fun n => S n)\n                       (1 :: nil))\n                  (2 :: nil))\n  &&\n  (equal_list_nat (map (fun n => S n)\n                       (1 :: 2 :: 3 :: nil))\n                  (2 :: 3 :: 4 :: nil))\n  &&\n  (equal_list_nat (map (fun n => n * 2)\n                       (1 :: 2 :: 3 :: nil))\n                  (2 :: 4 :: 6 :: nil))\n  &&\n  (equal_list_nat (map (fun n => 0)\n                       (1 :: 2 :: 3 :: nil))\n                  (0 :: 0 :: 0 :: nil))\n  .\n\n(* Exercise: add more tests. *)\n\nDefinition specification_of_map (T1 T2 : Type) (map : (T1 -> T2) -> list T1 -> list T2) :=\n  (forall f : T1 -> T2,\n     map f nil = nil)\n  /\\\n  (forall (f : T1 -> T2) (x : T1) (xs' : list T1),\n     map f (x :: xs') = (f x) :: (map f xs')).\n\nTheorem there_is_only_one_map :\n  forall (T1 T2 : Type)\n         (map_1 map_2 : (T1 -> T2) -> list T1 -> list T2),\n    specification_of_map T1 T2 map_1 ->\n    specification_of_map T1 T2 map_2 ->\n    forall (f : T1 -> T2)\n           (xs : list T1),\n      map_1 f xs = map_2 f xs.\nProof.\n  intros T1 T2.\n  intros map_1 map_2.\n  intros S_map1 S_map2.\n  intros f xs.\n\n  destruct S_map1 as [H_map1_bc H_map1_ic].\n  destruct S_map2 as [H_map2_bc H_map2_ic].\n\n  induction xs as [| x' xs' IHxs'].\n\n  rewrite -> (H_map1_bc f).\n  rewrite -> (H_map2_bc f).\n  reflexivity.\n  \n  rewrite -> (H_map1_ic f x' xs').\n  rewrite -> (H_map2_ic f x' xs').\n\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* An implementation of map: *)\n\nFixpoint map_ds (T1 T2 : Type) (f : T1 -> T2) (xs : list T1) : list T2 :=\n  match xs with\n    | nil => nil\n    | x :: xs' => (f x) :: (map_ds T1 T2 f xs')\n  end.\n\nDefinition map_v1 (T1 T2 : Type) (f : T1 -> T2) (xs : list T1) : list T2 :=\n  map_ds T1 T2 f xs.\n\nCompute unit_tests_for_map_nat (map_v1 nat nat).\n\nLemma unfold_map_ds_base_case :\n  forall (T1 T2 : Type)\n         (f : T1 -> T2),\n    map_ds T1 T2 f nil = nil.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic map_ds.\nQed.\n\nLemma unfold_map_ds_induction_case :\n  forall (T1 T2 : Type)\n         (f : T1 -> T2)\n         (x : T1)\n         (xs' : list T1),\n    map_ds T1 T2 f (x :: xs') =\n    (f x) :: (map_ds T1 T2 f xs').\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic map_ds.\nQed.\n\nProposition map_v1_fits_the_specification_of_map :\n  forall T1 T2 : Type,\n    specification_of_map T1 T2 (map_v1 T1 T2).\nProof.\n  intros T1 T2.\n\n  unfold specification_of_map.\n  split.\n\n  apply (unfold_map_ds_base_case T1 T2).\n  apply (unfold_map_ds_induction_case T1 T2).\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Properties:\n     for all f1 f2 xs,\n       map f2 (map f1 xs) = map (fun x => f2 (f1 x)) xs\n     for all f xs ys,\n        map f (append xs ys) = append (map f xs) (map f ys)\n     for all f xs,\n       map f (reverse xs) = reverse (map f xs)\n*)\n\nDefinition unit_tests_for_map_nat_properties\n           (map : (nat -> nat) -> list nat -> list nat)\n           (append : list nat -> list nat -> list nat)\n           (reverse : list nat -> list nat) :=\n  (equal_list_nat (map (fun a => a + 1) (map (fun b => b * 2) (0 :: 1 :: 2 :: 3 :: nil)))\n                  (map (fun x => (fun a => a + 1) ((fun b => b * 2) x)) (0 :: 1 :: 2 :: 3 :: nil)))\n    &&\n  (equal_list_nat (map (fun a => a * a) (append (0 :: 1 :: nil) (2 :: 3 :: nil)))\n                  (append (map (fun a => a * a) (0 :: 1 :: nil)) (map (fun a => a * a) (2 :: 3 :: nil))))\n  &&\n  (equal_list_nat (map (fun a => a * 3) (reverse (0 :: 1 :: nil)))\n                  (reverse (map (fun a => a * 3) (0 :: 1 :: nil))))\n  .\n\nCompute unit_tests_for_map_nat_properties (map_v1 nat nat) (append_v1 nat) (reverse_v1 nat).\n\n(* Exercise: write a unit test that validates these properties. *)\n\nProposition listlessness_of_map :\n  forall (T1 T2 T3 : Type)\n         (map12 : (T1 -> T2) -> list T1 -> list T2)\n         (map23 : (T2 -> T3) -> list T2 -> list T3)\n         (map13 : (T1 -> T3) -> list T1 -> list T3),\n    specification_of_map T1 T2 map12 ->\n    specification_of_map T2 T3 map23 ->\n    specification_of_map T1 T3 map13 ->\n    forall (f1 : T1 -> T2)\n           (f2 : T2 -> T3)\n           (xs : list T1),\n      map23 f2 (map12 f1 xs) = map13 (fun x => f2 (f1 x)) xs.\nProof.\n  intros T1 T2 T3.\n  intros map1 map2 map3.\n  intros S_map1 S_map2 S_map3.\n  intros f1 f2 xs.\n\n  destruct S_map1 as [H_map1_bc H_map1_ic].\n  destruct S_map2 as [H_map2_bc H_map2_ic].\n  destruct S_map3 as [H_map3_bc H_map3_ic].\n\n  induction xs as [| x' xs' IHxs'].\n  \n  rewrite -> (H_map1_bc f1).\n  rewrite -> (H_map2_bc f2).\n  rewrite -> (H_map3_bc (fun x : T1 => f2 (f1 x))).\n  reflexivity.\n\n  rewrite -> (H_map1_ic f1 x' xs').\n  rewrite -> (H_map2_ic f2 (f1 x') (map1 f1 xs')).\n  rewrite -> IHxs'.\n  rewrite -> (H_map3_ic (fun x : T1 => f2 (f1 x)) x' xs').\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nProposition append_preserves_map :\n  forall (T1 T2 : Type)\n         (map : (T1 -> T2) -> list T1 -> list T2)\n         (append_1 : list T1 -> list T1 -> list T1)\n         (append_2 : list T2 -> list T2 -> list T2),\n    specification_of_map T1 T2 map ->\n    specification_of_append T1 append_1 ->\n    specification_of_append T2 append_2 ->\n    forall (f : T1 -> T2) (xs ys : list T1),\n       map f (append_1 xs ys) = append_2 (map f xs) (map f ys).\nProof.\n  intros T1 T2 map append_1 append_2.\n  intros S_map S_append_1 S_append_2.\n  intros f xs.\n\n  destruct S_map as [H_map_bc H_map_ic].\n  destruct S_append_1 as [H_append_1_bc H_append_1_ic].\n  destruct S_append_2 as [H_append_2_bc H_append_2_ic].\n\n  induction xs as [| x' xs' IHxs'].\n\n  intro ys.  \n  rewrite -> (H_append_1_bc ys).\n  rewrite -> (H_map_bc f).\n  rewrite -> (H_append_2_bc (map f ys)).\n  reflexivity.\n\n  intro ys.\n  rewrite -> (H_append_1_ic x' xs' ys).\n  rewrite -> (H_map_ic f x' (append_1 xs' ys)).\n  rewrite -> (IHxs' ys).\n  \n  rewrite -> (H_map_ic f x' xs').\n  rewrite -> (H_append_2_ic (f x') (map f xs') (map f ys)).\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\nProposition reverse_preserves_map_sort_of :\n  forall (T1 T2 : Type)\n         (append_1 : list T1 -> list T1 -> list T1)\n         (append_2 : list T2 -> list T2 -> list T2)\n         (reverse_1 : list T1 -> list T1)\n         (reverse_2 : list T2 -> list T2)\n         (map : (T1 -> T2) -> list T1 -> list T2),\n    specification_of_append T1 append_1 ->\n    specification_of_append T2 append_2 ->\n    specification_of_reverse T1 reverse_1 ->\n    specification_of_reverse T2 reverse_2 ->\n    specification_of_map T1 T2 map ->\n    forall (f : T1 -> T2)\n           (xs : list T1),\n      map f (reverse_1 xs) = reverse_2 (map f xs).\nProof.\n  intros T1 T2 append1 append2 reverse1 reverse2 map.\n  intros S_append1 S_append2 S_reverse1 S_reverse2 S_map.\n  intros f xs.\n\n  assert (S_map_ := S_map).\n  assert (S_append1_ := S_append1).\n  assert (S_append2_ := S_append2).\n\n  destruct (S_reverse1 append1 S_append1) as [H_reverse1_bc H_reverse1_ic].\n  destruct (S_reverse2 append2 S_append2) as [H_reverse2_bc H_reverse2_ic].\n  clear S_reverse1 S_reverse2.\n  destruct S_append1 as [H_append1_bc H_append1_ic].\n  destruct S_append2 as [H_append2_bc H_append2_ic].\n  destruct S_map as [H_map_bc H_map_ic].\n  \n  induction xs as [| x' xs' IHxs'].\n\n  rewrite -> H_reverse1_bc.\n  rewrite -> H_map_bc.\n  rewrite -> H_reverse2_bc.  \n  reflexivity.\n\n  rewrite -> (H_reverse1_ic x' xs').\n  rewrite -> (append_preserves_map T1 T2 map append1 append2 S_map_ S_append1_ S_append2_\n                                   f (reverse1 xs') (x' :: nil)).\n  rewrite -> (H_map_ic f x' nil).\n  rewrite -> (H_map_bc f).\n  rewrite -> IHxs'.\n\n  rewrite -> (H_map_ic f x' xs').\n  rewrite -> (H_reverse2_ic (f x') (map f xs')).\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* end of week_37b_lists.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w37/week_37_Tsanas_JanPhilip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8962513703624558, "lm_q1q2_score": 0.8019562726075502}}
{"text": "Add LoadPath \"~/mystudy/Coq\u5165\u9580\".\n(* Require Import Basics_J. *)\nRequire Import Unicode.Utf8_core.\n\nModule NatList.\n\nInductive natprod : Type :=\n  pair : nat \u2192 nat \u2192 natprod.\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\n\nNotation \"( x , y )\" := (pair x y).\n\n\nEval simpl in (fst (3,4)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : \u2200 (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\n\nTheorem surjective_pairing : \u2200 (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 : \u2200 (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p. simpl. auto.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat \u2192 natlist \u2192 natlist.\n\n\nDefinition l_123 := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity. Qed.\nExample test_app2: nil ++ [4,5] = [4,5].\nProof. reflexivity. Qed.\nExample test_app3: [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity. Qed.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tail (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1: hd 0 [1,2,3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tail: tail [1,2,3] = [2,3].\nProof. reflexivity. Qed.\n\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605, recommended (list_funs)\n\u4ee5\u4e0b\u306e nonzeros\u3001 oddmembers\u3001 countoddmembers \u306e\u5b9a\u7fa9\u3092\u5b8c\u6210\u3055\u305b\u306a\u3055\u3044\u3002\n*)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n   match l with\n   | nil => nil\n   | x::xs => match x with\n     | 0 => nonzeros xs\n     | _ => x::(nonzeros xs)\n     end\n   end.\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\nFixpoint odd (x:nat) :=\n  match x with\n  | O => false\n  | S x' => even x'\n  end\nwith even (x:nat) :=\n  match x with\n  | O => true\n  | S x' => odd x'\n  end.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n   match l with\n   | nil => nil\n   | x::xs => match odd x with\n     | true => x::(oddmembers xs)\n     | false => oddmembers xs\n     end\n   end.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. reflexivity. Qed.\n\nFixpoint 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\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | x::xs => match l2 with\n    | nil => x::xs\n    | y::ys => x::y::(alternate xs ys)\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. (* multiset *)\n\nFixpoint eq_b (n m:nat) :=\n  match n with\n  | O => match m with\n    | O => true\n    | _ => false\n    end\n  | S n' => match m with\n    | O => false\n    | S m' => eq_b n' m'\n    end\n  end.\n\nLemma eq_b_is_eq: forall n m : nat, n = m <-> eq_b n m = true.\nProof.\n  split.\n  intros.\n  induction n. rewrite <- H. auto.\n  Admitted.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\n(*   | v::xs => S(count v xs) (* v\u304c\u5909\u6570\u6271\u3044\u3055\u308c\u3066\u30c0\u30e1\u306a\u306e\u304b *) *)\n  | x::xs => match eq_b x v with\n    | true => S(count v xs)\n    | false => count v xs\n    end\n  end.\n\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 \u2192 bag \u2192 bag :=\n   alternate.\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n   sum [v] s.\n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\nProof. auto. Qed.\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nProof. auto. Qed.\n\nFixpoint lt_b n m :=\n  match n with\n  | O => true\n  | S n' => match m with\n    | O => false\n    | S m' => lt_b n' m'\n    end\n  end.\n\nDefinition member (v:nat) (s:bag) : bool :=\n   lt_b 1 (count v s).\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. auto. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. auto. Qed.\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605, optional (bag_more_functions)\n\u7df4\u7fd2\u3068\u3057\u3066\u3001\u3055\u3089\u306b\u3044\u304f\u3064\u304b\u306e\u95a2\u6570\u3092\u4f5c\u6210\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n*)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | x::xs => match eq_b v x with\n    | true => xs\n    | false => x::(remove_one v xs)\n    end\n  end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2,1,5,4,1]) = 0.\nProof. auto. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\nProof. auto. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\nProof. auto. Qed.\nExample test_remove_one4:\n  count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\nProof. auto. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n   match s with\n   | nil => nil\n   | x::xs => match eq_b v x with\n     | true => remove_all v xs\n     | false => x::(remove_all v xs)\n     end\n   end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. auto. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. auto. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. auto. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\nProof. auto. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | x::xs => match count x s2 with\n    | O => false\n    | _ => subset xs (remove_one x s2)\n    end\n  end.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\nProof. auto. Qed.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\nProof. auto. Qed.\n\n(*\n\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605, recommended (bag_theorem)\ncount \u3084 add \u3092\u4f7f\u3063\u305f\u30d0\u30c3\u30b0\u306b\u95a2\u3059\u308b\u9762\u767d\u3044\u5b9a\u7406\u66f8\u304d\u3001\u305d\u308c\u3092\u8a3c\u660e\u3057\u306a\u3055\u3044\u3002\u3053\u306e\u554f\u984c\u306f\u3044\u308f\u3086\u308b\u81ea\u7531\u8ab2\u984c\u3067\u3001\u771f\u306b\u306a\u308b\u3053\u3068\u304c\u308f\u304b\u3063\u3066\u3044\u3066\u3082\u3001\u8a3c\u660e\u306b\u306f\u307e\u3060\u7fd2\u3063\u3066\u3044\u306a\u3044\u6280\u3092\u4f7f\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u5b9a\u7406\u3092\u601d\u3044\u3064\u3044\u3066\u3057\u307e\u3046\u3053\u3068\u3082\u3042\u308a\u307e\u3059\u3002\u8a3c\u660e\u306b\u884c\u304d\u8a70\u307e\u3063\u3066\u3057\u307e\u3063\u305f\u3089\u6c17\u8efd\u306b\u8cea\u554f\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n\n*)\n\n(* \u3046\uff57 *)\n\nLemma remall: forall (x : nat) (s : natlist),\n  count x (remove_all x s) = 0.\nProof.\n  intros.\n  induction s.\n  - (* s = nil *)\n    simpl. reflexivity.\n  - (* s = x::xs *)\n    simpl.\n    destruct (eq_b x n).\n    -- (* eq_b x n = true *)\n      rewrite IHs. reflexivity.\n    -- (* eq_b x n = false *)\n      Admitted. (* TODO : eq_b x n = false \u304c\u4eee\u5b9a\u306b\u306a\u3044\u306e\u306f\u306a\u305c\u2026 *)\n\nTheorem nil_app : \u2200 l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity. Qed.\n\n\nTheorem tl_length_pred : \u2200 l:natlist,\n  pred (length l) = length (tail l).\nProof.\n  intros l. destruct l as [| n l'].\n  -\n    reflexivity.\n  -\n    reflexivity. Qed.\n\nTheorem app_ass : \u2200 l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem app_length : \u2200 l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n  match l with\n  | nil => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\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\nTheorem length_snoc : \u2200 n : nat, \u2200 l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l. induction l as [| n' l'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\n\nTheorem rev_length : \u2200 l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> length_snoc.\n    rewrite -> IHl'. reflexivity. Qed.\n\nSearchAbout rev.\n\n(*\n\u7df4\u7fd2\u554f\u984c: \u2605\u2605\u2605, recommended (list_exercises)\n\u30ea\u30b9\u30c8\u306b\u3064\u3044\u3066\u3055\u3089\u306b\u7df4\u7fd2\u3057\u307e\u3057\u3087\u3046\u3002\n\n*)\n\nTheorem app_nil_end : \u2200 l : natlist,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma rev_snoc: forall (x : nat) (l : natlist),\n  rev (snoc l x) = x:: rev l.\nProof.\n  intros.\n  induction l.\n  -\n    simpl. reflexivity.\n  -\n    simpl. rewrite IHl.\n    simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : \u2200 l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l.\n  -\n    reflexivity.\n  -\n    simpl.\n    rewrite rev_snoc.\n    rewrite IHl. reflexivity.\nQed.\n\nLemma snoc_app: forall (l1 l2 : natlist) (x : nat),\n  snoc (l1 ++ l2) x = l1 ++ snoc l2 x.\nProof.\n  intros.\n  induction l1.\n  -\n    reflexivity.\n  -\n    simpl.\n    rewrite IHl1.\n    reflexivity.\nQed.\n\nTheorem distr_rev : \u2200 l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros.\n  induction l1.\n  -\n    simpl.\n    SearchAbout ([]).\n    rewrite app_nil_end.\n    reflexivity.\n  -\n    simpl.\n    rewrite IHl1.\n    rewrite snoc_app.\n    reflexivity.\nQed.\n\n\n(*\n\u6b21\u306e\u554f\u984c\u306b\u306f\u7c21\u5358\u306a\u89e3\u6cd5\u304c\u3042\u308a\u307e\u3059\u3002\u3053\u3093\u304c\u3089\u304c\u3063\u3066\u3057\u307e\u3063\u305f\u3088\u3046\u3067\u3042\u308c\u3070\u3001\u5c11\u3057\u623b\u3063\u3066\u5358\u7d14\u306a\u65b9\u6cd5\u3092\u63a2\u3057\u3066\u307f\u307e\u3057\u3087\u3046\u3002\n*)\n\nTheorem app_ass4 : \u2200 l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n\n\n\nTheorem snoc_append : \u2200 (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\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": "LumaKernel", "repo": "mynote", "sha": "a3114cbba3b69fa27a20c8baeb38d3199c8937e9", "save_path": "github-repos/coq/LumaKernel-mynote", "path": "github-repos/coq/LumaKernel-mynote/mynote-a3114cbba3b69fa27a20c8baeb38d3199c8937e9/note-coq/playground/Lists_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.8933093975331752, "lm_q1q2_score": 0.8019196503407299}}
{"text": "(* Final Exam --- January 8, 2018 *)\nRequire Import Nat.\nRequire Import List.\n\nNotation \"[ ]\" := nil. \nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition admit {T: Type} : T.  Admitted.\n\n(* 1. Define a function createList such that (createList n) returns \na list of n numbers from 1 to n. *)\n\nFixpoint createList (n : nat) : list nat :=\n match n with\n | O => nil\n | S n' => (createList n') ++ [n]\nend.\n\nExample test1 : createList 5 = [1;2;3;4;5].\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n\n(* 2. Complete the following definition so that (last n l) holds iff\n n is the last element of the list l. *)\n\nInductive last (n : nat) : list nat -> Prop :=\n  | last_emp: False -> last n []\n  | last_single: forall m, m = n -> last n [m]\n  | last_nxt: forall m l, last n l -> last n ([m] ++ l).\n\n\nExample test2 : last 5 [1;2;3;4;5].\nProof. apply last_nxt. apply last_nxt. apply last_nxt. apply last_nxt.\n apply last_single. reflexivity. Qed.\n\nExample test3 : forall n, ~ (last n [ ]).\nProof. unfold not. intros. inversion H. inversion H0. Qed.\n\n\n(* 3. Define the Fibonacci sequence. The function (fib n) returns the first\nn Fibonacci numbers. *)\nFixpoint fib (n: nat) : list nat :=\n  match n with\n  | O => [0]\n  | S n' => match n' with\n            | O => (fib n') ++ [1] \n            | S m => (fib n') ++ [(hd 0 (rev(fib m)) + hd 0 (rev(fib n')))] \n            end\n  end.\n\nPrint hd.\n\nExample test4 :  fib 15 =\n[0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610].\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n\n(* 4. Prove that the excluded middle axiom implies the double negation axiom. *)\nTheorem double_negation : \n  (forall P, P \\/ ~P) -> (forall P, ~~P <-> P).\nProof. \nintros.\nsplit.\n- destruct (H(P)).\n  + intros. apply H0.\n  + intros. \n    unfold not in H1.\n    unfold not in H0.\n    apply H1 in H0.\n    inversion H0.\n- destruct (H(P)).\n  + intros.\n    unfold not.\n    intros.\n    apply H2 in H0.\n    inversion H0.\n  + intros.\n    apply H0 in H1.\n    inversion H1.\nQed. \n\n\n(* 5. Define the greater than relation and show its transitivity. *)\nInductive gt : nat -> nat -> Prop :=\n| equal : forall n, gt n n\n| greater : forall n m, (gt n m) -> (gt (S n) m).\n\nExample test5 : gt 3 1.\nProof.\napply greater.\napply greater.\napply equal.\nQed.\n\nExample test6 : ~ (gt 1 2).\nProof.\nunfold not.\nintros H.\ninversion H.\ninversion H1.\nQed.\n\nExample gt_transitive : forall m n p,\n  gt m n -> gt n p -> gt m p.\nProof.\nintros.\ninduction H.\n- apply H0.\n- apply greater.\n  apply IHgt.\n  apply H0.\nQed.\n\n(* \u4f5c\u4e1a\u539f\u9898 *)\n\n(* 6. Consider the following function f. What does this function do? *)\nFixpoint f (l: list nat) : list nat :=\n   match l with\n   | nil => l\n   | h :: t => f t ++ [h]\n   end.\n\nLemma app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\nintros.\ninduction l as [| h l' IHl'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nLemma app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\nintros.\ninduction l as [| h l' IHl'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nLemma rev_app_distr: forall l1 l2 : list nat,\n  f (l1 ++ l2) = f l2 ++ f l1.\nProof.\nintros.\ninduction l1 as [| h1 l1 IHl1'].\n- simpl. rewrite -> app_nil_r. reflexivity.\n- simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed.\n\n(* Show that function f has the following property. *)\nTheorem double_f : forall l : list nat,\n  f (f l) = l.\nProof.\nintros.\ninduction l as [| h l' IHl'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite -> rev_app_distr. rewrite -> IHl'.\n  simpl.\n  reflexivity.\nQed.\n\n\n(* 7. Complete the following definition so that (div3 n) returns true \niff n is divisible by 3. *)\n\nFixpoint div3 (n : nat) : bool :=\n match n with\n | O => true\n | S O => false\n | S (S O) => false\n | S (S (S n')) => (div3 n')\nend.\n\nExample test7: div3 12 = true.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nExample test8: div3 13 = false.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n\n(* 8. Write a function (partition):\n\n      partition : list nat -> list nat * list nat\n\n   which partitions a list into a pair of sublists. The first member of\n   the pair is the sublist of the original list containing the\n   elements divisible by 3, and the second is the sublist\n   containing those that are not divisible by 3.  The order of elements in the\n   two sublists should be the same as their order in the original list. \n\n   Hint: You can make use of the Coq function (filter).\n*)\n\nDefinition partition (l : list nat)\n                   : list nat * list nat :=\n  (filter div3 l, filter (fun n => if (div3 n) then false else true) l).\n\nExample test9: partition [1;2;3;4;5;6] = ([3;6], [1;2;4;5]).\nProof.\nunfold partition.\nreflexivity.\nQed.\n\n\n(* 9. Consider the following type:\n\nInductive btree : Set :=\n | leaf : btree \n | node : nat->btree->btree->btree.\n\nDefine a function taking as argument a natural number n\nand a tree t: btree and returning true iff t has (at least) \nan occurrence of n. \n\nHint: You may use the function (eqb n m) which returns true iff the two natural\nnumbers n and m are equal.\n*)\n\n\nInductive btree : Set :=\n | leaf : btree\n | node : nat->btree->btree->btree.\n\nFixpoint occur (n: nat)(t: btree) : bool :=\n  match t with\n    | leaf => false\n    | node m tl tr => match (eqb m n) with\n                        | true => true\n                        | false => orb (occur n tl)  (occur n tr)\n                      end\n  end.\n\n\nExample test10 : occur 2 (node 1 leaf (node 3 (node 2 leaf leaf) leaf)) = true.\nProof. reflexivity. Qed.\n\n\n(* 10. The following definitions specify the abstract syntax of\n    some arithmetic expressions and an evaluation function. *)\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\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(* Suppose we define a function that takes an arithmetic expression \n   and slightly simplifies it, changing every occurrence of [e+0] \n   (i.e., [(APlus e (ANum 0)]) into just [e]. *)\n\nFixpoint optimize_plus0 (a:aexp) : aexp :=\n  match a with\n  | ANum n =>\n      ANum n\n  | APlus e1 (ANum 0) => optimize_plus0 e1\n  | APlus e1 e2 =>\n      APlus (optimize_plus0 e1) (optimize_plus0 e2)\n  | AMinus e1 e2 =>\n      AMinus (optimize_plus0 e1) (optimize_plus0 e2)\n  | AMult e1 e2 =>\n      AMult (optimize_plus0 e1) (optimize_plus0 e2)\n  end.\n\n(* Prove the following theorem that states the correctness of the \noptimization with respect to the evaluation of arithmetic expressions. *)\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [|n' IHn'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. destruct m as [|m'].\n  + rewrite -> IHn'. reflexivity.\n  + rewrite -> IHn'. rewrite plus_n_Sm. reflexivity. Qed. \n\n(* \u4f5c\u4e1a\u539f\u9898 *)\nTheorem optimize_plus0_sound: forall a,\n  aeval (optimize_plus0 a) = aeval a.\nProof.\n  intros.\n  induction a ;try (simpl;reflexivity).\n  destruct a2; \n  try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n  destruct n.\n  simpl; rewrite <- IHa1; rewrite plus_comm;reflexivity.  \n  simpl. rewrite <- IHa1. reflexivity. simpl. simpl in IHa2.  rewrite IHa2. rewrite <- IHa1. reflexivity.\n  simpl. simpl in IHa2. rewrite IHa2. rewrite <- IHa1. reflexivity.\n  simpl. simpl in IHa2. rewrite IHa2. rewrite <- IHa1. reflexivity.\n  simpl. simpl in IHa2. rewrite IHa2. rewrite <- IHa1. reflexivity.\n  simpl. simpl in IHa2. rewrite IHa2. rewrite <- IHa1. reflexivity.\nQed.\n", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/Solutions/exam2018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8933093989533708, "lm_q1q2_score": 0.8019196418356848}}
{"text": "Require Import ssreflect ssrnat.\n\n(**\n# \u7b2c7\u56de \u30bd\u30fc\u30b9\u30d5\u30a1\u30a4\u30eb\u306e\u5206\u5272\u3068\u30b3\u30f3\u30d1\u30a4\u30eb/Section\u3068Module (2014/05/18)\n\nhttp://qnighy.github.io/coqex2014/ex7.html\n\n## \u8ab2\u984c33 (\u7a2e\u5225:B / \u7de0\u3081\u5207\u308a : 2014/06/01)\n\n2\u3067\u5b9a\u7fa9\u3057\u305flist bool\u306e\u30e2\u30b8\u30e5\u30fc\u30eb\u3068\u30013\u3067\u5b9a\u7fa9\u3057\u305f\u51aa\u4e57\u306e\u30e2\u30b8\u30e5\u30fc\u30eb\u3092\u5408\u6210\u3057\u3066\u3001\u65b0\u305f\u306a\u30e2\u30b8\u30e5\u30fc\u30eb\u3092\n\u4f5c\u6210\u305b\u3088\u3002\n\n\u30d2\u30f3\u30c8\n\n\u30e2\u30b8\u30e5\u30fc\u30eb\u3078\u306e\u6a5f\u80fd\u306e\u8ffd\u52a0\u306e\u7df4\u7fd2\u3067\u3059\u3002\u6a19\u6e96\u30e9\u30a4\u30d6\u30e9\u30ea\u306eCoq.Structures\u306e\u8a18\u8ff0\u3092\u53c2\u8003\u306b\u3059\u308b\u3068\u3088\u3044\u3067\u3057\u3087\u3046\u3002\n*)\n\n(**\n### 1.\n\n\u8ab2\u984c32\u306e\u534a\u7fa4\u30e2\u30b8\u30e5\u30fc\u30eb\u578b\u3092\u53c2\u8003\u306b\u3057\u3066\u3001\u30e2\u30ce\u30a4\u30c9\u3092\u8868\u3059\u30e2\u30b8\u30e5\u30fc\u30eb\u578b Monoid \u3092\u5b9a\u7fa9\u305b\u3088\u3002\n *)\nRequire Import Arith List.\n\nModule Type Monoid.\n  Parameter G : Type.\n  Parameter Id : G.                         (* \u5358\u4f4d\u5143 *)\n  Parameter mult : G -> G -> G.\n  Axiom mult_assoc :                        (* \u7d50\u5408\u5247 *)\n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\n  Axiom left_id :                           (* \u5de6\u5358\u4f4d\u5143 *)\n    forall x : G, mult Id x = x.\n  Axiom right_id :                          (* \u53f3\u5358\u4f4d\u5143 *)\n    forall x : G, mult x Id = x.\nEnd Monoid.\n\n(**\n### 2.\n\nlist bool\u306b\u81ea\u7136\u306a\u30e2\u30ce\u30a4\u30c9\u306e\u69cb\u9020\u3092\u5165\u308c\u3001Monoid\u578b\u3092\u3082\u3064\u30e2\u30b8\u30e5\u30fc\u30eb\u3068\u3057\u3066\u5b9a\u7fa9\u305b\u3088\u3002\n*)\n\nCheck list bool.\nCheck @nil bool.\nCheck @app bool.\n\nModule BoolList_Monoid <: Monoid.\n  Definition G := list bool.\n  Definition Id := @nil bool.               (* [] *)\n  Definition mult := @app bool.             (* append. *)\n  Theorem mult_assoc :\n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\n  Proof.\n    by apply: app_assoc.\n  Qed.\n  Theorem left_id : forall x : G, mult Id x = x.\n  Proof.\n    by [].\n  Qed.\n  Theorem right_id : forall x : G, mult x Id = x.\n  Proof.\n    elim.\n      by [].\n    by move=> a l /= ->.\n  Qed.\nEnd BoolList_Monoid.\n\n(*\n### 3.\n\n\u30e2\u30ce\u30a4\u30c9\u306e\u5143\u306e\u51aa\u4e57(\u6307\u6570\u306f\u81ea\u7136\u6570)\u3092\u5b9a\u7fa9\u3057\u3001\u6307\u6570\u6cd5\u5247\u3092\u8a3c\u660e\u305b\u3088\u3002\u3053\u308c\u3092\u5b9a\u7fa9\u3059\u308b\u969b\u3001\u5b9a\u7fa9\u6e08\u307f\u306e\nMonoid\u30e2\u30b8\u30e5\u30fc\u30eb\u3092\u76f4\u63a5\u5909\u66f4\u3059\u308b\u306e\u3067\u306f\u306a\u304f\u3001Monoid\u30e2\u30b8\u30e5\u30fc\u30ebM\u3092\u5f15\u6570\u306b\u3068\u308b\u65b0\u305f\u306a\u30e2\u30b8\u30e5\u30fc\u30eb\u3092\u5b9a\n\u7fa9\u3059\u308b\u3053\u3068\u3002\n*)\n\nModule Type Exponent (M : Monoid).\n  Parameter exp : M.G -> nat -> M.G.\n  Axiom exp_law_add : forall (x : M.G) (n m : nat),\n    M.mult (exp x n) (exp x m) = exp x (n + m).\n  Axiom exp_law_mul : forall (x : M.G) (n m : nat),\n    exp (exp x n) m = exp x (n * m).\nEnd Exponent.\n\nFixpoint app_exp (x : list bool) (n : nat) :=\n  match n with\n    | 0 => nil\n    | n'.+1 => app x (app_exp x n')\n  end.\nEval compute in app_exp (true :: nil) 0.    (* [] *)\nEval compute in app_exp (true :: false :: nil) 6.\nEval compute in app_exp (app_exp (true :: false :: nil) 2) 3.\nEval compute in app_exp (app_exp (true :: false :: nil) 3) 2.\n\nLemma app_add_exp_law :\n  forall (x : list bool) (n m : nat),\n    (app_exp x n) ++ (app_exp x m) = app_exp x (n + m).\nProof.\n  move=> x n m.\n  elim n.\n    by rewrite /= add0n.\n  move=> n' IHn /=.\n  rewrite -app_assoc.\n  by rewrite IHn.\nQed.\n\nLemma app_exp_null :\n  forall (n : nat), app_exp nil n = nil.\nProof.\n  elim.\n    by [].\n  move=> n IHn.\n  by rewrite /= IHn.\nQed.\n\nLemma app_mul_exp_law :\n  forall (x : list bool) (n m : nat),\n    app_exp (app_exp x n) m = app_exp x (n * m).\nProof.\n  move=> x n m.\n  elim: n.\n    by rewrite /= app_exp_null.\n\n  elim: m.\n    move=> n.\n    by rewrite /= !muln0 /=.\n  move=> m IHm n.\n  admit.                                    (* XXXX *)\nQed.  \n\nModule Exponent_exp <: Exponent BoolList_Monoid.\n  Definition exp := app_exp.\n  Theorem exp_law_add : forall (x : BoolList_Monoid.G) (n m : nat),\n    BoolList_Monoid.mult (exp x n) (exp x m) = exp x (n + m).\n  Proof.\n    apply: app_add_exp_law.\n  Qed.\n  Theorem exp_law_mul : forall (x : BoolList_Monoid.G) (n m : nat),\n    exp (exp x n) m = exp x (n * m).\n  Proof.\n    apply: app_mul_exp_law.\n  Qed.\nEnd Exponent_exp.\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/ex33.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.8017933600823092}}
{"text": "Inductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\nDefinition next_weekday (d : day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\nCompute next_weekday friday.\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true ) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true ) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | 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  | false => false\n  | true => (andb b2 b3)\n  end.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck (negb true).\nCheck negb.\n\nDefinition xorb (b1:bool) (b2:bool) : bool :=\n  andb (negb (andb b1 b2)) (orb b1 b2).\nExample test_xor1: (xorb true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_xor2: (xorb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_xor3: (xorb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_xor4: (xorb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground1.\n\nInductive mynat: Type :=\n  | O\n  | S (n : mynat).\n\nDefinition mypred (n : mynat) : mynat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\nInductive mynat' : Type :=\n  | stop\n  | tick (foo : mynat').\n\nDefinition minustwo (n : mynat) : mynat :=  \n  match n with\n  | O => O\n  | S O => O\n  | S (S (n')) => n'\n  end.\n\nCheck (S (S (S (S O)))).\nEval simpl in (minustwo (S (S (S (S O))))).\n\nFixpoint evenb (n:mynat): bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:mynat) : bool := negb (evenb n).\n\nEval simpl in evenb (S (S (S (S (S O))))).\nEval simpl in oddb (S (S (S (S (S O))))).\nCompute oddb (S (S (S (S (S O))))).\nExample test_oddb1: (oddb (S O)) = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint plus (n:mynat) (m:mynat) : mynat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\nFixpoint mult (n m:mynat) : mynat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\nFixpoint minus (n m:mynat) : mynat :=\n  match n, m with\n  | O   , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\nFixpoint power (base index:mynat):mynat:=\n  match index with\n  | O => S O\n  | S n' => mult base (power base n')\n  end.\n\nEval simpl in plus (S (S (S O))) (S (S O)).\nEval simpl in mult (S (S (S O))) (S (S O)).\nEval simpl in minus (S (S (S O))) (S (S O)).\nEval simpl in power (S (S (S O))) (S (S O)).\n\nFixpoint factorial (n:mynat) : mynat :=\n  match n with\n  | O => S O\n  | S n' => mult n (factorial n')\n  end.\nExample test_factorial1: (factorial (S (S (S O)))) = S (S (S (S (S (S O))))).\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial (S (S (S (S (S O)))))) \n= (mult (mult (S (S O)) (S (S (S (S (S O))))))  (mult (S (S (S O))) (S (S (S (S O)))))).\nProof. simpl. reflexivity. Qed.\nNotation \"x + y\" := (plus x y) (at level 50, left associativity) : mynat_scope.\nNotation \"x - y\" := (minus x y) (at level 50, left associativity) : mynat_scope.\nNotation \"x * y\" := (mult x y) (at level 40, left associativity) : mynat_scope.\n\nFixpoint beq_nat (n m : mynat) : 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.\nFixpoint ble_nat (n m : mynat) : 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.\nDefinition blt_nat (n m : mynat) : bool :=\n andb (ble_nat n m) (negb (beq_nat n m)).\n\nExample test_blt_nat1: (blt_nat (S (S O)) (S (S O))) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat (S (S O)) (S (S (S (S O))))) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat (S (S (S (S O)))) (S (S O))) = false.\nProof. simpl. reflexivity. Qed.\nEnd Playground1.\n\nDefinition minustwo_ex (n : Playground1.mynat) : Playground1.mynat :=  \n  match n with\n  | Playground1.O => Playground1.O\n  | Playground1.S Playground1.O => Playground1.O\n  | Playground1.S (Playground1.S (n')) => n'\n  end.\n\nCheck (S (S (S (S 0)))).\n(*Eval simpl in (minustwo 4).*)\nCheck S.\nCheck Playground1.S.\n\nTheorem plus_0_n : forall n:nat, 0+n=n.\nProof. intros n. simpl. reflexivity. Qed.\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.\nTheorem plus_id_exercise : forall n m o:nat,\n  n=m->m=o->n+m=m+o.\nProof. intros n m o. intros H. intros I. rewrite <- I. rewrite<-H. reflexivity. Qed.\nTheorem mult_0_plus : forall n m:nat,\n  (0+n)*m=n*m.\nProof. intros n m. rewrite -> plus_0_n. reflexivity. Qed.\nTheorem mult_1_plus : forall n m:nat,(1+n)*m=m+(n*m).\nProof. intros n m. reflexivity. Qed.\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nTheorem plus_1_neq_0 : forall n:nat, beq_nat (n+1) 0 =false.\nProof. intros n. destruct n as [|n']. reflexivity. reflexivity. Qed.\nTheorem negb_involutive : forall b:bool, negb(negb b) = b.\nProof. intros b. destruct b. reflexivity. reflexivity. Qed.\nTheorem zero_nbeq_plus_1 : forall n:nat, beq_nat 0 (n+1) = false.\nProof. intros n. destruct n. reflexivity. reflexivity. Qed.\n\nTheorem plus_0_r : forall n:nat, n+0=n.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem minus_diag : forall n, minus n n = 0.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem mult_0_r : forall n:nat, n*0=0.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_n_Sm : forall n m:nat, S (n+m)=n+ (S m).\nProof. intros n m. induction n. rewrite plus_0_n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_comm : forall n m:nat, n+m=m+n.\nProof. intros n m. induction n. simpl. rewrite plus_0_r. reflexivity. simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity. Qed.\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. intros n. induction n. reflexivity. simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p:nat, n+(m+p)=(n+m)+p.\nProof. intros n m p. induction n. reflexivity. simpl. rewrite -> IHn. reflexivity. Qed.\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n  match reverse goal with\n  | H : _ |- _ => try move x after H\n  end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n  let H := fresh in\n  assert (x = v) as H by reflexivity;\n  clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n  first [\n    set (x := name); move_to_top x\n  | assert_eq x name; move_to_top x\n  | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\nTheorem mult_0_plus' : forall n m:nat, (0+n)*m=n*m.\nProof. intros n m. assert (H: 0 + n=n). reflexivity. rewrite -> H. reflexivity. Qed.\n\nTheorem plus_rearrange : forall n m p q:nat, (n+m)+(p+q)=(m+n)+(p+q).\nProof. intros n m p q. assert (H: n+m=m+n). rewrite plus_comm. reflexivity.\nrewrite H. reflexivity. Qed.\nTheorem plus_swap : forall n m p:nat, n+(m+p)=m+(n+p).\nProof. intros n m p. rewrite <- plus_comm. assert (H: p+n=n+p). rewrite plus_comm. reflexivity.\nrewrite <- H. assert(H2: m+(p+n)=(m+p)+n). rewrite plus_assoc. reflexivity. rewrite H2. reflexivity. Qed.\nTheorem S_plus : forall n:nat, S n = n+1.\nProof. intros n. induction n. reflexivity. assert (H1:S(S n)=S(n+1)). rewrite IHn. reflexivity.\nrewrite H1. simpl. reflexivity. Qed.\nTheorem mult_1 : forall n:nat, n*1=n.\nProof. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem mult_suc_r : forall n m:nat, n*(S m)=n+n*m.\nProof. induction n. reflexivity. simpl. intros m. rewrite IHn.\nrewrite plus_assoc. assert (H1:m+n=n+m). rewrite plus_comm. reflexivity.\nrewrite H1. rewrite plus_assoc. reflexivity. Qed.\nTheorem mult_comm : forall m n:nat, m*n=n*m.\nProof. induction m. intros n. rewrite mult_0_r. reflexivity.\nsimpl. intros n. rewrite IHm. simpl. rewrite mult_suc_r. 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.\nTheorem evenb_n__oddb_Sn : forall n:nat, evenb n=negb(evenb (S n)).\nProof. induction n. reflexivity. simpl. rewrite IHn. rewrite negb_involutive.\ndestruct n. reflexivity. reflexivity. Qed.\n\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof. reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof. destruct b. reflexivity. reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof. induction p. simpl. intros H. rewrite H. reflexivity.\nintros H2. simpl. rewrite IHp. reflexivity. rewrite H2. reflexivity. Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof. reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof. simpl. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\n\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n               (negb c))\n  = true.\nProof. destruct b. destruct c. reflexivity. reflexivity. destruct c. reflexivity. reflexivity. Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof. induction p. rewrite mult_0_r. rewrite mult_0_r. rewrite mult_0_r. reflexivity.\nrewrite mult_suc_r. rewrite mult_suc_r. rewrite mult_suc_r. rewrite IHp.\nrewrite plus_assoc. rewrite plus_assoc. \nassert (H0:m+n*p=n*p+m). rewrite plus_comm. reflexivity.\nassert (H1:n+m+n*p=n+n*p+m). rewrite <- plus_assoc. \nrewrite <- plus_assoc. rewrite H0. reflexivity.\nrewrite H1. reflexivity. Qed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof. induction n. reflexivity. simpl. intros m p. rewrite IHn. \nrewrite mult_plus_distr_r. reflexivity. Qed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof. intros n m p. rewrite plus_assoc. rewrite plus_assoc. replace (n+m) with (m+n).\nreflexivity. rewrite plus_comm. reflexivity. Qed.\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "elle-et-noire", "repo": "coq", "sha": "fd253f245131883ee55ff9f1824d4bb417b6e7b7", "save_path": "github-repos/coq/elle-et-noire-coq", "path": "github-repos/coq/elle-et-noire-coq/coq-fd253f245131883ee55ff9f1824d4bb417b6e7b7/study01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073577, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8017897642293281}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\n\nFixpoint div2 (n:nat):nat:=\n  match n with 0 => 0 | 1 => 0 | S (S p) => S (div2 p) end.\n\nFixpoint rem2 (n:nat):nat:=\n  match n with 0 => 0 | 1 => 1 | S (S p) => rem2 p end.\n\nTheorem div2_ind :\n  forall P: nat -> Prop,\n    P 0 -> P 1 ->\n    (forall n, P n -> P (S (S n))) ->\n    forall n, P n.\nProof.\n intros P H0 H1 Hstep n.\n assert (P n/\\P(S n)).\n elim n; intuition.\n intuition.\nQed.\n\nFixpoint fib (n:nat) : nat :=\n  match n with\n    0 => 1\n  | 1 => 1\n  | S ((S p) as q) => fib p + fib q\n  end.\n\nFixpoint fib2 (n:nat) : nat*nat :=\n  match n with\n    0 => (1, 1)\n  | S p => \n    let (v1, v2) := fib2 p in (v2, v1 + v2)\n  end.\n\nTheorem fib_ind :\n  forall P : nat -> Prop,\n    P 0 -> P 1 ->\n    (forall n, P n -> P (S n) -> P (S (S n)))->\n    forall n, P n.\nProof.\n intros P H0 H1 Hstep n.\n assert (P n/\\P(S n)).\n elim n; intuition.\n intuition.\nQed.\n\nTheorem div2_rem2_eq : forall n, 2 * div2 n + rem2 n = n.\nProof.\n intros n; elim n using div2_ind; try (simpl; auto with arith; fail).\n intros p IHp; pattern p at 3; rewrite <- IHp.\n simpl;ring.\nQed.\n\nTheorem fib_fib2_equiv : forall n, fib n = (fst (fib2 n)).\nProof.\n intros n; elim n using fib_ind; try(simpl;auto with arith;fail).\n intros p IHp IHSp.\n replace (fib (S (S p))) with (fib p + fib (S p)).\n rewrite IHp; rewrite IHSp.\n simpl.\n case (fib2 p); auto.\n auto.\nQed.\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch9_function_specification/SRC/div2tofib_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8017897620457347}}
{"text": "Inductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed. \n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => \n    match b2 with\n    | true => false\n    | false => true\n    end\n  | false => true\n  end.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | true => \n    match b2 with\n    | true => \n      match b3 with\n        | true => true\n        | false => false\n      end\n    | false => false\n    end\n  | false => false\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\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\nCompute (negb true).\nCompute (andb true false).\n\nExample test_orbff: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orbft: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orbtf: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orbtt: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample infixor: true || true || false = true.\nProof. simpl. reflexivity. Qed.\nExample infixand: true && true && false = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\nCheck (negb true).\nCheck negb.\nCheck andb.\n\nModule NatPlayground.\n  Inductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n  Definition pred (n : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => n'\n    end.\nEnd NatPlayground.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n : nat) : bool :=\n  negb (evenb n).\n\nFixpoint plus (n1 : nat) (n2 : nat) : nat :=\n  match n1 with\n  | O => n2\n  | S n' =>  S (plus n' n2)\n  end. \n\nFixpoint mul (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mul n' m) \n  end.\n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | S n', O => S n'\n  | S n', S m' => minus n' m'\n  end.\n\nExample mul33: (mul (S O) (S (S O))) = (S (S O)).\nProof. simpl. reflexivity. Qed.\nExample minus73: (minus 7 3) = 4.\nProof. simpl. reflexivity. Qed.\nCompute (plus 2 3).\nCompute (oddb 11).\nCompute (evenb 11).\nCompute (minustwo (S (S (S O)))).\nCompute (minustwo 9).\n\nFixpoint exp (a b : nat) : nat :=\n  match b with\n  | O => S O\n  | S p' => mul (exp a p') a\n  end.\n\nCompute (exp 2 4).\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mul (factorial n') n\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n(at level 50, left associativity) : nat_scope.\nNotation \"x - y\" := (minus x y)\n(at level 50, left associativity) : nat_scope.\nNotation \"x * y\" := (mul x y)\n(at level 40, left associativity) : 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', S m' => beq_nat n' m'\n  | _, _ => false\n  end.\n\nExample beq_nat11: (beq_nat 1 1) = true.\nProof. simpl. reflexivity. Qed.\nExample beq_nat10099: (beq_nat 100 99) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint leb (n m : nat) : bool :=\n  match n, m with \n  | O, _ => true\n  | _ , O => false\n  | S n', S m' => leb n' m'\n  end.\n\nExample leb12: (leb 1 2) = true.\nProof. simpl. reflexivity. Qed.\nExample leb21: (leb 2 1) = false.\nProof. simpl. reflexivity. Qed.\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.\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\nTheorem plus_1_1 : forall n:nat, 1 + n = S n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_O_1 : forall n : nat, 0 * n = 0.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_n_O : forall n, n = n + O.\nProof.\n  intros n. simpl. Abort.\n\nTheorem plus_id_example : forall n m : nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m. intros H. rewrite <- H. reflexivity. Qed.\n\nTheorem plus_id_excercise : forall n m : nat, \n  n = m -> m = O -> n + m = m + O.\nProof.\n  intros n m.\n  intros H.\n  intros P.\n  rewrite -> H.\n  rewrite -> P.\n  reflexivity.\nQed.\n\nTheorem  mult_O_plus : forall n m : nat,\n  (O + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_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_1.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_O : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative : forall b c,\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\nTheorem andb_exchange : forall a b c,\n  andb (andb a b) c = andb (andb a c) b .\nProof.\n  intros a b c. destruct a.\n  - destruct b.\n    { destruct c.\n      - reflexivity.\n      - reflexivity. }\n    { destruct c.\n      - reflexivity.\n      - reflexivity. }\n  - destruct b.\n    { destruct c.\n      - reflexivity.\n      - reflexivity. }\n    { destruct c.\n      - reflexivity.\n      - reflexivity. }\nQed.\n\nTheorem andb_communtative'' : forall a b,\n  a && b = b && a.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_true_elim1 : forall b c : bool,\n  andb b c = true -> b = true.\nProof.\n  intros [] [].\n  - reflexivity.\n  - simpl. intros H. \n    reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros [] [].\n  - reflexivity.\n  - simpl. intros H. \n    rewrite -> H. reflexivity.\n  - simpl. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice : \n  forall (f : bool -> bool),\n  (forall (x: bool), f x = x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f H b. rewrite -> H. rewrite -> H. reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall (x: bool), f x = negb x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f H b. rewrite -> H. rewrite -> H.\n  rewrite -> negb_involutive. reflexivity.\nQed.\n\nTheorem andb_eq_orb : \n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] []. \n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - reflexivity.\nQed.\n\nInductive bin : Type := \n  | O : bin\n  | T2 : bin -> bin\n  | P1 : bin -> bin.\n\n\n\nFixpoint incr (b : bin) : bin :=\n  match b with\n  | O => P1 (T2 O)\n  | T2 n' => \n    match n' with\n    | O => P1 (T2 O)\n    | P1 m => P1 (T2 (incr m))\n    | T2 m => P1 (T2 n')\n    end\n  | P1 n' => \n    match n' with\n    | O => T2 (P1 (T2 O))\n    | P1 m => P1 (incr n')\n    | T2 m => T2 (incr m)\n    end\n  end.\n\n(* \n1 + 2*(1 + m) = 1 + 2*(incr m)\n1 + 2*2*m \n1 + 1 + 1 + m = 1 + incr(m + 1)\n1 + 1 + 2*m = 2*(1 + m)\n*)\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n  | O => 0\n  | P1 n' => S (bin_to_nat n')\n  | T2 n' => mult 2 (bin_to_nat n')\n  end.\n\nCompute (incr (incr (incr O))).\nCompute (bin_to_nat (incr (incr (incr O)))).\n\nTheorem bin_P1_eq_P1_bin : forall (b : bin),\n  1 + (bin_to_nat b) = (bin_to_nat (P1 b)).\nProof.\n  intros b. simpl. reflexivity.\nQed.\n\nTheorem bin_T2_eq_P1_bin : forall (b : bin),\n  2 * (bin_to_nat b) = (bin_to_nat (T2 b)).\nProof.\n  intros b. simpl. reflexivity.\nQed.\n\nExample test_bin_incr1 : (incr (T2 (P1 (T2 O)))) = P1 (T2 (P1 (T2 O))).\nProof. reflexivity. Qed.\nExample test_bin_incr2 : (incr (P1 (T2 (P1 (T2 O)))) = (T2 (T2 (P1 (T2 O))))).\nProof. reflexivity. Qed.\nExample test_bin_incr3 : (incr (incr (incr (incr (incr (incr (incr (incr O)))))))) = T2 (T2 (T2 (P1 (T2 O)))).\nProof. reflexivity. Qed.\nExample test_bin_incr4 :  (incr (incr (incr (incr (incr (incr (incr (T2 (T2 (T2 (P1 (T2 O)))))))))))) = P1 (T2 (P1 (T2 (P1 (T2 (P1 (T2 O))))))).\nProof. reflexivity. Qed.\nExample test_bin_incr5 : (incr (incr (T2 (T2 (T2 (P1 (T2 O))))))) = T2 (P1 (T2 (T2 (P1 (T2 O))))).\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat1 : (bin_to_nat (incr (P1 (T2 (P1 (T2 O)))))) = (bin_to_nat (T2 (T2 (P1 (T2 O))))).\nProof. reflexivity. Qed.\nExample test_bin_to_nat2 : (bin_to_nat (incr (incr (P1 (T2 (P1 (T2 O))))))) = (bin_to_nat (T2 (T2 (P1 (T2 O))))) + 1.\nProof. reflexivity. Qed.\nExample test_bin_to_nat3 : (bin_to_nat (T2 (T2 (T2 (P1 (T2 O)))))) = (bin_to_nat (T2 (T2 (P1 (T2 O))))) + (bin_to_nat (T2 (T2 (P1 (T2 O))))).\nProof. reflexivity. Qed.\nExample test_bin_to_nat4 : (bin_to_nat (T2 (T2 (T2 (T2 (T2 (T2 (T2 (T2 (T2 (T2 (P1 (T2 O))))))))))))) = 1024.\nProof. reflexivity. Qed.\nExample test_bin_to_nat5 : (bin_to_nat (incr (incr (incr O)))) + (bin_to_nat (incr (incr O))) = (bin_to_nat (P1 (T2 (T2 (P1 (T2 O)))))).\nProof. reflexivity. Qed.\nExample test_bin_to_nat6 : (bin_to_nat  (T2 O)) = 0.\nProof. reflexivity. Qed.\n\n\n\nDefinition foo (t : False) : nat := 3.\n\nCheck foo.\nRequire Import Coq.omega.Omega.\nDefinition bar (l : list nat) (H : length l < 5) : { l : list nat | length l < 6}.\nrefine (exist _ (cons 0 l) _).\nsimpl. omega. Defined.\n\nExtraction bar.\nExtraction foo.\n(* create a subset type and take a proof argument and take in a list and a proof that the list has less than 5 elements *(\n(* incorrect inductive elimination, proofs can be eliminated only to build proofs *)\nDefinition bar (t : ) : nat :=\n  match t with\n  | conj I _ => 3\n  end.\n\nCheck bar.\nExtraction bar.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.8017897550222121}}
{"text": "Require Import List.\nImport ListNotations.\n\n(** * Preliminaries *)\n\n(** See the definition of lists *)\nPrint list.\n\n(** The raw constructors and the syntactic sugar *)\nCheck (cons 1 (cons 2 (cons 3 nil)) = [13;21]).\n\n(** Note that [Check] merely checks the type, not that the thing holds! *)\n\nCheck forall A (h:A) (t:list A), h::nil = cons h t.\n\nSection Lists_of_A.\n(* We use a section and a [Variable] so that we do not have to worry about [A]\n   at each definition / lemma *)\nVariable A: Type.\n\n(** ** Definition by pattern matching on lists *)\n\nDefinition tail (l : list A) : list A :=\n  match l with\n  | [] => []   (* functions are total in Coq ! *)\n  | h::t => t\n  end.\n\n(** Proof by computation *)\nLemma tail_1 : forall a b c, tail [a;b;c] = [b;c].\n  intros.\n  simpl.\n  trivial.\nQed.\n\n(** ** Definition by recursion (and pattern matching) *)\n\n(** The following definition always terminates:\n    the recursive call to length is allowed for subterms of [l] only (extracted by [match]) ! *)\n\nFixpoint length (l : list A) : nat :=\n  match l with\n  | [] => 0\n  | _ :: l' => S (length l')\n  end.\n\n(** Proof by case analysis *)\nLemma len_tail : forall l, l = [] \\/ 1 + length (tail l) = length l.\nProof.\n  (* for inductively defined objects,\n     we get a case for each constructor *)\n  destruct l.\n  + left.\n    trivial.\n  + right.\n    simpl tail.\n    simpl length.\n    (* or equivalently: simpl. *)\n    trivial.\nQed.\n\n(** Another definition, by induction on the first argument *)\nFixpoint app (l m : list A): list A :=\n  match l with\n  | [] => m\n  | a :: l1 => a :: app l1 m\n  end.\n\n(** Proof by induction on lists *)\nLemma app_length : forall l1 l2 : list A, \n  length l1 + length l2 = length (app l1 l2).\nProof.\n  (* similar to (destruct l1),\n     but you additionally get an induction hypothesis *)\n  induction l1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    intro.\n    rewrite -> IHl1.  (* [->] can be skipped; try also rewrite <- *)\n    reflexivity. (* trivial is also good enough *)\nQed.\n\n(** This lemma is very easy *)\nLemma app_nil_l : forall l, app nil l = l.\nProof.\n  simpl.\n  trivial.\nQed.\n\n(** What about this one? :) *)\nLemma app_nil_r : forall l, app l nil = l.\nProof.\n  simpl. (* no effect :) *)\n  (* exercise *)\nAdmitted.\n\n(** another proof by induction *)\nLemma app_assoc : forall l1 l2 l3 : list A,\n  app l1 (app l2 l3) = app (app l1 l2) l3.\nProof.\n  (* exercise *)\nAdmitted.\n\n(** recursive predicate on lists *)\nFixpoint In (a:A) (l:list A) : Prop :=\n  match l with \n  | [] => False\n  | h::t => a = h \\/ In a t\n  end.\n(* Note that we have defined a predicate [In : A -> list A -> Prop] by recursion on lists *)\n\n(* simple proof *)\nLemma In_sing : forall a:A, In a [a].\nProof.\n  intros.\n  simpl.\n  left.\n  trivial.\nQed.\n\n(** use the predicate by computing it *)\nLemma In_not_empty : forall (a:A) l, In a l -> l <> [].\nProof.\n  intros.\n  destruct l.\n  + simpl in H.\n    tauto.\n  + congruence. (* handle simple equality or disequality *)\nQed.\n\nLemma not_In_empty : forall a:A, ~ In a [].\nProof.\n  intros.\n  intro H.\n  simpl in H.\n  tauto.\nRestart. (* another possible proof *)\n  intros.\n  intro H.\n  apply In_not_empty in H as H2.  (* use a lemma for forward reasonning *)\n  apply In_not_empty in H. (* or simply if we don't care for the current state of H *)\n  congruence.  (* handle clearly wrong disequality in hypotheses *) \nQed.\n\nLemma in_app_or : forall a l1 l2, In a (app l1 l2) -> In a l1 \\/ In a l2.\nProof.\n  (* exercise *)\n  intros a l1 l2.\n  induction l1; intros; simpl.\n  + right.\n    simpl in H.\n    assumption.\n  + simpl in H.\n    destruct H as [B | C].\n    - intuition.\n    - apply IHl1 in C.\n      intuition.\nAdmitted.\n\n(** ** Inductive predicate *)\nInductive contains (a:A) : list A -> Prop :=\n| C_here : forall l, contains a (a::l)\n| C_there : forall l b, contains a l -> contains a (b::l).\n\n(* Corresponds to definitions by rules with \\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\n\nrule (C_here) \\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\n               contains a (a::l)\n\n\n                   contains a l\nrule (C_there) \\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\\u2013\n                 contains a (b::l)\n\n\nor to a Prolog definition:\n\ncontains(A, [[A|L]]).\ncontains(A, [[B|L]]] :- contains(A,L).\n\n*)\n\n\n(** proving an inductive predicate *)\nLemma cont_abc : forall a b c, contains b [a;b;c].\nProof.\n  intros.\n  apply C_there.\n  apply C_here.\nRestart. (* or simpler *)\n  intros.\n  constructor 2.\n  constructor 1.\nRestart. (* even simpler *)\n  intros.\n  constructor. (* any constructor that can be used *)\n  constructor.\nRestart. (* simplest *)\n  repeat constructor.\nQed.\n\n(** using an inductive predicate *)\nLemma cont_nempty : forall a l, contains a l -> l <> [].\nProof.\n  intros.\n  destruct H.  (* basic tactic - works well if [contains] is applied to variables *)\n  + congruence.\n  + congruence.\nQed.\n\nLemma not_cont_empty : forall a, ~ contains a [].\nProof.\n  intros.\n  intro H.\n  destruct H.  (* if [contains] is applied to terms other than variables,\n                  we can lose information *)\n  (* we are stuck *)\n  Undo.\n  inversion H. (* this works - [contains a []] is impossible\n                  and it is automatically discarded;\n                  both [C_here] and [C_there] need a non-empty list *)\n  (* do [Show Proof.] to see that some case analysis is really going on underneath *)\nQed.\n\n(** [inversion H] - for a hypothesis [H : C t1 t2] :\n   how could it happen that [C t1 t2] holds\n*)\n\n(* you may also try [inversion_clear] *)\nLemma cont_double : forall a b c, contains a [b;c] -> a=b \\/ a=c.\nProof.\n  (* exercise *)\nAdmitted.\n\n(** three lemmas establishing the correspondence between contains and In *)\nLemma cont_In : forall a l, contains a l -> In a l.\nProof.\n  (* exercise *)\nAdmitted.\n\nLemma In_cont : forall a l, In a l -> contains a l.\nProof.\n  (* exercise *)\nAdmitted.\n\n(* given the previous two lemmas, this one requires no more than three tactics *)\nLemma In_iff_cont : forall a l, In a l <-> contains a l.\nProof.\n  (* exercise *)\nAdmitted.\n\n\n(** ** Another inductive predicate *)\n\nInductive prefix : list A -> list A -> Prop :=\n| P_nil : forall l2, prefix [] l2\n| P_cons : forall a l1 l2, prefix l1 l2 -> prefix (a::l1) (a::l2).\n\nLemma pref_contains: forall a l, prefix [a] l -> contains a l.\nProof.\n  intros.\n  inversion H.\n  apply C_here.\nQed.\n\n(** a couple of simple lemmas *)\nLemma pref_reflexive: forall l, prefix l l.\nProof.\n (* exercise *)\nAdmitted.\n\n(* Hint: there are two lists to do induction on,\n   but only one will work. *)\nLemma pref_app : forall l1 l2, prefix l1 (l1++l2).\nProof.\n  (* exercise *)\nAdmitted.\n\nLemma pref_app2 : forall l1 l2 l3,\n  prefix l2 l3 -> prefix (l1++l2) (l1++l3).\nProof.\n  (* exercise *)\nAdmitted.\n\n(* Hint: this one needs induction + inversion *)\nLemma pref_short : forall l1 l2 l3, prefix (l1++l2) (l1++l3) -> prefix l2 l3.\nProof.\n  (* exercise *)\nAdmitted.\n\n(** example of proof by induction on the evidence for predicate \"prefix\" *)\nLemma pref_app3 : forall l1 l2 l3, prefix l1 l2 -> prefix l1 (l2++l3).\nProof.\n  intros.\n  induction H.\n  + constructor.\n  + simpl.\n    constructor.\n    trivial.\nQed.\n\n(** Hint: induction on the evidence for the first occurrence of \"prefix\" *)\nLemma pref_antisymm: forall l1 l2,\n  prefix l1 l2 -> prefix l2 l1 -> l1 = l2.\nProof.\n  (* exercise *)\nAdmitted.\n\n(** transitivity of prefix *)\nLemma pref_trans : forall l1 l2 l3, prefix l1 l2 -> prefix l2 l3 -> prefix l1 l3.\nProof.\n  intros.\n  induction H.\n  + constructor.\n  + (* IHprefix is useless! There are two reasons:\n      1) If prefix (a::l2) l3 than it is impossible that prefix l2 l3\n      2) we need to prove prefix (a :: l1) l3,\n         but the conclusion of the inductive assumption only says prefix l1 l3 *)\nRestart.  (* We need to strengthen our induction hypothesis\n             to the more general form forall l3... *)\n  intros l1 l2 l3 H.\n  revert l3.  (* now our goal is forall l3... ! *)\n  (* exercise *)\nAdmitted.\n\n(** ** Reversing lists for the bored ones only !!! *)\n\n(* this is the definition from the library, with quadratic time complexity *)\nFixpoint rev_slow (l: list A) :=\n  match l with\n  | [] => []\n  | h::t => rev_slow t ++ [h]\n  end.\n\n(* reversing in linear time using an accumulator *) \nFixpoint reva (lr l : list A) := match l with\n  | [] => lr\n  | h::t => reva (h::lr) t\nend.\n\nDefinition rev l := reva [] l.\n\nLemma rev_equiv: forall l: list A, rev l = rev_slow l.\nProof.\n  induction l.\n  + unfold rev. simpl. trivial.\n  + unfold rev in *.\n    simpl.\n    rewrite <- IHl.\n    simpl.\n    (* The inducton hypothesis is not strong enough *)\nAbort.\n\n(* This is a more general fact about the accumulator *)\n(* Hint: do induction on l3,\n   but make sure that the hypothesis is as general as possible! *)\nLemma reva_app: forall l1 l2 l3: list A,\n  reva (l1 ++ l2) l3 = reva l1 l3 ++ l2.\nProof.\n  (*Exercise*)\nAdmitted.\n\n(* Hint: specialise the previous lemma *)\nLemma reva_singl: forall a l,\n  reva [a] l = reva [] l ++ [a].\nProof.\n  (* Exercise *)\nAdmitted.\n\nLemma rev_equiv: forall l: list A, rev l = rev_slow l.\nProof.\n  induction l.\n  + unfold rev. simpl. trivial.\n  + unfold rev in *.\n    simpl.\n    rewrite <- IHl.\n    simpl. apply reva_singl.\nQed.\n\n(* another property we might want to prove is that reverse is an involution *)\nLemma rev_rev : forall l : list A, rev (rev l) = l.\nProof.\n  unfold rev.\n  induction l.\n  + simpl.\n    trivial.\n  + simpl.\n    (* No way! Induction hypothesis is no good. We need stronger assumptions... *)\nAbort.\n\n(* auxilary lemma 1 *)\nLemma reva_reva : forall l1 lr : list A, reva lr l1 = app (reva [] l1) lr.\nProof.\n  (* exercise *)\nAdmitted.\n\n(* auxilary lemma 2 *)\nLemma reva_app : forall l1 l2 lr, reva lr (app l1 l2) = app (reva [] l2) (reva lr l1).\nProof.\n  (* exercise *)\nAdmitted.\n\n(* Now, we can do the proof! *)\nLemma rev_rev : forall l : list A, rev (rev l) = l.\nProof.\n  (* exercise *)\nAdmitted.\n\n\n\n(* Hooray! *)\n\n\n(** ** Final notes *)\n\n\n(** NB: The official [rev] is quadratic (no problem unless you do some\n   serious computations within Coq) and friendlier with proofs *)\nPrint List.rev.\n(** NB2. [++] is [app] *)\nEval simpl in ([1;2;3] ++ [4;5;6]).\n\n(* see below *)\nCheck prefix.\nCheck app.\nCheck pref_trans.\n\nEnd Lists_of_A.\n\n(** NB3. Note that after closing the section, our definitions (and also lemmas)\n    get abstracted over variables from the section *)\nCheck prefix.\nCheck app.\nCheck pref_trans.\n\n(** This is the end... *)", "meta": {"author": "przxmek", "repo": "log-coq", "sha": "f189acd09bfef04f6961fb0ab45db88c61d35b14", "save_path": "github-repos/coq/przxmek-log-coq", "path": "github-repos/coq/przxmek-log-coq/log-coq-f189acd09bfef04f6961fb0ab45db88c61d35b14/lab/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8902942333990421, "lm_q1q2_score": 0.801736470831428}}
{"text": "(* begin hide *)\nRequire Import CoList.\nRequire Import CoTree.\nRequire Import PArith.\nRequire Import QArith.\n(* end hide *)\n\n(** * Enumerating The Rationals: The Calkin-Wilf Tree *)\n\n(** _Current Status: while the implementation of the tree and the deforestation\n    algorithm function perfectly, and were easy to implement, we haven't acutally\n    had the time to investigate proving anything with regard to our implementation_.\n  *)\n  \n(** The third approach of enumerating the rationals explored in the paper is the\n    construction and deforestation of the Calkin-Wilf tree.\n    \n    The Calkin-Wilf tree maps all levels in the Stern-Brocot tree to their\n    bit-reversal permutation.\n    \n  #\n    <img style=\"width:100%;\" alt=\"The Calkin-Wilf Tree\" src=\"calkin_wilf.png\" />\n  #\n  \n    Below we will construct the Calkin-Wilf tree.\n  *)\n\nModule CalkinWilf.\n\n  Local Open Scope positive_scope.\n  \n  (** The algorithm used to construct the Calkin-Wilf tree in the paper can be\n      seen below. It trivially translates to Coq, because it avoids all [0]'s,\n      and therefore we have no issues constructing rationals. Furthermore, it is\n      in itself much simpler.\n<<\n    rats6 :: [Rational]\n    rats6 = bf (unfold next (1, 1))\n      where next (m, n) = (m / n, (m, m + n), (n + m, n))\n>>\n      Our translation of the algorithm can be seen below.\n    *)\n\n  Definition next (q:positive*positive) : (positive*positive)*Q*(positive*positive) :=\n      match q with\n        | (m,n) => ((m,m + n),Zpos m # n,(m + n,n))\n      end.\n  \n  Definition tree : cotree Q := CoTree.unfold next (1,1).\n  \n  Definition enum : colist Q := CoTree.bf tree.\n\nEnd CalkinWilf.", "meta": {"author": "wenkokke", "repo": "EnumeratingTheRationals", "sha": "3257aa8c6ece5d1ad631a3295be4ef11e2e58f7e", "save_path": "github-repos/coq/wenkokke-EnumeratingTheRationals", "path": "github-repos/coq/wenkokke-EnumeratingTheRationals/EnumeratingTheRationals-3257aa8c6ece5d1ad631a3295be4ef11e2e58f7e/Enums/CalkinWilf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8705972734445508, "lm_q1q2_score": 0.8016369793541894}}
{"text": "Import Init.Nat.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import List.\nRequire Import Nat.\n\nFixpoint sum_n n :=\n  match n with\n    0 => 0\n  | S p => p + sum_n p\n  end.\n\nLemma sum_n_p : forall n, 2 * sum_n n + n = n * n.\n  induction n.\n  reflexivity.\n  assert (SnSn : S n * S n = n * n + 2 * n + 1).\n  ring.\n  rewrite SnSn.\n  rewrite <- IHn.\n  simpl.\n  ring.\nQed.\n\nFixpoint evenb n :=\n  match n with\n    0 => true\n  | 1 => false\n  | S (S p) => evenb p\n  end.\n\nLemma evenb_p : forall n, evenb n = true ->\n      exists x, n = 2 * x.\n  assert (Main :  \n    forall n,\n    (evenb n = true -> exists x, n = 2 * x) /\\\n    (evenb (S n) = true -> exists x, S n = 2 * x)).\n  induction n.\n  split. exists 0. ring.\n  simpl; intros H; discriminate H.\n  split.\n    destruct IHn as [_ IHn']; exact IHn'.\n  simpl evenb; intros H; destruct IHn as [IHn' _].\n  assert (H' : exists x, n = 2 * x).\n    apply IHn'; exact H.\n  destruct H' as [x q]; exists (x + 1); rewrite q; ring.\n  intros n ev.\n  destruct (Main n) as [H _].  apply H. exact ev.\nQed.\n\n(*\n\nExercise on addition, alternative definition We can define a new\naddition function on natural numbers:\n\nFixpoint add n m := match n with 0 => m | S p => add p (S m) end.\n\nProve the following statements.\nforall n m, add n (S m) = S (add n m)\nforall n m, add (S n) m = S (add n m)\nforall n m, add n m = n + m\n\nRemember that you may use a lemma you just proved when proving a new exercise\n\n*)\n\nFixpoint add n m := match n with 0 => m | S p => add p (S m) end.\n\nLemma add_assoc_l : forall n m, add n (S m) = S (add n m).\n  induction n.\n  simpl; reflexivity.\n  induction m.\n  simpl.\n  apply IHn.\n  simpl.\n  rewrite <- IHn with (m := S (S m)).\n  reflexivity.\nQed.\n\nLemma add_assoc_r : forall n m, add (S n) m = S (add n m).\n  induction n.\n  simpl; reflexivity.\n  induction m; simpl; apply IHn.\nQed.\n\nLemma add_plus : forall n m, add n m = n + m.\n  induction n.\n  intros m.\n  simpl.\n  reflexivity.\n  intros m.\n  simpl.\n  rewrite IHn.\n  ring.\nQed.\n\nFixpoint sum_odd_n (n : nat) : nat :=\n  match n with\n    0 => 0\n  | S p => 1 + 2 * p + sum_odd_n p \n  end.\n\nLemma sum_odd_n_lemma :  forall n : nat, sum_odd_n n = n * n.\n  induction n; simpl. reflexivity.\n  f_equal.\n  replace (n + 0) with n.\n  rewrite IHn.\n  ring.\n  ring.\nQed.\n\nDefinition is_zero (n : nat) : bool :=\n    match n with\n      0 => true\n    | _ => false\n    end.\n\nLemma not_is_zero_pred : \n    forall x, is_zero x = false -> S (Nat.pred x) = x.\n  intros x.\n  unfold is_zero, Nat.pred.\n  case x.\n  discriminate.\n  reflexivity.\nQed.\n\n(* Chap 6 *)\n\nRequire Import List.\nImport ListNotations.\n\nFixpoint insert n l :=\n  match l with\n    [] => n::nil\n  | a :: tl => if n <=? a\n                then n :: l\n                else a :: insert n tl\n  end.\n\nFixpoint sort l :=\n  match l with \n    [] => []\n  | a :: tl => insert a (sort tl)\n  end.\n\nFixpoint count n l :=\n  match l with\n    [] => 0\n  | a :: tl => \n      let r := count n tl \n        in if n =? a then 1+r else r\n  end.\n\nLemma insert_incr : forall n l, count n (insert n l) = 1 + count n l.\n  intros n l ; induction l.\n  { simpl.\n    rewrite Nat.eqb_refl.\n    reflexivity.\n  }\n  { simpl.\n    case (n <=? a).\n    { simpl. \n      rewrite Nat.eqb_refl.\n      reflexivity.\n    }\n    { simpl.\n      case (n =? a).\n      - rewrite IHl; reflexivity.\n      - rewrite IHl; reflexivity.\n    }\n  }\nQed.\n          \n", "meta": {"author": "dhilst", "repo": "coqstudy", "sha": "e24476c11c2945e18bc36ba4d0a8bad5a99b6c30", "save_path": "github-repos/coq/dhilst-coqstudy", "path": "github-repos/coq/dhilst-coqstudy/coqstudy-e24476c11c2945e18bc36ba4d0a8bad5a99b6c30/src/CoqHurry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.8016369669881311}}
{"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 => saturday\n  | saturday => sunday\n  | sunday => monday\n  end.\n\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday monday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday monday)) = wednesday.\n  Proof. 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\nCompute (andb true true).\nCompute (andb true false).\nCompute (andb false true).\nCompute (andb false false).\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.   \n\nExample test_orb5: true || true || false = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  negb (b1 && b2).\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  b1 && b2 && b3.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\nCheck negb.\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\nCheck (S (S O)).\n\nDefinition minusTwo (n:nat) : nat :=\n  pred (pred n).\n\nCheck minusTwo.\n\nCompute (minusTwo (S (S (S (S O))))).\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\n\nModule Playground2.\n\nFixpoint plus (n m:nat) : nat :=\n  match m with\n  | O => n\n  | S m' => plus (S n) m'\n  end.\n\nCompute (plus 3 3).\n\nFixpoint mult (n m:nat) : nat :=\n  match m with\n  | O => O\n  | S m' => plus n (mult n m')\n  end.\n\nCompute (mult 3 4).\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | S _, O => n\n  | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S p' => mult base (exp base p')\n  end.\n\nExample test_exp1: (exp 5 2) = 25.\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 5) = 120.\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.\n\nCheck ((0 + 1) + 1).\n\n\nFixpoint beq_nat (n m:nat) : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ => false\n  | S _, O => false\n  | S n', S m' => beq_nat n' m'\n  end.\n\nExample test_beq_nat1: (beq_nat 3 3) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_nat2: (beq_nat 4 3) = false.\nProof. simpl. reflexivity. Qed.\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  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\nTheorem plus_O_l: forall n : nat, O + 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_O_l: forall n : nat, O * n = O.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem mult_O_r: forall n: nat, n * O = O.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_O_r: forall n : nat, n = n + O.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_1_r: forall n: nat, S n = n + 1.\nProof.\n  intros.\n  induction n as [| n' IHn'].  \n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_id_example: forall n m : nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity. Qed.\n\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\nTheorem mult_O_plus: forall n m : nat,\n  (O + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_l.\n  reflexivity. Qed.\n\nTheorem mult_S_l: forall n m: nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity.  Qed.\n\nTheorem plus_1_neq_0: forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\n Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nTheorem andb_commutative: forall a b: bool,\n  a && b = b && a.\nProof.\n  intros a b. destruct a.\n    - destruct b.\n      + reflexivity.\n      + reflexivity.\n    - destruct b.\n      + reflexivity.\n      + reflexivity.\n  Qed.\n\n\nTheorem andb_true_elim2 : forall b c: bool,\n   (b && c) = true -> c = true.\nProof.\n  intros [] [].\n  intros H.\n  - reflexivity.\n  - simpl. intros. rewrite -> H. reflexivity.\n  - simpl. intros. reflexivity.\n  - simpl. intros. rewrite -> H. reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n: nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros [| n'].\n  - reflexivity.\n  - reflexivity. Qed.\n\n(* Fixpoint blah (n: nat) : nat :=\n  match n with\n  | O => blah (S O)\n  | _ => n\n  end.\n*)\n\n\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool), (forall (x : bool), f x = x) ->\n    forall (b : bool), f (f b) = b.\nProof.\n  intros.\n  destruct b.\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice : forall (f : bool -> bool),\n  (forall (x : bool), f x = negb x) ->\n    forall (b : bool), f (f b) = b.\nProof.\n  intros.\n  destruct b.\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem andb_eq_orb : forall (b c: bool),\n  (b && c = b || c) -> b = c.\nProof.                                     \n  intros b c.\n  destruct b.\n  - destruct c.\n    + reflexivity.\n    + simpl. intros. rewrite -> H. reflexivity.\n  - destruct c.\n    + simpl. intros. rewrite -> H. reflexivity.\n    + reflexivity.\nQed.\n\n\nInductive bin : Type :=\n  | Zero : bin\n  | TwicePlusOne : bin -> bin\n  | Twice : bin -> bin.\n\n\nFixpoint incr (b: bin) : bin :=\n  match b with\n  | Zero => TwicePlusOne Zero\n  | Twice n => TwicePlusOne n\n  | TwicePlusOne n => Twice (incr n)\n  end.\n\nFixpoint bin_to_nat (b: bin) : nat :=\n  match b with\n  | Zero => O\n  | Twice n => mult 2 (bin_to_nat n)\n  | TwicePlusOne n => (mult 2 (bin_to_nat n)) + 1\n  end.\n\nCompute (bin_to_nat (incr (incr (incr (incr Zero))))).\n\nExample test_bin_incr1: (bin_to_nat Zero) = 0.\nProof. reflexivity. Qed.\n\nExample test_bin_incr2: (bin_to_nat (incr Zero)) = 1.\nProof. reflexivity. Qed.\n\nExample test_bin_incr3: (bin_to_nat (incr (incr Zero))) = 2.\nProof. reflexivity. Qed.\n\nExample test_bin_incr4: (bin_to_nat (incr (incr (incr Zero)))) = 3.\nProof. reflexivity. Qed.\n\nExample test_bin_incr5: (bin_to_nat (incr Zero)) = S (bin_to_nat Zero).\nProof. reflexivity. Qed.\n\n", "meta": {"author": "atungare", "repo": "coq-software-foundations", "sha": "49bf005d87f530a54274ce9de06b6bce99c1e8aa", "save_path": "github-repos/coq/atungare-coq-software-foundations", "path": "github-repos/coq/atungare-coq-software-foundations/coq-software-foundations-49bf005d87f530a54274ce9de06b6bce99c1e8aa/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.8016253410575731}}
{"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_pred.\n\n  Variable (P : nat -> Prop)\n           (HP : forall p: { n | P n \\/ ~ P n }, { P (proj1_sig p) } + { ~ P (proj1_sig p) }).\n\n  Definition minimizer n := P n /\\ forall i, i < n -> ~ P i.\n\n  Inductive bar n : Prop :=\n    | in_bar_0 : P n -> bar n\n    | in_bar_1 : ~ P n -> bar (S n) -> bar n.\n\n  Let bar_ex n : bar n -> P n \\/ ~ P n.\n  Proof. induction 1; auto. Qed.\n\n  Let loop : forall n, bar n -> { k | P k /\\ forall i, n <= i < k -> ~ P i }.\n  Proof.\n    refine (fix loop n Hn { struct Hn } := match HP (exist _ n (bar_ex Hn)) with\n      | left H => exist _ n _\n      | right H => match loop (S n) _ with \n        | exist _ k Hk => exist _ k _\n      end \n    end).\n    * split; auto; intros; omega.\n    * destruct Hn; [ destruct H | ]; assumption.\n    * destruct Hk as (H1 & H2).\n      split; trivial; intros i Hi.\n      destruct (eq_nat_dec i n).\n      - subst; trivial.\n      - apply H2; 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    clear HP.\n    revert H1.\n    apply nat_rev_ind' with (k := k).\n    intros i H3.\n    apply in_bar_1, H2; trivial.\n    omega.\n  Qed.\n\n  Definition minimizer_pred : 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_pred.\n\nCheck minimizer_pred.\nPrint Assumptions minimizer_pred.\nRecursive Extraction minimizer_pred.\n\n(** Let P be a computable predicate:\n      - whenever P n has a value (P n or not P n) then that value can be computed\n    Then minimizer P is computable as well:\n      - whenever minimizer P holds for some n, then such an n can be computed\n *)\n      \n\nCorollary minimizer_alt (P : nat -> Prop) :\n    (forall n, P n \\/ ~ P n -> { P n } + { ~ P n }) -> ex (minimizer P) -> sig (minimizer P).\nProof.\n  intro H; apply minimizer_pred.\n  intros (n & Hn); apply H, Hn.\nDefined.\n\nCheck minimizer_alt.\nPrint Assumptions minimizer_alt.\nRecursive Extraction minimizer_alt.\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  Definition minimizer n := R n 0 /\\ forall i, i < n -> exists u, R i (S u).\n\n  Fact minimizer_fun n m : minimizer n -> minimizer m -> n = m.\n  Proof.\n    intros (H1 & H2) (H3 & H4).\n    destruct (lt_eq_lt_dec n m) as [ [ H | ] | H ]; auto; \n      [ apply H4 in H | apply H2 in H ]; destruct H as (u & Hu);\n      [ generalize (Rfun H1 Hu) | generalize (Rfun H3 Hu) ]; discriminate.\n  Qed. \n\n  Inductive bar n : Prop :=\n    | in_bar_0 : R n 0 -> bar n\n    | in_bar_1 : (exists u, R n (S u)) -> bar (S n) -> bar n.\n\n  Let bar_ex n : bar n -> ex (R n).\n  Proof.\n    induction 1 as [ n Hn | n (k & Hk) _ _ ].\n    exists 0; auto.\n    exists (S k); trivial.\n  Qed.\n\n  Let loop : forall n, bar n -> { k | R k 0 /\\ forall i, n <= i < k -> exists u, R i (S u) }.\n  Proof.\n    refine (fix loop n Hn { struct Hn } := match HR (bar_ex Hn) with\n        | exist _ u Hu => match u as m return R _ m -> _ with\n            | 0   => fun H => exist _ n _\n            | S v => fun H => match loop (S n) _ with\n                | exist _ k Hk => exist _ k _\n              end\n          end Hu\n      end).\n    * split; auto; intros; omega.\n    * destruct Hn as [ Hn | ]; trivial; exfalso; generalize (Rfun H Hn); discriminate.\n    * destruct Hk as (H1 & H2); split; trivial; intros i Hi.\n      destruct (eq_nat_dec i n).\n      - subst; exists v; trivial.\n      - apply H2; 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    clear Hmin HR.\n    revert H1.\n    apply nat_rev_ind' with (k := k).\n    intros i H3.\n    apply in_bar_1, H2; trivial.\n    omega.\n  Qed.\n\n  Definition minimizer_coq : sig minimizer.\n  Proof.\n    destruct (loop bar_0) as (k & H1 & H2).\n    exists k; split; auto.\n    intros; apply H2; omega.\n  Defined.\n\nEnd minimizer.\n\nCheck minimizer_coq.\nPrint Assumptions minimizer_coq.\n\nExtraction \"minimizer.ml\" 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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.8015963134486195}}
{"text": "(* bool ::= true | false *)\n\n\nInductive bool: Set :=\n  | true\n  | false\n.\n\n(* Cada linha iniciada com um s\u00edmbolo de pipeline, '|', representa um construtor; *)\n(* 'true' e 'false' s\u00e3o do tipo 'bool' e s\u00e3o as \u00fanicas express\u00f5es construtoras que pertencem a tal conjunto. *)\n\n\n\n\n(* ----------------------------------------- *)\n\n\n\n\n(* Deifini\u00e7\u00e3o 1.1. (negb) *)\n\n(* negb : bool -> bool *)\n\n(* |-------------------| *)\n(* |   b   | negb (b)  | *)\n(* |-------------------| *)\n(* | false |    true   | *)\n(* |  true |   false   | *)\n(* |-------------------| *)\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n\n\n\n(* Teorema 1.1. Demonstre que negb \u00e9 um fun\u00e7\u00e3o involutiva, ou seja, que, para todo 'b' em 'bool', negb (negb (b)) = b*)\nTheorem negb_involutive : forall (b : bool),\n  negb (negb b) = b.\nProof.\n\n  (*Seja 'b' em 'bool'.*)\n  intro b.\n  \n  destruct b eqn:E.\n\n  (*Caso b := true*)\n  - (* Pela defini\u00e7\u00e3o de 'negb', temos que negb (negb (true)) = true. *)\n    simpl.\n    (* Reflexividade da '=' *) \n    reflexivity.\n\n  (*Caso b := false*)\n  - (* Pela defini\u00e7\u00e3o de 'negb', temos que negb (negb (false)) = false. *)\n    simpl. \n    (* Reflexividade da '=' *)\n    reflexivity.\n\nQed.", "meta": {"author": "joaomendesln", "repo": "Coq", "sha": "6527fe7f2709a02c0d1425ef74e7173d47003212", "save_path": "github-repos/coq/joaomendesln-Coq", "path": "github-repos/coq/joaomendesln-Coq/Coq-6527fe7f2709a02c0d1425ef74e7173d47003212/Seminario_PET_2020_2/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.9019206659843132, "lm_q1q2_score": 0.8015899229261315}}
{"text": "Require Import Algebra.Semigroup.\nRequire Import Algebra.Monoid.\nSection GroupTheory.\nContext {G: Set}(mult: G -> G -> G)(ident: G)(inv: G -> G).\n\nClass Group := {\n  group_assoc: forall (a b c: G), mult (mult a b) c = mult a (mult b c);\n  group_ident_left: forall (a: G), mult ident a = a;\n  group_ident_right: forall (a: G), mult a ident = a;\n  group_inv_left: forall (a: G), mult (inv a) a = ident;\n  group_inv_right: forall (a: G), mult a (inv a) = ident;\n}.\n\nTheorem group_monoid:\n  Group -> Monoid mult ident.\nProof.\n  intros Ggroup.\n  constructor.\n  { apply group_assoc. }\n  { apply group_ident_left. }\n  { apply group_ident_right. }\nQed.\n\nTheorem group_semigroup:\n  Group -> Semigroup mult.\nProof.\n  intros Ggroup.\n  constructor.\n  apply group_assoc.\nQed.\n\nContext `{Ggroup: Group}.\n\nLemma group_left_mult (a b: G):\n  a = b -> forall (c: G), mult c a = mult c b.\nProof.\n  intros <-;\n    reflexivity.\nQed.\n\nLemma group_right_mult (a b: G):\n  a = b -> forall (c: G), mult a c = mult b c.\nProof.\n  intros <-;\n    reflexivity.\nQed.\n\nTheorem group_ident_unique (ident': G):\n  (forall (a: G), mult ident' a = a) ->\n  (forall (a: G), mult a ident' = a) ->\n  ident' = ident.\nProof.\n  intros Hlident' Hrident'.\n  rewrite <- (Hrident' ident).\n  rewrite <- (group_ident_left ident').\n  rewrite (group_ident_left (mult ident ident')).\n  reflexivity.\nQed.\n\nTheorem group_idemp_ident (a: G):\n  mult a a = a ->\n  a = ident.\nProof.\n  intros Hidemp.\n  apply group_right_mult with (c := inv a) in Hidemp.\n  rewrite group_assoc in Hidemp.\n  rewrite group_inv_right in Hidemp.\n  rewrite group_ident_right in Hidemp.\n  assumption.\nQed.\n\nTheorem group_left_cancel (a b c: G):\n  mult c a = mult c b -> a = b.\nProof.\n  intros Hcacb.\n  apply group_left_mult with (c := inv c) in Hcacb.\n  rewrite <- 2 group_assoc in Hcacb.\n  rewrite group_inv_left in Hcacb.\n  rewrite 2 group_ident_left in Hcacb.\n  assumption.\nQed.\n\nTheorem group_right_cancel (a b c: G):\n  mult a c = mult b c -> a = b.\nProof.\n  intros Hacbc.\n  apply group_right_mult with (c := inv c) in Hacbc.\n  rewrite 2 group_assoc in Hacbc.\n  rewrite group_inv_right in Hacbc.\n  rewrite 2 group_ident_right in Hacbc.\n  assumption.\nQed.\n\nTheorem group_inv_unique (a aInv: G):\n  mult aInv a = ident ->\n  mult a aInv = ident ->\n  aInv = inv a.\nProof.\n  intros Hlinv Hrinv.\n  rewrite <- (group_inv_right a) in Hrinv.\n  apply group_left_cancel in Hrinv.\n  assumption.\nQed.\n\nTheorem group_inv_involute (a: G):\n  inv (inv a) = a.\nProof.\n  symmetry.\n  apply group_inv_unique.\n  { apply group_inv_right. }\n  { apply group_inv_left. }\nQed.\n\nTheorem group_inv_mult (a b: G):\n  inv (mult a b) = mult (inv b) (inv a).\nProof.\n  symmetry.\n  apply group_inv_unique;\n    rewrite group_assoc.\n  { remember (mult (inv a) (mult a b)) as b'.\n    rewrite <- group_assoc in Heqb'.\n    rewrite group_inv_left in Heqb'.\n    rewrite group_ident_left in Heqb'.\n    subst b'.\n    apply group_inv_left. }\n  { remember (mult b (mult (inv b) (inv a))) as inva.\n    rewrite <- group_assoc in Heqinva.\n    rewrite group_inv_right in Heqinva.\n    rewrite group_ident_left in Heqinva.\n    subst inva.\n    apply group_inv_right. }\nQed.\n\nTheorem group_left_mult_soln (a b: G):\n  exists! (x: G), mult a x = b.\nProof.\n  exists (mult (inv a) b).\n  split.\n  { rewrite <- group_assoc.\n    rewrite group_inv_right.\n    rewrite group_ident_left.\n    reflexivity. }\n  { intros x Haxb.\n    apply group_left_mult with (c := inv a) in Haxb.\n    rewrite <- group_assoc in Haxb.\n    rewrite group_inv_left in Haxb.\n    rewrite group_ident_left in Haxb.\n    symmetry.\n    assumption. }\nQed.\n\nTheorem group_right_mult_soln (a b: G):\n  exists! (x: G), mult x a = b.\nProof.\n  exists (mult b (inv a)).\n  split.\n  { rewrite group_assoc.\n    rewrite group_inv_left.\n    rewrite group_ident_right.\n    reflexivity. }\n  { intros x Hxab.\n    apply group_right_mult with (c := inv a) in Hxab.\n    rewrite group_assoc in Hxab.\n    rewrite group_inv_right in Hxab.\n    rewrite group_ident_right in Hxab.\n    symmetry.\n    assumption. }\nQed.\n\nTheorem group_inv_ident:\n  inv ident = ident.\nProof.\n  symmetry.\n  apply group_inv_unique;\n    apply group_ident_right.\nQed.\nEnd GroupTheory.\n\nSection SemigroupTheory.\nContext {G: Set}(mult: G -> G -> G).\nContext `{Gsubgroup: Semigroup G mult}.\nContext (ident: G)(inv: G -> G).\n\nTheorem group_semigroup_left_ident_left_inv:\n  (Monoid mult ident /\\ Group mult ident inv) ->\n  forall (a: G), mult ident a = a /\\ mult (inv a) a = ident.\nProof.\n  intros [Gmonoid Ggroup] a.\n  split;\n    [apply monoid_ident_left | apply group_inv_left];\n    assumption.\nQed.\n\nTheorem group_semigroup_right_ident_right_inv:\n  (Monoid mult ident /\\ Group mult ident inv) ->\n  forall (a: G), mult a ident = a /\\ mult a (inv a) = ident.\nProof.\n  intros [Gmonoid Ggroup] a.\n  split;\n    [apply monoid_ident_right | apply group_inv_right];\n    assumption.\nQed.\n\nLemma semigroup_left_ident_left_inv_idemp_ident:\n  (forall (a: G), mult ident a = a) ->\n  (forall (a: G), mult (inv a) a = ident) ->\n  forall (a: G), mult a a = a -> a = ident.\nProof.\n  intros Hlident Hlinv a Hidemp.\n  apply semigroup_left_mult with (c := inv a)(mult0 := mult) in Hidemp.\n  rewrite <- semigroup_assoc in Hidemp;\n    try assumption.\n  rewrite Hlinv in Hidemp.\n  rewrite Hlident in Hidemp.\n  assumption.\nQed.\n\nLemma semigroup_right_ident_right_inv_idemp_ident:\n  (forall (a: G), mult a ident = a) ->\n  (forall (a: G), mult a (inv a) = ident) ->\n  forall (a: G), mult a a = a -> a = ident.\nProof.\n  intros Hrident Hrinv a Hidemp.\n  apply semigroup_right_mult with (c := inv a)(mult0 := mult) in Hidemp.\n  rewrite semigroup_assoc in Hidemp;\n    try assumption.\n  rewrite Hrinv in Hidemp.\n  rewrite Hrident in Hidemp.\n  assumption.\nQed.\n\nTheorem semigroup_left_ident_left_inv_group:\n  (forall (a: G), mult ident a = a) ->\n  (forall (a: G), mult (inv a) a = ident) ->\n  Monoid mult ident /\\ Group mult ident inv.\nProof.\n  intros Hlident Hlinv.\n  cut (forall (a: G), mult a (inv a) = ident).\n  { intros Hrinv.\n    split;\n      constructor;\n      try apply semigroup_assoc;\n      try assumption;\n    intros a;\n    rewrite <- (Hlinv a);\n    rewrite <- semigroup_assoc;\n      try assumption;\n    rewrite Hrinv;\n    apply Hlident. }\n  { intros a.\n    apply semigroup_left_ident_left_inv_idemp_ident;\n      try assumption.\n    rewrite semigroup_assoc;\n      try assumption.\n    remember (mult (inv a) (mult a (inv a))) as inva.\n    rewrite <- semigroup_assoc in Heqinva;\n      try assumption.\n    rewrite Hlinv in Heqinva.\n    rewrite Hlident in Heqinva.\n    subst inva.\n    reflexivity. }\nQed.\n\nTheorem semigroup_right_ident_right_inv_group:\n  (forall (a: G), mult a ident = a) ->\n  (forall (a: G), mult a (inv a) = ident) ->\n  Monoid mult ident /\\ Group mult ident inv.\nProof.\n  intros Hrident Hrinv.\n  cut (forall (a: G), mult (inv a) a = ident).\n  { intros Hlinv.\n    split;\n      constructor;\n      try apply semigroup_assoc;\n      try assumption;\n    intros a;\n    rewrite <- (Hrinv a);\n    rewrite semigroup_assoc;\n      try assumption;\n    rewrite Hlinv;\n    rewrite Hrident;\n    reflexivity. }\n  { intros a.\n    apply semigroup_right_ident_right_inv_idemp_ident;\n      try assumption.\n    rewrite <- semigroup_assoc;\n      try assumption.\n    remember (mult (mult (inv a) a) (inv a)) as inva.\n    rewrite semigroup_assoc in Heqinva;\n      try assumption.\n    rewrite Hrinv in Heqinva.\n    rewrite Hrident in Heqinva.\n    subst inva.\n    reflexivity. }\nQed.\nEnd SemigroupTheory.\n\nSection SubgroupTheory.\nContext {G: Set}(mult: G -> G -> G)(ident: G)(inv: G -> G).\nContext `{Gsubgroup: Semigroup G mult}.\nContext `{Gmonoid: Monoid G mult ident}.\nContext `{Ggroup: Group G mult ident inv}.\nContext (P: G -> Prop).\n\nClass Subgroup := {\n  subgroup_mult_closed: forall (a b: G), P a -> P b -> P (mult a b);\n  subgroup_ident: P ident;\n  subgroup_inv_closed: forall (a: G), P a -> P (inv a);\n}.\n\nTheorem subgroup_mult_inv_closed:\n  Subgroup ->\n  forall (a b: G), P a -> P b -> P (mult a (inv b)).\nProof.\n  intros Psubgroup a b Pa Pb.\n  apply subgroup_mult_closed;\n    try assumption.\n  apply subgroup_inv_closed;\n    assumption.\nQed.\n\nLemma subset_mult_inv_closed_ident:\n  {a: G | P a} ->\n  (forall (a b: G), P a -> P b -> P (mult a (inv b))) ->\n  P ident.\nProof.\n  intros [a Ha] Hmultinv.\n  rewrite <- (group_inv_right mult ident inv a).\n  apply Hmultinv;\n    assumption.\nQed.\n\nTheorem subset_mult_inv_closed_subgroup:\n  {a: G | P a} ->\n  (forall (a b: G), P a -> P b -> P (mult a (inv b))) ->\n  Subgroup.\nProof.\n  intros [g Pg] Hmultinv.\n  constructor.\n  { intros a b Pa Pb.\n    rewrite <- (group_inv_involute mult ident inv b).\n    apply Hmultinv;\n      try assumption.\n    rewrite <- (monoid_ident_left mult ident).\n    apply Hmultinv;\n      try assumption.\n    apply subset_mult_inv_closed_ident;\n      try exists g;\n      try assumption. }\n  { apply subset_mult_inv_closed_ident;\n      try exists g;\n      try assumption. }\n  { intros a Pa.\n    rewrite <- (monoid_ident_left mult ident).\n    apply Hmultinv;\n      try assumption.\n    apply subset_mult_inv_closed_ident;\n      try exists g;\n      try assumption. }\nQed.\nEnd SubgroupTheory.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/old_theories/attempt01/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.8014943759832497}}
{"text": "(*\nIf we have a map from P to Q and Q to R,\nthen we can decude a mapping from P to R using natural deduction.\n\nP -> Q    Q -> R\n----------------\n     P -> R\n\nWe can prove this in Coq.\n*)\nTheorem implication1 (P Q R: Prop):\n  forall\n  (f: P -> Q)\n  (g: Q -> R),\n  P ->\n  R.\nProof.\nintros f g p.\n(* If we need to prove R and\n   we know Q implies R\n   then we only need to prove Q *)\napply g.\n(* If we need to prove Q and\n   we know P implies Q\n   then we only need to prove P *)\napply f.\n(* but we have a P as an hypothesis *)\nexact p.\nQed.\n\n(* We can also do forwards instead of\n   backwards reasoning\n*)\nTheorem implication2 (P Q R: Prop):\n  forall\n  (f: P -> Q)\n  (g: Q -> R),\n  P ->\n  R.\nProof.\nintros f g p.\n(* lets apply f in p, since we know P implies Q *)\napply f in p.\n(* now lets apply g in p to get R *)\napply g in p.\n(* now we have R *)\nexact p.\nQed.\n\n(* Programmers might just know this as\n   function application.\n   Coq type checks this function,\n   so we know that it is correct.\n*)\nDefinition application (P Q R: Prop)\n  (f: P -> Q) (g: Q -> R): P -> R :=\nfun p => g (f p).\n\n(*\nWe can combine the two in the same proof,\nbecause the Curry-Howard Isomorphism says they are the same.\n*)\nTheorem implication3 (P Q R: Prop): forall\n  (f: P -> Q) (g: Q -> R), P -> R.\nProof.\nintros f g.\n(* This program is a proof *)\nexact (fun p =>\n  g (f p)\n).\nQed.\n\n(*\nUnderneath all these tactics, they are just code.\nWhen we Print our proofs and code they are all the same:\n`g (f p)`\n*)\nPrint implication3.\nPrint implication1.\nPrint application.\n\nTheorem implication4 (P Q R: Prop): forall\n  (f: P -> Q) (g: Q -> R) (p: P), R.\nProof.\n(* Some tactics can do some types of reasoning for us. *)\nauto.\n(* The proof is irrelevant, we only care that it is true *)\nQed.\n\n(* This is also the same `g (f p)` *)\nPrint implication4.\n\n(*\nGiven A and B, we can deduce A\n\nA /\\ B\n-------\n   A\n*)\nTheorem conjunction (A: Prop) (B: Prop):\n  forall\n  (pair: A /\\ B),\n  A.\nProof.\nintros pair.\ndestruct pair.\nexact H.\nRestart.\nintros pair.\n(*\nIf we squint this looks just like the `product` function below.\nThis is because logical conjunction is the same as:\nproducts, pairs, tuples or records in programming.\n*)\nexact (\n  match pair with\n  | conj A B => A\n  end\n).\nQed.\n\n(* A * B = (A, B) *)\nDefinition product (A: Set) (B: Set)\n  (pair: A * B): A :=\nmatch pair with\n  | (a, b) => a\nend.\n\n(*\nIf we have B then we can deduce A or B.\n\n   B\n-------\nA \\/ B\n*)\nTheorem disjunction (A: Prop) (B: Prop):\n  forall\n  (b: B),\n  A \\/ B.\nProof.\nintros.\nright.\nexact b.\nRestart.\nintros.\n(*\nIf we squint this looks just like the `sum` function below.\nThis is because logical disjunction is the same as:\nsum types, coproducts or algebriac data types in programming.\n*)\nexact (\n  (* Right b *)\n  or_intror b\n).\nQed.\n\n(* A + B = Either A B\n   inl   = Left\n   inr   = Right\n*)\nDefinition sum (A: Set) (B: Set)\n  (b: B): A + B :=\n(* Right b *)\ninr b.\n", "meta": {"author": "awalterschulze", "repo": "advertising-coq", "sha": "551d59906bea41c9cbb470e4a5b3bc2762e9f0cc", "save_path": "github-repos/coq/awalterschulze-advertising-coq", "path": "github-repos/coq/awalterschulze-advertising-coq/advertising-coq-551d59906bea41c9cbb470e4a5b3bc2762e9f0cc/CurryHoward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381042195331, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.8014298260548074}}
{"text": "Require Import Category.\nRequire Import natAsMonoid.\nRequire Import MonoidAsCategory.\n\n(* turning the monoids NatPlus and NatMult into a categories *)\n\nDefinition NatPlusAsCat : Category nat := toCategory NatPlus.\nDefinition NatMultAsCat : Category nat := toCategory NatMult.\n\n(*\nCheck NatPlusAsCat.\nCheck NatMultAsCat.\n*)\n\n(* the source of every morphism is the identity of the monoid *)\n\nExample source_test1 : forall n:nat, source NatPlusAsCat n = 0.\nProof. reflexivity. Qed.\n\nExample source_test2 : forall n:nat, source NatMultAsCat n = 1.\nProof. reflexivity. Qed.\n\n\n\n(* the target of every morphism is the identity of the monoid *)\n\nExample target_test1 : forall n:nat, target NatPlusAsCat n = 0.\nProof. reflexivity. Qed.\n\nExample target_test2 : forall n:nat, target NatMultAsCat n = 1.\nProof. reflexivity. Qed.\n\n\n\n(* composition is defined everywhere and coincides with summation *)\n\nExample compose_test1 : forall n m:nat, compose NatPlusAsCat n m = Some (n + m).\nProof. reflexivity. Qed.\n\n\nExample compose_test2 : forall n m:nat, compose NatMultAsCat n m = Some (n * m).\nProof. reflexivity. Qed.\n\n\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cat/natAsCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.801421322604395}}
{"text": "Require Import PeanoNat.\nRequire Import Omega.\n\nDefinition strict_incr (f: nat -> nat) :=\n  forall n, f n < f (S n).\n\nLemma f_nat_incr {f: nat -> nat}:\n  strict_incr f -> forall m, f 0 < f (S m).\nProof.\n  intros I.\n  induction m; [pose (I 0)|pose (I (S m))]; omega.\nQed.\n\nLemma f_nat_incr_neq {f: nat -> nat}:\n  strict_incr f -> forall {n m}, n <> m -> f n <> f m.\nProof.\n  intros I n m.\n  case (Nat.compare_spec n m); [now intros| |]; intros t _. \n  + assert (strict_incr (fun i => f (n + i))) as I'.\n    { intro i. now replace (n + S i) with (S (n + i)) by omega. }\n    replace n with (n + 0) by omega.\n    replace m with (n + S (m - n - 1)) by omega.\n    apply Nat.lt_neq, (f_nat_incr I').\n  + assert (strict_incr (fun i => f (m + i))) as I'.\n    { intro i. now replace (m + S i) with (S (m + i)) by omega. }\n    replace m with (m + 0) by omega.\n    replace n with (m + S (n - m - 1)) by omega.\n    apply Nat.neq_sym, Nat.lt_neq, (f_nat_incr I').\nQed.\n", "meta": {"author": "rootmos", "repo": "coq-hack", "sha": "957da2727d3d269c0c12fe9294cba33b437da738", "save_path": "github-repos/coq/rootmos-coq-hack", "path": "github-repos/coq/rootmos-coq-hack/coq-hack-957da2727d3d269c0c12fe9294cba33b437da738/src/CMP/Incr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780477, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.8014213214022872}}
{"text": "(*Software Foundations*)\n(* Exercice *** *)\nLemma plus_assoc: forall n m p: nat, (n + m) + p = n + (m + p).\nProof.\n    intros. induction n as [|n'].\n    simpl. reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem mult_plus_distr_r: forall n m p: nat, \n  (n+m)*p = (n*p) + (m*p).\nProof.\n    intros. induction n as [|n']. induction m as [|m'].\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHn'. rewrite plus_assoc. 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/chapter4_Library_Induction/mult_plus_distr_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566341975270265, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.8012959033948149}}
{"text": "Require Export MoreProp.\n\nInductive and (P Q : Prop) : Prop :=\n    conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\nCheck conj.\n\nTheorem and_example :\n    (beautiful 0) /\\ (beautiful 3).\nProof.\n    apply conj.\n    Case \"left\". apply b_0.\n    Case \"right\". apply b_3.\nQed.\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.\nQed.\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.\nQed.\n\nTheorem proj2 : forall P Q : Prop,\n    P /\\ Q -> Q.\nProof.\n    intros P Q H.\n    inversion H as [HP HQ].\n    apply HQ.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n    intros P Q H.\n    inversion H.\n    split.\n        apply H1.\n\n        apply H0.\nQed.\n\nTheorem and_assoc : forall P Q R : Prop,\n    P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n    intros P Q R H.\n    inversion H as (HP, (HQ, HR)).\n    split.\n    split.\n        apply HP.\n\n        apply HQ.\n\n        apply HR.\nQed.\n\nTheorem even__ev : forall n : nat,\n    (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n    intros n.\n    induction n as [| n'].\n        split.\n        intros H.\n        apply ev_0.\n\n        intros H1.\n        inversion H1.\n\n    inversion IHn' as (HP, HQ).\n    split.\n    apply HQ.\n\n    intros J.\n    apply ev_SS.\n    apply HP.\n    unfold even.\n    unfold even in J.\n    simpl in J.\n    apply J.\nQed.\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].\n    apply HAB.\nQed.\n\nTheorem iff_sym : forall P Q : Prop,\n    (P <-> Q) -> (Q <-> P).\nProof.\n    intros P Q H.\n    inversion H as [HAB HBA].\n    split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.\nQed.\n\nTheorem iff_refl : forall P : Prop,\n    P <-> P.\n\nProof.\n    intros P.\n    split.\n    Case \"->\". intros J. apply J.\n    Case \"<-\". intros J. apply J.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n    (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof. Admitted.\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.\nCheck or_introl.\n\nCheck or_intror.\n\nTheorem or_commut : forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n    intros P Q H.\n    inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.\nQed.\n\nTheorem or_commut' : forall P Q : Prop,\n    P \\/ Q -> Q \\/ P.\nProof.\n    intros P Q H.\n    inversion H as [HP | HQ].\n        Case \"left\". right. apply HP.\n        Case \"right\". left. apply HQ.\nQed.\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.\nQed.\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n    (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n    intros P Q R H.\n    inversion H as [[HP1| HQ1] [HP2| HR1]].\n    Case \"leftleft\".\n        left. apply HP1.\n\n    Case \"left\".\n        left. apply HP1.\n\n    Case \"right\".\n        left. apply HP2.\n\n    Case \"rightright\".\n        right. split.\n            SCase \"left\". apply HQ1.\n            SCase \"right\". apply HR1.\nQed.\n\nTheorem andb_prop : forall b c,\n    andb b c = true -> b = true /\\ c = true.\nProof.\n    intros b c H.\n    destruct b.\n    Case \"b = true\". destruct c.\n        SCase \"c = true\". apply conj. reflexivity. reflexivity.\n        SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.\nQed.\n\nTheorem andb_true_intro : forall b c,\n    b = true /\\ c = true -> andb b c = true.\nProof.\n    intros b c H.\n    inversion H.\n    rewrite H0. rewrite H1. reflexivity.\nQed.\n\nTheorem andb_false : forall b c,\n    andb b c = false -> b = false \\/ c = false.\nProof.\n    intros b c H.\n    destruct b.\n    Case \"b = true\".\n        simpl in H. right. apply H.\n\n    Case \"b = false\".\n        simpl in H. left. apply H.\nQed.\n\nTheorem orb_prop : forall b c,\n    orb b c = true -> b = true \\/ c = true.\nProof.\n    intros b c H.\n    destruct b.\n    Case \"b = true\".\n        simpl in H. left. apply H.\n\n    Case \"b = false\".\n        simpl in H. right. apply H.\nQed.\n\nTheorem orb_false_elim : forall b c,\n    orb b c = false -> b = false /\\ c = false.\nProof.\n    intros b c H.\n    destruct b.\n    Case \"b = true\".\n        inversion H.\n\n    Case \"b = false\".\n        simpl in H. split.\n        SCase \"left\". reflexivity.\n        SCase \"right\". apply H.\nQed.\n\nInductive False : Prop := .\nCheck tt.\n\nTheorem False_implies_nonsense :\n    False -> 2 + 2 = 5.\nProof.\n    intros contra.\n    inversion contra.\nQed.\n\nTheorem ex_falso_quodlibet : forall(P:Prop),\n    False -> P.\nProof.\n    intros P contra.\n    inversion contra.\nQed.\n\nInductive True : Prop := tt : True.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nTheorem not_False :\n    ~ False.\nProof.\n    unfold not.\n    intros H.\n    inversion H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n    (P /\\ ~P) -> Q.\nProof.\n    intros P Q H.\n    inversion H as [HP HNA]. unfold not in HNA.\n    apply HNA in HP. inversion HP.\nQed.\n\nTheorem double_neg : forall P : Prop,\n    P -> ~~P.\nProof.\n    intros P H. unfold not. intros G. apply G. apply H.\nQed.\n\nTheorem contrapositive : forall P Q : Prop,\n    (P -> Q) -> (~Q -> ~P).\nProof.\nintros P Q H NQ.\nunfold not.\nintros HP.\nunfold not in NQ.\napply NQ in H.\n    apply H.\n\n    apply HP.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n    ~ (P /\\ ~P).\nProof.\n    intros P.\n    unfold not.\n    intros H.\n    inversion H as [HL HR].\n    apply HR in HL.\n    apply HL.\nQed.\n\nTheorem five_not_even :\n    ~ ev 5.\nProof.\n    unfold not.\n    intros H.\n    inversion H.\n    inversion H1.\n    inversion H3.\nQed.\n\nTheorem classic_double_neg : forall P : Prop,\n    ~~P -> P.\nProof.\n    intros P H. unfold not in H. Abort.\n\n\n(*\n    TODO: Exercise classical_axioms\n*)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true : forall b : bool,\n    b <> false -> b = true.\nProof.\n    intros b H. destruct b.\n    Case \"b = true\". reflexivity.\n    Case \"b = false\".\n        unfold not in H.\n        apply ex_falso_quodlibet.\n        apply H. reflexivity.\nQed.\n\nTheorem false_beq_nat : forall n m : nat,\n    n <> m ->\n    beq_nat n m = false.\nProof. Admitted.\n\nTheorem beq_nat_false : forall n m,\n    beq_nat n m = false -> n <> m.\nProof. Admitted.\n\nTheorem ble_nat_false : forall n m ,\n    ble_nat n m = false -> ~(n <= m).\nProof. Admitted.\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n    ex_intro : forall(witness:X), P witness -> ex X P.\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n    (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n    (at level 200, x ident, right associativity) : type_scope.\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n    apply ex_intro with (witness:=2).\n    reflexivity.\nQed.\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n    exists 2.\n    reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n    (exists m, n = 4 + m) ->\n    (exists o, n = 2 + o).\nProof.\n    intros n H.\n    inversion H as [m Hm].\n    exists(2 + m).\n    apply Hm.\nQed.\n\nTheorem dist_not_exists : forall(X:Type) (P:X -> Prop),\n    (forall x, P x) -> ~ (exists x, ~P x).\nProof.\n    intros.\n    unfold not.\n    intros.\n    inversion H0.\n    apply H1.\n    apply H.\nQed.\n\nModule MyEQ.\nInductive eq {X:Type} : X -> X -> Prop :=\n    refl_equal : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\nLemma leibniz_equality : forall(X : Type) (x y : X),\n    x = y -> forall P : X -> Prop, P x -> P y.\nProof.\n    intros X x y H P.\n    inversion H.\n    intros J.\n    apply J.\nQed.\n\nEnd MyEQ.\n\nLemma four : 2 + 2 = 1 + 3.\nProof.\n    apply refl_equal.\nQed.\n\nInductive sumbool (A B : Prop) : Set :=\n| left : A -> sumbool A B\n| right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n    intros n.\n    induction n as [|n'].\n    Case \"n = 0\".\n        intros m.\n        destruct m as [|m'].\n        SCase \"m = 0\".\n            left. reflexivity.\n        SCase \"m = S m'\".\n            right. intros contra. inversion contra.\n    Case \"n = S n'\".\n        intros m.\n        destruct m as [|m'].\n        SCase \"m = 0\".\n            right. intros contra. inversion contra.\n        SCase \"m = S m'\".\n            destruct IHn' with (m := m') as [eq | neq].\n            left. apply f_equal. apply eq.\n            right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined.\n\nDefinition override' {X:Type} (f: nat -> X) (k:nat) (x:X) : nat -> X :=\n    fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall(X:Type) x1 k1 k2 (f : nat -> X),\n    f k1 = x1 ->\n    (override' f k1 x1) k2 = f k2.\nProof.\n    intros X x1 k1 k2 f. intros Hx1.\n    unfold override'.\n    destruct (eq_nat_dec k1 k2).\n    Case \"k1 = k2\".\n        rewrite <- e.\n        symmetry. apply Hx1.\n    Case \"k1 <> k2\".\n        reflexivity.\nQed.\n\n(*\n    TODO: Additional exercises\n*)\n", "meta": {"author": "montekki", "repo": "sf", "sha": "f91b70058bfeca1427fd402f0be158f6c779dffe", "save_path": "github-repos/coq/montekki-sf", "path": "github-repos/coq/montekki-sf/sf-f91b70058bfeca1427fd402f0be158f6c779dffe/Logic/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.8012338358314898}}
{"text": "Require Import ZArith Nnat ROmega.\nOpen Scope Z_scope.\n\n(** Test of the zify preprocessor for (R)Omega *)\n\n(* More details in file PreOmega.v\n\n   (r)omega with Z        : starts with zify_op\n   (r)omega with nat      : starts with zify_nat\n   (r)omega with positive : starts with zify_positive\n   (r)omega with N        : starts with uses zify_N\n   (r)omega with *        : starts zify (a saturation of the others)\n*)\n\n(* zify_op *)\n\nGoal forall a:Z, Z.max a a = a.\nintros.\nromega with *.\nQed.\n\nGoal forall a b:Z, Z.max a b = Z.max b a.\nintros.\nromega with *.\nQed.\n\nGoal forall a b c:Z, Z.max a (Z.max b c) = Z.max (Z.max a b) c.\nintros.\nromega with *.\nQed.\n\nGoal forall a b:Z, Z.max a b + Z.min a b = a + b.\nintros.\nromega with *.\nQed.\n\nGoal forall a:Z, (Z.abs a)*(Z.sgn a) = a.\nintros.\nzify.\nintuition; subst; romega. (* pure multiplication: omega alone can't do it *)\nQed.\n\nGoal forall a:Z, Z.abs a = a -> a >= 0.\nintros.\nromega with *.\nQed.\n\nGoal forall a:Z, Z.sgn a = a -> a = 1 \\/ a = 0 \\/ a = -1.\nintros.\nromega with *.\nQed.\n\n(* zify_nat *)\n\nGoal forall m: nat, (m<2)%nat -> (0<= m+m <=2)%nat.\nintros.\nromega with *.\nQed.\n\nGoal forall m:nat, (m<1)%nat -> (m=0)%nat.\nintros.\nromega with *.\nQed.\n\nGoal forall m: nat, (m<=100)%nat -> (0<= m+m <=200)%nat.\nintros.\nromega with *.\nQed.\n(* 2000 instead of 200: works, but quite slow *)\n\nGoal forall m: nat, (m*m>=0)%nat.\nintros.\nromega with *.\nQed.\n\n(* zify_positive *)\n\nGoal forall m: positive, (m<2)%positive -> (2 <= m+m /\\ m+m <= 2)%positive.\nintros.\nromega with *.\nQed.\n\nGoal forall m:positive, (m<2)%positive -> (m=1)%positive.\nintros.\nromega with *.\nQed.\n\nGoal forall m: positive, (m<=1000)%positive -> (2<=m+m/\\m+m <=2000)%positive.\nintros.\nromega with *.\nQed.\n\nGoal forall m: positive, (m*m>=1)%positive.\nintros.\nromega with *.\nQed.\n\n(* zify_N *)\n\nGoal forall m:N, (m<2)%N -> (0 <= m+m /\\ m+m <= 2)%N.\nintros.\nromega with *.\nQed.\n\nGoal forall m:N, (m<1)%N -> (m=0)%N.\nintros.\nromega with *.\nQed.\n\nGoal forall m:N, (m<=1000)%N -> (0<=m+m/\\m+m <=2000)%N.\nintros.\nromega with *.\nQed.\n\nGoal forall m:N, (m*m>=0)%N.\nintros.\nromega with *.\nQed.\n\n(* mix of datatypes *)\n\nGoal forall p, Z.of_N (N.of_nat (N.to_nat (Npos p))) = Zpos p.\nintros.\nromega with *.\nQed.\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/ROmegaPre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938533, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.8012338230504202}}
{"text": "Require Import Arith.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  rewrite (plus_assoc (n + m) p q).\n  rewrite (plus_assoc (n + p) m q).\n  rewrite <- (plus_assoc n m p).\n  rewrite <- (plus_assoc n p m).\n  rewrite (plus_comm m p).\n  reflexivity.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\n  intros.\n  rewrite (mult_plus_distr_r n m (n + m)).\n  rewrite (mult_plus_distr_l n n m).\n  rewrite (mult_plus_distr_l m n m).\n  rewrite (plus_assoc (n * n + n * m) (m * n) (m * m)).\n  rewrite <- (mult_1_r (n * m)).\n  rewrite (mult_comm m n).\n  rewrite <- (plus_assoc (n * n) (n * m * 1) (n * m)).\n  rewrite (mult_n_Sm (n * m) 1).\n  rewrite (mult_comm (n * m) 2).\n  rewrite (mult_assoc 2 n m).\n  rewrite <- (plus_assoc (n * n) (2 * n * m) (m * m)).\n  rewrite (plus_comm (2 * n * m) (m * m)).\n  rewrite (plus_assoc (n * n) (m * m) (2 * n * m)).\n  reflexivity.\nQed.", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/2/9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347912737016, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.8011696916648929}}
{"text": "(** * BagPerm:  Insertion Sort With Bags *)\n\n(** We have seen how to specify algorithms on \"collections\", such as\n    sorting algorithms, using [Permutation]s.  Instead of using\n    permutations, another way to specify these algorithms is to use\n    _bags_ (also called _multisets_), which we introduced in [Lists].\n    A _set_ of values is like a list with no repeats where\n    the order does not matter.  A _multiset_ is like a list, possibly\n    with repeats, where the order does not matter.  Whereas the principal\n    query on a set is whether a given element appears in it, the\n    principal query on a bag is _how many_ times a given element appears\n    in it. *)\n\nFrom Coq Require Import Strings.String. (* for manual grading *)\nFrom Coq Require Import Setoid Morphisms.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Sort.\n\n(** To keep this chapter more self-contained,\nwe restate the critical definitions from [Lists].  *)\nDefinition bag := list nat.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t =>\n      (if h =? v then 1 else 0) + count v t\n  end.\n\n(** We will say two bags are _equivalent_ if they have the same number\n    of copies of every possible element. *)\n\nDefinition bag_eqv (b1 b2: bag) : Prop :=\n  forall n, count n b1 = count n b2.\n\n(** **** Exercise: 2 stars, standard (bag_eqv_properties) *)\n\n(* It is easy to prove [bag_eqv] is an equivalence relation. *)\n\nLemma bag_eqv_refl : forall b, bag_eqv b b.\nProof.\n(* TODO: FILL IN HERE *) Admitted.\n\nLemma bag_eqv_sym: forall b1 b2, bag_eqv b1 b2 -> bag_eqv b2 b1.\nProof.\n(* TODO: FILL IN HERE *) Admitted.\n\nLemma bag_eqv_trans: forall b1 b2 b3, bag_eqv b1 b2 -> bag_eqv b2 b3 -> bag_eqv b1 b3.\nProof.\n(* TODO: FILL IN HERE *) Admitted.\n\n(** The following little lemma is handy in a couple of places. *)\n\nLemma bag_eqv_cons : forall x b1 b2, bag_eqv b1 b2 -> bag_eqv (x::b1) (x::b2).\nProof.\n  (* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Correctness *)\n\n(** A sorting algorithm must rearrange the elements into a list that\n    is totally ordered.  But let's say that a different way: the\n    algorithm must produce a list _with the same multiset of values_,\n    and this list must be totally ordered. *)\n\nDefinition is_a_sorting_algorithm' (f: list nat -> list nat) :=\n  forall al, bag_eqv al (f al) /\\ sorted (f al).\n\n(** **** Exercise: 3 stars, standard (insert_bag)\n\n    First, prove the auxiliary lemma [insert_bag], which will be\n    useful for proving [sort_bag] below.  Your proof will be by\n    induction.  *)\n\nLemma insert_bag: forall x l, bag_eqv (x::l) (insert x l).\nProof.\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (sort_bag)\n\n    Now prove that sort preserves bag contents. *)\nTheorem sort_bag: forall l, bag_eqv l (sort l).\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem insertion_sort_correct:\n  is_a_sorting_algorithm' sort.\nProof.\nsplit. apply sort_bag. apply sort_sorted.\nQed.\n\n(** **** Exercise: 1 star, standard (permutations_vs_multiset)\n\n    Compare your proofs of [insert_perm, sort_perm] with your proofs\n    of [insert_bag, sort_bag].  Which proofs are simpler?\n\n      - [ ] easier with permutations,\n      - [ ] easier with multisets\n      - [ ] about the same.\n\n   Regardless of \"difficulty\", which do you prefer / find easier to\n   think about?\n      - [ ] permutations or\n      - [ ] multisets\n\n   Put an X in one box in each list. *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_permutations_vs_multiset : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Permutations and Multisets *)\n\n(** The two specifications of insertion sort are equivalent.  One\n    reason is that permutations and multisets are closely related.\n    We're going to prove:\n\n       [Permutation al bl <-> bag_eqv al bl.] *)\n\n(** **** Exercise: 3 stars, standard (perm_bag)\n\n    The forward direction is straighforward, by induction on the evidence for\n    [Permutation]: *)\nLemma perm_bag:\n  forall al bl : list nat,\n   Permutation al bl -> bag_eqv al bl.\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The other direction,\n    [bag_eqv al bl -> Permutation al bl],\n    is surprisingly difficult.\n    This proof approach is due to Zhong Sheng Hu.\n    The first three lemmas are used to prove the fourth one. *)\n\n(** **** Exercise: 2 stars, advanced (bag_nil_inv) *)\nLemma bag_nil_inv : forall b, bag_eqv [] b -> b = [].\nProof.\n  (* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_cons_inv) *)\nLemma bag_cons_inv : forall l x n,\n    S n = count x l ->\n    exists l1 l2,\n      l = l1 ++ x :: l2\n      /\\ count x (l1 ++ l2) = n.\nProof.\n  (* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (count_insert_other) *)\nLemma count_insert_other : forall l1 l2 x y,\n    y <> x -> count y (l1 ++ x :: l2) = count y (l1 ++ l2).\nProof.\n  (* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_perm) *)\nLemma bag_perm:\n  forall al bl, bag_eqv al bl -> Permutation al bl.\nProof.\n(* TODO: FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The Main Theorem: Equivalence of Multisets and Permutations *)\nTheorem bag_eqv_iff_perm:\n  forall al bl, bag_eqv al bl <-> Permutation al bl.\nProof.\n  intros. split. apply bag_perm. apply perm_bag.\nQed.\n\n(** Therefore, it doesn't matter whether you prove your sorting\n    algorithm using the Permutations method or the multiset method. *)\n\nCorollary sort_specifications_equivalent:\n    forall sort, is_a_sorting_algorithm sort <->  is_a_sorting_algorithm' sort.\nProof.\n  unfold is_a_sorting_algorithm, is_a_sorting_algorithm'.\n  split; intros;\n  destruct (H al); split; auto;\n  apply bag_eqv_iff_perm; auto.\nQed.\n\n(** $Date$ *)\n\n(* 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/BagPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.8010607058628326}}
{"text": "Require Import Bool Arith List.\nImport ListNotations.\n\nDefinition cons [A:Type] (e :  A) (l: list A) := \n\te :: l\n.\n\nDefinition decons [A:Type] (l: list A) := \n\tmatch l with \n\t| [] => None\n\t| h::t => Some (h,t)\n\tend.\n\nFixpoint nth [A:Type] (l: list A) n := \nmatch n,l with \n| _,[] => None\n| 0,h::_ => Some h\n| S n, _::t => nth t n \n\nend.\n\nCompute nth [1;2;3] 2. \nCompute nth [1;2;3] 4.\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 blist (A:Type) : Type := \nlist (nat * tree A)\n.\n\nCheck  [ (0,leaf 0)] : blist nat.\nCheck  [] : blist nat.\n\nFixpoint tsize {A} (t: tree A) := \nmatch t with \n|leaf _ => 1\n|node t _ => 2 * (tsize t) \nend.\n\nCompute tsize (node (leaf 0) (leaf 0)).\nCompute tsize (node (node (leaf 0) (leaf 1)) (node (leaf 1) (leaf 0))).\n\nFixpoint tcons {A} (t:tree A) (l:blist A) := \n\tmatch l with \n\t|[] => [(tsize t, t)]\n\t|(st',t')::ll =>  \n\t\tlet st  := tsize t in\n\t\tif st =? st' \n\t\tthen tcons (node t t') ll \n\t\telse (st,t)::l\nend.\n\nDefinition bcons {A} (a:A) l := tcons (leaf a) l.\n\nCompute bcons 1 (bcons 2 (bcons 3 (bcons 4 []))).\nCompute bcons 1 (bcons 2 (bcons 3  [])).\n\nFixpoint tdecons {A} (st:nat) (t:tree A) (l:blist A) := \n\tmatch t with\n\t|leaf a =>  (a,l)\n\t|node fg fd => \n\t\tlet size := st-1 in\n\t\ttdecons size fg ((size,fd)::l) \n\tend.\n\n\nDefinition l := bcons 1 (bcons 2 (bcons 3  [])).\n\nDefinition bdecons [A:Type] (l: blist A) := \n\tmatch l with \n\t| [] => None\n\t| (st,t)::ll => Some (tdecons st t ll)\n\tend.\n\nCompute bdecons l .\n\n\nFixpoint tnth [A:Type] (t: tree A) n size := \n\tmatch t,n with \n\t|leaf a,0 => Some a \n\t|leaf _,_ => None \n\t|node fg fd, _ => \n\t\tlet size' := size/2 in \t\n\t\tif n <? size'  \n\t\tthen tnth fg n size' \n\t\telse tnth fd (n-size') size'\n\tend.\t\n\t\n\nFixpoint bnth [A:Type] (l: blist A) n := \nmatch l with \n\t| [] => None\n\t| (st,t)::ll => \n\t\tif n <? st \n\t\tthen tnth t n st\n\t\telse bnth ll (n-st) \nend.\n\nCompute l.\nCompute bnth l 1.\n\nFixpoint list_to_blist [A] (l:list A) : blist A := \n\tmatch l with \n\t|[] => []\n\t|h::t => bcons h (list_to_blist t)\nend.\n\nDefinition l' := list_to_blist [1;2;3;4;5;6;7;8].\nCompute bnth l' 4.\n\n\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/LMFI/td4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.8009903701292046}}
{"text": "(* Exercise 38 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\n(* Can the following theorem be proved without the \n   (exists x : D, x = x) in it? \n   If so, how? If not, why not? \n*)\n\nTheorem exercise_038 : \n  (exists x : D, x = x)\n-> \n    (forall x, P x \\/ Q x)\n  -> \n    ~ (forall x, ~ P x /\\ ~ Q x).\nProof.\nimp_i a1.\nimp_i a2.\nexi_e (exists y:D, y = y) y a3.\nhyp a1.\nneg_i (~P y /\\ ~Q y) a4.\ndis_e (P y \\/ Q y) a5 a5.\nall_e (forall x:D, P x \\/ Q x) y.\nhyp a2.\nneg_i (P y) a6.\ncon_e1 (~Q y).\nhyp a6.\nhyp a5.\nneg_i (Q y) a6.\ncon_e2 (~P y).\nhyp a6.\nhyp a5.\nall_e (forall x:D, ~P x /\\ ~Q x) y.\nhyp a4.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred038.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8007846945671899}}
{"text": "Require Import ZArith.\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: forall x y:Z, square (x+y) = square x + 2*x*y + square y.\nProof.\n  intros x y. unfold square. ring.\nQed.\n\nRequire Import Arith. (* otherwise ring tactic wil fail for nat *)\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", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.8007846856797946}}
{"text": "\n\n(*---------------------------------- Descriptions ---------------------------------------\n\nIn this file we define the idea of graph isomorphism. This is done by defining following\npredicates:\n\nDefinition iso (G G': @UG A) :=\n     exists (f: A->A), (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n                 (forall x y, In x G -> In y G-> edg G x y = edg G' (f x) (f y)).\n\n Definition iso_using (f: A->A)(G G': @UG A) :=\n     (forall x, f (f x) = x) /\\ \n     (nodes G') = (img f G) /\\ \n     (forall x y, edg G x y = edg G' (f x) (f y)).\n\nWhen we say (iso_using f G1 G2), we mean f is the function establishing the isomorphism\nbetween G1 and G2. We also prove that this relation is symmetric and transitive.\nNote that the self invertible nature of f makes it one_one on both G1 and G2. \nFollowing are some useful property of f:\n \n Lemma fx_is_one_one (l: list A)(f: A->A): (forall x, f (f x) = x) -> one_one_on l f.\n Lemma img_of_img (l: list A)(f: A->A)(Hl: IsOrd l):\n    (forall x, f (f x) = x)-> img f (img f l) = l.\n\n Lemma iso_sym1 (G G': @UG A)(f: A-> A): iso_using f G G' -> iso_using f G' G.\n Lemma iso_sym (G G': @UG A): iso G G' -> iso G' G.\n\n Lemma iso_one_one1 (G G': @UG A)(f: A-> A): iso_using f G G' -> one_one_on G f.\n Lemma iso_using_G' (G G': @UG A)(f: A-> A): iso_using f G G' -> nodes G' = (img f G).\n Lemma iso_one_one (G G': @UG A)(f: A-> A)(l: list A): iso_using f G G'-> one_one_on l f.\n Lemma iso_cardinal (G G': @UG A)(f: A-> A): iso_using f G G' -> |G|=|G'|.\n Lemma iso_sub_cardinal (G G': @UG A)(X: list A)(f: A->A): iso_using f G G' ->\n                                                           NoDup X -> |X|= | img f X |.\n Lemma iso_edg1  (G G': @UG A)(f: A-> A)(x y:A): iso_using f G G' ->\n                                                (edg G x y = edg G' (f x) (f y)).\n Lemma iso_edg2  (G G': @UG A)(f: A-> A)(x y: A): iso_using f G G' ->\n                                                (edg G' x y = edg G (f x) (f y)).\n-------------------------------------------------------------------------------------\n\n Stable Set, Cliq and Coloring of graphs has exact counterpart in the isomorphic Graphs.\n These results of existence of counterparts are summarized below: \n\n\n Lemma iso_cliq_in (G G': @UG A)(f: A-> A)(K: list A): iso_using f G G' -> \n                                                      Cliq_in G K -> Cliq_in G' (img f K).\n Lemma iso_cliq_in1 (G G': @UG A)(K: list A): iso G G' -> Cliq_in G K ->\n                                              (exists K', Cliq_in G' K' /\\ |K|=|K'|).\n Lemma max_K_in_G' (G G': @UG A)(f: A-> A)(K: list A): iso_using f G G' ->\n                                                    Max_K_in G K -> Max_K_in G' (img f K).\n\n\nLemma iso_stable (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G' -> \n                                                     Stable G I -> Stable G' (img f I).\nLemma iso_stable_in (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G'-> \n                                                Stable_in G I -> Stable_in G' (img f I).\nLemma max_I_in_G' (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G' -> \n                                                  Max_I_in G I -> Max_I_in G' (img f I).\n\nLemma cliq_num_G' (G G': @UG A)(n: nat): iso G G' -> cliq_num G n -> cliq_num G' n.\nLemma i_num_G' (G G': @UG A)(n: nat):  iso G G' -> i_num G n -> i_num G' n. \nLemma chrom_num_G' (G G': @UG A)(n:nat): iso G G' -> chrom_num G n -> chrom_num G' n.\n\nLemma nice_G' (G G': @UG A): iso G G' -> Nice G -> Nice G'.\nLemma iso_subgraphs (G G' H: @UG A)(f: A->A):  iso_using f G G' -> Ind_subgraph H G -> \n                                      (exists H', Ind_subgraph H' G' /\\ iso_using f H H').\nLemma perfect_G' (G G': @UG A): iso G G' -> Perfect G -> Perfect G'.\n\n\nFollowing definition represents the Graph G restricted to the vertex set K:\n\n  Definition Ind_at (K: list A)(Pk: IsOrd K)(G: @UG A): @UG A.\n     refine {|nodes:= K; nodes_IsOrd := Pk;\n              edg:= (G.(edg) at_ K); |}. all: auto. Defined. \n\n------------------------------------------------------------------------------------------*)\n\nRequire Export MoreUG.\n\nSet Implicit Arguments.\n\nSection GraphIsomorphism.\n\n  Context { A: ordType }.\n\n   Definition iso (G G': @UG A) :=\n     exists (f: A->A), (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n                 (forall x y, In x G-> In y G-> edg G x y = edg G' (f x) (f y)).\n\n   Definition iso_using (f: A->A)(G G': @UG A) :=\n     (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n     (forall x y, In x G-> In y G-> edg G x y = edg G' (f x) (f y)).\n\n   (*--------------------- properties of bijective function for isomorphism----------------*)\n\n   Lemma f_is_one_one (f: A->A): (forall x, f (f x) = x) -> one_one f.\n   Proof.  { intros H. unfold one_one. intros x y  Hxy HC. absurd (x=y).\n               auto. replace y with (f (f y)). rewrite <- HC. symmetry;auto. auto. } Qed.\n     \n  Lemma fx_is_one_one (l: list A)(f: A->A): (forall x, f (f x) = x) -> one_one_on l f.\n  Proof. { intros H. unfold one_one_on. intros x y Hx Hy Hxy HC. absurd (x=y).\n           auto. replace y with (f (f y)). rewrite <- HC. symmetry;auto. auto. } Qed.\n  \n  Lemma img_of_img (l: list A)(f: A->A)(Hl: IsOrd l):\n    (forall x, f (f x) = x)-> img f (img f l) = l.\n  Proof. { intro H.\n         assert (H1: Equal (img f (img f l)) l).\n         { unfold Equal. split.\n           { unfold Subset. intros a H1.\n             assert (H2: exists b, In b (img f l) /\\ a = f b); auto.\n             destruct H2 as [b H2]. destruct H2 as [H2a H2b].\n             assert (H3: exists x, In x l /\\ b = f x ); auto.\n             destruct H3 as [x H3]. destruct H3 as [H3a H3b].\n             subst a. subst b. replace (f (f x)) with x. auto. symmetry;auto. }\n           { unfold Subset. intros a H1.\n             assert (H2: In (f a) (img f l)). auto.\n             assert (H2a: In (f (f a)) (img f (img f l))). auto.\n             replace (f (f a)) with a in H2a. auto. symmetry;auto. } } \n         auto. } Qed.\n\n   Lemma img_of_img1 (l: list A)(f: A->A)(Hl: IsOrd l):\n     (forall x, f (f x) = x)-> l= img f (img f l).\n   Proof. intros. symmetry. auto using img_of_img. Qed.\n   \n   Hint Resolve f_is_one_one fx_is_one_one img_of_img img_of_img1: core.   \n\n   (* ---------------------- Isomorphism is commutative and transitive------------------*)\n   Lemma iso_sym1 (G G': @UG A)(f: A-> A): iso_using f G G' -> iso_using f G' G.\n    Proof. { intro H. destruct H as [Ha H]; destruct H as [Hb H].\n           split.\n           { auto. }\n           split.\n           { rewrite Hb;  auto. }\n           { intros; symmetry.\n             replace (edg G' x y) with ( edg G' (f (f x)) (f (f y))).\n             assert (H2: In (f x) G). \n             { rewrite Hb in H0.\n               assert (h1: exists x0, In x0 G /\\ x = f x0). auto.\n               destruct h1 as [x0 h1]. destruct h1 as [h1 h2].\n               subst x. specialize (Ha x0) as Hx0. rewrite Hx0. auto. }\n             assert (H3: In (f y) G).\n              { rewrite Hb in H1.\n               assert (h1: exists y0, In y0 G /\\ y = f y0). auto.\n               destruct h1 as [y0 h1]. destruct h1 as [h1 h2].\n               subst y. specialize (Ha y0) as Hy0. rewrite Hy0. auto. }\n             auto. replace (f (f x)) with x. replace (f (f y)) with y.\n             auto. all: symmetry;auto. } } Qed.\n\n  Lemma iso_elim1 (G G': @UG A)(f: A->A)(x:A): iso_using f G G'-> In x G-> In (f x) G'.\n   Proof. intros H Hx. replace (nodes G') with (img f G). auto. symmetry; apply H. Qed.  \n\n  Lemma iso_elim2 (G G': @UG A)(f: A->A)(x:A): iso_using f G G'-> In x G'-> In (f x) G.\n  Proof. intros H Hx. replace (nodes G) with (img f G'). auto. symmetry.\n         apply iso_sym1 in H as Ha. apply Ha. Qed.\n   \n  Lemma iso_sym (G G': @UG A): iso G G' -> iso G' G.\n  Proof. { intro H. destruct H as [f H].  exists f. apply iso_sym1. auto. } Qed.\n\n  Lemma iso_using_iso (G G':@UG A)(f: A->A): iso_using f G G' -> iso G G'.\n  Proof. intros h. exists f. auto. Qed.\n\n  Lemma iso_using_iso1 (G G':@UG A)(f: A->A): iso_using f G G' -> iso G' G.\n  Proof. intro h. apply iso_sym. eapply iso_using_iso. eauto. Qed.\n  \n  \n  Hint Immediate iso_sym1 iso_sym iso_elim1 iso_elim2: core.\n\n  Hint Resolve iso_using_iso iso_using_iso1: core.\n\n  \n\n  Lemma iso_one_one1 (G G': @UG A)(f: A-> A): iso_using f G G' -> one_one_on G f.\n  Proof.  intro H; apply fx_is_one_one; apply H. Qed.\n\n  Lemma iso_one_one2 (G G': @UG A)(f: A-> A): iso_using f G G' -> one_one_on G' f.\n  Proof. intro H; apply fx_is_one_one; apply H. Qed. \n\n  Lemma iso_using_G' (G G': @UG A)(f: A-> A): iso_using f G G' -> nodes G' = (img f G).\n  Proof.  intro H;apply H. Qed.\n\n  Lemma iso_using_G (G G': @UG A)(f: A-> A): iso_using f G G' -> nodes G = (img f G').\n  Proof. intro H0. cut (iso_using f G' G). intro H;apply H. auto. Qed.\n\n  Lemma iso_one_one (G G': @UG A)(f: A-> A)(l: list A):\n    iso_using f G G'-> one_one_on l f.\n  Proof. intro H; apply fx_is_one_one; apply H. Qed.\n\n  Lemma iso_f_one_one (G G': @UG A)(f: A-> A): iso_using f G G'-> one_one f.\n    Proof. intro H; apply f_is_one_one; apply H. Qed.\n  \n  \n    Hint Immediate iso_one_one1 iso_one_one2 iso_one_one iso_f_one_one\n         iso_using_G iso_using_G': core.\n\n  Lemma iso_cardinal (G G': @UG A)(f: A-> A): iso_using f G G' -> |G|=|G'|.\n  Proof. { intro H.  apply iso_one_one1 in H as H1.\n           replace (nodes G') with (img f G). auto. \n           symmetry; auto using iso_using_G'. } Qed.\n  Lemma iso_sub_cardinal (G G': @UG A)(X: list A)(f: A->A):\n    iso_using f G G' -> NoDup X -> |X|= | img f X |.\n  Proof. { intros H H0.\n         assert (H2: one_one_on G f). eauto.\n         assert (H2a: one_one_on X f). eauto. auto. } Qed.\n  \n   Lemma iso_edg1  (G G': @UG A)(f: A-> A)(x y:A): iso_using f G G' -> In x G -> In y G->\n                                                (edg G x y = edg G' (f x) (f y)).\n  Proof. intro H;apply H. Qed.\n\n  Lemma iso_edg2  (G G': @UG A)(f: A-> A)(x y: A): iso_using f G G' -> In x G'-> In y G'->\n                                                (edg G' x y = edg G (f x) (f y)).\n  Proof. intro H0. cut (iso_using f G' G). intro H;apply H. auto. Qed.\n\n  \n\n  Hint Immediate iso_cardinal iso_sub_cardinal iso_edg1 iso_edg2: core.\n\n   Lemma iso_edg3(G G': @UG A)(f: A-> A)(x y:A): iso_using f G G' -> In x G -> In y G->\n                                                edg G x y -> edg G' (f x) (f y).\n  Proof.  intros; replace (edg G' (f x) (f y)) with (edg G x y); auto.  Qed.\n\n  Lemma iso_edg4  (G G': @UG A)(f: A-> A)(x y: A): iso_using f G G' -> In x G -> In y G-> \n                                                ~ edg G x y -> ~ edg G' (f x) (f y).\n  Proof. intros ; replace (edg G' (f x) (f y)) with (edg G x y); auto. Qed.\n\n  Hint Immediate iso_edg3 iso_edg4: core.\n\n\n  (* ------------- Isomorphism preserves Cliques and Cliq_num for a graph-----------------*)\n\n   Lemma iso_cliq (G G': @UG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> K [<=] G-> Cliq G K -> Cliq G' (img f K).\n  Proof. {  unfold Cliq. intros H H1 h1.  intros x y Hx Hy.\n          assert (H2: exists x0, In x0 K /\\ x = f x0). auto.\n          destruct H2 as [x0 H2]. destruct H2 as [H2a H2b].\n          assert (H3: exists y0, In y0 K /\\ y = f y0). auto.\n          destruct H3 as [y0 H3]. destruct H3 as [H3a H3b].\n          replace x with (f x0). replace y with (f y0).\n          assert (H2:  x0 = y0 \\/ edg G x0 y0). auto.\n          destruct H2.\n          { left. subst x0. auto. }\n          { right. replace (edg G' (f x0) (f y0)) with (edg G x0 y0).\n            auto. apply H. all: auto. }  }  Qed.\n  \n  Lemma iso_cliq1 (G G': @UG A)(K: list A): iso G G' -> K [<=] G -> Cliq G K -> NoDup K ->\n                                           (exists K', Cliq G' K' /\\ |K|=|K'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H].\n         exists (img f K). split. eauto using iso_cliq.\n         assert (H3: one_one_on K f). eauto.\n         auto. } Qed.\n  \n\n  Lemma iso_cliq_in (G G': @UG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> Cliq_in G K -> Cliq_in G' (img f K).\n  Proof. { intros H H1.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c].\n         split.\n         { destruct H as [Ha H]. destruct H as [Hb Hc]. rewrite Hb; auto. }\n         split.\n         { auto. }\n         { eauto using iso_cliq. }  } Qed.\n\n  Lemma iso_cliq_in1 (G G': @UG A)(K: list A): iso G G' -> Cliq_in G K ->\n                                              (exists K', Cliq_in G' K' /\\ |K|=|K'|).\n  Proof. { intros H H1. destruct H as [f H].\n         exists (img f K). split. eauto using iso_cliq_in.\n         assert (H3: one_one_on K f). eauto.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c]. auto. } Qed.\n\n  Hint Immediate iso_cliq iso_cliq1 iso_cliq_in iso_cliq_in1: core.\n\n  Lemma max_K_in_G' (G G': @UG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> Max_K_in G K -> Max_K_in G' (img f K). \n  Proof. { intros H H1. assert (H0: iso_using f G' G); auto.\n         apply  Max_K_in_intro.         \n         { cut (Cliq_in G K); eauto. }\n         { intros Y H2.\n           replace (|Y|) with (|img f Y|).\n           replace (|img f K|) with (|K|).\n            assert (H3: Cliq_in G (img f Y)). eauto.\n           eauto using Max_K_in_elim. eapply iso_sub_cardinal;eauto.\n           symmetry. eapply iso_sub_cardinal; eauto. } } Qed.\n\n  Lemma cliq_num_G' (G G': @UG A)(n: nat):\n    iso G G' -> cliq_num G n -> cliq_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [K H1].\n         destruct H1 as [H1 H1b]. exists (img f K).\n         split. eauto using max_K_in_G'. replace n with (|K|).\n         symmetry. eapply iso_sub_cardinal;eauto. } Qed.\n  \n  Hint Immediate max_K_in_G' cliq_num_G': core.       \n\n\n  (*---------- Isomorphism preserves Stable set and i_num ----------------------------*)\n\n   Lemma iso_stable (G G': @UG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> I [<=] G-> Stable G I -> Stable G' (img f I).\n  Proof. {  unfold Stable. intros H h1 H1.  intros x y Hx Hy.\n          assert (H2: exists x0, In x0 I /\\ x = f x0). auto.\n          destruct H2 as [x0 H2]. destruct H2 as [H2a H2b].\n          assert (H3: exists y0, In y0 I /\\ y = f y0). auto.\n          destruct H3 as [y0 H3]. destruct H3 as [H3a H3b].\n          replace x with (f x0). replace y with (f y0).\n          assert (H2: edg G x0 y0 = false). auto. \n          replace (edg G' (f x0) (f y0)) with (edg G x0 y0).\n            auto. apply H. all: auto. } Qed.\n  \n   Lemma iso_stable1 (G G': @UG A)(I: list A): iso G G' -> I [<=] G-> Stable G I -> NoDup I ->\n                                           (exists I', Stable G' I' /\\ |I|=|I'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H].\n         exists (img f I). split. eauto using iso_stable.\n         assert (H3: one_one_on I f). eauto.\n         auto. } Qed.\n\n  Lemma iso_stable_in (G G': @UG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> Stable_in G I -> Stable_in G' (img f I).\n  Proof. { intros H H1.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c].\n         split.\n         { destruct H as [Ha H]. destruct H as [Hb Hc]. rewrite Hb; auto. }\n         split.\n         { auto. }\n         { eauto using iso_stable. }  } Qed.\n\n  Lemma iso_stable_in1 (G G': @UG A)(I: list A): iso G G' -> Stable_in G I ->\n                                              (exists I', Stable_in G' I' /\\ |I|=|I'|).\n  Proof. { intros H H1. destruct H as [f H].\n         exists (img f I). split. eauto using iso_stable_in.\n         assert (H3: one_one_on I f). eauto.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c]. auto. } Qed.\n\n  Hint Immediate iso_stable iso_stable1 iso_stable_in iso_stable_in1: core.\n\n  Lemma max_I_in_G' (G G': @UG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> Max_I_in G I -> Max_I_in G' (img f I).\n  Proof. { intros H H1. assert (H0: iso_using f G' G); auto.\n         apply  Max_I_in_intro.         \n         { cut (Stable_in G I); eauto. }\n         { intros Y H2.\n           replace (|Y|) with (|img f Y|).\n           replace (|img f I|) with (|I|).\n           assert (H3: Stable_in G (img f Y)). eauto.\n           eauto using Max_I_in_elim. eapply iso_sub_cardinal;eauto.\n           symmetry. eapply iso_sub_cardinal; eauto. } } Qed.\n\n  Lemma i_num_G' (G G': @UG A)(n: nat):\n    iso G G' -> i_num G n -> i_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [I H1].\n         destruct H1 as [H1 H1b]. exists (img f I).\n         split. eauto using max_I_in_G'. replace n with (|I|).\n         symmetry. eapply iso_sub_cardinal;eauto. } Qed.\n  \n  Hint Immediate max_I_in_G' i_num_G': core.\n\n  (*----------- Isomorphism, graph coloring and chromatic number -------------------------*)\n  \n  \n  Lemma iso_coloring (G G': @UG A)(f: A->A)(C: A->nat):\n    iso_using f G G' -> Coloring_of G C -> Coloring_of G' (fun (x:A) => C (f x)).\n  Proof. { intros H H1. assert (Ha: iso_using f G' G);auto. unfold Coloring_of.\n           intros x y Hx Hy H2. assert (H3: edg G (f x) (f y)). eauto. apply H1; eauto. } Qed.\n          \n  Lemma iso_same_clrs (G G': @UG A)(f: A->A)(C: A->nat):\n    iso_using f G G' -> Coloring_of G C -> (clrs_of C G) = clrs_of (fun (x:A) => C (f x)) G'.\n  Proof. { intros H H1. assert (Ha: iso_using f G' G). auto.\n         assert (H2: (nodes G) = img f G'). auto. unfold clrs_of; rewrite H2; auto. } Qed.\n\n  Lemma best_coloring_of_G' (G G': @UG A)(f: A-> A)(C: A->nat):\n    iso_using f G G' -> Best_coloring_of G C -> Best_coloring_of G' (fun (x:A) => C (f x)).\n  Proof. { unfold Best_coloring_of. intros H H1.\n         assert (H0: iso_using f G' G). auto.\n         destruct H1 as [H1 H2].\n         split. { eauto using iso_coloring. }\n                { intros C' H3.\n                  assert (H4: (clrs_of C G) = clrs_of (fun (x:A) => C (f x)) G').\n                  auto using iso_same_clrs. rewrite <- H4.\n                  assert (H5: (clrs_of C' G') = clrs_of (fun (x:A) => C' (f x)) G).\n                  auto using iso_same_clrs. rewrite H5.\n                  apply H2. eauto using iso_coloring. } } Qed. \n                  \n  Lemma chrom_num_G' (G G': @UG A)(n:nat):\n    iso G G' -> chrom_num G n -> chrom_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [C H1].\n         destruct H1 as [H1 H2].\n         exists (fun (x:A) => C (f x)). split. eauto using best_coloring_of_G'.\n         subst n. replace (clrs_of (fun x : A => C (f x)) G') with (clrs_of C G).\n         auto. destruct H1 as [H1 H2]. auto using iso_same_clrs. } Qed.\n\n  Hint Resolve iso_coloring iso_same_clrs best_coloring_of_G': core.\n  Hint Immediate chrom_num_G': core.\n\n\n  (*------------Isomorphism, nice graphs and perfect graph--------------------------------*)\n\n  Lemma nice_G' (G G': @UG A): iso G G' -> Nice G -> Nice G'.\n  Proof. { intro H.  assert (H0: iso G' G). auto.\n         unfold Nice. intros H1 n H2.\n         cut (chrom_num G n). eauto. cut (cliq_num G n); eauto. } Qed.\n\n  Lemma iso_subgraphs (G G' H: @UG A)(f: A->A):\n    iso_using f G G' -> Ind_subgraph H G -> (exists H', Ind_subgraph H' G' /\\ iso_using f H H').\n  Proof.  { intros F1 F2.\n            assert (F0: iso_using f G' G). auto. \n            assert (Nk: IsOrd (img f H)). auto.\n            pose H' := (ind_at (img f H) G').\n            exists H'.\n            assert (h0: H' [<=] G').\n            { replace (nodes G') with (img f G). simpl.\n              cut (img f H [<=] img f G). auto. \n              eapply img_subset. apply F2. symmetry. auto. }\n            assert (h1: img f H [<=] G').\n            { replace (nodes G') with (img f G).\n                cut (H [<=] G). auto. apply F2.  symmetry.\n                assert(F3: iso_using f G G'). auto. apply F3. }\n            assert (h2: img f H = inter (img f H) G').\n            { apply set_equal; auto. }\n            split.\n            (* Ind_subgraph H' G' *)\n            {  unfold Ind_subgraph. split.\n               { auto. }\n               { unfold H'. simpl. intros. symmetry. auto. } }\n           \n            {  (* iso_using f H H' *)\n              unfold iso_using.\n              split.\n              { apply F1. }\n              split. \n              { simpl. symmetry. auto.  }\n              { (* forall x y : A, edg H x y = edg (Ind_at Nk G') (f x) (f y) *)\n                simpl. intros x y Hx Hy.\n                replace (edg H x y) with (edg G x y). 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 x G). cut(In y G). all: auto. symmetry. auto. } } } Qed.\n                \n \n  Lemma perfect_G' (G G': @UG A): iso G G' -> Perfect G -> Perfect G'.\n  Proof. { intro F.  assert (F0: iso G' G). auto.\n         unfold Perfect. destruct F0 as [f F0].\n         intros F1 H' F2.\n         assert (F3: exists H, Ind_subgraph H G /\\ iso_using f H' H).\n         { eapply iso_subgraphs. apply F0. auto. }\n         destruct F3 as [H F3]. destruct F3 as [F3 F4]. \n         cut (Nice H).\n         { cut (iso H H'). eauto using nice_G'.\n           exists f. cut (iso_using f H H'); auto. } auto.  } Qed.\n\n  Hint Immediate nice_G' induced_fact1 iso_subgraphs perfect_G': core.\n\nEnd GraphIsomorphism.\n\n\nHint Resolve f_is_one_one fx_is_one_one img_of_img img_of_img1: core.\n\nHint Immediate iso_sym1 iso_sym iso_elim1 iso_elim2: core.\n Hint Resolve iso_using_iso iso_using_iso1: core.\nHint Immediate iso_one_one1 iso_one_one2: core.\nHint Immediate iso_one_one iso_f_one_one iso_using_G iso_using_G': core.\n\nHint Immediate iso_cardinal iso_sub_cardinal iso_edg1 iso_edg2: core.\nHint Immediate iso_edg3 iso_edg4: core.\n\nHint Immediate iso_cliq iso_cliq1 iso_cliq_in iso_cliq_in1: core.\nHint Immediate max_K_in_G' cliq_num_G': core.\n\nHint Immediate iso_stable iso_stable1 iso_stable_in iso_stable_in1: core.\nHint Immediate max_I_in_G' i_num_G': core.\n\nHint Resolve iso_coloring iso_same_clrs best_coloring_of_G': core.\nHint Immediate chrom_num_G': core.\n\nHint Immediate nice_G' iso_subgraphs perfect_G': core.\n\n\n\n\n\n\n\n", "meta": {"author": "Abhishek-TIFR", "repo": "List-Set", "sha": "f22e828ca348c8317a5235491e7e1dac848a691f", "save_path": "github-repos/coq/Abhishek-TIFR-List-Set", "path": "github-repos/coq/Abhishek-TIFR-List-Set/List-Set-f22e828ca348c8317a5235491e7e1dac848a691f/IsoUG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8007618091237919}}
{"text": "(*Sidorets Kirill et Ait gueni ssaid Abderrahmane*)\nRequire Import untypedLC. \n(* 1.1 \u03bb-calcul non typ\u00e9 *)\n\n  (* 1. Bool\u00e9ens (codage des constantes et des op\u00e9rations de base)   *)\n  (*bool\u00e9ens de Church vrai: \u03bbx y.x*)\n  Definition ctr := \\x y\u00b7x. \n  (*bool\u00e9ens de Church faux: \u03bbx y.y*)\n  Definition cfa := \\x y\u00b7y.\n  (*if b then m else n : \u03bb b m n .b m n*)\n  Definition cif := \\b m n \u00b7 b m n.\n  (* a and  b : \u03bb a b.\u03bbx y. a (b x y) y *)\n  Definition cand := \\ a b \u00b7 (\\ x y \u00b7 a (b x y) y).\n  (* a or  b : \u03bb a b.\u03bbx y. a x (b x y) *)\n  Definition cor := \\a b \u00b7\\x y\u00b7a x(b x y).\n  (* a or  b : \u03bb a b.\u03bbx y. cif a x (b x y) *)\n  Definition cor_cif :=\\a b\u00b7\\x y \u00b7cif a x( b x  y).\n  (*D\u00e9riv\u00e9e \u00e0 partir de la version non factoris\u00e9e *)\n  Definition cor' :=\\a\u00b7a a.\n  (*not a ( if a then {false} else {true}):\u03bb a.cif a cfa ctr*)\n  Definition cnot := \\ a\u00b7 cif a cfa ctr .\n  (*not a :\u03bb a.a cfa ctr*)\n  Definition cnot' := \\ a\u00b7 a cfa ctr .\n\n  \n  Compute show_cbn(cif ctr a b).\n  Compute show_cbn(cif cfa a b).\n  Compute show_cbn(cif (cor_cif cfa (cnot ctr)) a b).\n  Compute show_cbn(cor_cif cfa cfa a b).\n  Compute show_cbn(cif( cor' (cand cfa ctr) cnot' cfa) a b).\n  \n\n  (* 2. Entiers naturels (codage de quelques constantes, \n  des op\u00e9rations successeur, addition et multiplication, et \n  du test \u00e0 0)*)\n  (*Codage des entiers naturels en \u03bb-calcul invent\u00e9 par Alonzo Church *)\n  (* 0 :\u03bb f x .x *)  \n  Definition c0 := \\f x\u00b7x. \n  (* 1 :\u03bb f x . f x *)  \n  Definition c1 :=\\f x\u00b7f x.\n  (* 2 :\u03bb f x . f (f x) *)  \n  Definition c2 :=\\f x\u00b7f (f x).\n  (* 3 :\u03bb f x . f (f (f x)) *)  \n  Definition c3 :=\\f x\u00b7f (f (f x)).\n  (* 4 :\u03bb f x . f (f (f (f x))) *)  \n  Definition c4 :=\\f x\u00b7f (f (f (f x))).\n  (* csucc(n)=n+1 : \u03bb n.\u03bb f x. f (n f x)*)\n  Definition csucc := \\n\u00b7\\f x \u00b7 f ( n f x).\n  (* cadd (a,b)=a+b :\u03bb n m.\u03bb f x. n f (m f x) *)\n  Definition cadd := \\n m \u00b7\\f x \u00b7 n f ( m f x).\n  (* cmult (a,b)=a*b :\u03bb n m.\u03bb f . n (m f) *)\n  Definition cmult := \\n m \u00b7\\f\u00b7 n( m f).\n  (* ceq0(n) = {si n=c0 true sinon false}:\u03bb n .\u03bb x y . n (\u03bb z.y ) x*)\n  Definition ceq0 :=\\n\u00b7\\x y\u00b7n(\\z\u00b7y) x.\n  \n\n  Compute (show_cbn (csucc c4)).\n  Compute (show_cbn (cadd c2 c3)).\n  Compute (show_cbn (cmult c2 c4)).\n(* l'expression ceq0 retourne a si true sinon elle retourne b  *)\n  Compute (show_cbn ((ceq0 c0) a b)).\n  Compute (show_cbn ((ceq0 c3) a b )).\n  \n  (* 3. Couples*)\n  (*La fonction cpl prend deux arguments(a,b) et construit un couple : \u03bba b.\u03bbk.k a b *)\n  Definition cpl := \\ a b \u00b7 \\ k\u00b7k a b. \n  (*Prends en argument un couple, retournent premier \u00e9l\u00e9ment : \u03bb x y. x*)\n  Definition kfst := \\ x y\u00b7 x.\n  (*Prends en argument un couple, retournent deuxi\u00e8me \u00e9l\u00e9ment : \u03bb x y. y*)\n  Definition ksnd := \\ x y\u00b7 y.\n  (*fst(c) = x ou c - un couple x - premier \u00e9l\u00e9ment de c  : \u03bb c. c kfst *)\n  Definition fst := \\ x \u00b7 x kfst.\n  (*fst(c) = y ou c - une cople x - deuxi\u00e8me \u00e9l\u00e9ment de c  : \u03bb c. c ksnd *)\n  Definition snd := \\ x \u00b7 x ksnd.\n\n  Compute (show_cbn (fst (cpl a b))).\n  Compute (show_cbn (snd (cpl ctr cfa))).\n\n  (*ksumcpl(cp(n,m))= n+m Renvoie la somme des \u00e9l\u00e9ments d'une couple \n  :\u03bbx.(cadd (fst x) (snd x)) *)\n  Definition ksumcpl := \\x \u00b7 (cadd (fst x) (snd x)).\n  Compute show_cbn(ksumcpl (cpl c2 c3)).\n\n  (*4. Structure de choix (inj1, inj2, donn\u00e9e optionnelle).*)\n  (*Constructeur structure de choix a partir du premier \u00e9l\u00e9ment : \u03bb a b. a x *)\n  Definition inj1 := \\a b \u00b7 a x. \n  (*Constructeur structure de choix a partir du deuxi\u00e8me \u00e9l\u00e9ment : \u03bb a b. b x *)\n  Definition inj2 := \\a b \u00b7 b x.\n\n  Compute show_cbn(inj1 f g).\n  Compute show_cbn(inj2 f g).\n  (*Fonction prenant en argument une donn\u00e9e qui est soit un entier n (emball\u00e9 par\n  inj1) soit un bool\u00e9en b (emball\u00e9 par inj2) et qui rend le double de n dans le \n  premier cas, la n\u00e9gation de b dans le second *)\n  Definition funcinj1inj2:=\\a x \u00b7 a (cmult x c2) (cnot x).\n  Compute show_cbn(funcinj1inj2 inj1 c3).\n  Compute show_cbn(funcinj1inj2 inj2 ctr).\n\n  (* La donn\u00e9e optionnelle correspond \u00e0 un choix entre une donn\u00e9e (Some x) ou \n  son absence (None). Elle se repr\u00e9sente avec une continuation \u00e0 un argument \n  et une continuation \u00e0 z\u00e9ro argument. Coder en Coq les injections Some et None,\n  puis une fonction osucc prenant en argument un entier optionnel (Some n ou None)\n  et rendant un entier optionnel qui est Some (n+1) dans le premier cas et Some 0\n  dans le second *)\n  Definition Some:= \\f m n \u00b7 m f. \n  Definition None:= \\x y \u00b7 y. \n  Definition osucc:= \\a b \u00b7 a b csucc c0.\n  Compute show_cbn(osucc Some c3).\n  Compute show_cbn(osucc None).\n\n  (* 5. Pr\u00e9d\u00e9cesseur (cpred; cpredo en bonus)*)\n  (*la fonction iter qui prend un entier de Church n, une fonction g et\n  un argument x et qui applique n fois la fonction g sur x. *)\n  Definition iter := \\n g x \u00b7 n g x.\n  (*  la fonction cpred1 qui \u00e0 partir d\u2019un couple \u03bbk.k x y donn\u00e9 en\n  argument rend le couple \u03bbk.k y (csucc y).*)\n  Definition cpred1 := \\c \u00b7 \\k \u00b7 k (snd c) (csucc(snd c)).\n  Compute show_cbn(cpl c1 c2).\n  Compute show_cbn(fst (cpred1 (cpl c1 c2))).\n  Compute show_cbn(snd (cpred1 (cpl c1 c2))).\n  Compute show_cbn(cpred1 (cpl c1 c2)).\n  (* Pour d\u00e9finir le pr\u00e9d\u00e9cesseur sur les entiers de Church, on utilise les couples.\n  L\u2019id\u00e9e est d\u2019it\u00e9rer n fois une fonction agissant sur des couples d\u2019entiers. \n  Prenons une fonction g qui \u00e0 partir de (x, y) donn\u00e9 en argument rend (y, y +1).\n  Alors, en it\u00e9rant n fois g sur (0, 0), on obtient (n \u22121,n) et il suffit d\u2019extraire\n  la premi\u00e8re composante de ce couple. Si n est cod\u00e9 comme un entier de Church alors\n  it\u00e9rer n fois une fonction g sur un argument a est juste (n g a).*)\n  Definition cpred := \\n\u00b7 fst (iter n cpred1 (cpl c0 c0) ).\n  Compute show_cbn(cpred c3).\n  Definition cpred_v2 := \\n\u00b7 fst ( n cpred1 (cpl c0 c0) ).\n  Compute show_cbn(cpred_v2 c3).\n\n  (*6. Factorielle*)\n  (* cfonc -> f if(n==0) alors retourne 1 sinon n*f(n-1)  *)\n  Definition cfonc := \\f n\u00b7 cif (ceq0 n) c1 (cmult n (f f (cpred n))). \n  (*cfact(3)=1*2*3=6 *)\n  Definition cfact :=\\x\u00b7 cfonc cfonc x.\n  Compute red_cbn(cfact c0).\n  Compute red_cbn(cfact c1).\n  Compute red_cbn(cfact c2).\n  Compute red_cbn(cfact c3).", "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_1.1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8007445588196435}}
{"text": "Require Import Group.\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\nInclude BinIntDef.Z.\n\n(* Make a Group consisting of all integers under addition, with 0 as the identity element *)\nInstance ZAdd : Group Zplus opp 0.\nProof.\n  split.\n  * apply Zplus_assoc.\n  * intros x.\n    rewrite Z.add_opp_l.\n    apply Zminus_diag.\n  * intros x.\n    rewrite Z.add_opp_r.\n    apply Zminus_diag.\n  * reflexivity.\n  * apply Zplus_0_r.\nQed.\n", "meta": {"author": "Chobbes", "repo": "Groq", "sha": "0745f8b9ea9414cefcf8d2fd43b02b8943af34d0", "save_path": "github-repos/coq/Chobbes-Groq", "path": "github-repos/coq/Chobbes-Groq/Groq-0745f8b9ea9414cefcf8d2fd43b02b8943af34d0/ZAdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.8006959156951605}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\nPrint le.\n(* ====> Inductive le (n : nat) : nat -> Prop :=\n             le_n : n <= n\n           | le_S : forall m : nat, n <= m -> n <= S m *)\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, \n    R x y1 -> R x y2 -> y1 = y2.\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  discriminate Nonsense. \nQed.\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n.\nQed.\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, \n    (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - (* le_n *) apply Hnm.\n  - (* le_S *) apply le_S. apply IHHmo. \nQed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. \nQed.\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [|m' Hm'o].\n  - apply le_S in Hnm. apply Hnm.\n  - apply le_S, IHHm'o.\nQed.\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  - inversion Hmo.\n  - apply Sn_le_Sm__n_le_m in Hmo.\n    apply le_S in Hmo.\n    apply (le_trans (S n) m (S o')).\n    apply Hnm. apply Hmo.\nQed.\n\nTheorem le_Sn_le : forall n m, \n  S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n  apply le_S, le_n. apply H.\nQed.\n\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros n m H. inversion H. apply le_n. \n  apply le_Sn_le in H1. apply H1.\nQed.\n\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  unfold not. intros. induction n.\n  inversion H. apply le_S_n in H. \n  apply IHn in H. apply H.\nQed.\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold symmetric. intros H.\n  assert (1 <= 0) as Nonsense. \n  { apply H. apply le_S. apply le_n. }\n  inversion Nonsense.\nQed.\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric. intros.\n  inversion H. reflexivity.\n  assert (S a <= a) as Nonsense.\n  (* S b <= S a <= b *)\n  { apply le_trans with (b := b).\n  rewrite <- H2. apply le_n_S, H1. apply H0. }\n  apply le_Sn_n in Nonsense.\n  apply ex_falso_quodlibet, Nonsense.\nQed.\n\nTheorem le_step : forall n m p,\n  n < m -> m <= S p -> n <= p.\nProof.\n  unfold lt. intros.\n  apply le_S_n, (le_trans (S n) m (S p)).\n  apply H. apply H0.\nQed.\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(* Actually, it is Partial Orders *)\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ \n    (antisymmetric R) /\\ (transitive R).\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n  - apply le_reflexive.\n  - split.\n    + apply le_antisymmetric.\n    + apply le_trans.\nQed.\n\nInductive clos_refl_trans {A: Type} (R: relation A) : \n  relation A :=\n    | rt_step x y (H : R x y) : clos_refl_trans R x y\n    | rt_refl x : clos_refl_trans R x x\n    | rt_trans x y z\n          (Hxy : clos_refl_trans R x y)\n          (Hyz : clos_refl_trans R y z) :\n          clos_refl_trans R x z.\n\nPrint next_nat.\n(*\nInductive next_nat : nat -> nat -> Prop :=\n    nn : forall n : nat, next_nat n (S n)\n*)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n  - intros H. induction H.\n    + apply rt_refl.\n    + apply rt_trans with m. apply IHle.\n      apply rt_step. apply nn.\n  - intros H. induction H.\n    + inversion H. apply le_S, le_n.\n    + apply le_n.\n    + apply le_trans with y. \n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2.\nQed.\n\nInductive clos_refl_trans_1n {A : Type}\n                       (R : relation A) (x : A)\n                             : A -> Prop :=\n  | rt1n_refl : clos_refl_trans_1n R x x\n  | rt1n_trans (y z : A)\n      (Hxy : R x y) (Hrest : clos_refl_trans_1n R y z) :\n      clos_refl_trans_1n R x z.\n\nLemma rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> clos_refl_trans_1n R x y.\nProof.\n  intros X R x y H.\n  apply rt1n_trans with y. \n  apply H. apply rt1n_refl.\nQed.\n\nLemma rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      clos_refl_trans_1n R x y ->\n      clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\nProof.\n  intros. induction H.\n  - apply H0.\n  - apply rt1n_trans with y. apply Hxy.\n    apply IHclos_refl_trans_1n, H0.\nQed.\n\nTheorem rtc_rsc_coincide :\n  forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <->\n    clos_refl_trans_1n R x y.\nProof.\n  intros. split.\n  - intros H. induction H.\n    + apply rsc_R, H.\n    + apply rt1n_refl.\n    + apply rsc_trans with y.\n      apply IHclos_refl_trans1. \n      apply IHclos_refl_trans2.\n  - intros H. induction H.\n    + apply rt_refl.\n    + apply rt_trans with y. \n      apply rt_step in Hxy. apply Hxy.\n      apply IHclos_refl_trans_1n.\nQed.", "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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8006776873325131}}
{"text": "\nRequire Import Znumtheory.\nRequire Import Qreduction.\n\nOpen Scope Q_scope.\n\nCoercion inject_Z : Z >-> Q.\n\nFixpoint fib_pair (n:nat) : Z*Z := match n with \n | O => (0,1)%Z\n | S n => let (p,q) := fib_pair n in (q,p+q)%Z\n end.\n\nDefinition fibonacci (n:nat) := snd (fib_pair n). \n\nDefinition fibo_frac (n:nat) := Qred (fibonacci (S n) # Z2P (fibonacci n)).\n\nTime Eval vm_compute in fibo_frac 1000.\n\n(* display for humans: *)\n\nDefinition get_first_n_decimal_digits (n:nat)(q:Q) : Z :=\n let q' := q*(10^n) in \n Zdiv (Qnum q') (QDen q').\n\nEval vm_compute in get_first_n_decimal_digits 30 (fibo_frac 1000).\n\n(*\nFrom bc: \nscale=30\n(1+sqrt(5))/2\n1.618033988749894848204586834365\n*)\n\nFixpoint sqrt2_newton (n:nat) : Q := match n with \n | O => 1%Q\n | S n => let q := sqrt2_newton n in  \n               Qred ( (1/2)*q + /q)\n end.\n\n(*\nTime Eval vm_compute in sqrt2_newton 10.\n*)\n\nEval vm_compute in get_first_n_decimal_digits 100 (sqrt2_newton 10).\n(*\n1414213562373095048801688724209698078569671875376948073176679737990\\\n7324784621070388503875343276415727\n*)\n\n(* from bc: \nscale=100\nsqrt(2)\n1.414213562373095048801688724209698078569671875376948073176679737990\\\n7324784621070388503875343276415727\n*)\n\nFixpoint e_frac_aux (n:nat) : Q*(Z*Z) := match n with \n | O => (1,(1%Z,1%Z))\n | S n => let (q,pr) := e_frac_aux n in \n               let (fact,next) := pr in \n               let nextfact:=(next*fact)%Z in\n               (Qred (q+/nextfact), (nextfact,Zsucc next))\n end.\n\nDefinition e_frac (n:nat) := fst (e_frac_aux n).\n\nTime Eval vm_compute in e_frac 150.\nTime Eval vm_compute in get_first_n_decimal_digits 100 (e_frac 150).\n(*\n2718281828459045235360287471352662497757247093699959574966967627724\\\n0766303535475945713821785251664274\n*) \n\n(* from bc: \nscale=100\n2.718281828459045235360287471352662497757247093699959574966967627724\\\n0766303535475945713821785251664274\n*)\n\nFixpoint atan_aux (n:nat)(q:Q) {struct n } : (Q*(Q*Z)) := match n with \n\t                          (* part sum / last term / (-1)^n*(2n+1) *)\n  | O => (q,(q,1%Z)) \n  | S n => let (sum,pr) := atan_aux n q in \n                let (power,div) := pr in \n                let nextpower:=q*q*power in \n\t        let nextdiv:= ((-2)*Zsgn(div)-div)%Z in \n                (Qred (sum+nextpower/nextdiv), (nextpower, nextdiv))\n end.\n\nDefinition atan (n:nat)(q:Q) := fst (atan_aux n q).\n\nDefinition pi_frac (n:nat) := Qred (16*(atan n (1#5))-4*(atan n (1#239))).\n\nTime Eval vm_compute in get_first_n_decimal_digits 100 (pi_frac 70).\n(*\n3141592653589793238462643383279502884197169399375105820974944592307\\\n8164062862089986280348253421170679\n\nbc:\n3.141592653589793238462643383279502884197169399375105820974944592307\\\n8164062862089986280348253421170680\n*)\n\nExtraction \"pi.ml\" pi_frac get_first_n_decimal_digits.\n", "meta": {"author": "coq-contribs", "repo": "qarith", "sha": "a30fd6b2fa71e35dbadf38e5c04df98b842ca479", "save_path": "github-repos/coq/coq-contribs-qarith", "path": "github-repos/coq/coq-contribs-qarith/qarith-a30fd6b2fa71e35dbadf38e5c04df98b842ca479/Qexemples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8006671746307412}}
{"text": "Inductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\nFixpoint plus (m n : nat) : nat :=\n  match m with\n    | O => match n with\n        | O => O\n        | S n' => S n'\n      end\n    | S m' => match n with\n        | O => S m'\n        | S n' => S (S (plus m' n'))\n      end\n  end.\n\nTheorem S_injective : forall m n : nat, S m = S n -> m = n.\n  injection 1.\n  trivial.\nQed.\n\nTheorem O_left_id : forall m : nat, plus O m = m.\n  intros.\n  case m.\n    (* m = O *)\n    simpl.\n    trivial.\n    (* m = S m' *)\n    intros.\n    simpl.\n    trivial.\nQed.\n\nTheorem O_right_id : forall m : nat, plus m O = m.\n    intros.\n  case m.\n    (* m = O *)\n    simpl.\n    trivial.\n    (* m = S m' *)\n    intros.\n    simpl.\n    trivial.\nQed.\n\nTheorem O_id : forall m : nat, plus O m = m /\\ plus m O = m.\n  intros.\n  refine (conj _ _).\n    apply O_left_id.\n    apply O_right_id.\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/naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.8006671732592713}}
{"text": "(* 3 Introducing Inductive Types *)\n\nRequire Import Cpdt.CpdtTactics.\nSet Implicit Arguments.\n\n(* 3.1 Proof Terms *)\n\nCheck (fun x : nat => x).\n\nCheck (fun x : True => x).\n\nCheck I.\n\nCheck (fun _ : False => I).\n\nCheck (fun x : False => x).\n\n(* 3.2 Enumerations *)\n\nInductive unit : Set :=\n| tt\n.\n\nCheck unit.\nCheck tt.\n\n(* We can prove that unit is a genuine singleton type. *)\n\nTheorem unit_singleton : forall x : unit, x = tt.\n\ninduction x.\nreflexivity.\nQed.\n\nCheck unit_ind.\n\nInductive Empty_set : Set := .\n\nTheorem the_sky_is_falling : forall x : Empty_set, 2 + 2 = 5.\n   destruct 1.\nQed.\n\nCheck Empty_set_ind.\n\nDefinition e2u (e : Empty_set) : unit := match e with end.\n\nInductive bool : Set :=\n| true\n| false\n.\n\nDefinition negb (b :  bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end\n.\n\nDefinition negb' (b : bool) : bool :=\n  if b then false else true\n.\n\nDefinition negb'' (b : bool) : _ :=\n  if b then false else true\n.\n\nTheorem negb_inverse : forall b : bool , negb (negb b) = b.\n  destruct b; reflexivity.\nQed.\n\nTheorem negb_inqe : forall b : bool, negb b <> b.\n  destruct b; discriminate.\nQed.\n\nCheck bool_ind.\n\n(* 3.3 Simple Recursive Types *)\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.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end\n.\n\nCheck pred.\n\nFixpoint plus n m :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end\n.\n\nCheck plus.\n\nTheorem O_plus_n : forall n : nat , plus O n = n.\n  intro; reflexivity.\nQed.\n\nTheorem n_plus_O : forall n : nat , plus n O = n.\n                                      induction n.\n                                      reflexivity.\n                                      simpl.\n                                      rewrite IHn.\n                                      reflexivity.\nQed.\n\nTheorem n_plus_O' : forall n : nat , plus n O = n.\n  induction n; crush.\nQed.\n\nCheck nat_ind.\n\nTheorem S_inj : forall n m : nat , S n = S m -> n = m.\n  injection 1; trivial.\nQed.\n\n(* Haskell extraction of a given function *)\nExtraction Language Haskell.\nExtraction \"arith.hs\" plus.\n\nInductive nat_list : Set :=\n| NNil : nat_list\n| NCons : nat -> nat_list -> nat_list\n.\n\nFixpoint nlength (ls : nat_list) : nat :=\n  match ls with\n  | NNil => O\n  | NCons _ ls' => S (nlength ls')\n  end\n.\n\nFixpoint napp (ls1 ls2 : nat_list) : nat_list :=\n  match ls1 with\n  | NNil => ls2\n  | NCons n ls1' => NCons n (napp ls1' ls2)\n  end\n.\n\nTheorem nlength_app : forall ls1 ls2 : nat_list ,\n    nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2).\n      induction ls1; crush.\nQed.\n\nCheck nat_list_ind.\n\nInductive nat_btree : Set :=\n| Leaf : nat_btree\n| Node : nat_btree -> nat -> nat_btree -> nat_btree\n.\n\nFixpoint size (tr : nat_btree) : nat :=\n  match tr with\n  | Leaf => S O\n  | Node tr1 _ tr2 => plus (size tr1) (size tr2)\n  end\n.\n\nFixpoint splice (tr1 tr2 : nat_btree) : nat_btree :=\n  match tr1 with\n  | Leaf => Node tr2 O Leaf\n  | Node tr1' n tr2' => Node (splice tr1' tr2) n tr2'\n  end\n.\n\nTheorem plus_assoc : forall n1 n2 n3 : nat ,\n    plus (plus n1 n2) n3 = plus n1 (plus n2 n3).\n      induction n1; crush.\nQed.\n\nHint Rewrite n_plus_O plus_assoc.\n\nTheorem size_splice : forall tr1 tr2 : nat_btree ,\n    size (splice tr1 tr2) = plus (size tr2) (size tr1).\n      induction tr1; crush.\nQed.\n\nCheck nat_btree_ind.\n\n(* 3.4 Parameterized Types *)\n\n(* Without section \nInductive list (T : Set) : Set :=\n| Nil : list T\n| Cons : T -> list T -> list T\n.\n\nFixpoint length T (ls : list T) : nat :=\n  match ls with\n  | Nil => O\n  | Cons _ ls' => S (length ls')\n  end\n.\n\n(* Without implicit arguments\nFixpoint length T (ls : list T) : nat :=\n  match ls with\n  | Nil => O\n  | Cons _ ls' => S (length _ ls')\n  end\n.\n*)\n\nFixpoint app T (ls1 ls2 : list T) : list T :=\n  match ls1 with\n  | Nil => ls2\n  | Cons x ls1' => Cons x (app ls1' ls2)\n  end\n.\n\nTheorem length_app : forall T (ls1 ls2 : list T) ,\n    length (app ls1 ls2) = plus (length ls1) (length ls2).\n      induction ls1; crush.\nQed.\n*)\n\nSection list.\n  Variable T : Set.\n\n  Inductive list : Set :=\n  | Nil : list\n  | Cons : T -> list -> list\n  .\n\n  Fixpoint length (ls : list) : nat :=\n    match ls with\n    | Nil => O\n    | Cons _ ls' => S (length ls')\n    end.\n\n  Fixpoint app (ls1 ls2 : list) : list :=\n    match ls1 with\n    | Nil => ls2\n    | Cons x ls1' => Cons x (app ls1' ls2)\n    end.\n\n  Theorem length_app : forall ls1 ls2 : list,\n      length (app ls1 ls2) = plus (length ls1) (length ls2).\n        induction ls1; crush.\n  Qed.\nEnd list.\n\n(*\nImplicit Arguments Nil [T].\nWarning: Implicit Arguments is deprecated; use Arguments instead\n*)\n\nArguments Nil [T].\n\nPrint list.\n\nCheck length.\n\nCheck list_ind.\n\n(* 3.5 Mutually Inductive Types *)\n\nInductive even_list : Set :=\n| ENil : even_list\n| ECons : nat -> odd_list -> even_list\n\nwith odd_list : Set :=\n| OCons : nat -> even_list -> odd_list\n.\n\nFixpoint elength (el : even_list) : nat :=\n  match el with\n  | ENil => O\n  | ECons _ ol => S (olength ol)\n  end\n\nwith olength (ol : odd_list) : nat :=\n  match ol with\n  | OCons _ el => S (elength el)\n  end\n.\n\nFixpoint eapp (el1 el2 : even_list) : even_list :=\n  match el1 with\n  | ENil => el2\n  | ECons n ol => ECons n (oapp ol el2)\n  end\n\nwith oapp (ol : odd_list) (el : even_list) : odd_list :=\n  match ol with\n  | OCons n el' => OCons n (eapp el' el)\n  end\n.\n(*\nTheorem elength_eapp : forall el1 el2 : even_list ,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).\n      induction el1; crush.\nAbort.\n*)\nCheck even_list_ind.\n\nScheme even_list_mut := Induction for even_list Sort Prop\nwith odd_list_mut := Induction for odd_list Sort Prop\n.\n\nCheck even_list_mut.\n\nTheorem elength_eapp : forall el1 el2 : even_list ,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).\n      apply (even_list_mut\n               (fun el1 : even_list => forall el2 : even_list,\n                    elength (eapp el1 el2) = plus (elength el1) (elength el2))\n               (fun ol : odd_list => forall el : even_list,\n                    olength (oapp ol el) = plus (olength ol) (elength el))); crush.\nQed.\n\n(* 3.6 Reflexive Types *)\n\n(*\nA kind of inductive type called a reflexive type includes at least\none constructor that takes as an argument a function returning the\nsame tye we are defining.\n*)\n\nInductive pformula : Set :=\n| Truth : pformula\n| Falsehood : pformula\n| Conjuction : pformula -> pformula -> pformula\n.\n\nFixpoint pformulaDenote (f : pformula) : Prop :=\n  match f with\n  | Truth => True\n  | Falsehood => False\n  | Conjuction f1 f2 => pformulaDenote f1 /\\ pformulaDenote f2\n  end\n.\n\nInductive formula : Set :=\n| Eq : nat -> nat -> formula\n| And : formula -> formula -> formula\n| Forall : (nat -> formula) -> formula (* Constructor which makes this type reflexive *)\n.\n\nExample forall_refl : formula := Forall (fun x =>  Eq x x).\n\nFixpoint formulaDenote (f : formula) : Prop :=\n  match f with\n  | Eq n1 n2 => n1 = n2\n  | And f1 f2 => formulaDenote f1 /\\ formulaDenote f2\n  | Forall f' => forall n : nat, formulaDenote (f' n)\n  end\n.\n\nFixpoint swapper (f : formula) : formula :=\n  match f with\n  | Eq n1 n2 => Eq n2 n1\n  | And f1 f2 => And (swapper f2) (swapper f1)\n  | Forall f' => Forall (fun n => swapper (f' n))\n  end\n.\n\nTheorem swapper_preserves_truth : forall f , formulaDenote f -> formulaDenote (swapper f).\n   induction f; crush.\nQed.\n\nCheck formula_ind.\n\n(*\nInductive term : Set :=\n| App : term -> term -> term\n| Abs : (term -> term) -> term\n.\nError: Non strictly positive occurrence of \"term\" in \"(term -> term) -> term\".\n\nOur candidate definition above violates the positivity requirement because it\ninvolves an argument of type 'term -> term', where the type term that we are\ndefining appears to the left of an arrow. The candidate type of App is fine,\nhowever, since every occurrence of term is either a consturctor argument or\nthe final result type.\n*)\n\n(* 3.7 An Interlude on Induction Principles *)\n\nPrint nat_ind.\n\nCheck nat_rect.\n\nPrint nat_rec.\n\nFixpoint plus_recursive (n : nat) : nat -> nat :=\n  match n with\n  | O => fun m => m\n  | S n' => fun m => S (plus_recursive n' m)\n  end\n.\n\nDefinition plus_rec : nat -> nat -> nat :=\n  nat_rec (fun _ : nat => nat -> nat) (fun m => m) (fun _ r m => S (r m))\n.\n\nExtraction \"plus.hs\" plus_rec.\n\nTheorem plus_equivalent :\n  plus_recursive = plus_rec.\n    reflexivity.\nQed.\n\nPrint nat_rect.\n\nFixpoint nat_rect' (P : nat -> Type)\n         (HO : P O)\n         (HS : forall n , P n -> P (S n)) (n : nat) :=\n  match n return P n with\n  | O => HO\n  | S n' => HS n' (nat_rect' P HO HS n')\n  end\n.\n\nSection nat_ind'.\n  Variable P : nat -> Prop.\n  Hypothesis O_case : P O.\n  Hypothesis S_case : forall n : nat , P n -> P (S n).\n  Fixpoint nat_ind' (n : nat) : P n :=\n    match n with\n    | O => O_case\n    | S n' => S_case (nat_ind' n')\n    end\n  .\nEnd nat_ind'.\n\nPrint even_list_mut.\n\nSection even_list_mut'.\n  Variable Peven : even_list -> Prop.\n  Variable Podd : odd_list -> Prop.\n  Hypothesis ENil_case : Peven ENil.\n  Hypothesis ECons_case : forall (n : nat) (o : odd_list) , Podd o -> Peven (ECons n o).\n  Hypothesis OCons_case : forall (n : nat) (e : even_list) , Peven e -> Podd (OCons n e).\n  Fixpoint even_list_mut' (e : even_list) : Peven e :=\n    match e with\n    | ENil => ENil_case\n    | ECons n o => ECons_case n (odd_list_mut' o)\n    end\n  with\n  odd_list_mut' (o : odd_list) : Podd o :=\n    match o with\n    | OCons n e => OCons_case n (even_list_mut' e)\n    end.\nEnd even_list_mut'.\n\nSection formula_ind'.\n  Variable P : formula -> Prop.\n  Hypothesis Eq_case : forall n1 n2 : nat , P (Eq n1 n2).\n  Hypothesis And_case : forall f1 f2 : formula,\n      P f1 -> P f2 -> P (And f1 f2).\n  Hypothesis Forall_case : forall f : nat -> formula ,\n      (forall n : nat , P (f n)) -> P (Forall f).\n  Fixpoint formula_ind' (f : formula) : P f :=\n    match f with\n    | Eq n1 n2 => Eq_case n1 n2\n    | And f1 f2 => And_case (formula_ind' f1) (formula_ind' f2)\n    | Forall f' => Forall_case f' (fun n => formula_ind' (f' n))\n    end\n  .\nEnd formula_ind'.\n\n(* 3.8 Nested Inductive Types *)\n\nInductive nat_tree : Set :=\n| NNode' : nat -> list nat_tree -> nat_tree\n.\n\nCheck nat_tree_ind.\n\nSection All.\n  Variable T : Set.\n  Variable P : T -> Prop.\n  Fixpoint All (ls : list T) : Prop :=\n    match ls with\n    | Nil => True\n    | Cons h t => P h /\\ All t\n    end\n  .\nEnd All.\n\nPrint True.\n\nLocate \"/\\\".\n\nPrint and.\n\nSection nat_tree_ind'.\n  Variable P : nat_tree -> Prop.\n  Hypothesis NNode'_case : forall (n : nat) (ls : list nat_tree) ,\n      All P ls -> P (NNode' n ls).\n\n  Fixpoint nat_tree_ind' (tr : nat_tree) : P tr :=\n    match tr with\n    | NNode' n ls =>\n        NNode'_case n ls\n          ((fix list_nat_tree_ind (ls : list nat_tree) : All P ls :=\n             match ls with\n             | Nil => I\n             | Cons tr' rest => conj (nat_tree_ind' tr') (list_nat_tree_ind rest)\n             end)\n             ls)\n    end.\n\nEnd nat_tree_ind'.\n\nSection map.\n  Variables T T' : Set.\n  Variable F : T -> T'.\n  Fixpoint map(ls : list T) : list T' :=\n    match ls with\n    | Nil => Nil\n    | Cons h t => Cons (F h) (map t)\n    end.\nEnd map.\n\nFixpoint sum (ls : list nat) : nat :=\n  match ls with\n  | Nil => O\n  | Cons h t => plus h (sum t)\n  end.\n\nFixpoint ntsize (tr : nat_tree) : nat :=\n  match tr with\n  | NNode' _ trs => S (sum (map ntsize trs))\n  end.\n\nFixpoint ntsplice (tr1 tr2 : nat_tree) : nat_tree :=\n  match tr1 with\n  | NNode' n Nil => NNode' n (Cons tr2 Nil)\n  | NNode' n (Cons tr trs) => NNode' n (Cons (ntsplice tr tr2) trs)\n  end.\n\nLemma plus_S : forall n1 n2 : nat,\n    plus n1 (S n2) = S (plus n1 n2).\n      induction n1; crush.\nQed.\n\nHint Rewrite plus_S.\n\nTheorem ntsize_ntsplice : forall tr1 tr2 : nat_tree ,\n    ntsize (ntsplice tr1 tr2) = plus (ntsize tr2) (ntsize tr1).\n      induction tr1 using nat_tree_ind'; crush.\n      destruct ls; crush.\n    Restart.\n    Hint Extern 1 (ntsize (match ?LS with Nil => _ | Cons _ _ => _ end) = _) =>\n    destruct LS; crush.\n    induction tr1 using nat_tree_ind'; crush.\nQed.\n\n(* 3.9 Manual Proofs About Constructors *)\n\nTheorem true_neq_false :\n  true <> false.\n    red.\n    intro H.\n    Definition toProp (b : bool) := if b then True else False.\n    change (toProp false).\n    rewrite <- H.\n    simpl.\n    trivial.\nQed.\n\nTheorem S_inj' : forall n m : nat ,\n    S n = S m -> n = m.\n                   intros n m H.\n                   change (pred (S n) = pred (S m)).\n                   rewrite H.\n                   reflexivity.\nQed.\n", "meta": {"author": "andorp", "repo": "cpdt", "sha": "dd2099eeae2f12e1379a8706420f072aa174adc5", "save_path": "github-repos/coq/andorp-cpdt", "path": "github-repos/coq/andorp-cpdt/cpdt-dd2099eeae2f12e1379a8706420f072aa174adc5/chapter03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8824278741843883, "lm_q1q2_score": 0.8006375880819401}}
{"text": "(* Module NatPlayground.\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nInductive nat' : Type :=\n  | stop\n  | tick (foo : nat').\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\nEnd NatPlayground.*)\nInductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb(b:bool) : bool :=\nmatch b with\n| true => false\n| false => true\nend.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nNotation \"x && y\" := (andb x y).\n\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n: nat) (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\n(*Compute (mult 3 2).*)\n\nFixpoint factorial (n:nat) : nat:=\n  match n with\n    | 0 => 1\n    | S n' => mult n (factorial n')\n  end.\n\n(* Compute (factorial 3).*)\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.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nDefinition ltb (n m: nat) : bool:=\n  ((leb n m) && (negb (eqb n m))).\n\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.\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.\n  rewrite -> H1.\n  intros H2.\n  rewrite -> H2. \n  reflexivity.\n  Qed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  rewrite <- plus_1_l.\n  reflexivity. Qed.\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\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  -reflexivity. \n  -reflexivity. Qed.\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative : \n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c: bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c eqn:Ec.\n   { reflexivity. }\n   { rewrite <- H.\n      destruct b eqn:Eb.\n      { reflexivity. }\n      { reflexivity. } }\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n\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": "Ohyoukillkenny", "repo": "coq", "sha": "1d102cb966a1f3ff8a6e82bf145d6e0e09d8602d", "save_path": "github-repos/coq/Ohyoukillkenny-coq", "path": "github-repos/coq/Ohyoukillkenny-coq/coq-1d102cb966a1f3ff8a6e82bf145d6e0e09d8602d/number.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.8005312341907524}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* * Shared libraries *)\n\n(* ** Finitary sums and products over monoids *)\n\nRequire Import List Arith ZArith Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list binomial.\n\nSet Implicit Arguments.\n\nRecord monoid_theory (X : Type) (m : X -> X -> X) (u : X) := mk_monoid {\n  monoid_unit_l : forall x, m u x = x;\n  monoid_unit_r : forall x, m x u = x;\n  monoid_assoc  : forall x y z, m x (m y z) = m (m x y) z;\n}.\n\nFact Nat_plus_monoid : monoid_theory plus 0.\nProof. exists; intros; ring. Qed.\n\nFact Nat_mult_monoid : monoid_theory mult 1.\nProof. exists; intros; ring. Qed.\n\nFact Zplus_monoid : monoid_theory Zplus 0%Z.\nProof. exists; intros; ring. Qed.\n\nFact Zmult_monoid : monoid_theory Zmult 1%Z.\nProof. exists; intros; ring. Qed.\n\n#[export] Hint Resolve Nat_plus_monoid Nat_mult_monoid\n             Zplus_monoid Zmult_monoid : core.\n\nSection msum.\n\n  Variable (X : Type) (m : X -> X -> X) (u : X).\n\n  Infix \"\u2295\" := m (at level 50, left associativity).\n\n  Fixpoint msum n f := \n    match n with \n      | 0   => u\n      | S n => f 0 \u2295 msum n (fun n => f (S n))\n    end.\n\n  Notation \"\u2211\" := msum.\n\n  Fact msum_fold_map n f : \u2211 n f = fold_right m u (map f (list_an 0 n)).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; f_equal; auto.\n    rewrite IHn, <-  map_S_list_an, map_map; auto.\n  Qed.\n\n  Fact msum_0 f : \u2211 0 f = u.\n  Proof. auto. Qed.\n\n  Fact msum_S n f : \u2211 (S n) f = f 0 \u2295 \u2211 n (fun n => f (S n)).\n  Proof. auto. Qed.\n\n  Hypothesis Hmonoid : monoid_theory m u.\n\n  Fact msum_1 f : \u2211 1 f = f 0.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 H2 ].\n    rewrite msum_S, msum_0, H2; auto.\n  Qed.\n\n  Fact msum_plus a b f : \u2211 (a+b) f = \u2211 a f \u2295 \u2211 b (fun i => f (a+i)).\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 _ H3 ].\n    revert f; induction a as [ | a IHa ]; intros f; simpl; auto.\n    rewrite <- H3; f_equal; apply IHa.\n  Qed.\n\n  Fact msum_plus1 n f : \u2211 (S n) f = \u2211 n f \u2295 f n.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ _ H2 _ ].\n    replace (S n) with (n+1) by lia.\n    rewrite msum_plus; simpl; f_equal.\n    rewrite H2; f_equal; lia.\n  Qed.\n\n  Fact msum_ext n f g : (forall i, i < n -> f i = g i) -> \u2211 n f = \u2211 n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g Hfg; simpl; f_equal; auto.\n    + apply Hfg; lia.\n    + apply IHn; intros; apply Hfg; lia.\n  Qed.\n\n  Fact msum_unit n : \u2211 n (fun _ => u) = u.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 _ _ ].\n    induction n as [ | n IHn ]; simpl; auto.\n    rewrite IHn; auto.\n  Qed.\n\n  Fact msum_comm a n f : (forall i, i < n -> f i \u2295 a = a \u2295 f i) -> \u2211 n f \u2295 a = a \u2295 \u2211 n f.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f; induction n as [ | n IHn ]; intros f H; simpl; auto.\n    + rewrite H1, H2; auto.\n    + rewrite H3, <- H; try lia.\n      repeat rewrite <- H3; f_equal.\n      apply IHn.\n      intros; apply H; lia.\n  Qed.\n\n  Fact msum_sum n f g : (forall i j, i < j < n -> f j \u2295 g i = g i \u2295 f j) -> \u2211 n (fun i => f i \u2295 g i) = \u2211 n f \u2295 \u2211 n g.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f g; induction n as [ | n IHn ]; intros f g H; simpl; auto.\n    rewrite IHn.\n    + repeat rewrite <- H3; f_equal.\n      repeat rewrite H3; f_equal.\n      symmetry; apply msum_comm.\n      intros; apply H; lia.\n    + intros; apply H; lia.\n  Qed.\n\n  Fact msum_of_unit n f : (forall i, i < n -> f i = u) -> \u2211 n f = u.\n  Proof using Hmonoid.\n    intros H.\n    rewrite <- (msum_unit n).\n    apply msum_ext; auto.\n  Qed.\n\n  Fact msum_only_one n f i : i < n\n                          -> (forall j, j < n -> i <> j -> f j = u)\n                          -> \u2211 n f = f i.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ M1 M2 M3 ].\n    intros H1 H2.\n    replace n with (i + 1 + (n-i-1)) by lia.\n    do 2 rewrite msum_plus.\n    rewrite msum_of_unit, msum_1, msum_of_unit, M1, M2.\n    + f_equal; lia.\n    + intros j Hj; destruct (H2 (i+1+j)); auto; lia.\n    + intros j Hj; destruct (H2 j); auto; lia.\n  Qed.\n\n  Fact msum_msum n k f :\n          (forall i1 j1 i2 j2, i1 < n -> j1 < k -> i2 < n -> j2 < k -> f i1 j1 \u2295 f i2 j2 = f i2 j2 \u2295 f i1 j1)\n       -> \u2211 n (fun i => \u2211 k (f i)) = \u2211 k (fun j => \u2211 n (fun i => f i j)).\n  Proof using Hmonoid.\n    revert k f; induction n as [ | n IHn ]; intros k f Hf.\n    + rewrite msum_0, msum_of_unit; auto.\n    + rewrite msum_S, IHn.\n      * rewrite <- msum_sum.\n        - apply msum_ext.\n          intros; rewrite msum_S; trivial.\n        - intros; symmetry; apply msum_comm.\n          intros; apply Hf; lia.\n      * intros; apply Hf; lia.\n  Qed.\n\n  Fact msum_ends n f : (forall i, 0 < i <= n -> f i = u) -> \u2211 (n+2) f = f 0 \u2295 f (S n).\n  Proof using Hmonoid.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    intros H.\n    replace (n+2) with (1 + n + 1) by lia.\n    do 2 rewrite msum_plus; simpl.\n    rewrite msum_of_unit.\n    + rewrite H2, H2, H2; do 2 f_equal; lia.\n    + intros; apply H; lia.\n  Qed.\n\n  Fact msum_first_two n f : 2 <= n -> (forall i, 2 <= i -> f i = u) -> \u2211 n f = f 0 \u2295 f 1.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ _ M2 _ ].\n    intros Hn H1.\n    destruct n as [ | [ | n ] ]; try lia.\n    do 2 rewrite msum_S.\n    rewrite msum_of_unit.\n    + rewrite M2; trivial.\n    + intros; apply H1; lia.\n  Qed.\n\n  Definition mscal n x := msum n (fun _ => x).\n\n  Fact mscal_0 x : mscal 0 x = u.\n  Proof. apply msum_0. Qed.\n\n  Fact mscal_S n x : mscal (S n) x = x \u2295 mscal n x.\n  Proof. apply msum_S. Qed.\n\n  Fact mscal_1 x : mscal 1 x = x.\n  Proof using Hmonoid.\n    destruct Hmonoid as [ _ H2 _ ].\n    rewrite mscal_S, mscal_0, H2; trivial.\n  Qed.\n\n  Fact mscal_of_unit n : mscal n u = u.\n  Proof using Hmonoid. apply msum_of_unit; auto. Qed.\n\n  Fact mscal_plus a b x : mscal (a+b) x = mscal a x \u2295 mscal b x.\n  Proof using Hmonoid. apply msum_plus. Qed.\n\n  Fact mscal_plus1 n x : mscal (S n) x = mscal n x \u2295 x.\n  Proof using Hmonoid. apply msum_plus1. Qed.\n\n  Fact mscal_comm n x y : x \u2295 y = y \u2295 x -> mscal n x \u2295 y = y \u2295 mscal n x.\n  Proof using Hmonoid. intros H; apply msum_comm; auto. Qed.\n\n  Fact mscal_sum n x y : x \u2295 y = y \u2295 x -> mscal n (x \u2295 y) = mscal n x \u2295 mscal n y.\n  Proof using Hmonoid. intro; apply msum_sum; auto. Qed.\n\n  Fact mscal_mult a b x : mscal (a*b) x = mscal a (mscal b x).\n  Proof using Hmonoid.\n    induction a as [ | a IHa ]; simpl.\n    + do 2 rewrite mscal_0; auto.\n    + rewrite mscal_plus, IHa, mscal_S; auto.\n  Qed.\n\n  Fact msum_mscal n k f : (forall i j, i < n -> j < n -> f i \u2295 f j = f j \u2295 f i) \n                       -> \u2211 n (fun i => mscal k (f i)) = mscal k (\u2211 n f).\n  Proof using Hmonoid. intros H; apply msum_msum; auto. Qed.\n\nEnd msum.\n\nSection msum_morphism.\n\n  Variable (X Y : Type) (m1 : X -> X -> X) (u1 : X) \n                        (m2 : Y -> Y -> Y) (u2 : Y)\n           (H1 : monoid_theory m1 u1)\n           (H2 : monoid_theory m2 u2)\n           (phi : X -> Y)\n           (Hphi1 : phi u1 = u2)\n           (Hphi2 : forall x y, phi (m1 x y) = m2 (phi x) (phi y)).\n\n  Fact msum_morph n f : phi (msum m1 u1 n f) = msum m2 u2 n (fun x => phi (f x)).\n  Proof using Hphi1 Hphi2.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; auto.\n    rewrite Hphi2, IHn; trivial.\n  Qed.\n\n  Fact mscal_morph n x : phi (mscal m1 u1 n x) = mscal m2 u2 n (phi x).\n  Proof using Hphi1 Hphi2. apply msum_morph. Qed.\n\nEnd msum_morphism.\n\nSection binomial_Newton.\n\n  Variable (X : Type) (sum times : X -> X -> X) (zero one : X).\n\n  Infix \"\u2295\" := sum (at level 50, left associativity).\n  Infix \"\u2297\" := times (at level 40, left associativity).\n  \n  Notation z := zero.\n  Notation o := one.\n\n  Notation scal := (mscal sum zero).\n  Notation expo := (mscal times one).\n\n  Hypothesis (M_sum : monoid_theory sum zero) \n             (sum_comm : forall x y, x \u2295 y = y \u2295 x)\n             (sum_cancel : forall x u v, x \u2295 u = x \u2295 v -> u = v)\n             (M_times : monoid_theory times one)\n             (distr_l : forall x y z, x \u2297 (y\u2295z) = x\u2297y \u2295 x\u2297z)\n             (distr_r : forall x y z, (y\u2295z) \u2297 x = y\u2297x \u2295 z\u2297x).\n\n  Fact times_zero_l x : z \u2297 x = z.\n  Proof using M_sum M_times sum_cancel distr_r.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (z\u2297x).\n    rewrite S2, <- distr_r, S1; trivial.\n  Qed.\n\n  Fact times_zero_r x : x \u2297 z = z.\n  Proof using M_sum M_times sum_cancel distr_l.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (x\u2297z).\n    rewrite S2, <- distr_l, S1; trivial.\n  Qed.\n\n  Notation \"\u2211\" := (msum sum zero).\n\n  Fact sum_0n_scal n k f : \u2211 n (fun i => scal k (f i)) = scal k (\u2211 n f).\n  Proof using M_sum sum_comm. apply msum_mscal; auto. Qed.\n\n  Fact scal_times k x y : scal k (x\u2297y) = x\u2297scal k y.\n  Proof using M_sum M_times sum_cancel distr_l.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, mscal_0, times_zero_r; auto.\n    + rewrite mscal_S, mscal_S, IHk, distr_l; auto.\n  Qed.\n\n  Fact scal_one_comm k x : scal k o \u2297 x = x \u2297 scal k o.\n  Proof using M_sum M_times sum_cancel distr_r distr_l.\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, times_zero_l, times_zero_r; auto.\n    + rewrite mscal_S, distr_l, distr_r; f_equal; auto.\n      rewrite T1, T2; auto.\n  Qed.\n\n  Corollary scal_one k x : scal k x = scal k o \u2297 x.\n  Proof using M_sum M_times sum_cancel distr_r distr_l.\n    destruct M_times as [ T1 T2 T3 ].\n    rewrite <- (T2 x) at 1.\n    rewrite scal_times.\n    symmetry; apply scal_one_comm.\n  Qed.\n\n  Fact sum_0n_distr_l b n f : \u2211 n (fun i => b\u2297f i) = b\u2297\u2211 n f.\n  Proof using M_sum M_times sum_cancel distr_l.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_r; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_l; auto.\n  Qed.\n\n  Fact sum_0n_distr_r b n f : \u2211 n (fun i => f i\u2297b) = \u2211 n f \u2297 b.\n  Proof using M_sum M_times sum_cancel distr_r.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_l; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_r; auto.\n  Qed.\n\n  (*   Newton Binomial theorem for (X,\u2295,z,\u2297,o) where\n          1) (X,\u2295,z) is a cancellative commutative monoid\n          2) (X,\u2297,o) is a monoid\n          3) \u2297 distributes over \u2295 on the left and one the right \n\n        cancellative could be weakened into z is left and right\n        absorbing for \u2297, ie a\u2297z = z\u2297a = z \n\n   *)\n\n  Theorem binomial_Newton n a b :\n        a \u2297 b = b \u2297 a\n     -> expo n (a \u2295 b) = \u2211 (S n) (fun i => scal (binomial n i) (expo (n - i) a \u2297 expo i b)).\n  Proof using All.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    intros Hab; induction n as [ | n IHn ].\n    + rewrite mscal_0, msum_S, msum_0; simpl.\n      rewrite mscal_0, mscal_0, mscal_1; auto.\n      rewrite S2, T1; auto.\n    + rewrite msum_S with (n := S n), binomial_n0, mscal_1; auto.\n      rewrite mscal_0, Nat.sub_0_r; auto.\n      rewrite T2.\n      rewrite msum_ext with (g := fun i => b \u2297 scal (binomial n i) (expo (n-i) a \u2297 expo i b)\n                                         \u2295 a \u2297 scal (binomial n (S i)) (expo (n-S i) a \u2297 expo (S i) b)).\n      2: { intros; rewrite binomial_SS, mscal_plus; auto.\n           replace (S n - S i) with (n-i) by lia; f_equal.\n           * rewrite mscal_S. \n             do 3 rewrite scal_times.\n             do 2 rewrite T3; f_equal.\n             apply mscal_comm; auto.\n           * destruct (le_lt_dec n i).\n             + rewrite binomial_gt; try lia.\n               do 2 rewrite mscal_0.\n               rewrite times_zero_r; auto.\n             + replace (n - i) with (S (n - S i)) by lia.\n               rewrite mscal_S.\n               repeat rewrite scal_times.\n               repeat rewrite T3; auto. }\n      rewrite msum_sum; auto.\n      do 2 rewrite sum_0n_distr_l.\n      rewrite <- IHn.\n      rewrite msum_plus1, binomial_gt; auto.\n      rewrite mscal_0, S2.\n      generalize (msum_S sum z n (fun i => scal (binomial n i) (expo (n-i) a \u2297 expo i b))); intros H.\n      rewrite Nat.sub_0_r, binomial_n0, mscal_1, mscal_0, T2 in H; auto.\n      rewrite S3, (sum_comm (expo _ _)), <- S3.\n      rewrite mscal_S with (x :=a), <- distr_l, <- H, <- IHn.\n      rewrite mscal_S, distr_r.\n      apply sum_comm.\n  Qed.\n\nEnd binomial_Newton.\n\nSection Newton_nat.\n\n  Notation power := (mscal mult 1).\n  Notation \"\u2211\" := (msum plus 0).\n\n  Fact sum_fold_map n f : \u2211 n f = fold_right plus 0 (map f (list_an 0 n)).\n  Proof. apply msum_fold_map. Qed.\n\n  Fact power_0 x : power 0 x = 1.\n  Proof. apply mscal_0. Qed.\n\n  Fact power_S n x : power (S n) x = x * power n x.\n  Proof. apply mscal_S. Qed.\n\n  Fact power_1 x : power 1 x = x.\n  Proof. apply mscal_1, Nat_mult_monoid. Qed.\n\n  Fact power_of_0 n : 0 < n -> power n 0 = 0.\n  Proof. destruct n; try lia; rewrite power_S; auto. Qed.\n\n  Fact power_of_1 n : power n 1 = 1.\n  Proof. rewrite mscal_of_unit; auto. Qed.\n\n  Fact power_plus p a b : power (a+b) p = power a p * power b p.\n  Proof. apply mscal_plus, Nat_mult_monoid. Qed.\n\n  Fact power_mult p a b : power (a*b) p = power a (power b p).\n  Proof. apply mscal_mult; auto. Qed.\n  \n  Fact power_ge_1 k p : p <> 0 -> 1 <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + rewrite power_S.\n      apply (Nat.mul_le_mono 1 _ 1); lia.\n  Qed.\n\n  Fact power2_gt_0 n : 0 < power n 2.\n  Proof. apply power_ge_1; discriminate. Qed.\n\n  Fact power_sinc k p : 2 <= p -> power k p < power (S k) p.\n  Proof.\n    intros Hp; rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power k p)) at 1.\n    apply Nat.mul_lt_mono_pos_r; try lia.\n    apply power_ge_1; lia.\n  Qed.\n\n  Fact power_ge_n k p : 2 <= p -> k <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + apply Nat.le_lt_trans with (2 := power_sinc _ Hp); auto.\n  Qed.\n\n  Fact power_mono_l p q x : 1 <= x -> p <= q -> power p x <= power q x.\n  Proof.\n    intros Hx.\n    induction 1 as [ | q H IH ]; auto.\n    apply Nat.le_trans with (1 := IH).\n    rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power _ _)) at 1.\n    apply Nat.mul_le_mono; auto.\n  Qed.\n\n  Definition power_mono := power_mono_l.\n  \n  Fact power_smono_l p q x : 2 <= x -> p < q -> power p x < power q x.\n  Proof.\n    intros H1 H2.\n    apply Nat.lt_le_trans with (1 := power_sinc _ H1).\n    apply power_mono_l; lia.\n  Qed.\n\n  Fact power_mono_r n p q : p <= q -> power n p <= power n q.\n  Proof.\n    intros H.\n    induction n as [ | n IHn ].\n    + do 2 rewrite power_0; auto.\n    + do 2 rewrite power_S; apply Nat.mul_le_mono; auto.\n  Qed. \n\n  Fact power_0_inv p n : power p n = 0 <-> n = 0 /\\ 0 < p.\n  Proof.\n    induction p as [ | p IHp ].\n    + rewrite power_0; lia.\n    + rewrite power_S; split.\n      * intros H.\n        apply Nat.eq_mul_0 in H.\n        rewrite IHp in H; lia.\n      * intros (?&?); subst; simpl; auto.\n  Qed.\n\n  Fact plus_cancel_l : forall a b c, a + b = a + c -> b = c.\n  Proof. intros; lia. Qed.\n\n  Let plus_cancel_l':= plus_cancel_l.\n\n  Fact sum_0n_scal_l n k f : \u2211 n (fun i => k*f i) = k*\u2211 n f.\n  Proof. \n    apply sum_0n_distr_l with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_scal_r n k f : \u2211 n (fun i => (f i)*k) = (\u2211 n f)*k.\n  Proof. \n    apply sum_0n_distr_r with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_mono n f g : (forall i, i < n -> f i <= g i) -> \u2211 n f <= \u2211 n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g H.\n    + do 2 rewrite msum_0; auto.\n    + do 2 rewrite msum_S; apply Nat.add_le_mono.\n      * apply H; lia.\n      * apply IHn; intros; apply H; lia.\n  Qed.\n\n  Fact sum_0n_le_one n f i : i < n -> f i <= \u2211 n f.\n  Proof.\n    revert f i; induction n as [ | n IHn ]; intros f i H.\n    + lia.\n    + rewrite msum_S.\n      destruct i as [ | i ]; try lia.\n      apply Nat.succ_lt_mono, IHn with (f := fun i => f (S i)) in H.\n      lia.\n  Qed.\n\n  Fact sum_power_lt k n f : k <> 0 -> (forall i, i < n -> f i < k) -> \u2211 n (fun i => f i * power i k) < power n k.\n  Proof.\n    intros Hk.\n    revert f; induction n as [ | n IHn ]; intros f Hf.\n    + rewrite msum_0, power_0; lia.\n    + rewrite msum_S, power_S, power_0, Nat.mul_1_r.\n      apply Nat.le_trans with (k+ k * (power n k-1)).\n      * apply (@Nat.add_le_mono (S (f 0))).\n        - apply Hf; lia.\n        - rewrite msum_ext with (g := fun i => k*(f (S i)*power i k)).\n          ++ rewrite sum_0n_distr_l with (one := 1); auto; try (intros; ring).\n             apply Nat.mul_le_mono_l.\n             apply le_S_n, Nat.le_trans with (power n k); try lia.\n             apply IHn; intros; apply Hf; lia.\n          ++ intros; rewrite power_S; ring.\n      * generalize (power_ge_1 n Hk); intros ?.\n        replace (power n k) with (1+(power n k - 1)) at 2 by lia.\n        rewrite Nat.mul_add_distr_l.\n        apply Nat.add_le_mono; lia.\n  Qed. \n\n  Theorem Newton_nat a b n :\n       power n (a + b) = \u2211 (S n) (fun i => binomial n i * power (n - i) a * power i b).\n  Proof.\n    rewrite binomial_Newton with (1 := Nat_plus_monoid) (4 := Nat_mult_monoid); try (intros; ring); auto.\n    apply msum_ext; intros i Hi.\n    rewrite scal_one with (1 := Nat_plus_monoid) (3 := Nat_mult_monoid); auto; try (intros; ring).\n    rewrite <-Nat.mul_assoc; f_equal; auto.\n    generalize (binomial n i); intros k.\n    induction k as [ | k IHk ].\n    + rewrite mscal_0; auto.\n    + rewrite mscal_S, IHk; auto; apply plus_cancel_l.\n  Qed.\n\n  Theorem Newton_nat_S a n :\n       power n (1 + a) = \u2211 (S n) (fun i => binomial n i * power i a).\n  Proof.\n    rewrite Newton_nat.\n    apply msum_ext.\n    intros; rewrite power_of_1; ring.\n  Qed.\n\n  Lemma binomial_le_power n i : binomial n i <= power n 2.\n  Proof.\n    destruct (le_lt_dec i n) as [ Hi | Hi ].\n    + change 2 with (1+1).\n      rewrite Newton_nat_S.\n      eapply Nat.le_trans.\n      2:{ apply sum_0n_le_one with (f := fun i => binomial n i * power i 1).\n          apply le_n_S, Hi. }\n      rewrite power_of_1; lia.\n    + rewrite binomial_gt; auto; lia.\n  Qed.\n\n  Corollary binomial_lt_power n i : binomial n i < power (S n) 2.\n  Proof.\n    apply Nat.le_lt_trans with (1 := binomial_le_power _ _), power_sinc; auto.\n  Qed.\n\nEnd Newton_nat.\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/sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.800531229367589}}
{"text": "Require Import ZArith.\nRequire Import PolTac.\n\nOpen Scope Z_scope.\n\nTheorem pols_test1: forall (x y : Z), x < y ->  (x + x < y + x).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test2: forall (x y : Z), y < 0 ->  (x + y < x).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test3: forall (x y : Z), 0 < y * y ->  ((x + y) * (x - y) < x * x).\nintros.\npols.\nauto with zarith.\nQed.\n \nTheorem pols_test4:\n forall (x y : Z),\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\nTheorem polf_test1: forall x y, (0 <= x -> 1 <= y -> x  <= x  * y)%Z.\nintros.\npolf.\nQed.\n\nTheorem polf_test2: forall x y, (0 < x -> x  <= x  * y -> 1 <= y)%Z.\nintros.\nhyp_polf H0.\nQed.\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 with zarith.\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/Zex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96036116089903, "lm_q2_score": 0.8333246035907932, "lm_q1q2_score": 0.8002925837101781}}
{"text": "Require Export BasicTypes. \n(* Primal field arithmetics. *)\nDefinition P_add (p x y : N) :=\n  (x + y) mod p. \n\nDefinition P_mul (p x y : N) :=\n  (x * y) mod p.\n\nDefinition P_opp (p x : N) :=\n  (p - (x mod p)) mod p. \n\nDefinition P_sub (p x y : N) :=\n  P_add p x (P_opp p y). \n\nDefinition P_sq (p x : N) :=\n  (N.square x) mod p. \n\n\n(*B.1.1*)\nFixpoint power_tail (g : N)(e : bL)(q : N)(sq : N -> N)\n  (mp : N ->  N -> N)(acc : N) : N :=\n  match e with\n  | [] => acc\n  | h :: tl =>\n      power_tail g tl q sq mp\n      match h with\n      | true => (mp (sq acc) g) \n      | false => (sq acc)\n      end\n  end.\n\n(* Returns g ^ a, q is the size of the field *) \nDefinition power_general (g : N)(a : N)(q : N)(sq : N -> N)\n  (mp : N -> N -> N)  : N :=\n  let e := N.modulo a (q - 1) in\n  power_tail g (NtobL e) q sq mp 1. \n\n(*TODO added mod p for convenience of proof. Should remove it. *)\nDefinition P_pow (p : N)(g : N)(a : N) : N :=\n  (power_general g a p (P_sq p) (P_mul p)) mod p. \n\n(* B.1.2 *)\nDefinition P_inv (p g : N) :=\n  P_pow p g (p - 2). \nDefinition P_div (p : N)(x : N)(y : N) : N :=\n  P_mul p x (P_inv p y). \n\n(*4.2.5*)\n(*Inductive field_type : Set :=\n  pri : field_type | ext : field_type .*)\n(* The order of a primal field, a prime number greater than 3 *)\nRecord prime_order : Type := mkpo {order : N; gt3 : order > 3 }. \n\n(* The type of an element in F_p *)\nRecord Fpe (po : prime_order) : Type := \n  mkFpe {val : N; inrng : val < order po}. \n(* The type of an element in F_2m *)\nRecord Fbe (len : N) : Type := mkFbe {num : N; inlen : N.size num <= len}. \n\n(* U is the type of field elements. id0 is the identity of addition.\nid1 is the identity of multiplication. wrp is wrapper from N to U and\nuwp is the unwrapper. The rest are operators on the field.  *)\nClass ECField (U: Type) : Type := mkField {wrp : N -> U; uwp : U -> N;\n  id0 : U; id1 : U; eql : U -> U -> bool; opp : U -> U;\n     inv : U -> U; add : U -> U -> U; sub : U -> U -> U;\n       mul : U -> U -> U; div : U -> U -> U; dbl : U -> U;\n         squ : U -> U; pow : U -> N -> U}. \nDefinition wrapper {U : Type}(fd : ECField U):= @wrp _ fd. \nDefinition unwrapper {U : Type}(fd : ECField U):= @uwp _ fd. \n        \nSection inrng_sec. \nContext (po : prime_order). \nLemma mod_inrng (a : N) :\na mod (order po) < (order po).\nProof.\nintros. \ndestruct po as [p H]. \nassert (H0: p <> 0). {\ninversion H. unfold not. unfold eq. \nintros. rewrite H0 in H1. inversion H1.      \n}\napply mod_lt. apply H0. \nQed.\n\nDefinition pfe_builder (n : N) : Fpe po :=\n  mkFpe po (n mod (order po)) (mod_inrng n). \n\nLemma add_inrng (x y : Fpe po) : \nP_add (order po) (val po x) (val po y) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma opp_inrng (x : Fpe po) : \nP_opp (order po) (val po x) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma sub_inrng (x y : Fpe po) : \nP_sub (order po) (val po x) (val po y) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma dbl_inrng (x : Fpe po) : \n(N.double  (val po x)) mod (order po) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma sq_inrng (x : Fpe po) : \nP_sq (order po) (val po x) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma pow_inrng (g : Fpe po)(a : N): \nP_pow (order po) (val po g) a < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma mul_inrng (x y : Fpe po) : \nP_mul (order po) (val po x) (val po y) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma div_inrng (x y : Fpe po) : \nP_div (order po) (val po x) (val po y) < (order po). \nProof. apply mod_inrng. Qed.\n\nLemma inv_inrng (x : Fpe po) : \nP_inv (order po) (val po x) < (order po). \nProof. apply mod_inrng. Qed.\n\nDefinition po_eq (x y : Fpe po) : bool :=\n(val po x) =? (val po y). \nDefinition po_add (x y : Fpe po) : Fpe po :=\n  mkFpe po (P_add (order po) (val po x) (val po y)) (add_inrng x y). \nDefinition po_sub (x y : Fpe po) : Fpe po :=\n  mkFpe po (P_sub (order po) (val po x) (val po y)) (sub_inrng x y). \nDefinition po_mul (x y : Fpe po) : Fpe po :=\n  mkFpe po (P_mul (order po) (val po x) (val po y)) (mul_inrng x y). \nDefinition po_div (x y : Fpe po) : Fpe po :=\n  mkFpe po (P_div (order po) (val po x) (val po y)) (div_inrng x y). \nDefinition po_opp (x : Fpe po) : Fpe po :=\n  mkFpe po (P_opp (order po) (val po x)) (opp_inrng x). \nDefinition po_inv (x : Fpe po) : Fpe po :=\n  mkFpe po (P_inv (order po) (val po x)) (inv_inrng x). \nDefinition po_dbl (x : Fpe po) : Fpe po :=\n  mkFpe po ( (N.double (val po x)) mod (order po) ) (dbl_inrng x). \nDefinition po_sq (x : Fpe po) : Fpe po :=\n  mkFpe po (P_sq (order po) (val po x)) (sq_inrng x). \nDefinition po_pow (g : Fpe po)(a : N) : Fpe po :=\n  mkFpe po (P_pow (order po) (val po g) a) (pow_inrng g a). \nEnd inrng_sec. \n\n(* TODO Consider make pf_builder a constructor of ECField *)\n(* : ECField (Fpe {| order := p; gt3 := gt3 |})*)\nDefinition pf_builder (p : N)(gt3 : p > 3) :=\nlet po := mkpo p gt3 in\nlet U := Fpe po in\nmkField U (pfe_builder po) (val po)\n(pfe_builder po 0) (pfe_builder po 1) (po_eq po)\n(po_opp po) (po_inv po) (po_add po) (po_sub po) (po_mul po)\n  (po_div po) (po_dbl po) (po_sq po) (po_pow po).\n\nInductive FieldType : Type := primal_field | binary_field.  \n\n(*\nContext {fd : ECField}\nDefinition u := U fd.\nDefinition wp : N -> u := wrp fd.\nDefinition uw : u -> N := uwp fd.\nDefinition i0 := id0 fd.\nDefinition i1 := id1 fd.\nDefinition eq : u -> u -> bool := eql fd.\nDefinition eq0 := eq i0. \nDefinition op := opp fd.\nDefinition iv := inv fd.\nDefinition ad := add fd.\nDefinition sb := sub fd.\nDefinition ml := mul fd.\nDefinition dv := div fd.\nDefinition sq := squ fd.\nDefinition db := dbl fd.\nDefinition pw := pow fd.\n\n\n\nNotation \"- x\" := (op x). \nInfix \"+\" := ad.\nInfix \"-\" := sb.\nInfix \"*\" := ml. \nInfix \"/\" := dv.\nInfix \"^\" := pw. \nInfix \"=?\" := eq.\n*)\nDeclare Scope ecfield_scope. \nOpen Scope ecfield_scope. \nNotation \"- x\" := (opp x) : ecfield_scope.\nInfix \"+\" := add : ecfield_scope. \nInfix \"-\" := sub : ecfield_scope.\nInfix \"*\" := mul : ecfield_scope.\nInfix \"/\" := div : ecfield_scope.\nInfix \"^\" := pow : ecfield_scope.\nInfix \"=?\" := eql : ecfield_scope. \n(* Regular Condition on Primal Fields *)\nDefinition pf_rgl_cdt {U : Type}{_ : ECField U}(a b : U) : Prop :=\n  let (f4, f27) := (wrp 4, wrp 27) in\n    f4 * a^3 + f27 * (squ b) =? id0 = false. \n(*Definition pf_rgl_cdt {U : Type}{_ : ECField U}(a b : U) : Prop :=\n  let (f4, f27) := (wrp 4, wrp 27) in\n  let ad1 := f4 * (a^3) in\n  let ad2 := f27 * (squ b) in\n    ad1 + ad2 =? id0 = false. *)\n\nInductive ECurve {U : Type}{fd : ECField U} : Type :=\n  | pf_curve (a b : U) (rgl : pf_rgl_cdt a b).  \n  (*| bf_curve (a b : U) (rgl : b =? id0 = false) *)  \n\n(*\nInductive EC_Field : Type :=\n  | primal : ECField -> EC_Field\n  | binary : ECField -> EC_Field.\n*)\n(* Same as NtoBL *)\n(*Definition FieldtoBL_p (fd : ECField)(ele : U fd) :=  \n  NtoBL (uwr fd ele). *)\n(*Definition FieldtoBL_p := NtoBL.\n\nDefinition FieldtoBL_b (m : N) :=\n  NtoBL_len (N.to_nat (div_ceil_N m 8)). *)\n\nDefinition FieldtoBL {U : Type}{fd : ECField U}(ele : U) := NtoBL (uwp ele).\nDefinition FieldtobL {U : Type}{fd : ECField U}(ele : U) := NtoBbL (uwp ele).\n\n(*4.2.6*)\nDefinition BLtoField {U : Type}{fd : ECField U}(p : N)(Bl : BL) : option U :=\n  let alpha := BLtoN Bl in\n  if leb p alpha then None else\n    Some (wrapper fd alpha). (*TODO bf case*)\n\n(*Definition BLtoField_p (Bl : BL)(q : N) : option N :=\n  (fun (alpha : N)  => if leb q alpha then None else Some alpha) (BLtoN Bl).  \n\nDefinition BLtoField_b (Bl : BL)(m : N) : option N :=\n  BLtoField_p Bl (N.shiftl 1 m). *)\n\n(*\nDefinition BLtoField_b (Bl : BL) : bL :=\n  BLtobL Bl. \n*)\n\n(*4.2.7*)\n(* Still no need to convert since we are using N *)\n(*\nDefinition FieldtoN_m (alpha : bL) : N :=\n  bLtoN alpha. \n  *)\n\nClose Scope list_scope.\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/DataTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8001943675397049}}
{"text": "Require Import List.\nImport ListNotations.\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(* http://www.cs.nott.ac.uk/~pszgmh/fold.pdf *)\n\n(* Changing Haskell List function into Inductive data type, sort of Relational programming *)\nModule Haskellfun.\n  Section Hfold.\n  \n    Fixpoint fold (A B : Type) (f : A -> B -> B) (b : B) (l : list A) : B :=\n      match l with\n      | [] => b\n      | h :: tl => f h (fold A B f b tl)\n      end.\n\n\n    Inductive foldind (A B : Type) (f : A -> B -> B) (b : B) : list A -> B -> Type :=\n    | Basecase  : foldind A B f b [] b\n    | Conscase b' h tl : foldind A B f b tl b' -> foldind A B f b (h :: tl) (f h b').\n    \n\n    Lemma same_fold_foldind :\n      forall (A B : Type) (f : A -> B -> B) (b : B) (l : list A),\n        foldind A B f b l (fold A B f b l).\n    Proof.\n      refine (fun A B f b =>\n                fix Fn l :=\n                match l with\n                | [] => Basecase A B f b (* Base case *)\n                | h :: tl => _ (* Cons case *)\n                end).\n      cbn. eapply Conscase. apply Fn.\n    Qed.\n    \n    Lemma same_fold_foldind_proof :\n      forall (A B : Type) (f : A -> B -> B) (b : B) (l : list A) (v : B),\n        foldind A B f b l v -> v = fold A B f b l.\n    Proof.\n      refine (fun A B f b =>\n                fix Fn l :=\n                match l with\n                | [] => fun v Hi => _\n                | h :: tl => fun v Hi => _\n                end).\n      inversion Hi; cbn; reflexivity.\n      inversion Hi; subst; cbn; f_equal;\n        apply Fn; assumption.\n    Qed.\n    \n    Lemma fold_fun_correctness :\n      forall (A B : Type) (f : A -> B -> B) (l : list A) (b v : B),\n        v = fold A B f b l -> foldind A B f b l v.\n    Proof.\n      refine (fun A B f =>\n                fix Fn l :=\n                match l with\n                | [] => fun b v Hv => _\n                | h :: t => fun b v Hv => _\n                end).\n      subst; cbn; eapply Basecase.\n      subst; cbn; eapply Conscase; auto.\n    Qed.\n    \n    \n  End Hfold. \n  \n  Section Htakewhile.\n\n    \n    Fixpoint takewhile (A : Type) (p : A -> bool) (l : list A) : list A :=\n      match l with\n      | [] => []\n      | h :: t => if p h then h :: takewhile A p t else []\n      end.\n    \n    \n    (* constant space *)\n    Fixpoint takewhile_acc (A : Type) (p : A -> bool) (l acc : list A) :=\n      match l with\n      | [] => List.rev acc\n      | h :: tl => if p h then takewhile_acc A p tl (h :: acc)\n                  else List.rev acc\n      end.\n    \n    Lemma same_takewhile_acc :\n      forall (A : Type) (p : A -> bool) (l acc : list A),\n        takewhile_acc A p l acc = List.rev acc ++ takewhile A p l.\n    Proof.\n      intros A p.\n      induction l.\n      + cbn. intro acc.  rewrite app_nil_r.\n        auto.\n      + cbn. intro acc. case_eq (p a); intro Pa.\n        ++ rewrite IHl. cbn.\n           rewrite <-  app_assoc.\n           auto.\n        ++ rewrite app_nil_r. auto.\n    Qed.\n\n    (* Turing takewhile_acc into relation. \n       R : l -> acc -> takewhile_acc A p l acc *)\n    Inductive Takewhileind (A : Type) (p : A -> bool) : list A -> list A -> list A -> Prop :=\n    | TBasecase acc : Takewhileind A p [] acc acc \n    | TTruecase h tl acc ts : p h = true -> Takewhileind A p tl (h :: acc) ts -> \n                              Takewhileind A p (h :: tl) acc ts\n    | TFalsecase h tl acc : p h = false -> Takewhileind A p (h :: tl) acc acc.\n\n    Lemma same_takewhile_takewhileind :\n      forall (A : Type) (p : A -> bool) (l acc : list A),\n        Takewhileind A p l acc (List.rev (takewhile_acc A p l acc)).\n    Proof.\n      intros A p.\n      induction l.\n      + cbn; intros acc.\n        rewrite rev_involutive.\n        constructor.\n      + cbn; intros acc.\n        case_eq (p a); intros Pa.\n        constructor 2. auto.\n        apply IHl.\n        rewrite rev_involutive. constructor 3.\n        auto.\n    Qed.\n    \n  End  Htakewhile.\n\n  Section Hdropwhile.\n    \n    Fixpoint dropWhile (A : Type) (p : A -> bool) (l : list A) : list A :=\n      match l with\n      | [] => []\n      | h :: tl => if p h then dropWhile A p tl else h :: tl\n      end.\n    \n    Inductive Dropwhileind (A : Type) (p : A -> bool) : list A -> list A -> Prop :=\n    | DBasecase : Dropwhileind A p [] []\n    | DTruecase h tl t : p h = true ->  Dropwhileind A p tl t ->   Dropwhileind A p (h :: tl) t \n    | DFalsecase h t : p h = false -> Dropwhileind A p (h :: t) (h :: t).\n    \n    Lemma same_drop_caitlin_convinced_and_smiling :\n      forall (A : Type) (p : A -> bool) l, Dropwhileind A p l (dropWhile A p l).\n    Proof.\n      intros A p.\n      induction l.\n      + cbn. constructor 1.\n      + cbn. case_eq (p a); intros Pa.\n        eapply DTruecase. auto. auto.\n        constructor 3.  auto.\n    Qed.\n\n  End Hdropwhile.\n\n  Section Hintersperse.\n     \n    Fixpoint intersperse (A : Type) (c : A) (l : list A) : list A :=\n      match l with\n      | [] => []\n      | [h] => [h]\n      | h :: t => h :: c :: intersperse _ c t\n      end.\n    \n    Fixpoint intersperse_acc (A : Type) (c : A) (l : list A) (acc : list A) : list A :=\n      match l with\n      | [] => acc\n      | [h] => acc ++ [h]\n      | h :: t => intersperse_acc A c t (acc ++ [h; c])\n      end.\n     \n\n     \n     \n     \n    Eval cbn in intersperse_acc nat 0 [1; 2; 3; 4] []. (*  [1; 0; 2; 0; 3; 0; 4]\n     : list nat *)\n    Eval cbn in intersperse nat 0 [1; 2; 3; 4].\n\n    \n    Lemma intersperse_intersperse_acc :\n      forall (A : Type) (c : A) (l acc : list A),\n        acc ++ intersperse A c l = intersperse_acc A c l acc.\n    Proof.\n      induction l.\n      + cbn. intros. rewrite app_nil_r. auto.\n      + destruct l.\n        ++ cbn. intros acc.  auto.  \n        ++ assert (intersperse A c (a :: a0 :: l) = a :: c :: intersperse A c (a0 :: l)).\n           auto. rewrite H.\n           intro acc.\n           assert (intersperse_acc A c (a :: a0 :: l) acc =\n                   intersperse_acc A c (a0 :: l) (acc ++ [a; c])).\n           auto. rewrite H0.\n           rewrite <- IHl. rewrite <- app_assoc.\n           auto.\n    Qed.\n    \n    Inductive Intersperseind (A : Type) (c : A) : list A -> list A -> list A -> Prop :=\n    | IBasecase acc : Intersperseind A c [] acc acc\n    | IOnecase h xs : Intersperseind A c [h] xs (xs ++ [h])\n    | IGencase h t acc zs : Intersperseind A c t (acc ++ [h; c]) zs ->\n                            Intersperseind A c (h :: t) acc  zs. \n\n    Lemma same_intersperse : forall (A : Type) (c : A) (l acc : list A), \n        Intersperseind A c l acc (intersperse_acc A c l acc).\n    Proof.\n      intros A c.\n      induction l.\n      + cbn. intros.\n        constructor. \n      + intros. destruct l.\n        ++ cbn in *. constructor 2.\n        ++ constructor 3. \n           eapply IHl.\n    Qed.\n    \n    Lemma intersperse_acc_same : forall (A : Type) (c : A) (l acc : list A), \n        Intersperseind A c l acc (acc ++ intersperse A c l).\n    Proof.\n      intros. rewrite intersperse_intersperse_acc.\n      apply same_intersperse.\n    Qed.\n        \n      \n  End Hintersperse.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtility", "sha": "3a25343d0a77177adb7530a08b0c7854bb1ed02f", "save_path": "github-repos/coq/mukeshtiwari-CoqUtility", "path": "github-repos/coq/mukeshtiwari-CoqUtility/CoqUtility-3a25343d0a77177adb7530a08b0c7854bb1ed02f/Relational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.9019206758704633, "lm_q1q2_score": 0.8001881668007128}}
{"text": "Lemma Na : forall N :nat, (N * 1) = N.\nintros.\nelim N.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nreflexivity.\nQed.\n\n\nFixpoint f (n : nat) {struct n} : nat := \n match n with \n | 0 => 1\n | S p => 2 * (f p)\nend.\n\nLemma  f10 : (f 10) = 1024.\n\nsimpl.\nreflexivity.\nQed.\n\nRequire Export List.\nLemma trois : forall E: Type ,forall l : list E, forall e:\nE , rev(l ++ e::nil) = e :: rev l.\nintros.\nelim l.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nsimpl.\nreflexivity.\nQed.\n\n\nLemma quatre : forall E : Type , forall l : list E , rev(rev l) = l.\nintros.\nelim l.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite trois.\nrewrite H.\nreflexivity.\nQed.\n\n\n\nInductive is_even : nat -> Prop :=\n| is_even_0 : is_even 0\n| is_even_S : forall n : nat, is_even n -> is_even (S (S n)).\n\nLemma iseven2 : is_even 2.\napply is_even_S.\napply is_even_0.\nQed.\n\n\nLtac isEven :=\nintros;\n(repeat\n apply is_even_S);\n  apply is_even_0.\n\n\nLemma is_even4 : is_even 4.\n\nisEven.\nQed.\n\nLtac NotIsEven :=\nintro;\n(repeat\nmatch goal with  \n|H : is_even ?A |-_ => inversion H\nend).\n\nLemma nonIsEven3 : ~is_even 2037.\n\nNotIsEven.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "hogoww", "repo": "spec_formelles", "sha": "01818eac3794a70a6888c5a791971646dcf777af", "save_path": "github-repos/coq/hogoww-spec_formelles", "path": "github-repos/coq/hogoww-spec_formelles/spec_formelles-01818eac3794a70a6888c5a791971646dcf777af/Baptiste/Inductif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8001881639936811}}
{"text": "Load \"7_list_induction.v\".\n\nTheorem app_nil_r : forall l : natlist, l ++ [] = l.\nProof.\n  intros l.\n  induction l.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall l1 l2 : natlist, rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2.\n  induction l1.\n  - (* base *) simpl. rewrite app_nil_r. reflexivity.\n  - (* i.h. *) simpl. rewrite -> IHl1. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist, rev (rev l) = l.\nProof.\n  intros l.\n  induction l.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist, l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  case l1.\n  - (* empty list case *) rewrite app_assoc. reflexivity.\n  - (* l1 = n : l1'    *) intros n n0. simpl. rewrite app_assoc. rewrite app_assoc. reflexivity.\nQed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | [ ]       => []\n  | cons 0 l' => (nonzeros l')\n  | cons x l' => cons x (nonzeros l')\n  end.\n\nLemma nonzeros_app : forall l1 l2 : natlist, nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite IHl1. case n. (* we run case on n for cons zero on nonzeros *)\n    + (* zero *) reflexivity.\n    + (* S _  *) intros n0. simpl. rewrite <- IHl1. 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/3_Lists/8_list_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.800188163701563}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Axiom replace_with_your_solution_here : forall {A : Type}, A. *)\n\n\n\n(** * Exercise *)\n\nFixpoint fib (n : nat) : nat :=\n  if n is (n''.+1 as n').+1 then\n    fib n'' + fib n'\n  else n.\n\nArguments fib : simpl nomatch.\n\nFixpoint fib_iter (n : nat) (f0 f1 : nat) : nat :=\n  if n is n'.+1 then\n    fib_iter n' f1 (f0 + f1)\n  else f0.\n\nArguments fib_iter : simpl nomatch.\n\nLemma fib_iterS n f0 f1 :\n  fib_iter n.+1 f0 f1 = fib_iter n f1 (f0 + f1).\nProof. by []. Qed.\n\n\n(** Sometimes instead of a custom induction\n    principle we can come up with a different\n    formulation of the specification.*)\nLemma fib_iter_spec n f0 f1 :\n  fib_iter n.+1 f0 f1 = f0 * fib n + f1 * fib n.+1.\nProof.\nelim: n f0 f1 => [| n IHn] f0 f1 ; first by rewrite /(fib 0) /(fib 1) muln0 muln1.\nby rewrite fib_iterS IHn /= mulnDr mulnDl addnCA.\nQed.\n\nLemma fib_iter_correct' n :\n  fib_iter n 0 1 = fib n.\nProof.\nby case: n=> [| n] // ; rewrite (fib_iter_spec n 0 1) mul0n add0n mul1n.\nQed.\n\n\n\n\n\n(** * Exercise *)\n(** Implement a recursive function performing integer division by 2 *)\nFixpoint div2 (n : nat) : nat :=\n    if n is (n''.+1 as n').+1 then\n        1 + div2 n''\n    else 0.\n\nArguments div2 : simpl nomatch.\n\n(** * Exercise *)\nLemma nat_ind2' (P : nat -> Prop) :\n  P 0 ->\n  P 1 ->\n  (forall n, P n -> P n.+2) ->\n  forall n, P n.\nProof.\nmove=> p0 p1 IHyp n.\nsuff: P n /\\ P n.+1 by case.\nby elim: n => [| n] // [] /IHyp.\nQed.\n\n\n(** Exercise: use [nat_ind2'] to prove the following *)\nLemma div2_le n : div2 n <= n.\nProof.\nelim/nat_ind2': n=> // n IHn /=.\nrewrite leqW //.\nQed.\n\n\n\n(** Hints: you might want to use [leqW] view lemma *)\n\nLemma catA T :\n  associative (@cat T).\nProof.\nby move=> x y z ; elim: x=> // a l /= ->.\nQed.\n\n(* Double induction *)\nLemma seq_ind2 {S T} (P : seq S -> seq T -> Type) :\n  P [::] [::] ->\n  (forall x y s t, size s = size t ->\n                   P s t -> P (x :: s) (y :: t)) ->\n  forall s t, size s = size t -> P s t.\nProof.\nmove=> P00 IHyp ; elim; first by move=> t /= st0 ; rewrite [t]size0nil.\nby move=> x s IHs [// | y t /= [] st]; apply: IHyp => //; apply: IHs.\nQed.\n\n(* === Optional exercises === *)\n\n(* due to D.A. Turner, see his \"Total Functional\nProgramming\" (2004) paper *)\n\n(** * Optional Exercise *)\nLemma fib_iter_spec' n p :\n  fib_iter n (fib p) (fib p.+1) = fib (p + n).\nProof.\nAdmitted.\n\n(** * Optional Exercise *)\nLemma fib_iter_correct'' n :\n  fib_iter n 0 1 = fib n.\nProof.\nAdmitted.\n\n\n(** * Optional Exercise *)\nLemma ltn_ind (P : nat -> Prop) :\n  (forall m, (forall k : nat, (k < m) -> P k) -> P m) ->\n  forall n, P n.\nProof.\nAdmitted.", "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/seminar05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.9136765181249676, "lm_q1q2_score": 0.800186009148036}}
{"text": "Require Export Induction.\nModule NatList.\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint snoc (l:natlist) (x:nat) : natlist :=\n  match l with\n  | nil => x :: nil\n  | h :: t => h :: (snoc t x)\n  end.\n                  \n(* Exercise: Define the \"member\" function on natlists *)\nFixpoint member (l:natlist) (x:nat) : bool := admit.\n\n(* Prove the following three theorems. Looking at them: Which do you\nneed to use induction on? Which require destruct (only)? Which require\nonly intros and reflexivity? *)\n\nTheorem member_in_cons : forall (l : natlist) (x : nat),\n  member (x :: l) x = true.\nProof. Admitted.\n\nTheorem member_not_in_nil : forall (x : nat),\n  member (nil) x = false.\nProof. Admitted.\n\nTheorem snoc_plus_one : forall (x : nat) (l : natlist),\n  length (snoc l x) = 1 + (length l).\nProof. Admitted.\n\n(* To do: Quick visit of PartialMap from Lists.v *)\n\n", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/Foundations/Lists_review.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8001860090105732}}
{"text": "\nDefinition peirce := forall P Q:Prop, ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, ~~P -> P.\nDefinition excluded_middle := forall P:Prop, P\\/~P.\nDefinition de_morgan_not_and_not := forall P Q:Prop, ~(~P/\\~Q)->P\\/Q.\nDefinition implies_to_or := forall P Q:Prop, (P->Q)->(~P\\/Q).\n\n\nLemma excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n unfold peirce; intros H P Q H0.\n destruct (H P) as [p | np].\n -  assumption.\n -  apply H0; intro H1; now absurd P.\nQed.\n\nLemma peirce_classic : peirce -> classic.\nProof.\n intros HPeirce P H0; apply (HPeirce P False).\n intro H1; now destruct H0.\nQed.\n\nLemma classic_excluded_middle: classic -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intro H0; absurd P.\n -  intro H1; apply H0 ; now left.\n -  apply H; intro H1; apply H0; now right.\nQed.\n\n\nLemma excluded_middle_implies_to_or :  excluded_middle -> implies_to_or.\nProof.\n intros H P Q H0;\n  destruct (H P) as [p | np].\n  -  right; auto.\n  - now  left.\nQed.\n\nLemma implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P; destruct (H P P);auto.\nQed.\n\nLemma classic_de_morgan_not_and_not : classic -> \n                                      de_morgan_not_and_not.\nProof.\n unfold de_morgan_not_and_not; intros H P Q H0.\n apply H.\n intro H1; apply H0; split;intro;apply H1; auto.\nQed.\n\nLemma de_morgan_not_and_not_excluded_middle : de_morgan_not_and_not ->\n                                              excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intros [H1 H2]; contradiction. \nQed.\n\n", "meta": {"author": "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/class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.8000934191865705}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := zero : Nat | succ : Nat -> Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint plus (plus_arg0 : Nat) (plus_arg1 : Nat) : Nat\n           := match plus_arg0, plus_arg1 with\n              | zero, n => n\n              | succ n, m => succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : Nat) (mult_arg1 : Nat) : Nat\n           := match mult_arg0, mult_arg1 with\n              | zero, n => zero\n              | succ n, m => plus (mult n m) m\n              end.\n\nFixpoint fac (fac_arg0 : Nat) : Nat\n           := match fac_arg0 with\n              | zero => succ zero\n              | succ n => mult (fac n) n\n              end.\n\nFixpoint qfac (qfac_arg0 : Nat) (qfac_arg1 : Nat) : Nat\n           := match qfac_arg0, qfac_arg1 with\n              | zero, n => n\n              | succ n, m => qfac n (mult m n)\n              end.\n\nLemma plus_succ : forall (x y : Nat), plus x (succ y) = succ (plus x y).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : Nat), plus (plus x y) z = plus x (plus y z).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : Nat), plus x zero = x.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : Nat), plus x y = plus y x.\nProof.\n  intros.\n  induction x.\n  - rewrite plus_zero. reflexivity.\n  - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_zero : forall (x : Nat), 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 : Nat), plus (mult x y) x = mult x (succ y).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite plus_succ. rewrite plus_assoc. rewrite (plus_commut y x). rewrite <- plus_assoc. rewrite IHx. rewrite plus_succ. reflexivity.\nQed.\n\nLemma mult_commut : forall (x y : Nat), mult x y = mult y x.\nProof.\n  intros.\n  induction x.\n  - rewrite mult_zero. reflexivity.\n  - simpl. rewrite IHx. rewrite mult_succ. reflexivity.\nQed.\n\nLemma distrib : forall (x y z : Nat), mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut (mult y z) z). rewrite <- plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall (x y z : Nat), 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 : Nat), 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). rewrite mult_assoc. rewrite (mult_commut y x). reflexivity.\nQed.\n\nTheorem fac_eq_qfac : forall (x : Nat), eq (fac x) (qfac x (succ zero)).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite qfac_mult. rewrite IHx. reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal33.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.8000067391819693}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nTheorem contrapositive : forall (P Q : Prop), (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H NQ PP.\n  apply (NQ (H PP)).\nQed.\n\nInductive seq : nat -> Set :=\n  | niln : seq 0\n  | consn : forall n : nat, nat -> seq n -> seq (S n).\n\nFixpoint length (n : nat) (s : seq n) {struct s} : nat :=\n  match s with\n  | niln => 0\n  | consn _ s' => S (length s')\n  end.\n\nTheorem length_corr : forall (n : nat) (s : seq n), length s = n.\nProof.\n  intros n s.\n  induction s.\n  simpl.\n  trivial.\n  simpl.\n  rewrite IHs.\n  trivial.\nQed.\n\nLemma add_succ : forall (n m : nat), n + S m = S (n + m).\nProof.\n  intros n m.\n  induction n.\n\n  simpl.\n  trivial.\n\n  simpl.\n  rewrite IHn.\n  trivial.\nQed.\n\nTheorem add_comm : forall (n m : nat), n + m = m + n.\nProof.\n  intros n m.\n\n  induction m.\n  induction n.\n  trivial.\n\n  simpl.\n  rewrite IHn.\n  simpl.\n  trivial.\n\n  simpl.\n  symmetry in IHm.\n  rewrite IHm.\n  apply add_succ.\nQed.\n\nLemma add_zero : forall (n : nat), n + 0 = n.\nProof.\n  intros.\n  rewrite add_comm.\n  simpl.\n  trivial.\nQed.\n\nTheorem add_assoc : forall (n m k : nat), n + (m + k) = (n + m) + k.\nProof.\n  intros n m k.\n\n  induction n.\n  simpl.\n  trivial.\n\n  rewrite add_comm.\n  rewrite add_succ.\n  rewrite add_comm.\n  rewrite IHn.\n  simpl.\n  trivial.\nQed.\n\nTheorem add_switch : forall (n m k : nat), n + (m + k) = m + (n + k).\nProof.\n  intros.\n  rewrite add_assoc.\n  rewrite [n + m]add_comm.\n  rewrite -add_assoc.\n  trivial.\nQed.\n\nTheorem add_elim : forall (n m k : nat), (n + m = n + k) -> (m = k).\nProof.\n  intros.\n  induction n.\n  apply H.\n\n  assert (P : n + m = n + k).\n  simpl in H.\n  injection H.\n  trivial.\n  apply IHn in P.\n  trivial.\nQed.\n\nTheorem add_elim_simple : forall (n m : nat), n + m = n -> m = 0.\nProof.\n  intros.\n  rewrite -[n]add_zero in H.\n  rewrite -add_assoc in H.\n  simpl in H.\n  apply add_elim in H.\n  apply H.\nQed.\n\nTheorem mult_succ : forall (n m : nat), m + m * n = m * S n.\nProof.\n  intros.\n  induction m.\n  trivial.\n  simpl.\n  rewrite add_assoc.\n  rewrite [m + n]add_comm.\n  rewrite -add_assoc.\n  rewrite IHm.\n  trivial.\nQed.\n\nTheorem mult_comm : forall (n m : nat), n * m = m * n.\nProof.\n  intros.\n  induction n.\n  induction m.\n  trivial.\n  trivial.\n\n  simpl.\n  rewrite IHn.\n  apply mult_succ.\nQed.\n\nTheorem mult_dist : forall (n m k : nat), n * (m + k) = n * m + n * k.\nProof.\n  intros.\n  induction n.\n  trivial.\n\n  simpl.\n  rewrite IHn.\n  rewrite -[m + k + (n * m + n * k)]add_assoc.\n  rewrite [k + (n * m + n * k)]add_assoc.\n  rewrite [k + n * m]add_comm.\n  rewrite -[n * m + k + n * k]add_assoc.\n  rewrite add_assoc.\n  trivial.\nQed.\n\nTheorem mult_assoc : forall (n m k : nat), n * (m * k) = (n * m) * k.\nProof.\n  intros.\n  induction n.\n  trivial.\n  simpl.\n  rewrite IHn.\n  rewrite mult_comm.\n  rewrite [n * m * k]mult_comm.\n  rewrite -mult_dist.\n  rewrite mult_comm.\n  trivial.\nQed.\n\nTheorem add_zpp : forall (n m : nat), n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  split.\n  induction n.\n  trivial.\n  simpl in H.\n  inversion H.\n\n  induction m.\n  trivial.\n  rewrite add_succ in H.\n  inversion H.\nQed.\n\nTheorem mult_zpp : forall (n m : nat), n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  induction n.\n  left.\n  trivial.\n\n  right.\n  simpl in H.\n  apply add_zpp in H.\n  destruct H as [Hl Hr].\n  apply Hl.\nQed.\n\n\nDefinition le (n m : nat) : Prop := exists (k : nat), k + n = m.\n\nTheorem le_trans : forall (n m k : nat), le n m -> le m k -> le n k.\nProof.\n  intros n m k [i Hi] [j Hj].\n  exists (j + i).\n  rewrite -Hi in Hj.\n  rewrite add_assoc in Hj.\n  apply Hj.\nQed.\n\nTheorem le_refl : forall (n : nat), le n n.\nProof.\n  intros.\n  exists 0.\n  trivial.\nQed.\n\nTheorem le_succ : forall (n : nat), le n (S n).\nProof.\n  intro n.\n  exists 1.\n  simpl.\n  trivial.\nQed.\n\nTheorem le_anti_sym : forall (n m : nat), le n m -> le m n -> n = m.\nProof.\n  intros n m [i Hi] [j Hj].\n  rewrite -Hi in Hj.\n  rewrite [i + n]add_comm in Hj.\n  rewrite add_switch in Hj.\n  apply add_elim_simple in Hj.\n  apply add_zpp in Hj.\n  destruct Hj as [_ Pi].\n  rewrite Pi in Hi.\n  simpl in Hi.\n  apply Hi.\nQed.\n\nDefinition divides_with (n m r : nat) : Prop := exists (q : nat), r + q * n = m /\\ 0 <= r < q.\n\nDefinition divides (n m : nat) : Prop := exists (k : nat), k * n = m.\n\nTheorem divides_both : forall (n m k : nat), n * m = k -> divides n k /\\ divides m k.\nProof.\n  split.\n  exists m; rewrite mult_comm; apply H.\n  exists n; apply H.\nQed.\n\nTheorem divides_trans : forall (n m k : nat), divides n m -> divides m k -> divides n k.\nProof.\n  intros n m k [i Hn] [j Hm].\n  rewrite -Hn in Hm.\n  rewrite mult_assoc in Hm.\n  exists (j * i).\n  apply Hm.\nQed.\n\nTheorem divides_refl : forall (n : nat), divides n n.\nProof.\n  intros.\n  exists 1.\n  simpl; rewrite add_comm; simpl.\n  trivial.\nQed.\n\nTheorem divides_one : forall (n : nat), divides 1 n.\nProof.\n  intros.\n  exists n.\n  rewrite mult_comm.\n  simpl.\n  rewrite add_zero. trivial.\nQed.\n\nTheorem divides_le : forall (n m : nat), divides n m -> le n m \\/ m = 0.\nProof.\n  intros n m [k Hk].\n  induction k.\n  simpl in Hk.\n  right; symmetry; apply Hk.\n\n  left.\n  simpl in Hk.\n  exists (k * n).\n  rewrite add_comm in Hk.\n  apply Hk.\nQed.\n\nTheorem divides_anti_sym : forall (n m : nat), divides n m -> divides m n -> n = m.\n  intros n m p q.\n  pose proof (divides_le p) as Hp.\n  pose proof (divides_le q) as Hq.\n  destruct p as [k Hk]; destruct q as [j Hj].\n  destruct Hp as [ple | p0].\n  destruct Hq as [qle | q0].\n  - apply ((le_anti_sym ple) qle).\n  - transitivity 0.\n    apply q0.\n    rewrite q0 in Hk.\n    rewrite mult_comm in Hk; simpl in Hk; apply Hk.\n  - symmetry; transitivity 0.\n    apply p0.\n    rewrite p0 in Hj; rewrite mult_comm in Hj; simpl in Hj; apply Hj.\nQed.\n\nTheorem mult_one : forall (n m : nat), n * m = 1 -> n = 1 /\\ m = 1.\n  intros.\n  pose proof (divides_both H) as [Pn Pm].\n  split.\n  apply ((divides_anti_sym Pn) (divides_one n)).\n  apply ((divides_anti_sym Pm) (divides_one m)).\nQed.\n\n\nDefinition prime (p : nat) : Prop := forall (n : nat), divides n p -> n = 1 \\/ n = p.\n\nDefinition composite (c : nat) : Prop := exists (n m : nat), n * m = c /\\ n <> 1 /\\ n <> c.\n\nTheorem decidable_eq : forall (n m : nat), n = m \\/ n <> m.\nProof.\n  intros n.\n  induction n.\n  intro m.\n  destruct m.\n  left; trivial.\n  right; trivial.\n\n  intro m.\n  destruct m.\n  right.\n  inversion 1.\n\n  destruct (IHn m) as [IHn_eq | IHn_neq].\n  - left. rewrite IHn_eq. trivial.\n  - right. injection. apply IHn_neq.\nDefined.\n\nTheorem prime_not_comp : forall (p : nat), p <> 1 -> prime p <-> ~ composite p.\n  intros p H. split. intro Pp.\n  unfold not; intro Cp.\n  destruct Cp as [n [m [Hnm [Hnn Hnc]]]].\n  cut (divides n p).\n  intro L.\n  apply Pp in L.\n  destruct L as [Lpn | Lnp].\n  - apply (Hnn Lpn).\n  - apply (Hnc Lnp).\n  - exists (m).\n    rewrite mult_comm; apply Hnm.\n  - intro NCp. unfold not in NCp.\n    intros m [k Hk].\n    pose proof (decidable_eq m 1) as [Mone_eq | Mone_neq].\n    -- left. apply Mone_eq.\n    -- right.\n       pose proof (decidable_eq m p) as [Mp_eq | Mp_neq].\n       * apply Mp_eq.\n       * cut (composite p).\n         intro Cp. exfalso. apply (NCp Cp).\n         exists m.\n         exists k.\n         rewrite mult_comm in Hk.\n         split.\n         apply Hk.\n         split.\n         apply Mone_neq.\n         apply Mp_neq.\nQed.\n\nDefinition less (n m : nat) : Prop := le n m /\\ n <> m.\n\nTheorem less_succ : forall (n : nat), less n (S n).\nProof.\n  intro n. split.\n  apply le_succ.\n  induction n.\n  trivial.\n\n  injection. apply IHn.\nQed.\n\nTheorem less_zero : forall (n : nat), ~ less n 0.\nProof.\n  intro n. unfold not. intro P.\n  destruct P as [Ple Pneq].\n  induction n.\n  auto.\n\n  destruct Ple as [k Pk].\n  pose proof (add_zpp Pk) as [Hk HSn].\n  inversion HSn.\nQed.\n\nTheorem le_ind : forall (n m : nat), le n (S m) -> le n m \\/ n = S m.\nProof.\n  intros n m [k Hk].\n  destruct k.\n  right.\n  simpl in Hk. apply Hk.\n\n  left; exists k.\n  simpl in Hk.\n  injection Hk.\n  trivial.\nQed.\n\nTheorem le_less : forall (n m : nat), le n m <-> less n (S m).\nProof.\n  intros n m.\n  split.\n  - intro H.\n    split.\n    -- apply ((le_trans H) (le_succ m)).\n    -- destruct H as [k Hk].\n       destruct k.\n       --- simpl in Hk.\n           rewrite Hk.\n           trivial.\n       --- rewrite add_comm in Hk; simpl in Hk.\n           rewrite -Hk.\n           rewrite -add_succ.\n           rewrite -[n]add_zero.\n           rewrite -add_assoc.\n           simpl.\n           cut (0 <> S (S k)). intro P.\n           pose proof ((decidable_eq (n + 0)) (n + S (S k))) as [Qeq | Qneq].\n           * pose proof (add_elim Qeq) as NQ.\n             exfalso. apply (P NQ).\n           * apply Qneq.\n           * trivial.\n  - intro H.\n    destruct H as [Hle Hneq].\n    pose proof (le_ind Hle) as [Hlem | Heq].\n    -- apply Hlem.\n    -- exfalso. apply (Hneq Heq).\nQed.\n\nTheorem less_trans : forall (n m k : nat), less n m -> less m k -> less n k.\nProof.\n  intros n m k P Q.\n  destruct m.\n  - exfalso. apply (less_zero P).\n  - destruct k.\n    exfalso; apply (less_zero Q).\n    apply le_less in P.\n    apply le_less in Q.\n    pose proof (le_succ m) as H.\n    pose proof ((le_trans P) H) as A.\n    pose proof ((le_trans A) Q) as J.\n    apply le_less in J.\n    apply J.\nQed.\n\nTheorem succ_neq : forall (n m k : nat), n <> 0 -> n + m = k -> m <> k.\nProof.\n  intros n m k H P.\n  pose proof (decidable_eq m k) as [Qeq | Qneq].\n  - rewrite -[k]add_zero in P.\n    rewrite add_comm in P.\n    rewrite Qeq in P.\n    apply add_elim in P.\n    exfalso.\n    apply (H P).\n  - apply Qneq.\nQed.\n\nTheorem less_ind : forall (n m : nat), less n (S m) -> less n m \\/ n = m.\nProof.\n  intros n m [Hle Hneq].\n  apply le_ind in Hle.\n  destruct Hle as [[k Hk] | Hle_eq].\n  - destruct k.\n    -- simpl in Hk. right. apply Hk.\n    -- cut (S k <> 0). intro A.\n       pose proof ((succ_neq A) Hk) as Q.\n       left.\n       split.\n       * exists (S k). apply Hk.\n       * apply Q.\n       * auto.\n  - exfalso. apply (Hneq Hle_eq).\nQed.\n\nTheorem le_def : forall (n m : nat), le n m <-> less n m \\/ n = m.\nProof.\n  intros n m.\n  split.\n  intro P.\n  apply le_less in P.\n  apply less_ind.\n  apply P.\n  intro Q.\n  destruct Q as [Qless | Qeq].\n  - pose proof (less_succ m) as H.\n    pose proof ((less_trans Qless) H) as K.\n    apply le_less in K.\n    apply K.\n  - rewrite Qeq.\n    apply (le_refl m).\nQed.\n\n\nTheorem strong_ind : forall (P : nat -> Prop), (forall (n : nat), (forall (k : nat), less k n -> P k) -> P n) -> (forall (n : nat), P n).\nProof.\n  intros P H n.\n  cut (forall (m j : nat), le j m -> P j).\n  * intro A.\n    pose proof (le_refl n) as RefN.\n    pose proof ((A n) n) as AN.\n    apply (AN RefN).\n  * intro m.\n    induction m.\n\n    ** intro j; intro Q.\n       apply le_def in Q.\n       destruct Q as [Qless | Qeq].\n       - exfalso. apply (less_zero Qless).\n       - cut (forall (k : nat), less k 0 -> P k).\n         -- intro A.\n            rewrite Qeq.\n            apply ((H 0) A).\n         -- intros k K. exfalso. apply (less_zero K).\n    ** intros j LEJ.\n       apply le_def in LEJ.\n       destruct LEJ as [LEJ_less | LEJ_eq].\n       - apply le_less in LEJ_less.\n         apply ((IHm j) LEJ_less).\n       - rewrite LEJ_eq.\n         cut (forall (k : nat), less k (S m) -> P k).\n         -- intro L.\n            apply ((H (S m)) L).\n         -- intros k K.\n            apply le_less in K.\n            apply le_def in K.\n            destruct K as [K_less | K_eq].\n            --- pose proof (less_succ m) as A.\n                pose proof ((less_trans K_less) A) as K_le.\n                apply le_less in K_le.\n                apply ((IHm k) K_le).\n            --- pose proof (le_refl m) as A.\n                rewrite K_eq.\n                apply ((IHm m) A).\nQed.\n\n", "meta": {"author": "FayeAlephNil", "repo": "playing-with-coq", "sha": "f5a58b271885121a9444f607d33d59c74136be80", "save_path": "github-repos/coq/FayeAlephNil-playing-with-coq", "path": "github-repos/coq/FayeAlephNil-playing-with-coq/playing-with-coq-f5a58b271885121a9444f607d33d59c74136be80/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.8000067219810509}}
{"text": "Require Import Bool Arith List.\n\nVariables P Q R : Prop.\n\n(* 5. Write the script that proves the following formula\n   (P -> (P /\\ Q) -> R) -> P /\\ (Q /\\ P) -> R. *)\n\nLemma ex5 :\n   (P -> (P /\\ Q) -> R) -> P /\\ (Q /\\ P) -> R.\nProof.\nintros r_if_pq_if_p.\nintros pqp.\n  destruct pqp as [p qp].\n  apply r_if_pq_if_p.\n  exact p.\n  split.\n  exact p.\napply qp.\n\nQed.\n  \n(* 7. Write the script that proves the following formula\n     (P /\\ Q) \\/ R -> P \\/ R *)\n\nLemma ex6 :\n  (P /\\ Q) \\/ R -> P \\/ R.\nProof.\nintros p_a_q_o_r.\ndestruct p_a_q_o_r as [ pq | r].\n\ndestruct pq as [ p q].\n\nleft.\nexact p.\nright.\nexact r.\n\nQed.\n\n(* 7. Write the script that proves the following formula\n   ((P -> Q \\/ P) -> R) -> R \\/ Q  *)\n\nLemma ex7 :\n  ((P -> Q \\/ P) -> R) -> R \\/ Q.\nProof.\n\nintros qp_if_p.\nleft.\napply qp_if_p.\nintros qop_if_p.\nright.\nexact qop_if_p.\nQed.\n\n(*\n8. P \\/ R -> (P -> Q) -> ~ Q -> R\n*)\nLemma ex8 :\n  P \\/ R -> (P -> Q) -> ~ Q -> R.\nProof.\n  intros pr.\n  intros q_if_p.\n  intros nq.\n  destruct pr as [p | r].\n  case nq.\n  apply q_if_p.\n  exact p.\n  exact r.\nQed.\n\n(*\n9. P \\/ ~Q -> ~P -> (Q -> R) \\/ P\n*)\n\nLemma ex9 :\n  P \\/ ~Q -> ~P -> (Q -> R) \\/ P.\nProof.\nintros p_o_nq.\nintros np.\ndestruct p_o_nq as [p | nq].\nright.\nexact p.\nleft.\nintros q.\ncase nq.\nexact q.\nQed.", "meta": {"author": "vabh", "repo": "Coq", "sha": "75b90a61d518aead333de748a08b5ed04585ef9c", "save_path": "github-repos/coq/vabh-Coq", "path": "github-repos/coq/vabh-Coq/Coq-75b90a61d518aead333de748a08b5ed04585ef9c/ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.8000048322171616}}
