(* Práctica 6 *)
(* Gabina Luz Bianchi *)

(* Ejercicio 3 *)

Definition Value := bool.

Inductive BoolExpr : Set :=
| bbool : bool -> BoolExpr
| band : BoolExpr -> BoolExpr -> BoolExpr
| bnot : BoolExpr -> BoolExpr.

Inductive BEval : BoolExpr -> Value -> Prop :=
| ebool : forall b : bool, BEval (bbool b) (b:Value)
| eandl : forall e1 e2 : BoolExpr, BEval e1 false -> BEval (band e1 e2) false
| eandr : forall e1 e2 : BoolExpr, BEval e2 false -> BEval (band e1 e2) false
| eandrl : forall e1 e2 : BoolExpr, BEval e1 true -> BEval e2 true -> BEval (band e1 e2) true
| enott : forall e : BoolExpr, BEval e true -> BEval (bnot e) false
| enotf : forall e : BoolExpr, BEval e false -> BEval (bnot e) true.

Fixpoint beval1 (e : BoolExpr) : Value :=
match e with
| bbool b => b
| band e1 e2 =>
               match beval1 e1, beval1 e2 with
               | true, true => true
               | _, _ => false
               end
| bnot e1 => if beval1 e1 then false else true
end.

Fixpoint beval2 (e : BoolExpr) : Value :=
match e with
| bbool b => b
| band e1 e2 =>
               match beval2 e1 with
               | false => false
               | _ => beval2 e2
               end
| bnot e1 => if beval2 e1 then false else true
end.

Lemma beval1cor: forall e:BoolExpr, {b:Value |(BEval e b)}.
Proof.
intros.
exists (beval1 e).
induction e.
   * unfold beval1.
     constructor.
   * simpl.
     case_eq (beval1 e1);intros.
        + case_eq (beval1 e2);intros.
           - constructor.
              rewrite H in IHe1.
              assumption.
              rewrite H0 in IHe2.
              assumption.
           - apply eandr.
             rewrite H0 in IHe2.
             assumption.
        + constructor.
          rewrite H in IHe1.
          auto.
    * simpl.
     case_eq (beval1 e); intros.
        + rewrite H in IHe.
          constructor.
          auto.
       + rewrite H in IHe.
         constructor.
         auto.
Qed.

Lemma beval2cor: forall e:BoolExpr, {b:Value |(BEval e b)}.
Proof.
intros.
exists (beval2 e).
induction e.
   * unfold beval2.
     constructor.
   * simpl.
     case_eq (beval2 e1);intros.
        + case_eq (beval2 e2);intros.
           - constructor.
              rewrite H in IHe1.
              assumption.
              rewrite H0 in IHe2.
              assumption.
           - apply eandr.
             rewrite H0 in IHe2.
             assumption.
        + constructor.
          rewrite H in IHe1.
          auto.
    * simpl.
     case_eq (beval2 e); intros.
        + rewrite H in IHe.
          constructor.
          auto.
       + rewrite H in IHe.
         constructor.
         auto.
Qed.

Hint Constructors BEval.
Hint Constructors BoolExpr.

Lemma beval1cor2: forall e:BoolExpr, {b:Value |(BEval e b)}.
Proof.
  intro; exists (beval1 e).
  induction e.
    auto.

    simpl; destruct (beval1 e1); destruct (beval1 e2); auto.

    simpl; destruct (beval1 e); auto.
Qed.

Lemma beval2cor2: forall e:BoolExpr, {b:Value |(BEval e b)}.
Proof.
  intro; exists (beval2 e).
  induction e.
    auto.

    simpl; destruct (beval2 e1); destruct (beval2 e2); auto.

    simpl; destruct (beval2 e); auto.
Qed.

Extraction Language Haskell.
Extraction "beval1" beval1cor2.
Extraction "beval2" beval2cor2.

Extract Inductive bool => "Bool" [ "true" "false" ].
Extraction "beval12" beval1cor.
Extraction "beval22" beval2cor.

(* Ejercicio 5 *)

Inductive Le: nat -> nat -> Prop :=
| le0 : forall n:nat, Le 0 n
| leS : forall n m : nat, Le n m -> Le (S n) (S m).

Inductive Gt: nat -> nat -> Prop :=
| gt0 : forall n:nat, (n <> 0) -> Gt n 0
| gtS : forall n m : nat, Gt n m -> Gt (S n) (S m).

Function leBool (n m : nat) : bool :=
match n with
| 0 => true
| S k => match m with
         | 0 => false
         | S p => leBool k p
         end
end.

Hint Constructors Le.
Hint Constructors Gt.
Require Import Omega.

Lemma Le_Gt_dec: forall n m:nat, {(Le n m)}+{(Gt n m)}.
Proof.
intros.
functional induction (leBool n m).
   +left.
    auto.
  +right.
   constructor.
   discriminate.
  + elim IHb; intros.
     - left.
       auto.
     - right.
       auto.
Qed.

Lemma le_gt_dec: forall n m:nat, {(le n m)}+{(gt n m)}.
Proof.
intros.
functional induction (leBool n m).
   + left.
     omega.
   + right.
     omega.
   + elim IHb; intros.
        - left.
          omega.
        - right.
          omega.
Qed.

(* Ejercicio 6 *)

Definition spec_res_nat_div_mod (a b:nat) (qr:nat*nat) :=
 match qr with
 (q,r) => (a = b*q + r) /\ r < b
 end.

Require Import Omega.
Require Import DecBool.
Require Import Compare_dec.
Require Import Plus.
Require Import Mult.
Require Import Coq.Arith.Compare_dec.

Definition nat_div_mod :
 forall a b:nat, not(b=0) -> {qr:nat*nat | spec_res_nat_div_mod a b qr}.
Proof.
intros.
destruct b; intros.
   - omega.
   - induction a.
        + exists (0, 0).
          unfold spec_res_nat_div_mod.
          omega.
        + elim IHa.
          intros.
          destruct x.
          case_eq (le_lt_dec b n0); intros.
             * exists (S n,0).
               unfold spec_res_nat_div_mod.
               split; intros.
               rewrite -> plus_0_r.
               unfold spec_res_nat_div_mod in p.
               elim p; intros.
               rewrite -> H1.
               simpl.
               assert (n0 = b).
                  omega.
               rewrite -> H3.
               assert (b * n + b = b * S n).
                  assert ( S n = n + 1).
                  omega.
               rewrite -> H4.
               rewrite -> mult_plus_distr_l.
               omega.
               symmetry in H4.
               rewrite -> H4.
               omega.
               omega.
             * exists (n, S n0).
               unfold spec_res_nat_div_mod.
               split; intros.
               unfold spec_res_nat_div_mod in p.
               elim p; intros.
               rewrite -> H1.
               omega.
               omega.
Qed.

Extraction "divmod" nat_div_mod.

(* Ejercicio 7 *)

Inductive tree (A:Set) : Set :=
| leaf : tree A
| node : A -> tree A -> tree A -> tree A.

Inductive tree_sub (A:Set) (t:tree A) : tree A -> Prop :=
| tree_sub1 : forall (t':tree A) (x:A), tree_sub A t (node A x t t')
| tree_sub2 : forall (t':tree A) (x:A), tree_sub A t (node A x t' t).

Theorem well_founded_tree_sub : forall A:Set, well_founded (tree_sub A).
Proof.
intros.
unfold well_founded.
intros.
induction a.
   + apply (Acc_intro).
     intros.
     inversion H.
   + apply (Acc_intro).
     intros.
     inversion H; assumption.
Qed.

(* Ejercicio 8 *)

Fixpoint size (be : BoolExpr) :=
match be with
 | bbool b => 0
 | band b1 b2 => 2 + size b1 + size b2
 | bnot b =>  1 + size b
end.

Definition elt (e1 e2 : BoolExpr) := size e1 < size e2.

Theorem well_founded_elt : well_founded (elt).
Proof.
apply well_founded_ltof.
Qed.


From MyCoq.Lib Require Export Nat.
From MyCoq.Lib Require Export Poly.

Check 3 = 3.
Check forall n m : nat, n + m = m + n.

Definition plus_claim : Prop := N 2 + N 2 = N 4.

Theorem plus_claim_is_true: plus_claim.
Proof.
  unfold plus_claim.
  reflexivity.
Qed.

Definition is_three (n : nat) : Prop :=
  n = N 3.
Check is_three.

Definition injective {A B} (f : A -> B) :=
  forall x y : A, f x = f y -> x = y.

Lemma succ_inj: injective S.
Proof.
  unfold injective.
  intros x y H.
  injection H as H'.
  apply H'.
Qed.

Locate eq.
Check @eq.

(* 逻辑联结词 *)
Example and_example: (N 3 + N 4 = N 7) /\ (N 2 * N 2 = N 4).
Proof.
  split.
  - reflexivity.
  - reflexivity.
Qed.

Lemma and_intro: forall A B : Prop, A -> B -> A /\ B.
Proof.
  intros A B H1 H2.
  split.
  - apply H1.
  - apply H2.
Qed.

Example and_exercise:
  forall n m : nat, n + m = O -> n = O /\ m = O.
Proof.
  intros n m H.
  assert (H1: n = O).
  {
    destruct n as [| n'].
    - reflexivity.
    - discriminate H.
  }
  assert (H2: m = O).
  {
    destruct m as [| m'].
    - reflexivity.
    - rewrite plus_comm in H.
      discriminate H.
  }
  split.
  - apply H1.
  - apply H2.
Qed.

Lemma and_example2:
  forall n m : nat, n = O /\ m = O -> n + m = O.
Proof.
  intros n m H.
  destruct H as [Hn Hm] eqn : HE.
  rewrite Hn.
  rewrite Hm.
  reflexivity.
Qed.

Lemma and_example2':
  forall n m : nat, n = O /\ m = O -> n + m = O.
Proof.
  intros n m [Hn Hm].
  rewrite Hn.
  rewrite Hm.
  reflexivity.
Qed.

Lemma and_example3:
  forall n m : nat, n + m = O -> n * m = O.
Proof.
  intros n m H.
  assert (H': n = O /\ m = O).
  {
    apply and_exercise.
    apply H.
  }
  destruct H' as [Hn Hm].
  rewrite Hn.
  reflexivity.
Qed.

Lemma proj1: forall P Q : Prop, P /\ Q -> P.
Proof.
  intros P Q HPQ.
  destruct HPQ as [HP _].
  apply HP.
Qed.

Lemma proj2: forall P Q : Prop, P /\ Q -> Q.
Proof.
  intros P Q HPQ.
  destruct HPQ as [_ HQ].
  apply HQ.
Qed.

Theorem and_commut: forall P Q : Prop, P /\ Q -> Q /\ P.
Proof.
  intros P Q [HP HQ].
  split.
  - apply HQ.
  - apply HP.
Qed.

Theorem and_assoc: forall P Q R : Prop,
  P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R [HP [HQ HR]].
  split.
  - split.
    + apply HP.
    + apply HQ.
  - apply HR.
Qed.

Lemma eq_mult_O:
  forall n m : nat, n = O \/ m = O -> n * m = O.
Proof.
  intros n m [Hn | Hm].
  - rewrite Hn.
    reflexivity.
  - rewrite Hm.
    rewrite -> mult_n_O.
    reflexivity.
Qed.

Lemma or_intro_l: forall A B : Prop, A -> A \/ B.
Proof.
  intros A B HA.
  left.
  apply HA.
Qed.

Module MyNot.
Definition not (P : Prop) := P -> False.
Notation "~ x" := (not x) : type_scope.
Check not.
End MyNot.

Theorem ex_falso_quodlibet: forall P : Prop,
  False -> P.
Proof.
  intros P contra.
  destruct contra.
Qed.

Fact not_implies_our_not: forall P : Prop,
  ~ P -> (forall Q : Prop, P -> Q).
Proof.
  intros P HNP.
  unfold not in HNP.
  intros Q HP.
  apply HNP in HP.
  destruct HP.
Qed.

Notation "x <> y" := (~ (x = y)).

Theorem zero_not_one: O <> N 1.
Proof.
  unfold not.
  intros contra.
  discriminate contra.
Qed.

Theorem not_False:
  ~ False.
Proof.
  unfold not.
  intros H.
  destruct H.
Qed.

Theorem contradiction_implies_anything: forall P Q : Prop,
  (P /\ ~ P) -> Q.
Proof.
  intros P Q [HP HNA].
  unfold not in HNA.
  apply HNA in HP.
  destruct HP.
Qed.

Theorem double_neg: forall P : Prop,
  P -> ~ ~ P.
Proof.
  intros P H.
  unfold not.
  intros G.
  apply G.
  apply H.
Qed.

Theorem contrapositive: forall (P Q : Prop),
  (P -> Q) -> (~ Q -> ~P).
Proof.
  intros P Q H HNQ.
  unfold not in HNQ.
  unfold not.
  intros HP.
  apply H in HP.
  apply HNQ in HP.
  apply HP.
Qed.

Theorem not_both_true_and_false: forall P : Prop,
  ~ (P /\ ~ P).
Proof.
  intros P.
  unfold not.
  intros [HP HNP].
  apply HNP in HP.
  apply HP.
Qed.

Theorem not_true_is_false: forall b : bool,
  b <> true -> b = false.
Proof.
  intros b H.
  destruct b eqn : HE.
  - (* b = true *)
    unfold not in H.
    apply ex_falso_quodlibet.
    apply H.
    reflexivity.
  - (* b = false *)
    reflexivity.
Qed.

Theorem not_true_is_false': forall b : bool,
  b <> true -> b = false.
Proof.
  intros [] H.
  - (* b = true *)
    unfold not in H.
    exfalso. (* <=== *)
    apply H.
    reflexivity.
  - (* b = false *)
    reflexivity.
Qed.

Check I.

Lemma True_is_true: True.
Proof.
  apply I.
Qed.

Module MyIff.
Definition iff (P Q : Prop) := (P -> Q) /\ (Q -> P).
Notation "P <-> Q" := (iff P Q)
                      (at level 95, no associativity)
                      : type_scope.
End MyIff.

Theorem iff_sym: forall P Q : Prop,
  (P <-> Q) -> (Q <-> P).
Proof.
  intros P Q [HAB HBA].
  split.
  - (* -> *)
    apply HBA.
  - (* <- *)
    apply HAB.
Qed.

Lemma not_true_iff_false: forall b,
  b <> true <-> b = false.
Proof.
  intros b.
  split.
  - (* -> *)
    apply not_true_is_false.
  - (* <- *)
    intros H.
    rewrite H.
    intros H'.
    discriminate H'.
Qed.

Theorem or_distributes_over_and: forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R.
  split.
  - intros [H1 | H2].
    + split.
      * left.
        apply H1.
      * left.
        apply H1.
    + destruct H2 as [H21 H22].
      split.
      * right.
        apply H21.
      * right.
        apply H22.
  - intros [H1 H2].
    destruct H1 as [H11 | H12].
    + left.
      apply H11.
    + destruct H2 as [H21 | H22].
      * left.
        apply H21.
      * right.
        split.
        -- apply H12.
        -- apply H22.
Qed.

From Coq Require Import Setoids.Setoid.

Lemma mult_eq_O: forall n m, n * m = O -> n = O \/ m = O.
Proof.
  intros n m H.
  destruct n as [| n'].
  - left.
    reflexivity.
  - destruct m as [| m'].
    + right.
      reflexivity.
    + discriminate H.
Qed.

Lemma mult_O: forall n m, n * m = O <-> n = O \/ m = O.
Proof.
  split.
  - apply mult_eq_O.
  - apply eq_mult_O.
Qed.

Lemma or_assoc:
  forall P Q R : Prop, P \/ (Q \/ R) <-> (P \/ Q) \/ R.
Proof.
  intros P Q R.
  split.
  - intros [H | [H | H]].
    + left.
      left.
      apply H.
    + left.
      right.
      apply H.
    + right.
      apply H.
  - intros [[H | H] | H].
    + left.
      apply H.
    + right.
      left.
      apply H.
    + right.
      right.
      apply H.
Qed.

Lemma mult_O_3:
  forall n m p, n * m * p = O <-> n = O \/ m = O \/ p = O.
Proof.
  intros n m p.
  rewrite mult_O.
  rewrite mult_O.
  rewrite or_assoc.
  reflexivity.
Qed.

Lemma apply_iff_example:
  forall n m : nat, n * m = O -> n = O \/ m = O.
Proof.
  intros n m H.
  apply mult_O.
  apply H.
Qed.

Definition even x := exists n : nat, x = double n.

Lemma four_is_even: even (N 4).
Proof.
  unfold even.
  exists (N 2).
  reflexivity.
Qed.

Theorem exists_example_2: forall n,
  (exists m, n = (N 4) + m) ->
  (exists o, n = (N 2) + o).
Proof.
  intros n [m Hm].
  exists ((N 2) + m).
  apply Hm.
Qed.

Theorem dist_not_exists: forall (X : Type) (P : X -> Prop),
  (forall x, P x) -> not (exists x, not (P x)).
Proof.
  intros X P.
  intros H1 H2.
  destruct H2 as [x H2'].
  unfold not in H2'.
  apply H2'.
  apply H1.
Qed.

Theorem dist_exists_or: forall (X : Type) (P Q : X -> Prop),
  (exists x, P x \/ Q x) <-> (exists x, P x) \/ (exists x, Q x).
Proof.
  intros X P Q.
  split.
  - intros [x [H1 | H2]].
    + left.
      exists x.
      apply H1.
    + right.
      exists x.
      apply H2.
  - intros [[x H1] | [x H2]].
    + exists x.
      left.
      apply H1.
    + exists x.
      right.
      apply H2.
Qed.

(* 使用命题编程 *)
Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
  | [] => False
  | x' :: l' => x' = x \/ In x l'
  end.

Example In_example_1: In 4 [1; 2; 3; 4; 5].
Proof.
  simpl. right. right. right. left. reflexivity.
Qed.

Example In_example_2:
  forall n, In n [N 2; N 4] ->
  exists n', n = (N 2) * n'.
Proof.
  simpl.
  intros n [H | [H | []]].
  - exists (N 1).
    rewrite <- H.
    reflexivity.
  - exists (N 2).
    rewrite <- H.
    reflexivity.
Qed.

Lemma In_map:
  forall (A B : Type) (f : A -> B) (l : list A) (x : A),
  In x l -> In (f x) (map f l).
Proof.
  intros A B f l x.
  induction l as [|x' l' IHl'].
  - simpl.
    intros [].
  - simpl.
    intros [H | H].
    + rewrite H.
      left.
      reflexivity.
    + right.
      apply IHl'.
      apply H.
Qed.

Lemma In_map_iff:
  forall (A B : Type) (f : A -> B) (l : list A) (y : B),
  In y (map f l) <-> exists x, f x = y /\ In x l.
Proof.
  intros A B f l y.
  split.
  - induction l as [| x' l' IHl'].
    + simpl.
      intros [].
    + simpl.
      intros [H1 | H2].
      * exists x'.
        split.
        ** apply H1.
        ** left.
           reflexivity.
      * apply IHl' in H2.
        destruct H2 as [x [H21 H22]].
        exists x.
        split.
        ** apply H21.
        ** right.
           apply H22.
  - induction l as [| x' l' IHl'].
    + simpl.
      intros [x [H1 H2]].
      apply H2.
    + simpl.
      intros [x [H1 H2]].
      destruct H2 as [H21 | H22].
      * rewrite <- H21 in H1.
        left.
        apply H1.
      * right.
        apply IHl'.
        exists x.
        split.
        ** apply H1.
        ** apply H22.
Qed.

Lemma In_app_iff: forall A l1 l2 (a : A),
  In a (l1 ++ l2) <-> In a l1 \/ In a l2.
Proof.
  intros A l1 l2.
  split.
  induction l1 as [|x' l' IHl'].
  - simpl.
    right.
    apply H.
  - simpl.
    intros [H1 | H2].
    + left.
      left.
      apply H1.
    + apply IHl' in H2.
      destruct H2 as [H21 | H22].
      * left.
        right.
        apply H21.
      * right.
        apply H22.
  - induction l1 as [|x' l' IHl'].
    + simpl.
      intros [[] | H2].
      apply H2.
    + simpl.
      intros [[H1 | H2] | H3].
      * left.
        apply H1.
      * right.
        apply IHl'.
        left.
        apply H2.
      * right.
        apply IHl'.
        right.
        apply H3.
Qed.

Fixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=
  match l with
    | [] => True
    | x :: y => P x /\ All P y
  end.

Lemma All_In:
  forall T (P : T -> Prop) (l : list T),
  (forall x, In x l -> P x) <-> All P l.
Proof.
  intros T P l.
  split.
  - induction l as [| x' l' IHl'].
    + reflexivity.
    + simpl.
      intro H.
      split.
      * apply H.
        left.
        reflexivity.
      * apply IHl'.
        intros x H1.
        apply H.
        right.
        apply H1.
  - induction l as [| x' l' IHl'].
    + simpl.
      intros H x [].
    + simpl.
      intros [H11 H12] x.
      intros [H21 | H22].
      * rewrite <- H21.
        apply H11.
      * apply IHl'.
       ** apply H12.
       ** apply H22.
Qed.

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  fun n =>
    match oddb n with
      | true => Podd n
      | false => Peven n
    end.

Theorem combine_odd_even_intro:
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  intros Podd Peven n H1 H2.
  unfold combine_odd_even.
  destruct (oddb n).
  - apply H1.
    reflexivity.
  - apply H2.
    reflexivity.
Qed.

Theorem combine_odd_even_elim_odd:
  forall (Podd Peven : nat -> Prop) (n : nat),
  combine_odd_even Podd Peven n ->
  oddb n = true ->
  Podd n.
Proof.
  intros Podd Peven n.
  unfold combine_odd_even.
  destruct (oddb n).
  - intros.
    apply H.
  - intros.
    discriminate H0.
Qed.

Theorem combine_odd_even_elim_even:
  forall (Podd Peven : nat -> Prop) (n : nat),
  combine_odd_even Podd Peven n ->
  oddb n = false ->
  Peven n.
Proof.
  intros Podd Peven n.
  unfold combine_odd_even.
  destruct (oddb n).
  - intros.
    discriminate H0.
  - intros.
    apply H.
Qed.

(* 对参数应用定理 *)
Check plus_comm.

Lemma plus_comm3:
  forall x y z, x + (y + z) = (z + y) + x.
Proof.
  intros x y z.
  rewrite plus_comm.
  Check (plus_comm y z).
  rewrite (plus_comm y z).
  reflexivity.
Qed.

Theorem in_not_nil:
  forall A (x : A) (l : list A), In x l -> l <> [].
Proof.
  intros A x l H.
  unfold not.
  intro Hl.
  destruct l eqn : HE.
  - simpl in H.
    destruct H.
  - discriminate Hl.
Qed.

Lemma in_not_nil_42:
  forall l : list nat, In (N 42) l -> l <> [].
Proof.
  intros l H.
  (* apply in_not_nil with (x := N 42). *)
  apply (in_not_nil nat (N 42)).
  apply H.
  (* apply (in_not_nil _ _ _ H). *)
Qed.

Example lemma_application_ex:
  forall {n : nat} {ns : list nat},
  In n (map (fun m => m * (N 0)) ns) -> n = N 0.
Proof.
  intros n ns H.
  Check (proj1 _ _ (In_map_iff _ _ _ _ _) H).
  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H) as [m [Hm _]].
  rewrite mult_comm in Hm.
  rewrite mult_O_n in Hm.
  rewrite <- Hm.
  reflexivity.
Qed.


(** * Logic: Logic in Coq *)

Require Export Tactics.

(** In previous chapters, we have seen many examples of factual
    claims (_propositions_) and ways of presenting evidence of their
    truth (_proofs_).  In particular, we have worked extensively with
    _equality propositions_ of the form [e1 = e2], with
    implications ([P -> Q]), and with quantified propositions ([forall
    x, P]).  In this chapter, we will see how Coq can be used to carry
    out other familiar forms of logical reasoning.

    Before diving into details, let's talk a bit about the status of
    mathematical statements in Coq.  Recall that Coq is a _typed_
    language, which means that every sensible expression in its world
    has an associated type.  Logical claims are no exception: any
    statement we might try to prove in Coq has a type, namely [Prop],
    the type of _propositions_.  We can see this with the [Check]
    command: *)

Check 3 = 3.
(* ===> Prop *)

Check forall n m : nat, n + m = m + n.
(* ===> Prop *)

(** Note that all well-formed propositions have type [Prop] in Coq,
    regardless of whether they are true or not. Simply _being_ a
    proposition is one thing; being _provable_ is something else! *)

Check forall n : nat, n = 2.
(* ===> Prop *)

Check 3 = 4.
(* ===> Prop *)

(** Indeed, propositions don't just have types: they are _first-class
    objects_ that can be manipulated in the same ways as the other
    entities in Coq's world.  So far, we've seen one primary place
    that propositions can appear: in [Theorem] (and [Lemma] and
    [Example]) declarations. *)

Theorem plus_2_2_is_4 :
  2 + 2 = 4.
Proof. reflexivity.  Qed.

(** But propositions can be used in many other ways.  For example, we
    can give a name to a proposition using a [Definition], just as we
    have given names to expressions of other sorts. *)

Definition plus_fact : Prop  :=  2 + 2 = 4.
Check plus_fact.
(* ===> plus_fact : Prop *)

(** We can later use this name in any situation where a proposition is
    expected -- for example, as the claim in a [Theorem] declaration. *)

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

(** We can also write _parameterized_ propositions -- that is,
    functions that take arguments of some type and return a
    proposition. For instance, the following function takes a number
    and returns a proposition asserting that this number is equal to
    three: *)

Definition is_three (n : nat) : Prop :=
  n = 3.
Check is_three.
(* ===> nat -> Prop *)

(** In Coq, functions that return propositions are said to define
    _properties_ of their arguments.  For instance, here's a
    polymorphic property defining the familiar notion of an _injective
    function_. *)

Definition injective {A B} (f : A -> B) :=
  forall x y : A, f x = f y -> x = y.

Lemma succ_inj : injective S.
Proof.
  intros n m H. inversion H. reflexivity.
Qed.

(** The equality operator [=] that we have been using so far is also
    just a function that returns a [Prop]. The expression [n = m] is
    just syntactic sugar for [eq n m], defined using Coq's [Notation]
    mechanism. Because [=] can be used with elements of any type, it
    is also polymorphic: *)

Check @eq.
(* ===> forall A : Type, A -> A -> Prop *)

(** (Notice that we wrote [@eq] instead of [eq]: The type argument [A]
    to [eq] is declared as implicit, so we need to turn off implicit
    arguments to see the full type of [eq].) *)

(* #################################################################### *)
(** * Logical Connectives *)

(** ** Conjunction *)

(** The _conjunction_ or _logical and_ of propositions [A] and [B] is
    written [A /\ B], denoting the claim that both [A] and [B] are
    true. *)

Example and_example : 3 + 4 = 7 /\ 2 * 2 = 4.

(** To prove a conjunction, use the [split] tactic.  Its effect is to
    generate two subgoals, one for each part of the statement: *)

Proof.
  split.
  - (* 3 + 4 = 7 *) reflexivity.
  - (* 2 + 2 = 4 *) reflexivity.
Qed.

(** More generally, the following principle works for any two
    propositions [A] and [B]: *)

Lemma and_intro : forall A B : Prop, A -> B -> A /\ B.
Proof.
  intros A B HA HB. split.
  - apply HA.
  - apply HB.
Qed.

(** A logical statement with multiple arrows is just a theorem that
    has several hypotheses.  Here, [and_intro] says that, for any
    propositions [A] and [B], if we assume that [A] is true and we
    assume that [B] is true, then [A /\ B] is also true.

    Since applying a theorem with hypotheses to some goal has the
    effect of generating as many subgoals as there are hypotheses for
    that theorem, we can, apply [and_intro] to achieve the same effect
    as [split]. *)

Example and_example' : 3 + 4 = 7 /\ 2 * 2 = 4.
Proof.
  apply and_intro.
  - (* 3 + 4 = 7 *) reflexivity.
  - (* 2 + 2 = 4 *) reflexivity.
Qed.

Require Peano.
(** **** Exercise: 2 stars (and_exercise)  *)
Example and_exercise :
  forall n m : nat, n + m = 0 -> n = 0 /\ m = 0.
Proof.
  induction n, m.
  - simpl. intros. split. reflexivity. reflexivity.
  - simpl. intros. split. reflexivity. assumption.
  - intros. split. inversion H. reflexivity.
  - intros. inversion H.
Qed.

(** [] *)

(** So much for proving conjunctive statements.  To go in the other
    direction -- i.e., to _use_ a conjunctive hypothesis to prove
    something else -- we employ the [destruct] tactic.

    If the proof context contains a hypothesis [H] of the form [A /\
    B], writing [destruct H as [HA HB]] will remove [H] from the
    context and add two new hypotheses: [HA], stating that [A] is
    true, and [HB], stating that [B] is true.  For instance: *)

Lemma and_example2 :
  forall n m : nat, n = 0 /\ m = 0 -> n + m = 0.
Proof.
  intros n m H.
  destruct H as [Hn Hm].
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** As usual, we can also destruct [H] when we introduce it instead of
    introducing and then destructing it: *)

Lemma and_example2' :
  forall n m : nat, n = 0 /\ m = 0 -> n + m = 0.
Proof.
  intros n m [Hn Hm].
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** You may wonder why we bothered packing the two hypotheses [n = 0]
    and [m = 0] into a single conjunction, since we could have also
    stated the theorem with two separate premises: *)

Lemma and_example2'' :
  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.
Proof.
  intros n m Hn Hm.
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** In this case, there is not much difference between the two
    theorems.  But it is often necessary to explicitly decompose
    conjunctions that arise from intermediate steps in proofs,
    especially in bigger developments.  Here's a simplified
    example: *)

Lemma and_example3 :
  forall n m : nat, n + m = 0 -> n * m = 0.
Proof.
  intros n m H.
  assert (H' : n = 0 /\ m = 0).
  { apply and_exercise. apply H. }
  destruct H' as [Hn Hm].
  rewrite Hn. reflexivity.
Qed.

(** Another common situation with conjunctions is that we know [A /\
    B] but in some context we need just [A] (or just [B]).  The
    following lemmas are useful in such cases: *)

Lemma proj1 : forall P Q : Prop,
  P /\ Q -> P.
Proof.
  intros P Q [HP HQ].
  apply HP.  Qed.

(** **** Exercise: 1 star, optional (proj2)  *)
Lemma proj2 : forall P Q : Prop,
  P /\ Q -> Q.
Proof.
  intros. destruct H. assumption.
Qed.
(** [] *)

(** Finally, we sometimes need to rearrange the order of conjunctions
    and/or the grouping of conjuncts in multi-way conjunctions.  The
    following commutativity and associativity theorems come in handy
    in such cases. *)

Theorem and_commut : forall P Q : Prop,
  P /\ Q -> Q /\ P.
Proof.
  (* WORKED IN CLASS *)
  intros P Q [HP HQ].
  split.
    - (* left *) apply HQ.
    - (* right *) apply HP.
Qed.

(** **** Exercise: 2 stars (and_assoc)  *)
(** (In the following proof of associativity, notice how the _nested_
    intro pattern breaks the hypothesis [H : P /\ (Q /\ R)] down into
    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from
    there.) *)

Theorem and_assoc : forall P Q R : Prop,
  P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R [HP [HQ HR]].
  split. split.  assumption. assumption. assumption.
Qed.

(** [] *)

(** By the way, the infix notation [/\] is actually just syntactic
    sugar for [and A B].  That is, [and] is a Coq operator that takes
    two propositions as arguments and yields a proposition. *)

Check and.
(* ===> and : Prop -> Prop -> Prop *)

(** ** Disjunction *)

(** Another important connective is the _disjunction_, or _logical or_
    of two propositions: [A \/ B] is true when either [A] or [B]
    is.  (Alternatively, we can write [or A B], where [or : Prop ->
    Prop -> Prop].)

    To use a disjunctive hypothesis in a proof, we proceed by case
    analysis, which, as for [nat] or other data types, can be done
    with [destruct] or [intros].  Here is an example: *)

Lemma or_example :
  forall n m : nat, n = 0 \/ m = 0 -> n * m = 0.
Proof.
  (* This pattern implicitly does case analysis on
     [n = 0 \/ m = 0] *)
  intros n m [Hn | Hm].
  - (* Here, [n = 0] *)
    rewrite Hn. reflexivity.
  - (* Here, [m = 0] *)
    rewrite Hm. rewrite <- mult_n_O.
    reflexivity.
Qed.

(** We can see in this example that, when we perform case analysis on
    a disjunction [A \/ B], we must satisfy two proof obligations,
    each showing that the conclusion holds under a different
    assumption -- [A] in the first subgoal and [B] in the second.
    Note that the case analysis pattern ([Hn | Hm]) allows us to name
    the hypothesis that is generated in each subgoal.

    Conversely, to show that a disjunction holds, we need to show that
    one of its sides does. This is done via two tactics, [left] and
    [right].  As their names imply, the first one requires proving the
    left side of the disjunction, while the second requires proving
    its right side.  Here is a trivial use... *)

Lemma or_intro : forall A B : Prop, A -> A \/ B.
Proof.
  intros A B HA.
  left.
  apply HA.
Qed.

(** ... and a slightly more interesting example requiring the use of
    both [left] and [right]: *)

Lemma zero_or_succ :
  forall n : nat, n = 0 \/ n = S (pred n).
Proof.
  intros [|n].
  - left. reflexivity.
  - right. reflexivity.
Qed.

(** **** Exercise: 1 star (mult_eq_0)  *)
Lemma mult_eq_0 :
  forall n m, n * m = 0 -> n = 0 \/ m = 0.
Proof.
  induction n, m.
  - simpl. intros. left. reflexivity.
  - intros. left. reflexivity.
  - intros. right. reflexivity.
  - intros.   left. inversion H.
Qed.

(** [] *)

(** **** Exercise: 1 star (or_commut)  *)
Theorem or_commut : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros. destruct H. right. assumption. left. assumption.
Qed.

(** [] *)

(** ** Falsehood and Negation *)

(** So far, we have mostly been concerned with proving that certain
    things are _true_ -- addition is commutative, appending lists is
    associative, etc.  Of course, we may also be interested in
    _negative_ results, showing that certain propositions are _not_
    true. In Coq, such negative statements are expressed with the
    negation operator [~].

    To see how negation works, recall the discussion of the _principle
    of explosion_ from the [Tactics] chapter; it asserts that, if we
    assume a contradiction, then any other proposition can be derived.
    Following this intuition, we could define [~ P] ("not [P]") as
    [forall Q, P -> Q].  Coq actually makes a slightly different
    choice, defining [~ P] as [P -> False], where [False] is a
    _particular_ contradictory proposition defined in the standard
    library. *)

Module MyNot.

Definition not (P:Prop) := P -> False.

Notation "~ x" := (not x) : type_scope.

Check not.
(* ===> Prop -> Prop *)

End MyNot.

(** Since [False] is a contradictory proposition, the principle of
    explosion also applies to it. If we get [False] into the proof
    context, we can [destruct] it to complete any goal: *)

Theorem ex_falso_quodlibet : forall (P:Prop),
  False -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P contra.
  destruct contra.
Qed.

(** The Latin _ex falso quodlibet_ means, literally, "from falsehood
    follows whatever you like"; this is another common name for the
    principle of explosion. *)

(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)
(** Show that Coq's definition of negation implies the intuitive one
    mentioned above: *)

Fact not_implies_our_not : forall (P:Prop),
  ~ P -> (forall (Q:Prop), P -> Q).
Proof.
  intros. destruct H. assumption.
Qed.

(** [] *)

(** This is how we use [not] to state that [0] and [1] are different
    elements of [nat]: *)

Theorem zero_not_one : ~(0 = 1).
Proof.
  intros contra. inversion contra.
Qed.

(** Such inequality statements are frequent enough to warrant a
    special notation, [x <> y]: *)

Check (0 <> 1).
(* ===> Prop *)

Theorem zero_not_one' : 0 <> 1.
Proof.
  intros H. inversion H.
Qed.

(** It takes a little practice to get used to working with negation in
    Coq.  Even though you can see perfectly well why a statement
    involving negation is true, it can be a little tricky at first to
    get things into the right configuration so that Coq can understand
    it!  Here are proofs of a few familiar facts to get you warmed
    up. *)

Theorem not_False :
  ~ False.
Proof.
  unfold not. intros H. destruct H.
Qed.

Theorem contradiction_implies_anything : forall P Q : Prop,
  (P /\ ~P) -> Q.
Proof.
  (* WORKED IN CLASS *)
  intros P Q [HP HNA]. unfold not in HNA.
  apply HNA in HP. destruct HP.
Qed.

Theorem double_neg : forall P : Prop,
  P -> ~~P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not. intros G. apply G. apply H.
Qed.

(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)
(** Write an informal proof of [double_neg]:

   _Theorem_: [P] implies [~~P], for any proposition [P].

   _Proof_:
(* FILL IN HERE *)
   []
*)

(** **** Exercise: 2 stars, recommended (contrapositive)  *)
Theorem contrapositive : forall P Q : Prop,
  (P -> Q) -> (~Q -> ~P).
Proof.
  intros. unfold not. intros. apply H in H1. destruct H0. assumption.
Qed.
(** [] *)

(** **** Exercise: 1 star (not_both_true_and_false)  *)
Theorem not_both_true_and_false : forall P : Prop,
  ~ (P /\ ~P).
Proof.
  intros. unfold not. intros. destruct H. apply H0. assumption.
Qed.

(** [] *)

(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)
(** Write an informal proof (in English) of the proposition [forall P
    : Prop, ~(P /\ ~P)]. *)

(* FILL IN HERE *)
(** [] *)

(** Similarly, since inequality involves a negation, it requires a
    little practice to be able to work with it fluently.  Here is one
    useful trick.  If you are trying to prove a goal that is
    nonsensical (e.g., the goal state is [false = true]), apply
    [ex_falso_quodlibet] to change the goal to [False].  This makes it
    easier to use assumptions of the form [~P] that may be available
    in the context -- in particular, assumptions of the form
    [x<>y]. *)

Theorem not_true_is_false : forall b : bool,
  b <> true -> b = false.
Proof.
  intros [] H.
  - (* b = true *)
    unfold not in H.
    apply ex_falso_quodlibet.
    apply H. reflexivity.
  - (* b = false *)
    reflexivity.
Qed.

(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq
    provides a built-in tactic, [exfalso], for applying it. *)

Theorem not_true_is_false' : forall b : bool,
  b <> true -> b = false.
Proof.
  intros [] H.
  - (* b = false *)
    unfold not in H.
    exfalso.                (* <=== *)
    apply H. reflexivity.
  - (* b = true *) reflexivity.
Qed.

(** ** Truth *)

(** Besides [False], Coq's standard library also defines [True], a
    proposition that is trivially true. To prove it, we use the
    predefined constant [I : True]: *)

Lemma True_is_true : True.
Proof. apply I. Qed.

(** Unlike [False], which is used extensively, [True] is used quite
    rarely, since it is trivial (and therefore uninteresting) to prove
    as a goal, and it carries no useful information as a hypothesis.
    But it can be quite useful when defining complex [Prop]s using
    conditionals or as a parameter to higher-order [Prop]s.  We will
    see some examples such uses of [True] later on. *)

(** ** Logical Equivalence *)

(** The handy "if and only if" connective, which asserts that two
    propositions have the same truth value, is just the conjunction of
    two implications. *)

Module MyIff.

Definition iff (P Q : Prop) := (P -> Q) /\ (Q -> P).

Notation "P <-> Q" := (iff P Q)
                      (at level 95, no associativity)
                      : type_scope.

End MyIff.

Theorem iff_sym : forall P Q : Prop,
  (P <-> Q) -> (Q <-> P).
Proof.
  (* WORKED IN CLASS *)
  intros P Q [HAB HBA].
  split.
  - (* -> *) apply HBA.
  - (* <- *) apply HAB.
Qed.

Lemma not_true_iff_false : forall b,
  b <> true <-> b = false.
Proof.
  (* WORKED IN CLASS *)
  intros b. split.
  - (* -> *) apply not_true_is_false.
  - (* <- *)
    intros H. rewrite H. intros H'. inversion H'.
Qed.

(** **** Exercise: 1 star, optional (iff_properties)  *)
(** Using the above proof that [<->] is symmetric ([iff_sym]) as
    a guide, prove that it is also reflexive and transitive. *)

Theorem iff_refl : forall P : Prop,
  P <-> P.
Proof.
  intros. split. intros. assumption. intros. assumption.
Qed.

Theorem iff_trans : forall P Q R : Prop,
  (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros P Q R [H11 H12] [H21 H22]. split. intros.  apply H21. apply H11. assumption.
  intros. apply H12. apply H22. assumption.
Qed.
  (** [] *)

(** **** Exercise: 3 stars (or_distributes_over_and)  *)
Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros. split.
  -  intros. destruct H. split. left. assumption. left. assumption. destruct H. split.
     right. assumption.  right. assumption.
  - intros. destruct H.  destruct H. left. assumption. destruct H0. left. assumption. right. split. assumption.  assumption.
Qed.
(** [] *)

(** Some of Coq's tactics treat [iff] statements specially, avoiding
    the need for some low-level proof-state manipulation.  In
    particular, [rewrite] and [reflexivity] can be used with [iff]
    statements, not just equalities.  To enable this behavior, we need
    to import a special Coq library that allows rewriting with other
    formulas besides equality: *)

Require Import Coq.Setoids.Setoid.

(** Here is a simple example demonstrating how these tactics work with
    [iff].  First, let's prove a couple of basic iff equivalences: *)

Lemma mult_0 : forall n m, n * m = 0 <-> n = 0 \/ m = 0.
Proof.
  split.
  - apply mult_eq_0.
  - apply or_example.
Qed.

Lemma or_assoc :
  forall P Q R : Prop, P \/ (Q \/ R) <-> (P \/ Q) \/ R.
Proof.
  intros P Q R. split.
  - intros [H | [H | H]].
    + left. left. apply H.
    + left. right. apply H.
    + right. apply H.
  - intros [[H | H] | H].
    + left. apply H.
    + right. left. apply H.
    + right. right. apply H.
Qed.

(** We can now use these facts with [rewrite] and [reflexivity] to
    give smooth proofs of statements involving equivalences.  Here is
    a ternary version of the previous [mult_0] result: *)

Lemma mult_0_3 :
  forall n m p, n * m * p = 0 <-> n = 0 \/ m = 0 \/ p = 0.
Proof.
  intros n m p.
  rewrite mult_0. rewrite mult_0. rewrite or_assoc.
  reflexivity.
Qed.

(** The [apply] tactic can also be used with [<->]. When given an
    equivalence as its argument, [apply] tries to guess which side of
    the equivalence to use. *)

Lemma apply_iff_example :
  forall n m : nat, n * m = 0 -> n = 0 \/ m = 0.
Proof.
  intros n m H. apply mult_0. apply H.
Qed.

(* ############################################################ *)
(** ** Existential Quantification *)

(** Another important logical connective is _existential
    quantification_.  To say that there is some [x] of type [T] such
    that some property [P] holds of [x], we write [exists x : T,
    P]. As with [forall], the type annotation [: T] can be omitted if
    Coq is able to infer from the context what the type of [x] should
    be.

    To prove a statement of the form [exists x, P], we must show that
    [P] holds for some specific choice of value for [x], known as the
    _witness_ of the existential.  This is done in two steps: First,
    we explicitly tell Coq which witness [t] we have in mind by
    invoking the tactic [exists t]; then we prove that [P] holds after
    all occurrences of [x] are replaced by [t].  Here is an example: *)

Lemma four_is_even : exists n : nat, 4 = n + n.
Proof.
  exists 2. reflexivity.
Qed.

(** Conversely, if we have an existential hypothesis [exists x, P] in
    the context, we can destruct it to obtain a witness [x] and a
    hypothesis stating that [P] holds of [x]. *)

Theorem exists_example_2 : forall n,
  (exists m, n = 4 + m) ->
  (exists o, n = 2 + o).
Proof.
  intros n [m Hm].
  exists (2 + m).
  apply Hm.
Qed.

(** **** Exercise: 1 star (dist_not_exists)  *)
(** Prove that "[P] holds for all [x]" implies "there is no [x] for
    which [P] does not hold." *)

Theorem dist_not_exists : forall (X:Type) (P : X -> Prop),
  (forall x, P x) -> ~ (exists x, ~ P x).
Proof.
  intros X P h1 h2.  elim h2.  intros x h3. elim h3. apply h1.
Qed.

(** [] *)

(** **** Exercise: 2 stars (dist_exists_or)  *)
(** Prove that existential quantification distributes over
    disjunction. *)

Theorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),
  (exists x, P x \/ Q x) <-> (exists x, P x) \/ (exists x, Q x).
Proof.
  intros. split.
  - intros. destruct H. destruct H. left. exists x. assumption. right. exists x. assumption.
  - intros [H1 | H2]. destruct H1. exists x. left. assumption.  destruct H2. exists x. right. assumption.
Qed.

Print dist_exists_or.
(** [] *)

(* #################################################################### *)
(** * Programming with Propositions *)

(** The logical connectives that we have seen provide a rich
    vocabulary for defining complex propositions from simpler ones.
    To illustrate, let's look at how to express the claim that an
    element [x] occurs in a list [l].  Notice that this property has a
    simple recursive structure:

    - If [l] is the empty list, then [x] cannot occur on it, so the
      property "[x] appears in [l]" is simply false.

    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]
      occurs in [l] if either it is equal to [x'] or it occurs in
      [l']. *)

(** We can translate this directly into a straightforward Coq
    function, [In].  (It can also be found in the Coq standard
    library.) *)

Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
  | nil => False
  | h::t => h = x \/ In x t
  end.

(** When [In] is applied to a concrete list, it expands into a
    concrete sequence of nested conjunctions. *)

Example In_example_1 : In 4 [3; 4; 5].
Proof.
  simpl. right. left. reflexivity.
Qed.

Example In_example_2 :
  forall n, In n [2; 4] ->
  exists n', n = 2 * n'.
Proof.
  simpl.
  intros n [H | [H | []]].
  - exists 1. rewrite <- H. reflexivity.
  - exists 2. rewrite <- H. reflexivity.
Qed.

(** (Notice the use of the empty pattern to discharge the last case
    _en passant_.) *)

(** We can also prove more generic, higher-level lemmas about [In].
    Note, in the next, how [In] starts out applied to a variable and
    only gets expanded when we do case analysis on this variable: *)

Lemma In_map :
  forall (A B : Type) (f : A -> B) (l : list A) (x : A),
    In x l ->
    In (f x) (map f l).
Proof.
  intros A B f l x.
  induction l as [|x' l' IHl'].
  - (* l = nil, contradiction *)
    simpl. intros [].
  - (* l = x' :: l' *)
    simpl. intros [H | H].
    + rewrite H. left. reflexivity.
    + right. apply IHl'. apply H.
Qed.

(** This way of defining propositions, though convenient in some
    cases, also has some drawbacks.  In particular, it is subject to
    Coq's usual restrictions regarding the definition of recursive
    functions, e.g., the requirement that they be "obviously
    terminating."  In the next chapter, we will see how to define
    propositions _inductively_, a different technique with its own set
    of strengths and limitations. *)

(** **** Exercise: 2 stars (In_map_iff)  *)
Lemma In_map_iff :
  forall (A B : Type) (f : A -> B) (l : list A) (y : B),
    In y (map f l) <->
    exists x, f x = y /\ In x l.
Proof.
  intros. split.
  - intros. induction l.
    + simpl in H. destruct H.
    + simpl in H. destruct H. exists x. split. assumption. simpl. left. reflexivity.
      apply IHl in H. destruct H.  exists x0. destruct H.  split. assumption. simpl. right. assumption.
  - intros. destruct H. destruct H. rewrite <- H.  induction l.
    + simpl. destruct H0.
    + destruct H0. rewrite <- H0.   unfold map.  simpl.  left.  reflexivity. simpl. right. apply IHl. apply H0.
Qed.

(** [] *)

(** **** Exercise: 2 stars (in_app_iff)  *)
Lemma in_app_iff : forall A l l' (a:A),
  In a (l++l') <-> In a l \/ In a l'.
Proof.
  intros. split.
  - intros. induction l,  l'.
    + simpl in H. destruct H.
    + simpl in H. destruct H. right. rewrite <- H. simpl. left. reflexivity. right. simpl. right. assumption.
    + simpl in H.    rewrite app_nil_r in H. rewrite app_nil_r in IHl. left. simpl. assumption.
    + 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.
      right. simpl. right. assumption.
  - intros [H1 | H2].
    + induction l. destruct H1. simpl. destruct H1. left. assumption. apply IHl in H. right.  apply H.
    + induction l. simpl. assumption. simpl. right. assumption.
Qed.

(** [] *)

(** **** Exercise: 3 stars (All)  *)
(** Recall that functions returning propositions can be seen as
    _properties_ of their arguments. For instance, if [P] has type
    [nat -> Prop], then [P n] states that property [P] holds of [n].

    Drawing inspiration from [In], write a recursive function [All]
    stating that some property [P] holds of all elements of a list
    [l]. To make sure your definition is correct, prove the [All_In]
    lemma below.  (Of course, your definition should _not_ just
    restate the left-hand side of [All_In].) *)

Fixpoint All {T: Type} (P : T -> Prop) (l : list T) : Prop :=
  match l with
  | [] => True
  | x' :: l' => (P x') /\ All P l'
  end.

Lemma All_In :
  forall T (P : T -> Prop) (l : list T),
    (forall x, In x l -> P x) <->
    All P l.
Proof.
  intros. split.
  + intros. induction l.
    - simpl. reflexivity.
    - simpl. split. apply H. simpl. left. reflexivity. apply IHl. intros. apply H. simpl. right. apply H0.
  + intros.  induction l.
    -  destruct H0.
    -  destruct H0. simpl in H. destruct H. rewrite <- H0.  assumption.  apply IHl. simpl in H. destruct H. assumption. assumption.
Qed.

(** **** Exercise: 3 stars (combine_odd_even)  *)
(** Complete the definition of the [combine_odd_even] function below.
    It takes as arguments two properties of numbers, [Podd] and
    [Peven], and it should return a property [P] such that [P n] is
    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]
    otherwise. *)

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  fun (n: nat) => match (oddb n) with
                  | true  =>  (Podd n)
                  | false => (Peven n)
                  end.

Print oddb.
Print evenb.

(** To test your definition, prove the following facts: *)

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  intros P Q n h1 h2. unfold combine_odd_even. destruct (oddb n).
  + apply h1. reflexivity.
  + apply h2. reflexivity.
Qed.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  intros. unfold combine_odd_even in H. destruct (oddb n).
  assumption. exfalso. inversion H0.
Qed.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  intros. unfold combine_odd_even in H. destruct (oddb n).
  + inversion H0.
  + assumption.
Qed.

(** [] *)

(* #################################################################### *)
(** * Applying Theorems to Arguments *)

(** One feature of Coq that distinguishes it from many other proof
    assistants is that it treats _proofs_ as first-class objects.

    There is a great deal to be said about this, but it is not
    necessary to understand it in detail in order to use Coq.  This
    section gives just a taste, while a deeper exploration can be
    found in the optional chapters [ProofObjects] and
    [IndPrinciples]. *)

(** We have seen that we can use the [Check] command to ask Coq to
    print the type of an expression.  We can also use [Check] to ask
    what theorem a particular identifier refers to. *)

Check plus_comm.
(* ===> forall n m : nat, n + m = m + n *)

(** Coq prints the _statement_ of the [plus_comm] theorem in the same
    way that it prints the _type_ of any term that we ask it to
    [Check].  Why?

    The reason is that the identifier [plus_comm] actually refers to a
    _proof object_ -- a data structure that represents a logical
    derivation establishing of the truth of the statement [forall n m
    : nat, n + m = m + n].  The type of this object _is_ the statement
    of the theorem that it is a proof of.

    Intuitively, this makes sense because the statement of a theorem
    tells us what we can use that theorem for, just as the type of a
    computational object tells us what we can do with that object --
    e.g., if we have a term of type [nat -> nat -> nat], we can give
    it two [nat]s as arguments and get a [nat] back.  Similarly, if we
    have an object of type [n = m -> n + n = m + m] and we provide it
    an "argument" of type [n = m], we can derive [n + n = m + m].

    Operationally, this analogy goes even further: by applying a
    theorem, as if it were a function, to hypotheses with matching
    types, we can specialize its result without having to resort to
    intermediate assertions.  For example, suppose we wanted to prove
    the following result: *)

Lemma plus_comm3 :
  forall n m p, n + (m + p) = (p + m) + n.

(** It appears at first sight that we ought to be able to prove this
    by rewriting with [plus_comm] twice to make the two sides match.
    The problem, however, is that the second [rewrite] will undo the
    effect of the first. *)

Proof.
  intros n m p.
  rewrite plus_comm.
  rewrite plus_comm.
  (* We are back where we started... *)

(** One simple way of fixing this problem, using only tools that we
    already know, is to use [assert] to derive a specialized version
    of [plus_comm] that can be used to rewrite exactly where we
    want. *)

  rewrite plus_comm.
  assert (H : m + p = p + m).
  { rewrite plus_comm. reflexivity. }
  rewrite H.
  reflexivity.
Qed.

(** A more elegant alternative is to apply [plus_comm] directly to the
    arguments we want to instantiate it with, in much the same way as
    we apply a polymorphic function to a type argument. *)

Lemma plus_comm3_take2 :
  forall n m p, n + (m + p) = (p + m) + n.
Proof.
  intros n m p.
  rewrite plus_comm.
  rewrite (plus_comm m).
  reflexivity.
Qed.

Check plus_comm3_take2.
(** You can "use theorems as functions" in this way with almost all
    tactics that take a theorem name as an argument.  Note also that
    theorem application uses the same inference mechanisms as function
    application; thus, it is possible, for example, to supply
    wildcards as arguments to be inferred, or to declare some
    hypotheses to a theorem as implicit by default.  These features
    are illustrated in the proof below. *)

Example lemma_application_ex :
  forall {n : nat} {ns : list nat},
    In n (map (fun m => m * 0) ns) ->
    n = 0.
Proof.
  intros n ns H.
  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)
           as [m [Hm _]].
  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.
Qed.

(** We will see many more examples of the idioms from this section in
    later chapters. *)

(* #################################################################### *)
(** * Coq vs. Set Theory *)

(** Coq's logical core, the _Calculus of Inductive Constructions_,
    differs in some important ways from other formal systems that are
    used by mathematicians for writing down precise and rigorous
    proofs.  For example, in the most popular foundation for
    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set
    Theory (ZFC), a mathematical object can potentially be a member of
    many different sets; a term in Coq's logic, on the other hand, is
    a member of at most one type.  This difference often leads to
    slightly different ways of capturing informal mathematical
    concepts, though these are by and large quite natural and easy to
    work with.  For example, instead of saying that a natural number
    [n] belongs to the set of even numbers, we would say in Coq that
    [ev n] holds, where [ev : nat -> Prop] is a property describing
    even numbers.

    However, there are some cases where translating standard
    mathematical reasoning into Coq can be either cumbersome or
    sometimes even impossible, unless we enrich the core logic with
    additional axioms.  We conclude this chapter with a brief
    discussion of some of the most significant differences between the
    two worlds. *)

(** ** Functional Extensionality

    The equality assertions that we have seen so far mostly have
    concerned elements of inductive types ([nat], [bool], etc.).  But
    since Coq's equality operator is polymorphic, these are not the
    only possibilities -- in particular, we can write propositions
    claiming that two _functions_ are equal to each other: *)

Example function_equality_ex : plus 3 = plus (pred 4).
Proof. reflexivity. Qed.

(** In common mathematical practice, two functions [f] and [g] are
    considered equal if they produce the same outputs:

    (forall x, f x = g x) -> f = g

    This is known as the principle of _functional extensionality_.

    Informally speaking, an "extensional property" is one that
    pertains to an object's observable behavior.  Thus, functional
    extensionality simply means that a function's identity is
    completely determined by what we can observe from it -- i.e., in
    Coq terms, the results we obtain after applying it.

    Functional extensionality is not part of Coq's basic axioms: the
    only way to show that two functions are equal is by
    simplification (as we did in the proof of [function_equality_ex]).
    But we can add it to Coq's core logic using the [Axiom]
    command. *)

Axiom functional_extensionality : forall {X Y: Type}
                                    {f g : X -> Y},
  (forall (x:X), f x = g x) -> f = g.

(** Using [Axiom] has the same effect as stating a theorem and
    skipping its proof using [Admitted], but it alerts the reader that
    this isn't just something we're going to come back and fill in
    later!

    We can now invoke functional extensionality in proofs: *)

Print functional_extensionality.

Lemma plus_comm_ext : plus = fun n m => m + n.
Proof.
  apply functional_extensionality. intros n.
  apply functional_extensionality. intros m.
  apply plus_comm.
Qed.

Check plus_comm_ext.
(** Naturally, we must be careful when adding new axioms into Coq's
    logic, as they may render it inconsistent -- that is, it may
    become possible to prove every proposition, including [False]!
    Unfortunately, there is no simple way of telling whether an axiom
    is safe: hard work is generally required to establish the
    consistency of any particular combination of axioms.  Fortunately,
    it is known that adding functional extensionality, in particular,
    _is_ consistent.

    Note that it is possible to check whether a particular proof
    relies on any additional axioms, using the [Print Assumptions]
    command. For instance, if we run it on [plus_comm_ext], we see
    that it uses [functional_extensionality]: *)

Print Assumptions plus_comm_ext.
(* ===>
     Axioms:
     functional_extensionality :
         forall (X Y : Type) (f g : X -> Y),
                (forall x : X, f x = g x) -> f = g *)

(** **** Exercise: 5 stars (tr_rev)  *)
(** One problem with the definition of the list-reversing function
    [rev] that we have is that it performs a call to [app] on each
    step; running [app] takes time asymptotically linear in the size
    of the list, which means that [rev] has quadratic running time.
    We can improve this with the following definition: *)

Fixpoint rev_append {X} (l1 l2 : list X) : list X :=
  match l1 with
  | [] => l2
  | x :: l1' => rev_append l1' (x :: l2)
  end.

Definition tr_rev {X} (l : list X) : list X :=
  rev_append l [].

(** This version is said to be _tail-recursive_, because the recursive
    call to the function is the last operation that needs to be
    performed (i.e., we don't have to execute [++] after the recursive
    call); a decent compiler will generate very efficient code in this
    case.  Prove that both definitions are indeed equivalent. *)

Check tr_rev.

Lemma tr_rev_correct : forall X, @tr_rev X = @rev X.
(* FILL IN HERE *) Admitted.
(** [] *)

(** ** Propositions and Booleans *)

(** We've seen that Coq has two different ways of encoding logical
    facts: with _booleans_ (of type [bool]), and with
    _propositions_ (of type [Prop]). For instance, to claim that a
    number [n] is even, we can say either (1) that [evenb n] returns
    [true] or (2) that there exists some [k] such that [n = double k].
    Indeed, these two notions of evenness are equivalent, as can
    easily be shown with a couple of auxiliary lemmas (one of which is
    left as an exercise).

    We often say that the boolean [evenb n] _reflects_ the proposition
    [exists k, n = double k].  *)

Theorem evenb_double : forall k, evenb (double k) = true.
Proof.
  intros k. induction k as [|k' IHk'].
  - reflexivity.
  - simpl. apply IHk'.
Qed.

(** **** Exercise: 3 stars (evenb_double_conv)  *)
Theorem evenb_double_conv : forall n,
  exists k, n = if evenb n then double k
                else S (double k).
Proof.
  intros. induction n.
  + simpl. exists 0. reflexivity.
  +  rewrite evenb_S. destruct (evenb n).
  - simpl. destruct IHn as [x IHn]. rewrite  IHn. exists x.   reflexivity.
  - simpl. destruct IHn as [x IHn]. rewrite IHn.  exists (S x).  simpl. reflexivity.
Qed.
  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)

(** [] *)

Theorem even_bool_prop : forall n,
  evenb n = true <-> exists k, n = double k.
Proof.
  intros n. split.
  - intros H. destruct (evenb_double_conv n) as [k Hk].
    rewrite Hk. rewrite H. exists k. reflexivity.
  - intros [k Hk]. rewrite Hk. apply evenb_double.
Qed.

(** Similarly, to state that two numbers [n] and [m] are equal, we can
    say either (1) that [beq_nat n m] returns [true] or (2) that [n =
    m].  These two notions are equivalent. *)

Theorem beq_nat_true_iff : forall n1 n2 : nat,
  beq_nat n1 n2 = true <-> n1 = n2.
Proof.
  intros n1 n2. split.
  - apply beq_nat_true.
  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.
Qed.

(** However, while the boolean and propositional formulations of a
    claim are equivalent from a purely logical perspective, we have
    also seen that they need not be equivalent _operationally_.
    Equality provides an extreme example: knowing that [beq_nat n m =
    true] is generally of little help in the middle of a proof
    involving [n] and [m]; however, if we convert the statement to the
    equivalent form [n = m], we can rewrite with it.

    The case of even numbers is also interesting.  Recall that, when
    proving the backwards direction of
    [even_bool_prop] ([evenb_double], going from the propositional to
    the boolean claim), we used a simple induction on [k]).  On the
    other hand, the converse (the [evenb_double_conv] exercise)
    required a clever generalization, since we can't directly prove
    [(exists k, n = double k) -> evenb n = true].

    For these examples, the propositional claims were more useful than
    their boolean counterparts, but this is not always the case.  For
    instance, we cannot test whether a general proposition is true or
    not in a function definition; as a consequence, the following code
    fragment is rejected: *)

Fail Definition is_even_prime n :=
  if n = 2 then true
  else false.

(** Coq complains that [n = 2] has type [Prop], while it expects an
    elements of [bool] (or some other inductive type with two
    elements).  The reason for this error message has to do with the
    _computational_ nature of Coq's core language, which is designed
    so that every function that it can express is computable and
    total.  One reason for this is to allow the extraction of
    executable programs from Coq developments.  As a consequence,
    [Prop] in Coq does _not_ have a universal case analysis operation
    telling whether any given proposition is true or false, since such
    an operation would allow us to write non-computable functions.

    Although general non-computable properties cannot be phrased as
    boolean computations, it is worth noting that even many
    _computable_ properties are easier to express using [Prop] than
    [bool], since recursive function definitions are subject to
    significant restrictions in Coq.  For instance, the next chapter
    shows how to define the property that a regular expression matches
    a given string using [Prop].  Doing the same with [bool] would
    amount to writing a regular expression matcher, which would be
    more complicated, harder to understand, and harder to reason
    about.

    Conversely, an important side benefit of stating facts using
    booleans is enabling some proof automation through computation
    with Coq terms, a technique known as _proof by
    reflection_. Consider the following statement: *)

Example even_1000 : exists k, 1000 = double k.

(** The most direct proof of this fact is to give the value of [k]
    explicitly. *)

 Proof. exists 500. reflexivity. Qed.

(** On the other hand, the proof of the corresponding boolean
    statement is even simpler: *)

Example even_1000' : evenb 1000 = true.
Proof. reflexivity. Qed.

(** What is interesting is that, since the two notions are equivalent,
    we can use the boolean formulation to prove the other one without
    mentioning 500 explicitly: *)

Example even_1000'' : exists k, 1000 = double k.
Proof. apply even_bool_prop. reflexivity. Qed.

(** Although we haven't gained much in terms of proof size in this
    case, larger proofs can often be made considerably simpler by the
    use of reflection.  As an extreme example, the Coq proof of the
    famous _4-color theorem_ uses reflection to reduce the analysis of
    hundreds of different cases to a boolean computation.  We won't
    cover reflection in great detail, but it serves as a good example
    showing the complementary strengths of booleans and general
    propositions. *)

(** **** Exercise: 2 stars (logical_connectives)  *)
(** The following lemmas relate the propositional connectives studied
    in this chapter to the corresponding boolean operations. *)

Lemma andb_true_iff : forall b1 b2:bool,
  b1 && b2 = true <-> b1 = true /\ b2 = true.
Proof.
  intros. split.
  intros.
  + split. destruct b1. reflexivity. destruct H. reflexivity.
    destruct b1. destruct H. simpl.  reflexivity.  simpl in H. inversion H.
  + intros. destruct H. rewrite H. rewrite H0. reflexivity.
Qed.

Lemma orb_true_iff : forall b1 b2,
  b1 || b2 = true <-> b1 = true \/ b2 = true.
Proof.
  intros. split. destruct b1.
  +  simpl. intros. left. reflexivity.
  + intros.  destruct b2.
    - right. reflexivity.
    - destruct H.  simpl.  left.  reflexivity.
      + intros. destruct H. rewrite H. simpl. reflexivity. rewrite H. simpl. destruct b1.  simpl. reflexivity. simpl. reflexivity.
Qed.

(** [] *)

(** **** Exercise: 1 star (beq_nat_false_iff)  *)
(** The following theorem is an alternate "negative" formulation of
    [beq_nat_true_iff] that is more convenient in certain
    situations (we'll see examples in later chapters). *)

Theorem beq_nat_false_iff : forall x y : nat,
  beq_nat x y = false <-> x <> y.
Proof.
  intros. split.
  + intros h1 h2.
    rewrite h2 in h1. rewrite <- beq_nat_refl in h1. inversion h1.
  + intros h1. destruct (beq_nat x y) eqn:x_eq_y.
    - apply beq_nat_true in x_eq_y. elim h1. assumption.
    - reflexivity.
Qed.

(** Exercise: 3 stars (beq_list)  *)
(** Given a boolean operator [beq] for testing equality of elements of
    some type [A], we can define a function [beq_list beq] for testing
    equality of lists with elements in [A].  Complete the definition
    of the [beq_list] function below.  To make sure that your
    definition is correct, prove the lemma [beq_list_true_iff]. *)

Fixpoint beq_list {A} (beq : A -> A -> bool)
(l1 l2 : list A) : bool :=
    match l1 with
    | nil => match l2  with
             | nil => true
             | t2::l2 => false
             end
    | h1 :: t1 =>
      match l2 with
      | nil => false
      | h2 :: t2 => (beq h1 h2) && (beq_list beq t1 t2)
      end
    end.

Lemma beq_list_true_iff :
  forall A (beq : A -> A -> bool),
    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->
    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.
Proof.
  intros A beq h1.
  induction l1 as [|a l1].
  + induction l2 as [|b l2].
    - split; reflexivity.
    - split;  intros h2; inversion h2.
  + induction l2 as [|b l2].
    - split; inversion 1.
    - simpl; split.
      * intros h2.
        apply andb_true_iff in h2.
        destruct h2 as [h2 h3].
        apply h1 in h2.
        apply IHl1 in h3.
        rewrite h2; rewrite h3; reflexivity.
      * intros h2.
        apply andb_true_iff.
        injection h2 as h3 h4.
        split. rewrite h1. assumption.
        rewrite -> IHl1.  assumption.
Qed.
        (**
  intros. induction l1.
  + induction l2.
    - simpl. split;  intros; reflexivity.
    - simpl. split; intros; inversion H0.
  + induction l2 as [|b l2].
    - split. inversion 1.  intros; inversion H0.
    - simpl. split.
      * intros. apply andb_true_iff in H0.  destruct H0.  apply H in H0. rewrite H0.
    * intros. inversion H0.
  + induction l2. split; split.
    - intros. inversion H0.
    - intros. inversion H0.
    - split.
      * intros. inversion H0. apply andb_true_iff in H2. destruct H2. apply H in H1. rewrite H1.
        destruct H0. injuection H2.

    reflexivity.     intros. induction l1.
    - induction l2.
      *  reflexivity.
      * inversion H0.
    - induction l2.
      * inversion 1.  destruct H0. inversion H0.
    - inversion H0.
    - inversion H0. rewrite andb_true_iff in H2.  destruct H2.  apply H in H1. rewrite H1.

      destruct H2.
*)

(** [] *)

(** **** Exercise: 2 stars, recommended (All_forallb)  *)
(** Recall the function [forallb], from the exercise
    [forall_exists_challenge] in chapter [Tactics]: *)

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => true
  | x :: l' => andb (test x) (forallb test l')
  end.

(** Prove the theorem below, which relates [forallb] to the [All]
    property of the above exercise. *)

Theorem forallb_true_iff : forall X test (l : list X),
   forallb test l = true <-> All (fun x => test x = true) l.
Proof.
  intros. split.
  + intros.  induction l.
    - simpl. reflexivity.
    - simpl.  simpl in H. rewrite  andb_true_iff in H. destruct H.  split. assumption.  apply IHl.  assumption.
  + intros. induction l.
    - reflexivity.
    - simpl.  simpl in H. rewrite andb_true_iff. destruct H. split. assumption. apply IHl. assumption.
Qed.

(** Are there any important properties of the function [forallb] which
    are not captured by your specification? *)

(* FILL IN HERE *)
(** [] *)

(** ** Classical vs. Constructive Logic *)

(** We have seen that it is not possible to test whether or not a
    proposition [P] holds while defining a Coq function.  You may be
    surprised to learn that a similar restriction applies to _proofs_!
    In other words, the following intuitive reasoning principle is not
    derivable in Coq: *)

Definition excluded_middle := forall P : Prop,
  P \/ ~ P.

(** To understand operationally why this is the case, recall that, to
    prove a statement of the form [P \/ Q], we use the [left] and
    [right] tactics, which effectively require knowing which side of
    the disjunction holds.  However, the universally quantified [P] in
    [excluded_middle] is an _arbitrary_ proposition, which we know
    nothing about.  We don't have enough information to choose which
    of [left] or [right] to apply, just as Coq doesn't have enough
    information to mechanically decide whether [P] holds or not inside
    a function.  On the other hand, if we happen to know that [P] is
    reflected in some boolean term [b], then knowing whether it holds
    or not is trivial: we just have to check the value of [b].  This
    leads to the following theorem: *)

Theorem restricted_excluded_middle : forall P b,
  (P <-> b = true) -> P \/ ~ P.
Proof.
  intros P [] H.
  - left. rewrite H. reflexivity.
  - right. rewrite H. intros contra. inversion contra.
Qed.

(** In particular, the excluded middle is valid for equations [n = m],
    between natural numbers [n] and [m].

    You may find it strange that the general excluded middle is not
    available by default in Coq; after all, any given claim must be
    either true or false.  Nonetheless, there is an advantage in not
    assuming the excluded middle: statements in Coq can make stronger
    claims than the analogous statements in standard mathematics.
    Notably, if there is a Coq proof of [exists x, P x], it is
    possible to explicitly exhibit a value of [x] for which we can
    prove [P x] -- in other words, every proof of existence is
    necessarily _constructive_.  Because of this, logics like Coq's,
    which do not assume the excluded middle, are referred to as
    _constructive logics_.  More conventional logical systems such as
    ZFC, in which the excluded middle does hold for arbitrary
    propositions, are referred to as _classical_.

    The following example illustrates why assuming the excluded middle
    may lead to non-constructive proofs: *)

(** _Claim_: There exist irrational numbers [a] and [b] such that [a ^
    b] is rational.

    _Proof_: It is not difficult to show that [sqrt 2] is irrational.
    If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =
    sqrt 2] and we are done.  Otherwise, [sqrt 2 ^ sqrt 2] is
    irrational.  In this case, we can take [a = sqrt 2 ^ sqrt 2] and
    [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^
    2 = 2].  []

    Do you see what happened here?  We used the excluded middle to
    consider separately the cases where [sqrt 2 ^ sqrt 2] is rational
    and where it is not, without knowing which one actually holds!
    Because of that, we wind up knowing that such [a] and [b] exist
    but we cannot determine what their actual values are (at least,
    using this line of argument).

    As useful as constructive logic is, it does have its limitations:
    There are many statements that can easily be proven in classical
    logic but that have much more complicated constructive proofs, and
    there are some that are known to have no constructive proof at
    all!  Fortunately, like functional extensionality, the excluded
    middle is known to be compatible with Coq's logic, allowing us to
    add it safely as an axiom.  However, we will not need to do so in
    this book: the results that we cover can be developed entirely
    within constructive logic at negligible extra cost.

    It takes some practice to understand which proof techniques must
    be avoided in constructive reasoning, but arguments by
    contradiction, in particular, are infamous for leading to
    non-constructive proofs.  Here's a typical example: suppose that
    we want to show that there exists [x] with some property [P],
    i.e., such that [P x].  We start by assuming that our conclusion
    is false; that is, [~ exists x, P x]. From this premise, it is not
    hard to derive [forall x, ~ P x].  If we manage to show that this
    intermediate fact results in a contradiction, we arrive at an
    existence proof without ever exhibiting a value of [x] for which
    [P x] holds!

    The technical flaw here, from a constructive standpoint, is that
    we claimed to prove [exists x, P x] using a proof of [~ ~ exists
    x, P x]. However, allowing ourselves to remove double negations
    from arbitrary statements is equivalent to assuming the excluded
    middle, as shown in one of the exercises below.  Thus, this line
    of reasoning cannot be encoded in Coq without assuming additional
    axioms. *)

(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)
(** The consistency of Coq with the general excluded middle axiom
    requires complicated reasoning that cannot be carried out within
    Coq itself.  However, the following theorem implies that it is
    always safe to assume a decidability axiom (i.e., an instance of
    excluded middle) for any _particular_ Prop [P].  Why? Because we
    cannot prove the negation of such an axiom; if we could, we would
    have both [~ (P \/ ~P)] and [~ ~ (P \/ ~P)], a contradiction. *)

Theorem excluded_middle_irrefutable:  forall (P:Prop),
  ~ ~ (P \/ ~ P).
Proof.
  unfold not.
  intros. apply H. right. intros. apply H. left. assumption.
Qed.
  (** [] *)

(** **** Exercise: 3 stars, optional (not_exists_dist)  *)
(** It is a theorem of classical logic that the following two
    assertions are equivalent:

    ~ (exists x, ~ P x)
    forall x, P x

    The [dist_not_exists] theorem above proves one side of this
    equivalence. Interestingly, the other direction cannot be proved
    in constructive logic. Your job is to show that it is implied by
    the excluded middle. *)

Theorem not_exists_dist :
  excluded_middle ->
  forall (X:Type) (P : X -> Prop),
    ~ (exists x, ~ P x) -> (forall x, P x).
Proof.
  cbv. intros em X P h2 x. destruct  (em (P x)). assumption. elim h2.
  exists x.  assumption.
Qed.

Check not_exists_dist.
(** [] *)

(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)
(** For those who like a challenge, here is an exercise taken from the
    Coq'Art book by Bertot and Casteran (p. 123).  Each of the
    following four statements, together with [excluded_middle], can be
    considered as characterizing classical logic.  We can't prove any
    of them in Coq, but we can consistently add any one of them as an
    axiom if we wish to work in classical logic.

    Prove that all five propositions (these four plus
    [excluded_middle]) are equivalent. *)

Definition peirce := forall P Q: Prop,
  ((P->Q)->P)->P.

Definition double_negation_elimination := forall P:Prop,
  ~~P -> P.

Definition de_morgan_not_and_not := forall P Q:Prop,
  ~(~P /\ ~Q) -> P\/Q.

Definition implies_to_or := forall P Q:Prop,
  (P->Q) -> (~P\/Q).

Check implies_to_or.
Theorem peirce_double_neg_elim : peirce -> double_negation_elimination.
Proof.
  cbv. intros. specialize (H P False). apply H. intros. contradiction.
Qed.

Theorem double_negation_elimination_de_morgan_not_and_not: double_negation_elimination -> de_morgan_not_and_not.
Proof.
  intros dne P Q H.  red in dne.
   apply dne.  intro H2. apply H.
   split. intro H3. apply H2. left. assumption.  intro H3.   apply H2. right. assumption.
Qed.

Check double_negation_elimination_de_morgan_not_and_not.

Theorem de_morgan_not_and_not_implies_to_or:
  de_morgan_not_and_not -> implies_to_or.
Proof.
  intros dm P Q H. red in dm. apply dm.  hnf.  intros [nnp nq].
  apply nnp. intro H2. apply H in H2.  contradiction.
Qed.

Theorem implies_to_or_excluded_middle: implies_to_or -> excluded_middle.
Proof.
  intros.  red. intros. red in H. specialize (H (P) P).
  rewrite or_comm.
  apply H.  intros. assumption.
Qed.

Check implies_to_or_excluded_middle.

Theorem excluded_middle_peirce : excluded_middle -> peirce.
Proof.
  cbv. intros em P Q H.  destruct (em P) as [p|np].
  assumption. apply H. intros. contradiction.
Qed.

Check excluded_middle_peirce.
(** [] *)

(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)


Require Import List.
Open Scope list_scope.

Section BooleanValuedFunction.

  (* a ∈ l *)
  Definition elem {A : Type} (eqb : A -> A -> bool) (l : list A) (a : A) :=
    fold_left orb (map (eqb a) l) false.

  Goal forall (l : list bool), fold_left orb (true :: l) false = true.
  Proof.
    induction l.
    - reflexivity.
    - simpl in IHl.
      simpl.
      now rewrite IHl.
  Qed.

  Check filter.
  (* l1 ∩ l2 *)
  Fixpoint intersection {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A) :=
     filter (elem eqb l2) l1.

  Compute intersection Nat.eqb (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil) (3 :: 6 :: 9 :: nil).

  Definition not_elem {A : Type} (eqb : A -> A -> bool) (l : list A) (a : A) :=
    negb (elem eqb l a).

  (* l1 \ l2 *)
  Fixpoint sub {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A) :=
    filter (not_elem eqb l2) l1.

  Compute sub Nat.eqb (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil) (2 :: 4 :: 5 :: nil).
End BooleanValuedFunction.

Require Import Extraction.
Extraction Language Haskell.
Extract Inductive list => "([])" ["[]" "(:)"].
Extract Inductive bool => "Prelude.Bool" ["Prelude.True" "Prelude.False"].
Extraction "difflist2.hs" intersection sub.


(** * Introduction *)
(** ** Booleans *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

Definition negb (b:bool) : bool :=
  match b with
  | true => false
  | false => true
  end.

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Definition orb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => true
  | false => b2
  end.

(** **** Exercise: 1 star (nandb) *)
(** Complete the definition of the following function, then make
    sure that the [Example] assertions below can each be verified by
    Coq.  *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  match b1 with
    | true => negb b2
    | false => true
  end.

Example test_nandb1:               (nandb true false) = true.
Proof. reflexivity. Qed.
Example test_nandb2:               (nandb false false) = true.
Proof. reflexivity. Qed.
Example test_nandb3:               (nandb false true) = true.
Proof. reflexivity. Qed.
Example test_nandb4:               (nandb true true) = false.
Proof. reflexivity. Qed.

(** **** Exercise: 1 star (andb3) *)
(** Do the same for the [andb3] function below. This function should
    return [true] when all of its inputs are [true], and [false]
    otherwise. *)

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  match b1 with
    | true => andb b2 b3
    | false => false
  end.

Example test_andb31:                 (andb3 true true true) = true.
Proof. reflexivity. Qed.
Example test_andb32:                 (andb3 false true true) = false.
Proof. reflexivity. Qed.
Example test_andb33:                 (andb3 true false true) = false.
Proof. reflexivity. Qed.
Example test_andb34:                 (andb3 true true false) = false.
Proof. reflexivity. Qed.

(** ** Numbers *)

Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n'
  end.

Fixpoint evenb (n:nat) : bool :=
  match n with
  | O        => true
  | S O      => false
  | S (S n') => evenb n'
  end.

Definition oddb (n:nat) : bool   :=   negb (evenb n).

Fixpoint exp (base power : nat) : nat :=
  match power with
    | O => S O
    | S p => mult base (exp base p)
  end.

(** **** Exercise: 1 star (factorial) *)
(** Recall the standard factorial function:
<<
    factorial(0)  =  1
    factorial(n)  =  n * factorial(n-1)     (if n>0)
>>
    Translate this into Coq. *)

Fixpoint factorial (n : nat) : nat :=
  match n with
    | O => 1
    | S n' => mult n (factorial n')
  end.

Example test_factorial1:          (factorial 3) = 6.
Proof. reflexivity. Qed.
Example test_factorial2:          (factorial 5) = (mult 10 12).
Proof. reflexivity. Qed.

Fixpoint beq_nat (n m : nat) : bool :=
  match n with
  | O => match m with
         | O => true
         | S m' => false
         end
  | S n' => match m with
            | O => false
            | S m' => beq_nat n' m'
            end
  end.

Fixpoint ble_nat (n m : nat) : bool :=
  match n with
  | O => true
  | S n' =>
      match m with
      | O => false
      | S m' => ble_nat n' m'
      end
  end.

(** **** Exercise: 2 stars (blt_nat) *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for
    this one, define it in terms of a previously defined function.

    Note: If you have trouble with the [simpl] tactic, try using
    [compute], which is like [simpl] on steroids.  However, there is a
    simple, elegant solution for which [simpl] suffices. *)

Definition blt_nat (n m : nat) : bool :=
  match n with
    | O => ble_nat (S O) m
    | n' => ble_nat (S n') m
  end.

Example test_blt_nat1:             (blt_nat 2 2) = false.
Proof. simpl. reflexivity. Qed.
Example test_blt_nat2:             (blt_nat 2 4) = true.
Proof. simpl. reflexivity. Qed.
Example test_blt_nat3:             (blt_nat 4 2) = false.
Proof. simpl. reflexivity. Qed.

(** * Proof by Simplification *)

Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
  intros n. reflexivity.  Qed.

Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
  intros n. reflexivity.  Qed.

Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
  intros n. reflexivity.  Qed.

(** * Proof by Rewriting *)

Theorem plus_id_example : forall n m:nat,
  n = m ->
  n + n = m + m.

Proof.
  intros n m.   (* move both quantifiers into the context *)
  intros H.     (* move the hypothesis into the context *)
  rewrite <- H. (* Rewrite the goal using the hypothesis *)
  reflexivity.  Qed.

(** **** Exercise: 1 star (plus_id_exercise) *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  intros n m o.
  intros H1.
  rewrite -> H1.
  intros H2.
  rewrite -> H2.
  reflexivity. Qed.

Theorem mult_0_plus : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_O_n.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (mult_S_1) *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  intros n m.
  intros H.
  rewrite -> H.
  reflexivity. Qed.

(** * Proof by Case Analysis *)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b. destruct b.
    reflexivity.
    reflexivity.  Qed.

(** **** Exercise: 1 star (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  intros n. destruct n as [|n'].
  reflexivity.
  reflexivity.  Qed.

(** * More Exercises *)

(** **** Exercise: 2 stars (boolean functions) *)
(** Use the tactics you have learned so far to prove the following
    theorem about boolean functions. *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros.
  rewrite -> H.
  rewrite -> H.
  reflexivity. Qed.

(** Now state and prove a theorem [negation_fn_applied_twice] similar
    to the previous one but where the second hypothesis says that the
    function [f] has the property that [f x = negb x].*)

Theorem negation_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = negb x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros.
  rewrite -> H.
  rewrite -> H.
  rewrite -> negb_involutive.
  reflexivity. Qed.

(** **** Exercise: 2 stars (andb_eq_orb) *)
(** Prove the following theorem.  (You may want to first prove a
    subsidiary lemma or two. Alternatively, remember that you do
    not have to introduce all hypotheses at the same time.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  intros b c. destruct b. destruct c.
  simpl. reflexivity.
  simpl. intros H. rewrite -> H.
  reflexivity.
  simpl. intros H. rewrite -> H.
  reflexivity.
Qed.

(** **** Exercise: 3 stars (binary) *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

      - zero,
      - twice a binary number, or
      - one more than twice a binary number.

    (a) First, write an inductive definition of the type [bin]
        corresponding to this description of binary numbers.

    (Hint: Recall that the definition of [nat] from class,
    Inductive nat : Type :=
      | O : nat
      | S : nat -> nat.
    says nothing about what [O] and [S] "mean."  It just says "[O] is
    in the set called [nat], and if [n] is in the set then so is [S
    n]."  The interpretation of [O] as zero and [S] as successor/plus
    one comes from the way that we _use_ [nat] values, by writing
    functions to do things with them, proving things about them, and
    so on.  Your definition of [bin] should be correspondingly simple;
    it is the functions you will write next that will give it
    mathematical meaning.)

    (b) Next, write an increment function for binary numbers, and a
        function to convert binary numbers to unary numbers.

    (c) Write some unit tests for your increment and binary-to-unary
        functions. Notice that incrementing a binary number and
        then converting it to unary should yield the same result as first
        converting it to unary and then incrementing.
*)

(* TODO *)

(** * Optional Material *)

(** **** Exercise: 2 stars, optional (decreasing) *)
(** To get a concrete sense of this, find a way to write a sensible
    [Fixpoint] definition (of a simple function on numbers, say) that
    _does_ terminate on all inputs, but that Coq will _not_ accept
    because of this restriction. *)

(* TODO See https://github.com/etosch/software_foundations/blob/master/lesson1_Basics.v *)


Require Import Arith Omega.

Theorem complete_ind : forall P, (forall n, (forall i, i < n -> P i) -> P n) -> forall n, P n.
Proof.
  intros ? IH m.
  assert (H : forall i, i <= m -> P i).
  - induction m; intros i ?.
    + apply IH.
      intros.
      omega.
    + destruct (eq_nat_dec i m);
        [| apply IH; intros ];
        apply IHm;
        omega.
  - apply H.
    omega.
Qed.


(***************************** LIFLF - TPA ************************************)
(************* Evaluation pratique en temps limité : 30' **********************)
(******************************************************************************)

Require Import Arith.
Require Import List.
Export ListNotations.

(* Partie 1. Exercices sur les listes d'entiers *)
(* -------------------------------------------- *)

(* EXERCICE *)
(* Écrire la fonction "lgr" qui calcule la longueur d'une liste de nat (et donc de type list nat) *)
Fixpoint lgr (l : list nat) : nat :=
match l with
|[] => 0
|n::l' => 1 + lgr l'
end.

Example ex_lgr : (lgr (1::2::3::4::5::[])) = 5.
Proof. cbv. reflexivity. Qed.

(* EXERCICE *)
(* Écrire la fonction "mir" qui calcule le miroir d'une liste de nat *)
Fixpoint mir (l : list nat) : list nat :=
  match l with
  |[] => []
  |n::l' => (mir l')++(n::[])
end.

Example ex_mir : (mir (1::2::3::4::5::[])) = 5::4::3::2::1::[].
Proof. cbv. reflexivity. Qed.

(* EXERCICE *)
(* Exprimer et prouver que le miroir d'une liste à laquelle on a ajouté un élément en tête
   est le miroir de la liste concaténé à la liste constituée de juste cet élément *)
Theorem miroirEtConcat (l : list nat) (n : nat) : mir (n::l) = (mir l)++(n::[]).
Proof.
induction l as [ | n'].
-simpl.
reflexivity.
-simpl.
reflexivity.
Qed.
(* Partie 2. Exercices sur les arbres binaires *)
(* ------------------------------------------- *)

(* On donne le type "btree" des arbres binaires avec valeurs de type nat stockées dans les feuilles *)
Inductive btree : Type :=
| F : nat -> btree
| N : btree -> btree -> btree
.

(* exemples *)
(* L'arbre "ab1" :  o    et "ab2" :    o
                   / \                / \
                  o   2              1   o
                 / \                    / \
                1   o                  o   5
                   / \                / \
                  o   3              2   o
                 / \                    / \
                4   5                  3   4
*)
(* On donne l'arbre "ab1" : *)
Definition ab1 := N (N (F 1) (N (N (F 4) (F 5)) (F 3))) (F 2).

(* EXERCICE *)
(* Définir l'arbre "ab2" correspondant à l'exemple ci-dessus *)
Definition ab2 := N (F 1) (N (N (F 2) (N (F 3) (F 4))) (F 5)).

(* EXERCICE *)
(* Écrire la fonction "bnbf" qui calcule le nombre de feuilles d'un tel arbre *)
Fixpoint bnbf (ab : btree) : nat :=
match ab with
|F n => 1
|N abG abD => bnbf abG + bnbf abD
end.

Example ex_bnbf_ab1 : (bnbf ab1) = 5.
Proof. cbv. reflexivity. Qed.

(* EXERCICE *)
(* Écrire la fonction "bnbn" qui calcule le nombre de noeuds d'un tel arbre *)
Fixpoint bnbn (ab : btree) : nat :=
match ab with
|F n => 0
|N abG abD => 1 + bnbn abG + bnbn abD
end.

Example ex_bnbn_ab1 : (bnbn ab1) = 4.
Proof. cbv. reflexivity. Qed.

(* EXERCICE *)
(* Écrire la fonction "bsumval" qui calcule la somme des valeurs contenues dans l'arbre *)
Fixpoint bsumval (ab : btree) : nat :=
match ab with
|F n => n
|N abG abD => bsumval abG + bsumval abD
end.

Example ex_bsumval_ab1 : (bsumval ab1) = 15.
Proof. cbv. reflexivity. Qed.

(* EXERCICE *)
(* Écrire la fonction "bajout" qui ajoute un élément dans un arbre *)
Fixpoint bajout (x : nat)(ab : btree): btree :=
match ab with
|F n => N (F n) (F x)
|N abG abD => N abG (bajout x abD)
end.

Example ex_bajout_ab1 : bnbf (bajout 10 ab1) = 1 + bnbf ab1.
Proof. cbv. reflexivity. Qed.


Require Import bool.
Require Import nat.
Require Import list.
Require Import fmap.
Require Import In.
Require Import induction.

Example test_In1 : In 4 [3,4,5].
Proof. simpl. right. left. reflexivity. Qed.

Example test_In2 : forall n,
    In n [2,4] -> exists m, n = 2 * m.
Proof.
    simpl. intros n [H|[H|H]].
    - exists 1. symmetry in H. apply H.
    - exists 2. symmetry in H. apply H.
    - inversion H.
Qed.

Definition combine_odd_even (Po Pe:nat -> Prop) (n:nat) : Prop :=
    if oddb n then Po n else Pe n.

Theorem combine_odd_even_intro : forall (Po Pe:nat -> Prop) (n:nat),
    (oddb n = true -> Po n)  ->
    (oddb n = false -> Pe n) ->
    combine_odd_even Po Pe n.
Proof.
    intros Po Pe n Ho He. destruct (oddb n) eqn:H.
    - unfold combine_odd_even. rewrite H. apply Ho. reflexivity.
    - unfold combine_odd_even. rewrite H. apply He. reflexivity.
Qed.

Theorem combine_odd_even_elim_odd : forall (Po Pe:nat -> Prop) (n:nat),
    combine_odd_even Po Pe n -> oddb n = true -> Po n.
Proof.
    intros Po Pe n H H'. unfold combine_odd_even in H. rewrite H' in H. exact H.
Qed.

Theorem combine_odd_even_elim_even : forall (Po Pe:nat -> Prop) (n:nat),
    combine_odd_even Po Pe n -> oddb n = false -> Pe n.
Proof.
    intros Po Pe n H H'. unfold combine_odd_even in H. rewrite H' in H. exact H.
Qed.

Example lemma_application_ex1 : forall (n:nat) (ns:list nat),
    In n (map (fun m => m * 0) ns) -> n = 0.
Proof.
    intros n ns. induction ns as [|x xs H].
    - intros H. inversion H.
    - simpl. intros [H'|H'].
        + rewrite mult_n_0 in H'. symmetry. exact H'.
        + apply H. exact H'.
Qed.


Section Group.
  Variable G : Set.
  Variable op : G -> G -> G.
  Variable e : G.
  Notation "x * y" := (op x y).
  (* Axioms for the Group *)
  Definition Identity (g : G) := forall x:G, x * g = x /\ g * x = x.
  Axiom G1: Identity e.
  Axiom G2: forall x y z:G, (x * y) * z = x * (y * z).
  Axiom G3: forall x:G, exists y:G, x * y = e.
  Theorem IdentityUniqueness : forall (x : G) (y : G), (Identity x /\ Identity y) -> (x = y).
    Proof.
      intros.
      destruct H.
      assert (x = x * y).
      unfold Identity in H0.
      destruct (H0 x).
      symmetry.
      assumption.
      assert (x * y = y).
      unfold Identity in H.
      destruct (H y).
      assumption.
      transitivity (x * y).
      assumption.
      assumption.
  Qed.
Print IdentityUniqueness.
End Group