(*
I hereby assign copyright in my past and future contributions
to the Software Foundations project to the Author of Record of
each volume or component, to be licensed under the same terms
as the rest of Software Foundations. I understand that, at present,
the Authors of Record are as follows: For Volumes 1 and 2, known
until 2016 as "Software Foundations" and from 2016 as (respectively)
"Logical Foundations" and "Programming Foundations," and for Volume 4,
"QuickChick: Property-Based Testing in Coq," the Author of Record is
Benjamin C. Pierce. For Volume 3, "Verified Functional Algorithms",
the Author of Record is Andrew W. Appel. For components outside of
designated volumes (e.g., typesetting and grading tools and other
software infrastructure), the Author of Record is Benjamin Pierce.
*)

From LF Require Export Basics.

(* ################################################################# *)
(** * Proof by Induction *)

Theorem plus_n_O_firsttry : forall n:nat,
  n = n + 0.

Proof.
  intros n.
  simpl. (* Does nothing! *)
Abort.

Theorem plus_n_O_secondtry : forall n:nat,
  n = n + 0.
Proof.
  intros n. destruct n as [| n'].
  - (* n = 0 *)
    reflexivity. (* so far so good... *)
  - (* n = S n' *)
    simpl.       (* ...but here we are stuck again *)
Abort.

Theorem plus_n_O : forall n:nat, n = n + 0.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)    reflexivity.
  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.

Theorem minus_diag : forall n,
  minus n n = 0.
Proof.
  (* WORKED IN CLASS *)
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    simpl. reflexivity.
  - (* n = S n' *)
    simpl. rewrite -> IHn'. reflexivity.  Qed.

(** **** Exercise: 2 stars, recommended (basic_induction)  *)
(** Prove the following using induction. You might need previously
    proven results. *)

Theorem mult_0_r : forall n:nat,
  n * 0 = 0.
Proof.
  intros. induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite -> IHn'. reflexivity.  Qed.

Theorem plus_n_Sm : forall n m : nat,
  S (n + m) = n + (S m).
Proof.
    intros. induction n as [|n' IHn'].
    reflexivity.
    simpl. rewrite -> IHn'. reflexivity.  Qed.

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros. induction n as [|n' IHn'].
  - rewrite <- plus_n_O.
    + reflexivity.
  - simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity.  Qed.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros. induction n as [|n' IHn'].
  reflexivity.
  simpl. rewrite -> IHn'. reflexivity.  Qed.

(** **** Exercise: 2 stars (double_plus)  *)
(** Consider the following function, which doubles its argument: *)

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

(** Use induction to prove this simple fact about [double]: *)

Lemma double_plus : forall n, double n = n + n .
Proof.
  intros. induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity.  Qed.

Theorem double_plus_2:
  forall m n: nat, double m + double n = double (m + n).

Proof. (*FILL IN HERE *)
  intros. induction m as [|n' IHn'].
  reflexivity.
  simpl. rewrite IHn'. reflexivity. Qed.

(** **** Exercise: 2 stars, optional (evenb_S)  *)
(** One inconvenient aspect of our definition of [evenb n] is the
    recursive call on [n - 2]. This makes proofs about [evenb n]
    harder when done by induction on [n], since we may need an
    induction hypothesis about [n - 2]. The following lemma gives an
    alternative characterization of [evenb (S n)] that works better
    with induction: *)

Theorem evenb_S : forall n : nat,
  evenb (S n) = negb (evenb n).
Proof.
  intros. induction n as [|n' IHn'].
  reflexivity.
  rewrite IHn'.
  simpl.
  rewrite negb_involutive.
  reflexivity.
  Qed.


(*|
###################################
How to give a counterxample in Coq?
###################################

:Link: https://stackoverflow.com/q/13862940
|*)

(*|
Question
********

Is it possible to give a counterexample for a statement which doesn't
hold in general? Like, for example that the all quantor does not
distribute over the connective ``or``. How would you state that to
begin with?
|*)

Parameter X : Set.
Parameter P : X -> Prop.
Parameter Q : X -> Prop.

(* This holds in general *)
Theorem forall_distributes_over_and :
  (forall x : X, P x /\ Q x) -> (forall x : X, P x) /\ (forall x : X, Q x).
Proof.
  intro H. split. apply H. apply H.
Qed.

(* This doesn't hold in general *)
Theorem forall_doesnt_distributes_over_or :
  (forall x : X, P x \/ Q x) -> (forall x : X, P x) \/ (forall x : X, Q x).
Abort.

(*|
Answer (Ptival)
***************

Here is a quick and dirty way to prove something similar to what you
want:
|*)

Theorem forall_doesnt_distributes_over_or :
  ~ (forall X P Q, (forall x : X, P x \/ Q x) ->
                   (forall x : X, P x) \/ (forall x : X, Q x)).
Proof.
  intros H.
  assert (X : forall x : bool, x = true \/ x = false).
  - destruct x; intuition.
  - specialize (H _ (fun b => b = true) (fun b => b = false) X).
    destruct H as [H | H].
    now specialize (H false).
    now specialize (H true).
Qed.

(*|
I have to quantify ``X``, ``P`` and ``Q`` inside the negation in order
to be able to provide the one I want. You couldn't quite do that with
your ``Parameter``\ s as they somehow fixed an abstract ``X``, ``P``
and ``Q``, thus making your theorem potentially true.
|*)

(*|
Answer (Yves)
*************

In general, if you want to produce a counterexample, you can state the
negation of the formula and then prove that this negation is
satisfied.
|*)


Definition sig_extract (A:Set) (P:A -> Prop) (x:sig P) : A :=
  match x with
  | exist a Ha => a
  end.

Theorem sig_extract_ok :
 forall (A:Set) (P:A -> Prop) (y:sig P), P (sig_extract A P y).
Proof.
 intros A P y; case y; simpl; trivial.
Qed.

Require Import ZArith.
Open Scope Z_scope.

Parameter
  div_pair :
    forall a b:Z,
      0 < b ->
      {p : Z * Z | a = fst p * b + snd p  /\ 0 <= snd p < b}.

Definition div_pair' : forall a b:Z, 0 < b -> Z * Z.
 intros a b Hb.
 apply (sig_extract _ _ (div_pair a b Hb)).
Defined.

Theorem div_pair'_ok :
 forall (a b:Z) (H:0 < b),
   let p := div_pair' a b H in
   a = fst p * b + snd p /\ 0 <= snd p < b.
 intros a b H.
 pattern (div_pair' a b H).
 unfold div_pair'; apply sig_extract_ok.
Qed.


(** Exercise sheet for lecture 4: Tactics in Coq.

Written by Ralph Matthes.
 *)

(** * Exercise 1
Formalize the solutions of exercise 1 of Lecture 1.

[[
For each of the following types, write down an element of that type, if it has one. If it does not have any elements, you should establish that this is the case. But first think how this can be done in type theory! It ought to be just another construction.

1.    A × (B + C) → A × B + A × C, given types A, B, C
2.    (A → A) → (A → A), given type A (for extra credit, write down five elements of this type)
3.    Id_nat (0, succ 0)
4.    ∑ (A : Universe) (A → empty) → empty
5.    ∏ (n : nat), ∑ (m : nat), (n = 2 * m) + (n = 2 * m + 1), assuming you have got arithmetic
6.    (∑ (x : A) B × P x) → B × ∑ (x : A) P x, given types A, B, and P : A → Universe
7.    B → (B → A) → A, given types A and B
8.    B → ∏ (A : Universe) (B → A) → A, given type B
9.    (∏ (A : Universe) (B → A) → A) → B, given type B
]]

For the present exercise, this means: state the formula as a lemma, give a proof interactively if there is a proof, and give a counter-example otherwise, i.e., give specific parameters and a proof of the negation of the statement.

More precise instructions and hints:

1. Use ⨿ in place of the + and pay attention to operator precedence.

2. Write a function that provides different elements for any natural number argument, not just five elements; for extra credits: state correctly that they are different - for a good choice of [A]; for more extra credits: prove that they are different.

3. An auxiliary function may be helpful - better recall the trick.

4. The symbol for Sigma-types is ∑, not Σ.

5. Same as 1; and there is need for module UniMath.Foundations.NaturalNumbers, e.g., for Lemma natpluscomm.

6.-9. no further particulars
*)

Require Import UniMath.Foundations.Preamble.
Require Import UniMath.Foundations.PartA.
Require Import UniMath.Foundations.NaturalNumbers.

(** * Exercise 2
Define two computable strict comparison operators for natural numbers based on the fact that m < n iff
n - m <> 0 iff (m+1) - n = 0. Prove that the two operators are equal (using function extensionality, i.e., [funextfunStatement] in the UniMath library).

It may be helpful to use the definitions of the exercises for lecture 2. The following lemmas on substraction sub in the natural numbers may be useful:

a) sub n (S m) = pred (sub n m)

b) sub 0 n = 0

c) pred (sub 1 n) = 0

d) sub (S n) (S m) = sub n m

*)

(** from exercises to Lecture 2: *)
Definition ifbool (A : UU) (x y : A) : bool -> A :=
  bool_rect (λ _ : bool, A) x y.

Definition negbool : bool -> bool := ifbool bool false true.

Definition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=
  nat_rect (λ _ : nat, A) a f.

Definition pred : nat -> nat := nat_rec nat 0 (fun x _ => x).

Definition is_zero : nat -> bool := nat_rec bool true (λ _ _, false).

Definition iter (A : UU) (a : A) (f : A → A) : nat → A :=
  nat_rec A a (λ _ y, f y).

Notation "f ̂ n" := (λ x, iter _ x f n) (at level 10).

Definition sub (m n : nat) : nat := pred ̂ n m.


From mathcomp Require Import ssreflect.

Set Implicit Arguments.
Unset Strict Implicit.
Import Prenex Implicits.

Require Import class_set.

Definition BinaryRelation (U:Type) := U -> U -> Prop.

Section BinaryRelation.

  Variable U:Type.
  Variable R: BinaryRelation U.

  Definition reflexive : Prop := forall (x:U), R x x.
  Definition transitive : Prop := forall (x y z:U), R x y -> R y z -> R x z.
  Definition symmetric : Prop := forall (x y:U), R x y -> R y x.
  Definition antisymmetric : Prop := forall (x y:U), R x y -> R y x -> x = y.
  Definition total_relation: Prop := forall (x y:U), R x y \/ R y x.

  Definition equivalence := reflexive /\ transitive /\ symmetric.
  Definition pre_order := reflexive /\ transitive.
  Definition partiality_order :=  pre_order /\ antisymmetric.
  Definition total_order := partiality_order /\ total_relation.

  Definition right_unique: Prop := forall (x y z:U), R x y -> R x z -> y = z.
  Definition left_total: Prop := forall (x:U), exists y:U, R x y.
  Definition functional_relaton: Prop := right_unique /\ left_total.

End BinaryRelation.


Require Import Coq.Setoids.Setoid.
Require Import Coq.Lists.List.
Require Import PeanoNat.
Require Import Bool.
Require Import Coq.Program.Basics.

(* Locate "*". *)
(* Definition aaa (l: (list nat * bool)): nat := fold_left mult 0 if evenb. *)

(* G - носитель группы *)
Class Semigroup G : Type :=
{
    mult : G -> G -> G;
    assoc : forall x y z:G,
        mult x (mult y z) = mult (mult x y) z
}.

Class Monoid G `{Hsemi: Semigroup G} : Type :=
{
  e : G;
  left_id : forall x: G, mult e x = x;
}.

Class Group G `{Hmono: Monoid G} : Type :=
{
    inv : G -> G;
    left_inv : forall x: G, mult (inv x) x = e;
}.

Class AbelianGroup G `{Hgr: Group G} : Type :=
{
    comm : forall (x y : G), mult x y = mult y x;
}.

Declare Scope group_scope.
Infix "*" := mult (at level 40, left associativity) : group_scope.
Open Scope group_scope.

Section Group_theorems.

  Variable G: Type.
  Context `{Hgr: Group G}.

  (* № 24 *)
  (* Вспомогательная лемма, нужна в дальнейшем *)
  (* Пусть a, b — произвольные элементы некоторой группы G. *)
  (* Доказать, что каждое из уравнений ax = b и ya = b *)
  (* имеет, и притом ровно одно, решение в данной группе. *)
  (* Условие единственности можно выразить *)
  (* следующим образом: если a*b1 = a*b2 или b1*a = b2*a, то *)
  (* b1 = b2. *)
  (* Set Printing All. *)
  Proposition left_cancel : forall a x y:G,
      a * x = a * y -> x = y.
  Proof.
    intros a x y H. assert (inv a * (a * x) = inv a * (a * y))
      as Hinvx.
    - rewrite H. reflexivity.
    - repeat rewrite assoc in Hinvx. rewrite left_inv in Hinvx. repeat rewrite left_id in Hinvx. assumption.
  Qed.

  Proposition left_cancel_alt_proof : forall a x y:G,
      a * x = a * y -> x = y.
  Proof.
    intros a x y H.
    (* Здесь самое интересное: по сути это умножение гипотезы слева на inv a *)
    (* f_equal : forall (A B : Type) (f : A -> B) (x y : A), *)
    (*    x = y -> f x = f y *)
    apply f_equal with (f := fun g:G => inv a * g) in H. repeat rewrite assoc in H. repeat rewrite left_inv in H. repeat rewrite left_id in H. assumption.
  Qed.

  Proposition right_id : forall x:G, x * e = x.
  Proof.
    intro. apply left_cancel with (a := inv x). rewrite assoc. repeat rewrite left_inv. rewrite left_id. reflexivity.
  Qed.

  Proposition right_inv:
    forall x:G, x * inv x = e.
  Proof.
    intro. apply left_cancel with (a := inv x). rewrite assoc.
    rewrite left_inv. rewrite left_id. rewrite right_id. reflexivity.
  Qed.

  Proposition right_inv_unique: forall x y:G, x * y = e -> inv x = y.
  Proof.
    intros x y H. apply left_cancel with (a := x). transitivity e.
    - apply right_inv.
    - symmetry. assumption.
  Qed.

  (* № 20.1 Доказать, что e^{−1} = e. *)
  Proposition e_inv : (inv e) = e.
  Proof.
    rewrite <- left_inv with (x:=e) at 2. rewrite right_id. reflexivity.
  Qed.

  (* № 20.2 Доказать, что (a^{−1})^{−1} = a. *)
  Proposition inv_involution : forall x:G, inv (inv x) = x.
  Proof.
    intro. apply right_inv_unique. apply left_inv.
  Qed.

  (* № 23.1 Доказать, что в произвольной группе: *)
  (* 1) (a*b)^{−1} = b^{−1} * a^{−1} *)
  Proposition inv_prod : forall x y:G, inv (x*y) = inv y * inv x.
  Proof.
    intros x y. apply right_inv_unique. rewrite assoc. rewrite <- assoc with (z := inv y). rewrite right_inv. rewrite right_id. rewrite right_inv. reflexivity.
  Qed.

  (* № 23.2 Доказать, что в произвольной группе: *)
  (* (a_1 * (a_2 * a_3) * ... a_n * a) = a * (a_1 * a_2 * a_3 * ... * e) *)
  Proposition extra1 : forall (a: G) (lst: list G), fold_left mult lst a = mult a (fold_left mult lst e).
  Proof.
    intros a lst. revert a. induction lst as [| a' lst' IH].
    - intros a. simpl. rewrite right_id. reflexivity.
    - intros a. simpl. rewrite left_id. rewrite IH. rewrite (IH a'). rewrite assoc. reflexivity.
  Qed.

  Definition commutator : G -> G -> G :=
    fun x y:G => x * y * inv x * inv y.

  Notation "[ x , y ]" := (commutator x y).

  Proposition commutator_inv : forall x y:G, inv [x, y] = [y, x].
  Proof.
    intros. unfold commutator. repeat rewrite inv_prod. repeat rewrite inv_involution. repeat rewrite assoc. reflexivity.
  Qed.

  Definition commutes_with : G -> G -> Prop :=
    fun x y:G => x * y = y * x.

  Proposition product_commutes :
    forall x y z:G, commutes_with x z -> commutes_with y z ->
               commutes_with (x * y) z.
  Proof.
    intros x y z Hxz Hyz. red. rewrite <- assoc. rewrite Hyz. rewrite assoc. rewrite Hxz. rewrite <- assoc. reflexivity.
  Qed.

  (* № 24.2 *)
  Proposition right_cancel : forall x y z:G, x * z = y * z -> x = y.
  Proof.
    intros x y z H. apply f_equal with (f := fun g:G => g * inv z) in H. repeat rewrite <- assoc in H. repeat rewrite right_inv in H. repeat rewrite right_id in H. assumption.
  Qed.

  (* № 19 Доказать, что для любого элемента a группы суще-
ствует единственный обратный элемент inv a. *)
  Proposition left_inv_unique: forall y: G, exists x: G, (x * y = e /\ forall x':G, x'*y = e -> x = x').
  Proof.
    intros y. exists (inv y). split.
    - apply left_inv.
    (* left_cancel : forall x y z:G, *)
    (* x * y = x * z -> y = z. *)
    - intros x' H. rewrite <- (left_inv y) in H. apply right_cancel in H. rewrite H. reflexivity.
  Qed.

  Proposition commutator_e_impl_commutes : forall x y:G, [x, y] = e -> commutes_with x y.
  Proof.
    intros x y H. red. unfold commutator in H. rewrite <- right_inv with (x:=y) in H. apply f_equal with (f := fun g:G => g * y) in H. rewrite <- assoc in H. rewrite left_inv in H. rewrite right_id in H.  rewrite <- (assoc y _ _) in H. rewrite left_inv in H. rewrite <- right_inv with (x:=x) in H. apply f_equal with (f := fun g:G => g * x) in H. rewrite <- assoc in H. rewrite left_inv in H. rewrite right_id in H. rewrite assoc in H. rewrite <- (assoc _ x _) in H. rewrite right_inv in H. rewrite right_id in H. assumption.
  Qed.

  Proposition commutes_impl_commutator_e : forall x y:G, commutes_with x y -> [x, y] = e.
  Proof.
    intros x y H. unfold commutator. red in H. apply f_equal with (f := fun g:G => g * inv x) in H. rewrite <- (assoc _ x _) in H. rewrite right_inv in H. rewrite right_id in H. apply f_equal with (f := fun g:G => g * inv y) in H. rewrite right_inv in H. assumption.
  Qed.

  (* Сопряжение, соединение *)
  Definition conjugation (x y: G) : G :=
    inv y * x * y.

  Notation "x ^ y" := (conjugation x y).

  Proposition xy_conj_e : forall x y z:G, (x^z) * (y^z)  = (x*y)^z.
  Proof.
    intros. unfold conjugation. rewrite <- (assoc (inv z) y z). rewrite (assoc (inv z * x * z) (inv z) (y * z)). rewrite <- (assoc ((inv z) * x) z (inv z)). rewrite right_inv. rewrite right_id. repeat rewrite assoc. reflexivity.
  Qed.

  Proposition e_conj_y_eq_e : forall x:G, e^x = e.
  Proof.
    intro. unfold conjugation. rewrite <- assoc. rewrite left_id. apply left_inv.
  Qed.

  Proposition x_conj_e_eq_x : forall x:G, x^e = x.
  Proof.
    intro. unfold conjugation. rewrite e_inv. rewrite left_id. rewrite right_id. reflexivity.
  Qed.

  Proposition x_min1 : forall x y:G, (inv x)^y = inv (x^y).
  Proof.
    intros. unfold conjugation. repeat rewrite inv_prod. rewrite inv_involution. rewrite assoc. reflexivity.
  Qed.

  Proposition x_y_z : forall x y z:G, (x^y)^z = x^(y*z).
  Proof.
    intros. unfold conjugation. rewrite inv_prod. repeat rewrite assoc. reflexivity.
  Qed.

  Proposition fold_unfold : forall lst: list G, inv (fold_left mult lst e) = fold_left mult (map inv (rev lst)) e.
  Proof.
    intro. induction lst as [| a lst' IH'].
    - simpl. apply e_inv.
    - simpl. rewrite left_id. rewrite extra1. rewrite inv_prod. rewrite IH'. rewrite map_app. simpl. rewrite fold_left_app. simpl. reflexivity.
  Qed.

  (* № 25 *)
  Proposition aa_e_commutative : forall a b: G, (forall x : G, x * x = e) -> commutes_with a b.
  Proof.
    intros a b He. specialize (He a) as Ha. specialize (He b) as Hb. rewrite <- Hb in Ha. apply f_equal with (f := fun g:G => b * g * b) in Ha. repeat rewrite assoc in Ha. rewrite <- (assoc (b*a) a b) in Ha. rewrite <- (assoc (b*b) b b) in Ha. rewrite Hb in Ha. rewrite left_id in Ha.
    specialize (He (a*b)) as Hab. rewrite <- Hab in Ha. apply f_equal with (f := fun g:G => g * (inv (a*b))) in Ha. rewrite <- (assoc (b*a) (a*b) (inv (a*b))) in Ha. rewrite <- (assoc (a*b) (a*b) (inv (a*b))) in Ha. rewrite right_inv in Ha. repeat rewrite right_id in Ha. unfold commutes_with. symmetry in Ha. assumption.
  Qed.

  Lemma aa_e_commutative' : (forall x : G, x * x = e) -> (forall x : G, x = inv x).
  Proof.
    intros. specialize (H x) as Hx. rewrite <- (left_inv x) in Hx. apply (right_cancel x (inv x) x) in Hx. assumption.
  Qed.

  Lemma aa_e_commutative'' : forall a b: G, (forall x : G, x * x = e) -> commutes_with a b.
  Proof.
    intros. unfold commutes_with. rewrite (aa_e_commutative' H a) at 2. rewrite (aa_e_commutative' H b) at 2. rewrite <- inv_prod. rewrite <- (aa_e_commutative' H (a*b)). reflexivity.
  Qed.

  Fixpoint pow (a: G) (n: nat) {struct n} : G :=
    match n with
    | 0 => e
    | S n' => a * (pow a n')
    end.

  Notation "a ** b" := (pow a b) (at level 35, right associativity).

  (* № 27 *)
  Proposition a_pow_m_n : forall (a: G) (n m: nat), (pow a n)*(pow a m) = pow a (n + m).
  Proof.
    intros. induction n as [| n' IH] ; simpl.
    - rewrite left_id. reflexivity.
    - rewrite <- IH. rewrite assoc. reflexivity.
  Qed.

  (* № 26 *)
  Proposition a_pow_m : forall (a: G) (n: nat), inv (pow a n) = pow (inv a) n.
  Proof.
    intros. apply right_cancel with (z := (pow a n)). rewrite left_inv. symmetry. induction n as [| n' IHn'].
    - simpl. apply left_id.
    - rewrite <- Nat.add_1_r at 1. rewrite <- (a_pow_m_n (inv a) n' 1). simpl. rewrite right_id. rewrite assoc. rewrite <- (assoc (pow (inv a) n') (inv a) a). rewrite left_inv. rewrite right_id. assumption.
  Qed.

  Proposition e_pow_n_eq_e : forall (n: nat), (pow e n) = e.
  Proof.
    intros. induction n as [| n' IH] ; simpl; try reflexivity.
    rewrite left_id. apply IH.
  Qed.

  (* № 28 *)
  Proposition theo_28 : forall (a: G) (n m: nat), (pow (pow a n) m) = pow a (n * m).
  Proof.
    intros. induction m as [| m' IH] ; simpl.
    - rewrite <- mult_n_O. simpl. reflexivity.
    - rewrite IH. rewrite Nat.mul_succ_r. rewrite Nat.add_comm. rewrite <- a_pow_m_n. reflexivity.
  Qed.

  Proposition a_pow_comm : forall (a: G) (n m: nat), commutes_with (pow a n) (pow a m).
  Proof.
    intros. unfold commutes_with. repeat rewrite a_pow_m_n. rewrite Nat.add_comm. reflexivity.
  Qed.

  (* Произведение всех элементов списка *)
  Fixpoint prod (lst : list G) :=
    match lst with
    | nil => e
    | h :: t => h * (prod t)
    end.

  (* Pos.to_nat *)
  (* Pos2Nat.inj_add: forall p q : positive, Pos.to_nat (p + q) = Pos.to_nat p + Pos.to_nat q *)
  (* Proposition lemma1 : forall () zpow a (Z.pos_sub p p0) = (pow a p) * inv (pow a p0). *)
    (* Search Pos_to_nat. *)
  (* Proposition a_pow_m_n : forall (a: G) (n m: nat), (pow a n)*(pow a m) = pow a (n + m). *)

  (* Proposition pow_i_neq_poq_j: *)
  (*   forall i j a n, order a n ->  i < j < n -> *)
  (*              pow a i <> pow a j. *)

  (*   forall (i, j: nat) (a: G) (n: nat), order a n ->  i < j < n -> *)
  (*              pow a i <> pow a j. *)
  (*   Proof. *)
  (*     intro. *)

Class r_action (S: Type) (r_action: S -> G -> S) : Type :=
{
  property: forall (x y: G) (s: S), r_action s (x*y) = r_action (r_action s x) y;
  e_property: forall (s: S), r_action s e = s
}.

Instance exists_GG : r_action G (mult) :=
{
  property := fun x y s => assoc s x y;
  e_property := right_id
}.

Definition commutative_group := forall (x y : G),
    (mult x y) = (mult y x).

End Group_theorems.

Section Subgroup.
  (* Пусть дано множество - носитель группы *)
  Variable G: Type.
  (* Групповые свойства *)
  Context `{Hgr: Group G}.

  Axiom functional_extensionality :
  forall A (B : A -> Type)
         (f g : forall a, B a),
    (forall a, f a = g a) ->
    f = g.

  Axiom proof_irrelevance :
  forall (P : Prop) (p q : P), p = q.

  (* Предикат, определяющий подмножество *)
  Variable P : G -> Prop.
  (* Единица принадлежит подмножеству *)
  Variable s_e: P(e).
  (* Умножение 2-х элементов подмножества принадлежит подмножеству *)
  Variable mul_axiom: forall x y: sig P, P (proj1_sig x * proj1_sig y).
  (* Обратный элемент для элемента подмножества принадлежит подмножеству *)
  Variable inv_axiom: forall x: sig P, P (inv (proj1_sig x)).

  (* Ф-ция умножения 2-х элементов подмножества: *)
  (* (умножение 2-х первых проекций | s_mul) *)
  Definition mult1 x y := exist P (proj1_sig x * proj1_sig y) (mul_axiom x y).
  (* Ф-ция получения обратного элемента для данного элемента подмножества *)
  Definition inv1 (x: sig P) : sig P := exist P (inv (proj1_sig x)) (inv_axiom x).

  Theorem assoc1: forall x y z: sig P,
      mult1 x (mult1 y z) = mult1 (mult1 x y) z.
  Proof.
    intros [x Px] [y Py] [z Pz].
    set (Hproj1 := assoc x y z).
    - unfold mult1. simpl. set (R := exist P (x * (y * z))
    (mul_axiom (exist P x Px)
           (exist P (y * z) (mul_axiom (exist P y Py) (exist P z Pz))))).
      set (L := exist P (x * y * z)
                      (mul_axiom
                         (exist P (x * y) (mul_axiom (exist P x Px) (exist P y Py)))
                         (exist P z Pz))).
      set (Q := @eq_sig G P R L Hproj1). apply Q. simpl. apply proof_irrelevance.
  Qed.

  Instance semigroupSubgroup : Semigroup (sig P) :=
  {
    mult := mult1;
    assoc := assoc1
  }.

  (* e с доказательством того, что e принадлежит подмножеству *)
  Definition sub_e := exist P e s_e.
  Theorem subgroup_left_id: forall x: (sig P), mult1 sub_e x = x.
  Proof.
    intros [x Px]. set (x_pair := exist P x Px). unfold mult1. simpl. set (Q := @eq_sig G P (exist P (e * x) (mul_axiom sub_e x_pair)) x_pair). simpl in Q. apply (Q (left_id _)). apply proof_irrelevance.
  Qed.

  Instance monoidSubgroup : Monoid (sig P) :=
  {
    e := sub_e;
    left_id := subgroup_left_id;
  }.

  Definition sub_inv (x: sig P): sig P := exist P (inv (proj1_sig x)) (inv_axiom x).
  Theorem subgroup_left_inv: forall x: (sig P), mult1 (inv1 x) x = sub_e.
  Proof.
    intros [x Px]. set (x_pair := exist P x Px). unfold mult1. simpl.
    set (Q := @eq_sig G P (exist P (inv x * x) (mul_axiom (inv1 x_pair) x_pair)) sub_e). simpl in Q.
    apply (Q (left_inv x)). apply proof_irrelevance.
  Qed.

  Instance subgroup_Group : Group (sig P) :=
  {
    inv := sub_inv;
    left_inv := subgroup_left_inv;
  }.

  Context `{Hab: @AbelianGroup G _ _ Hgr}.

  Theorem AbelianSubgroup_Abelian: forall x y: (sig P), x * y = y * x.
  Proof.
    intros. set (Q := @eq_sig G P (x*y) (y*x)). simpl in Q. apply (Q (comm (proj1_sig x) (proj1_sig y))). apply proof_irrelevance.
  Qed.

  Instance Abelian_subgroup_Group : AbelianGroup (sig P) :=
  {
    comm := AbelianSubgroup_Abelian;
  }.

  Definition Normal_subgroup (x y: G) (p: P x) := P (conjugation G x y).

  (* Сопряжение - это изоморфизм группы в саму себя *)
  (* 99 Докажите, что в коммутативной группе всякая подгруппа является нормальной подгруппой. *)

  Theorem EveryAbelianSubgroup_normal: forall (x: sig P) (y: G), Normal_subgroup (proj1_sig x) y (proj2_sig x).
  Proof.
    intros x y. destruct x. simpl. unfold Normal_subgroup. unfold conjugation. rewrite comm. rewrite assoc. rewrite right_inv. rewrite left_id. apply p.
  Qed.

End Subgroup.

Section Homomorphismus.

  Variable G: Type.
  Context `{Gsemi: Semigroup G}.

  Variable F: Type.
  Context `{Fsemi: Semigroup F}.

  Record Homomorphism: Type :=
    Build_homomorphism
    {
        f: G -> F;
        proof: forall (x y: G), f (mult x y) = mult (f x) (f y)
    }.

    Record Isomorphism: Type :=
    Build_isomorphism
      {
        fun1: Homomorphism;
        fun2: F -> G;
        left_right_id: forall (x: G), fun2 ((f fun1) x) = x;
        right_left_id: forall (y: F), (f fun1) (fun2 y) = y;
        (* Homo_f: forall (a b: G), fun1 (a * b) = (fun1 a) * (fun1 b); *)
        (* Homo_right: forall (a b: G2), right (a * b) = (right a) * (right b) *)
      }.

  Theorem homo1 (phi: Homomorphism) (Hcomm: commutative_group G) (Hsur: forall (f1: F), exists (g: G), (f phi g) = f1):
      (commutative_group F).
  Proof.
    unfold commutative_group. intros. destruct (Hsur x). destruct (Hsur y). rewrite <- H. rewrite <- H0. rewrite <- (proof phi x0). rewrite <- (proof phi x1). rewrite (Hcomm x0 x1). reflexivity.
  Qed.

  (* 133. Доказать, что при гомоморфизме группы G в *)
  (* группу F единица группы G переходит в единицу группы F . *)
  Theorem homomorphism_saves_e: forall (phi: Homomorphism) `{Hmono: @Monoid G Gsemi} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono}, (f phi) e = e.
  Proof.
    intros. apply (left_cancel_alt_proof F (f phi e)). rewrite <- (proof phi e e). rewrite left_id. rewrite right_id.
    - reflexivity.
    - apply Fgroup.
  Qed.
    (* Theorem homo2 (phi: Homomorphism): (f phi e) = e. *)
  (* Proof. *)
  (*   apply left_cancel with (Hsemi := Hsemi0) (Hmono := Hmono0) (x := (f phi e)). *)
  (*   - apply Fsemi. *)
  (*   - rewrite  <- (proof phi e). rewrite left_id. rewrite (@right_id F _ _ Fsemi). reflexivity. *)
  (* Qed. *)

  (* 134 *)
  Theorem homomorphism_saves_inv: forall (x: G) (phi: Homomorphism) `{Hmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Hmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono}, (f phi (inv x)) = inv (f phi x).
  Proof.
    intros. apply (left_cancel_alt_proof F (f phi x)). rewrite <- (proof phi). rewrite right_inv. rewrite right_inv. apply homomorphism_saves_e. apply Fgroup.
  Qed.

  Definition Im_prop (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (y: F) := exists x: G, y = (f phi x).

  Definition Im (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} := sig (Im_prop phi).

  Definition Im_mult (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y: (Im phi)): Im phi.
  Proof.
    exists (mult (proj1_sig x) (proj1_sig y)). unfold Im_prop. destruct x. destruct y. destruct i. destruct i0. simpl. exists (x1*x2). rewrite (proof phi). rewrite <- e0. rewrite <- e1. reflexivity.
  Defined.

  Theorem Im_mult_assoc: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y z: Im phi), Im_mult phi x (Im_mult phi y z) = Im_mult phi (Im_mult phi x y) z.
  Proof.
    intros phi Gmono Ggroup Fmono Fgroup x y z. unfold Im_mult. destruct x. destruct y. destruct z. simpl. destruct i. destruct i0. destruct i1. assert (Hproj1: x * (x0 * x1) = (x * x0 * x1)).
    - apply assoc.
    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end.
      set (Q := @eq_sig F (Im_prop phi) name1 name2 Hproj1). apply Q. simpl. apply proof_irrelevance.
  Qed.

  Instance semigroupIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Semigroup (@Im phi Gmono Ggroup Fmono Fgroup) :=
  {
    mult := Im_mult phi;
    assoc := Im_mult_assoc phi
  }.

  Definition Im_e (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Im phi.
  Proof.
    exists e. exists e. symmetry. apply homomorphism_saves_e. apply Fgroup.
  Defined.

  Theorem Im_mult_left_id: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)), Im_mult phi (Im_e phi) x = x.
  Proof.
    intros phi Gmono Ggroup Fmono Fgroup x. unfold Im_mult. destruct x as [x0 Px]. destruct Px. assert (H_left_id: e * x0 = x0).
    - apply left_id.
    - simpl. match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig F (Im_prop phi) name1 name2 H_left_id). apply Q. simpl. apply proof_irrelevance.
  Qed.

  Instance monoidIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Monoid (@Im phi Gmono Ggroup Fmono Fgroup) :=
  {
    e := Im_e phi;
    left_id := Im_mult_left_id phi
  }.

  Definition Im_inv (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)) : Im phi.
  Proof.
    destruct x as [y P]. exists (inv y). destruct P as [x H]. set(H_inv := homomorphism_saves_inv x). exists (inv x). rewrite H. symmetry. apply H_inv.
  Defined.

  Theorem Im_mult_left_inv: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Im phi)), Im_mult phi (Im_inv phi x) x = Im_e phi.
  Proof.
    intros phi Gmon Ggroup Fmono Fgroup x. unfold Im_mult. destruct x as [y P]. destruct P as [x Py]. simpl. assert (H_left_inv: inv y * y = e).
    - apply left_inv.
    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig F (Im_prop phi) name1 name2 H_left_inv). apply Q. apply proof_irrelevance.
  Qed.

  Instance groupIm (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Group (@Im phi Gmono Ggroup Fmono Fgroup) :=
  {
    inv := Im_inv phi;
    left_inv := Im_mult_left_inv phi
  }.

  (* Ядро гомоморфизма *)
  Definition Ker (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} := sig (fun x => (f phi x) = e).

  Definition Ker_mult (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y: Ker phi): Ker phi.
  Proof.
    destruct x as [x Px]. destruct y as [y Py]. exists (mult x y). rewrite (proof phi). rewrite Px. rewrite Py. rewrite left_id. reflexivity.
  Defined.

  Theorem Ker_mult_assoc: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x y z: Ker phi), Ker_mult phi x (Ker_mult phi y z) = Ker_mult phi (Ker_mult phi x y) z.
  Proof.
    intros phi Gmono Ggroup Fmono Fgroup x y z. destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold Ker_mult.
    assert (Hassoc: x * (y * z) = (x * y * z)).
    - apply assoc.
    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hassoc). apply Q. unfold proj1_sig. unfold proj2_sig. simpl. apply proof_irrelevance.
  Qed.

  Instance semigroupKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Semigroup (@Ker phi Gmono Ggroup Fmono Fgroup) :=
  {
    mult := Ker_mult phi;
    assoc := Ker_mult_assoc phi
  }.

  Definition Ker_e (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Ker phi.
  Proof.
    exists e. apply homomorphism_saves_e. apply Fgroup.
  Defined.

  Theorem Ker_mult_left_id: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)), Ker_mult phi (Ker_e phi) x = x.
  Proof.
    intros phi Gmono Ggroup Fmono Fgroup x. destruct x as [x0 Px]. unfold Ker_mult. unfold Ker_e. assert (Hleft_id: e * x0 = x0).
    - apply left_id.
    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hleft_id). apply Q. simpl. apply proof_irrelevance.
  Qed.

  Instance monoidKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Monoid (@Ker phi Gmono Ggroup Fmono Fgroup) :=
  {
    e := Ker_e phi;
    left_id := Ker_mult_left_id phi
  }.

  Definition Ker_inv (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)): Ker phi.
  Proof.
    destruct x as [x P]. exists (inv x). rewrite (@homomorphism_saves_inv x phi Gmono Ggroup Fmono Fgroup). rewrite P. apply e_inv.
  Defined.

  Theorem Ker_mult_left_inv: forall (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} (x: (Ker phi)), Ker_mult phi (Ker_inv phi x) x = Ker_e phi.
  Proof.
    intros phi Gmono Ggroup Fmono Fgroup x. destruct x as [x0 Px]. unfold Ker_mult. unfold Ker_e. unfold Ker_inv. assert (Hinv: (inv x0) * x0 = e).
    - apply left_inv.
    - match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G (fun x => (f phi x) = e) name1 name2 Hinv). apply Q. apply proof_irrelevance.
  Qed.

  Instance groupKer (phi: Homomorphism) `{Gmono: @Monoid G Gsemi} `{Ggroup: @Group G Gsemi Gmono} `{Fmono: @Monoid F Fsemi} `{Fgroup: @Group F Fsemi Fmono} : Group (@Ker phi Gmono Ggroup Fmono Fgroup) :=
  {
    inv := Ker_inv phi;
    left_inv := Ker_mult_left_inv phi
  }.

End Homomorphismus.

(* 135. Пусть f1 : G → F и f2 : F → H — гомоморфизмы. *)
(* Доказать, что f2 f1 : G → H — гомоморфизм. *)
Theorem homomorphism_mult_homo: forall (G F H: Type) `{Gsemi: Semigroup G} `{Fsemi: Semigroup F} `{Hsemi: Semigroup H} (phi1: Homomorphism G F) (phi2: Homomorphism F H) (x y: G), (f F H phi2 (f G F phi1 (x*y))) = (f _ _ phi2 (f _ _ phi1 x)) * (f _ _ phi2 (f _ _ phi1 y)).
Proof.
  intros. rewrite (proof G F). rewrite (proof F H). reflexivity.
Qed.

Definition homomorphism_composition (G F H: Type) `{Gsemi: Semigroup G} `{Fsemi: Semigroup F} `{Hsemi: Semigroup H} (phi1: Homomorphism G F) (phi2: Homomorphism F H) := Build_homomorphism G H (fun x: G => (f F H phi2) (f G F phi1 x)) (homomorphism_mult_homo G F H phi1 phi2).
(* Section Isomorphismus. *)

  (* Record Isomorphism: Type := *)
  (*   Build_isomorphism *)
  (*   { *)
  (*       phi: G1 -> G2; *)
  (*       totality: forall (x: G1), exists (y: G2), phi x = y; *)
  (*       injectivity: forall (x1 x2: G1), (phi x1) = (phi x2) -> x1 = x2; *)
  (*       operation_preservation: forall (a b: G1), phi (a * b) = (phi a) * (phi b) *)
  (*   }. *)

(* End Isomorphismus. *)

Theorem th01: forall (G F: Type) `{Hgr1: Semigroup G} `{Hgr2: Semigroup F} (phi: Isomorphism G F), forall (a b: F), (fun2 _ _ phi) (a * b) = ((fun2 _ _ phi) a) * ((fun2 _ _ phi) b).
Proof.
  intros. rewrite <- (right_left_id _ _ phi a). rewrite <- (right_left_id _ _ phi b). rewrite <- (proof G F (fun1 _ _ phi)). repeat rewrite (left_right_id _ _ phi). reflexivity.
Qed.

Theorem th1: forall (G F: Type) `{Hgr1: Semigroup G} `{Hgr2: Semigroup F} (phi: Isomorphism G F), Isomorphism F G.
Proof.
  intros. set (Homo2 := th01 G F phi). set (phi1 := phi). destruct phi. simpl in Homo2.
  set (Homo1 := Build_homomorphism F G fun4 Homo2).
  apply (Build_isomorphism F G Homo1 (f G F fun3)).
  - apply (right_left_id G F phi1).
  - apply (left_right_id G F phi1).
Qed.

(* Если группа изоморфна полугруппе, то полугруппа является группой *)
   (* compose (phi1.(phi)) (psi.(phi)) =1 id). *)

(* Print exist. *)
(* Lemma l (r1 r2 : { R : nat -> nat -> bool | *)
(*                    forall n, R n n = true }) : *)
(*   (forall n1 n2, proj1_sig r1 n1 n2 = proj1_sig r2 n1 n2) -> *)
(*   r1 = r2. *)
(* Proof. *)
(*   destruct r1 as [r1 H1], r2 as [r2 H2]. *)
(*   simpl. *)
(*   intros H. *)
(*   assert (H': r1 = r2). *)
(*   { apply functional_extensionality. *)
(*     intros n1. *)
(*     apply functional_extensionality. *)
(*     intros n2. *)
(*     apply H. } *)
(*   subst r2. *)
(*   rename r1 into r. *)
(*   f_equal. *)
(*   apply proof_irrelevance. *)
(* Qed. *)

(* Inductive bool: Set := *)
(*   | true *)
(*   | false. *)

(* Lemma equality_commutes: *)
(*   forall (a: bool) (b: bool), a = b -> b = a. *)
(* Proof. *)
(*   intros. *)
(*   subst a. *)
(*   reflexivity. *)
(* Qed. *)

Inductive megaeq: forall (A B: Type) (x: A) (y: B), Prop :=
  megarefl A x : megaeq A A x x.

Section generatedSubgroup.
  (* Пусть дано множество - носитель группы *)
  Variable G: Type.
  (* Групповые свойства *)
  Context `{Hgr: Group G}.

  Definition id_or_inv (P1: G -> Prop): Type := ((sig P1) * bool).
  Definition invert_list (P: G -> Prop) (l: list (id_or_inv P)): (list (id_or_inv P)) :=
    rev (
        map
          (fun x => (fst x, negb (snd x)))
          l).

  Lemma inv_app (P: G -> Prop) (l1: list (id_or_inv P)) (l2: list (id_or_inv P)):
      invert_list P (l1 ++ l2) = invert_list P l2 ++ invert_list P l1.
  Proof.
    destruct l1 as [| x t].
    - unfold invert_list. simpl. rewrite app_nil_r. reflexivity.
    - unfold invert_list. simpl. rewrite map_app. rewrite rev_app_distr. rewrite <- app_assoc. reflexivity.
  Qed.

  Definition gfold (P1: G -> Prop) (l: list (id_or_inv P1)) :=
    fold_right
      mult e
      (map (fun (v: (sig P1) * bool) =>
              if snd v
              then (proj1_sig (fst v))
              else inv (proj1_sig (fst v)))
           l).

  (* Порождающее множество группы G — это подмножество S в G, такое, что каждый элемент G может быть записан как произведение конечного числа элементов S и их обратных.  *)
  Definition generatedSubgroup (P1: G -> Prop) :=
    sig (fun x =>
           @ex
             (list (id_or_inv P1))
             (fun l =>
                (x = gfold P1 l))).

  Theorem generatedSubgroup_mul: forall (P1: G -> Prop) (x y: list (id_or_inv P1)), gfold P1 (x ++ y) = gfold P1 x * gfold P1 y.
  Proof.
    intros. unfold gfold. induction x as [|x0 x].
    - simpl. rewrite left_id. reflexivity.
    - simpl. rewrite <- assoc. rewrite IHx. reflexivity.
  Qed.

  Lemma unapp L (x: L) (l: list L): x::l = (x::nil)++l.
  Proof.
    reflexivity.
  Qed.

  Lemma gfold_inv (P: G -> Prop) (l: list (id_or_inv P)): gfold P (invert_list P l) = inv (gfold P l).
  Proof.
    induction l as [|x t].
    - unfold gfold. simpl. symmetry. apply e_inv.
    - rewrite unapp. rewrite inv_app. rewrite generatedSubgroup_mul. rewrite generatedSubgroup_mul. rewrite inv_prod. rewrite IHt. unfold gfold. simpl. destruct (snd x).
      +  simpl. repeat rewrite right_id. reflexivity. apply Hgr. apply Hgr.
      + simpl. repeat rewrite right_id. rewrite inv_involution. reflexivity. apply Hgr. apply Hgr.
  Qed.

  Definition mult_gen (P1: G -> Prop) (x y: generatedSubgroup P1): generatedSubgroup P1.
  Proof.
    unfold generatedSubgroup. destruct x as [x0 Px]. destruct y as [y0 Py]. exists (x0 * y0). destruct Px as [list_x Px]. destruct Py as [list_y Py]. exists (list_x ++ list_y). symmetry. rewrite Px. rewrite Py. apply generatedSubgroup_mul.
  Defined.

  Theorem generatedSubgroup_assoc: forall (P1: G -> Prop) (x y z: generatedSubgroup P1), mult_gen P1 x (mult_gen P1 y z) = mult_gen P1 (mult_gen P1 x y) z.
  Proof.
    intros. assert (Hproj1: proj1_sig (mult_gen P1 x (mult_gen P1 y z)) = proj1_sig (mult_gen P1 (mult_gen P1 x y) z)).
    - destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold mult_gen. simpl.
      rewrite assoc. reflexivity.
    - destruct x as [x Px]. destruct y as [y Py]. destruct z as [z Pz]. unfold mult_gen. simpl.
      match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G _ name1 name2 Hproj1). apply Q. simpl. apply proof_irrelevance. (* unfold eq_rect. destruct Px as [x0 Px]. destruct Py as [y0 Py]. destruct Pz as [z0 Pz]. subst. simpl. unfold eq_sym. unfold eq_ind_r. unfold eq_ind. simpl. assert (Hassoc: x0 ++ y0 ++ z0 = (x0 ++ y0) ++ z0). *)
      (* + apply app_assoc. *)
      (* + match goal with |- ?L = ?R => set (name3 := L); set (name4 := R) end. set (Q := @eq_sig (list (id_or_inv P1)) _ name3 name4 Hassoc). *)
  Qed.

  Instance semigroupGeneratedSubgroup (P1: G -> Prop) : Semigroup (generatedSubgroup P1) :=
  {
    mult := mult_gen P1;
    assoc := generatedSubgroup_assoc P1
  }.

  Definition e_gen (P1: G -> Prop): generatedSubgroup P1.
  Proof.
    unfold generatedSubgroup. exists e. exists nil. unfold gfold. simpl. reflexivity.
  Defined.

  Theorem generatedSubgroup_left_id: forall (P1: G -> Prop) (x: generatedSubgroup P1), mult_gen P1 (e_gen P1) x = x.
  Proof.
    intros. destruct x as [x Px]. unfold e_gen. simpl. unfold mult_gen. simpl. match goal with |- ?L = ?R => set (name1 := L); set (name2 := R) end. set (Q := @eq_sig G _ name1 name2 (left_id x)). apply Q. simpl. apply proof_irrelevance.
Qed.

  Instance monoidGeneratedSubgroup (P1: G -> Prop) : Monoid (generatedSubgroup P1) :=
  {
    e := e_gen P1;
    left_id := generatedSubgroup_left_id P1
  }.

  Definition inv_gen (P1: G -> Prop) (x: generatedSubgroup P1): generatedSubgroup P1.
  Proof.
    unfold generatedSubgroup. destruct x as [x Px]. exists (inv x). unfold gfold. destruct Px as [l0 Px]. simpl. reflexivity.
  Defined.

  (* Definition commutant := { x : G | exists l: list (G*G), x = fold (fun p a => mult1 (commutator (fst p) (snd p)) a) e l }. *)
End generatedSubgroup.

Section CartesianGroupProduct.
  (* Пусть дано множество - носитель группы *)
  Variable G: Type.
  Variable H: Type.
  (* Групповые свойства *)
  Context `{Hgr1: Group G}.
  Context `{Hgr2: Group H}.

  Definition mulp (x y : G * H): (G * H) := (mult (fst x) (fst y), mult (snd x) (snd y)).

  Theorem assocGroupProduct: forall x y z: G * H,
      mulp x (mulp y z) = mulp (mulp x y) z.
  Proof.
    intros. unfold mulp. simpl. rewrite (@assoc G). rewrite (@assoc H). reflexivity.
  Qed.

  Instance semigroupGroupProduct : Semigroup (G * H) :=
  {
    mult := mulp;
    assoc := assocGroupProduct;
  }.

  Definition groupProduct_e: (G * H) := (e, e).

  Theorem GroupProductLeftId: forall x: G * H,
      mult groupProduct_e x = x.
  Proof.
    intros. unfold groupProduct_e. destruct x. unfold mult. simpl. unfold mulp. simpl. repeat rewrite left_id. reflexivity.
  Qed.

  Instance monoidGroupProduct : Monoid (G * H) :=
  {
    e := groupProduct_e;
    left_id := GroupProductLeftId;
  }.

  Definition groupProduct_inv (x: G*H) := (inv (fst x), inv(snd x)).

  Theorem groupProduct_left_inv : forall x: (G * H), mult (groupProduct_inv x) x = groupProduct_e.
  Proof.
    intros. destruct x. unfold mult. simpl. unfold mulp. simpl. repeat rewrite left_inv. unfold groupProduct_e. reflexivity.
  Qed.

  Instance groupGroupProduct : Group (G * H) :=
  {
      inv := groupProduct_inv;
      left_inv := groupProduct_left_inv;
  }.

  Theorem projectHomomorphismus : forall (x y: (G * H)), fst (mult x y) = mult (fst x) (fst y).
  Proof.
    intros. simpl. reflexivity.
  Qed.

  Theorem projectHomomorphismus2 : forall (x y: (G * H)), snd (mult x y) = mult (snd x) (snd y).
  Proof.
    intros. simpl. reflexivity.
  Qed.

  Definition rec_fst := Build_homomorphism (G*H) G fst projectHomomorphismus.

  Definition rec_snd := Build_homomorphism (G*H) H snd projectHomomorphismus2.

  Definition get_e_pair (x: G): (G*H) := (x, e).

  Theorem projectHomomorphismus3 : forall (x y: G), get_e_pair (mult x y) = mult (get_e_pair x) (get_e_pair y).
  Proof.
    intros. unfold get_e_pair. simpl. unfold mulp. simpl. rewrite left_id. reflexivity.
  Qed.

  Definition rec_get_e_pair := Build_homomorphism G (G*H) get_e_pair projectHomomorphismus3.

  Context `{Gab: @AbelianGroup G Hsemi Hmono Hgr1}.
  Context `{Hab: @AbelianGroup H _ _ Hgr2}.

  Theorem AbelianProduct: forall (x y : (G*H)), mult x y = mult y x.
  Proof.
    intros. unfold mult. simpl. unfold mulp. rewrite (@comm G _ _ _ Gab). rewrite (@comm H _ _ _ Hab). reflexivity.
  Qed.
End CartesianGroupProduct.
Close Scope group_scope.


(** * Prop: Propositions and Evidence *)

Require Export Logic.

(* ####################################################### *)
(** * From Boolean Functions to Propositions *)

(** In chapter [Basics] we defined a _function_ [evenb] that tests a
    number for evenness, yielding [true] if so.  We can use this
    function to define the _proposition_ that some number [n] is
    even: *)

Definition even (n:nat) : Prop :=
  evenb n = true.

(** That is, we can define "[n] is even" to mean "the function [evenb]
    returns [true] when applied to [n]."

    Note that here we have given a name
    to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. This isn't a fundamentally
    new kind of proposition;  it is still just an equality. *)

(** Another alternative is to define the concept of evenness
    directly.  Instead of going via the [evenb] function ("a number is
    even if a certain computation yields [true]"), we can say what the
    concept of evenness means by giving two different ways of
    presenting _evidence_ that a number is even. *)

(** * Inductively Defined Propositions *)

Inductive ev : nat -> Prop :=
  | ev_0 : ev O
  | ev_SS : forall n:nat, ev n -> ev (S (S n)).

(** This definition says that there are two ways to give
    evidence that a number [m] is even.  First, [0] is even, and
    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some
    [n] and we can give evidence [e] that [n] is even, then [m] is
    also even, and [ev_SS n e] is the evidence. *)

(** **** Exercise: 1 star (double_even) *)

Theorem double_even : forall n,
  ev (double n).
Proof.
    induction n.
    simpl. apply ev_0.
    simpl. apply ev_SS. apply IHn.
Qed.
(** [] *)

(** *** Discussion: Computational vs. Inductive Definitions *)

(** We have seen that the proposition "[n] is even" can be
    phrased in two different ways -- indirectly, via a boolean testing
    function [evenb], or directly, by inductively describing what
    constitutes evidence for evenness.  These two ways of defining
    evenness are about equally easy to state and work with.  Which we
    choose is basically a question of taste.

    However, for many other properties of interest, the direct
    inductive definition is preferable, since writing a testing
    function may be awkward or even impossible.

    One such property is [beautiful].  This is a perfectly sensible
    definition of a set of numbers, but we cannot translate its
    definition directly into a Coq Fixpoint (or into a recursive
    function in any other common programming language).  We might be
    able to find a clever way of testing this property using a
    [Fixpoint] (indeed, it is not too hard to find one in this case),
    but in general this could require arbitrarily deep thinking.  In
    fact, if the property we are interested in is uncomputable, then
    we cannot define it as a [Fixpoint] no matter how hard we try,
    because Coq requires that all [Fixpoint]s correspond to
    terminating computations.

    On the other hand, writing an inductive definition of what it
    means to give evidence for the property [beautiful] is
    straightforward. *)

(** **** Exercise: 1 star (ev__even) *)
(** Here is a proof that the inductive definition of evenness implies
    the computational one. *)

Theorem ev__even : forall n,
  ev n -> even n.
Proof.
  intros n E. induction E as [| n' E'].
  Case "E = ev_0".
    unfold even. reflexivity.
  Case "E = ev_SS n' E'".
    unfold even. apply IHE'.
Qed.

(** Could this proof also be carried out by induction on [n] instead
    of [E]?  If not, why not? *)

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

(** The induction principle for inductively defined propositions does
    not follow quite the same form as that of inductively defined
    sets.  For now, you can take the intuitive view that induction on
    evidence [ev n] is similar to induction on [n], but restricts our
    attention to only those numbers for which evidence [ev n] could be
    generated.  We'll look at the induction principle of [ev] in more
    depth below, to explain what's really going on. *)

(** **** Exercise: 1 star (l_fails) *)
(** The following proof attempt will not succeed.
     Theorem l : forall n,
       ev n.
     Proof.
       intros n. induction n.
         Case "O". simpl. apply ev_0.
         Case "S".
           ...
   Intuitively, we expect the proof to fail because not every
   number is even. However, what exactly causes the proof to fail?

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

(** **** Exercise: 2 stars (ev_sum) *)
(** Here's another exercise requiring induction. *)

Theorem ev_sum : forall n m,
   ev n -> ev m -> ev (n+m).
Proof.
    intros n m.
    intros Evn Evm.
    induction Evn.
    simpl. apply Evm.
    simpl. apply ev_SS.
    apply IHEvn.
Qed.
(** [] *)

(* ##################################################### *)
(** ** Example *)

(**  As a running example, let's
    define a simple property of natural numbers -- we'll call it
    "[beautiful]." *)

(** Informally, a number is [beautiful] if it is [0], [3], [5], or the
    sum of two [beautiful] numbers.

    More pedantically, we can define [beautiful] numbers by giving four
    rules:

       - Rule [b_0]: The number [0] is [beautiful].
       - Rule [b_3]: The number [3] is [beautiful].
       - Rule [b_5]: The number [5] is [beautiful].
       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is
         their sum. *)
(** ** Inference Rules *)
(** We will see many definitions like this one during the rest
    of the course, and for purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**
                              -----------                               (b_0)
                              beautiful 0

                              ------------                              (b_3)
                              beautiful 3

                              ------------                              (b_5)
                              beautiful 5

                       beautiful n     beautiful m
                       ---------------------------                      (b_sum)
                              beautiful (n+m)
*)

(** *** *)
(** Each of the textual rules above is reformatted here as an
    inference rule; the intended reading is that, if the _premises_
    above the line all hold, then the _conclusion_ below the line
    follows.  For example, the rule [b_sum] says that, if [n] and [m]
    are both [beautiful] numbers, then it follows that [n+m] is
    [beautiful] too.  If a rule has no premises above the line, then
    its conclusion holds unconditionally.

    These rules _define_ the property [beautiful].  That is, if we
    want to convince someone that some particular number is [beautiful],
    our argument must be based on these rules.  For a simple example,
    suppose we claim that the number [5] is [beautiful].  To support
    this claim, we just need to point out that rule [b_5] says so.
    Or, if we want to claim that [8] is [beautiful], we can support our
    claim by first observing that [3] and [5] are both [beautiful] (by
    rules [b_3] and [b_5]) and then pointing out that their sum, [8],
    is therefore [beautiful] by rule [b_sum].  This argument can be
    expressed graphically with the following _proof tree_: *)
(**
         ----------- (b_3)   ----------- (b_5)
         beautiful 3         beautiful 5
         ------------------------------- (b_sum)
                   beautiful 8
*)
(** *** *)
(**
    Of course, there are other ways of using these rules to argue that
    [8] is [beautiful], for instance:
         ----------- (b_5)   ----------- (b_3)
         beautiful 5         beautiful 3
         ------------------------------- (b_sum)
                   beautiful 8
*)

(** **** Exercise: 1 star (varieties_of_beauty) *)
(** How many different ways are there to show that [8] is [beautiful]? *)

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

(** *** *)
(** In Coq, we can express the definition of [beautiful] as
    follows: *)

Inductive beautiful : nat -> Prop :=
  b_0   : beautiful 0
| b_3   : beautiful 3
| b_5   : beautiful 5
| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).

(** The first line declares that [beautiful] is a proposition -- or,
    more formally, a family of propositions "indexed by" natural
    numbers.  (That is, for each number [n], the claim that "[n] is
    [beautiful]" is a proposition.)  Such a family of propositions is
    often called a _property_ of numbers.  Each of the remaining lines
    embodies one of the rules for [beautiful] numbers.
*)
(** *** *)
(**
    The rules introduced this way have the same status as proven
    theorems; that is, they are true axiomatically.
    So we can use Coq's [apply] tactic with the rule names to prove
    that particular numbers are [beautiful].  *)

Theorem three_is_beautiful: beautiful 3.
Proof.
   (* This simply follows from the rule [b_3]. *)
   apply b_3.
Qed.

Theorem eight_is_beautiful: beautiful 8.
Proof.
   (* First we use the rule [b_sum], telling Coq how to
      instantiate [n] and [m]. *)
   apply b_sum with (n:=3) (m:=5).
   (* To solve the subgoals generated by [b_sum], we must provide
      evidence of [beautiful 3] and [beautiful 5]. Fortunately we
      have rules for both. *)
   apply b_3.
   apply b_5.
Qed.

(** *** *)
(** As you would expect, we can also prove theorems that have
hypotheses about [beautiful]. *)

Theorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).
Proof.
  intros n B.
  apply b_sum with (n:=8) (m:=n).
  apply eight_is_beautiful.
  apply B.
Qed.

(** **** Exercise: 2 stars (b_times2) *)
Theorem b_times2: forall n, beautiful n -> beautiful (2*n).
Proof.
    intros n.
    intros B.
    assert (lemma : 2*n = n + n).
    simpl. apply f_equal. apply plus_0_r.
    rewrite -> lemma.
    apply b_sum.
    apply B.
    apply B.
Qed.
(** [] *)

(** **** Exercise: 3 stars (b_timesm) *)
Theorem b_timesm: forall n m, beautiful n -> beautiful (m*n).
Proof.
   intros n m.
   intros B.
   induction m.
   simpl.
   apply b_0.
   simpl.
   apply b_sum.
   apply B.
   apply IHm.
Qed.
(** [] *)

(* ####################################################### *)
(** ** Induction Over Evidence *)

(** Besides _constructing_ evidence that numbers are beautiful, we can
    also _reason about_ such evidence. *)

(** The fact that we introduced [beautiful] with an [Inductive]
    declaration tells Coq not only that the constructors [b_0], [b_3],
    [b_5] and [b_sum] are ways to build evidence, but also that these
    four constructors are the _only_ ways to build evidence that
    numbers are beautiful. *)

(** In other words, if someone gives us evidence [E] for the assertion
    [beautiful n], then we know that [E] must have one of four shapes:

      - [E] is [b_0] (and [n] is [O]),
      - [E] is [b_3] (and [n] is [3]),
      - [E] is [b_5] (and [n] is [5]), or
      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is
        evidence that [n1] is beautiful and [E2] is evidence that [n2]
        is beautiful). *)

(** *** *)
(** This permits us to _analyze_ any hypothesis of the form [beautiful
    n] to see how it was constructed, using the tactics we already
    know.  In particular, we can use the [induction] tactic that we
    have already seen for reasoning about inductively defined _data_
    to reason about inductively defined _evidence_.

    To illustrate this, let's define another property of numbers: *)

Inductive gorgeous : nat -> Prop :=
  g_0 : gorgeous 0
| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)
| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).

(** **** Exercise: 1 star (gorgeous_tree) *)
(** Write out the definition of [gorgeous] numbers using inference rule
    notation.

(* FILL IN HERE *)
[]
*)

(** **** Exercise: 1 star (gorgeous_plus13) *)
Theorem gorgeous_plus13: forall n,
  gorgeous n -> gorgeous (13+n).
Proof.
    intros n G.
    apply g_plus5.
    apply g_plus5.
    apply g_plus3.
    apply G.
Qed.
(** [] *)

(** *** *)
(** It seems intuitively obvious that, although [gorgeous] and
    [beautiful] are presented using slightly different rules, they are
    actually the same property in the sense that they are true of the
    same numbers.  Indeed, we can prove this. *)

Theorem gorgeous__beautiful : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros n H.
   induction H as [|n'|n'].
   Case "g_0".
       apply b_0.
   Case "g_plus3".
       apply b_sum. apply b_3.
       apply IHgorgeous.
   Case "g_plus5".
       apply b_sum. apply b_5. apply IHgorgeous.
Qed.

(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)

(** Let's see what happens if we try to prove this by induction on [n]
   instead of induction on the evidence [H]. *)

Theorem gorgeous__beautiful_FAILED : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros. induction n as [| n'].
   Case "n = 0". apply b_0.
   Case "n = S n'". (* We are stuck! *)
Abort.

(** The problem here is that doing induction on [n] doesn't yield a
    useful induction hypothesis. Knowing how the property we are
    interested in behaves on the predecessor of [n] doesn't help us
    prove that it holds for [n]. Instead, we would like to be able to
    have induction hypotheses that mention other numbers, such as [n -
    3] and [n - 5]. This is given precisely by the shape of the
    constructors for [gorgeous]. *)

(** **** Exercise: 2 stars (gorgeous_sum) *)
Theorem gorgeous_sum : forall n m,
  gorgeous n -> gorgeous m -> gorgeous (n + m).
Proof.
    intros n m N M.
    induction N.
    simpl. apply M.
    apply g_plus3. apply IHN.
    apply g_plus5. apply IHN.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)
Theorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.
Proof.
    intros n B.
    induction B.
    apply g_0.
    apply g_plus3. apply g_0.
    apply g_plus5. apply g_0.
    apply gorgeous_sum.
    apply IHB1.
    apply IHB2.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (g_times2) *)
(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].
    You might find the following helper lemma useful. *)

Lemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.
Proof.
   intros x y z.
   rewrite plus_assoc.
   replace (x+z) with (z+x).
   reflexivity.
   apply plus_comm.
Qed.

Theorem g_times2: forall n, gorgeous n -> gorgeous (2*n).
Proof.
   intros n H. simpl.
   induction H.
   simpl. apply g_0.
   rewrite -> helper_g_times2.
    apply g_plus3. rewrite -> helper_g_times2. apply g_plus3. fold plus.
    rewrite <- plus_assoc. apply IHgorgeous.
   rewrite -> helper_g_times2. apply g_plus5. fold plus.
   rewrite -> helper_g_times2. apply g_plus5. fold plus.
   rewrite <- plus_assoc. apply IHgorgeous.
Qed.
(** [] *)

(* ####################################################### *)
(** ** [Inversion] on Evidence *)

(** Another situation where we want to analyze evidence for evenness
    is when proving that, if [n] is even, then [pred (pred n)] is
    too.  In this case, we don't need to do an inductive proof.  The
    right tactic turns out to be [inversion].  *)

Theorem ev_minus2: forall n,
  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  inversion E as [| n' E'].
  Case "E = ev_0". simpl. apply ev_0.
  Case "E = ev_SS n' E'". simpl. apply E'.  Qed.

(** **** Exercise: 1 star, optional (ev_minus2_n) *)
(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)

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

(** *** *)
(** Another example, in which [inversion] helps narrow down to
the relevant cases. *)

Theorem SSev__even : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  apply E'. Qed.

(** ** [inversion] revisited *)

(** These uses of [inversion] may seem a bit mysterious at first.
    Until now, we've only used [inversion] on equality
    propositions, to utilize injectivity of constructors or to
    discriminate between different constructors.  But we see here
    that [inversion] can also be applied to analyzing evidence
    for inductively defined propositions.

    (You might also expect that [destruct] would be a more suitable
    tactic to use here. Indeed, it is possible to use [destruct], but
    it often throws away useful information, and the [eqn:] qualifier
    doesn't help much in this case.)

    Here's how [inversion] works in general.  Suppose the name
    [I] refers to an assumption [P] in the current context, where
    [P] has been defined by an [Inductive] declaration.  Then,
    for each of the constructors of [P], [inversion I] generates
    a subgoal in which [I] has been replaced by the exact,
    specific conditions under which this constructor could have
    been used to prove [P].  Some of these subgoals will be
    self-contradictory; [inversion] throws these away.  The ones
    that are left represent the cases that must be proved to
    establish the original goal.

    In this particular case, the [inversion] analyzed the construction
    [ev (S (S n))], determined that this could only have been
    constructed using [ev_SS], and generated a new subgoal with the
    arguments of that constructor as new hypotheses.  (It also
    produced an auxiliary equality, which happens to be useless here.)
    We'll begin exploring this more general behavior of inversion in
    what follows. *)

(** **** Exercise: 1 star (inversion_practice) *)
Theorem SSSSev__even : forall n,
  ev (S (S (S (S n)))) -> ev n.
Proof.
  intros n.
  intros E.
  inversion E.
  inversion H0.
  apply H2.
Qed.

(** The [inversion] tactic can also be used to derive goals by showing
    the absurdity of a hypothesis. *)

Theorem even5_nonsense :
  ev 5 -> 2 + 2 = 9.
Proof.
  intros H. inversion H. inversion H1. inversion H3.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)
(** Finding the appropriate thing to do induction on is a
    bit tricky here: *)

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
    intros n m.
    intros EV.
    intros evn.
    induction evn.
    simpl in EV.
    apply EV.
    apply IHevn.
    inversion EV.
    apply H0.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus) *)
(** Here's an exercise that just requires applying existing lemmas.  No
    induction or even case analysis is needed, but some of the rewriting
    may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
  intros n m p.
  intros enm enp.

 assert (e1: ev (n + m + (n + p))).
 apply ev_sum. apply enm. apply enp.

 replace (n + m + (n+ p)) with (n+n+(m+p)) in e1.
 apply ev_ev__ev with (n:=n+n). apply e1.
 assert(lemmad: forall n, n+n = double n).
 induction n0.
    reflexivity. simpl. apply f_equal. rewrite <- plus_n_Sm.
    apply f_equal. apply IHn0.

 rewrite -> lemmad. apply double_even.

 rewrite <- plus_assoc.
 rewrite <- plus_assoc.
 apply f_equal.
 rewrite plus_comm.
 rewrite <- plus_assoc.
 apply f_equal.
 apply plus_comm.
Qed.
(** [] *)

(* ####################################################### *)
(** * Additional Exercises *)

(** **** Exercise: 4 stars (palindromes) *)
(** A palindrome is a sequence that reads the same backwards as
    forwards.

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor
    c : forall l, l = rev l -> pal l
      may seem obvious, but will not work very well.)

    - Prove that
       forall l, pal (l ++ rev l).
    - Prove that
       forall l, pal l -> l = rev l.
*)

Inductive pal {X: Type}:  list X -> Prop :=
    | pal_nil: pal []
    | pal_add: forall x: X, forall l: list X,
                pal l -> pal (x :: (snoc l x))
    | pal_one: forall x: X, pal [x].

Theorem snoc_rev_comm : forall X:Type, forall l1 l2: list X, forall x : X,
    l1 ++ (snoc l2 x) = (snoc (l1++l2) x).
Proof.
    intros X.  intros l1 l2 x.
    induction l1. reflexivity.
    simpl. apply f_equal.
    apply IHl1.
Qed.

Theorem pal1: forall X: Type, forall l: list X, pal(l ++ rev l).
Proof.
    intros X l.
    induction l.
    simpl. apply pal_nil.
    simpl.
    rewrite snoc_rev_comm.
    apply pal_add.
    apply IHl.
Qed.

Theorem pal2: forall X: Type, forall l: list X,
    pal l -> l = rev l.
Proof.
    intros X. intros l.
    intros P.
    induction P. reflexivity.
    rewrite IHP.
    simpl.
    rewrite rev_snoc.
    rewrite rev_involutive.
    simpl.
    apply f_equal.
    rewrite <- IHP.
    reflexivity.
    reflexivity.
Qed.
(** [] *)

(** **** Exercise: 5 stars, optional (palindrome_converse) *)
(** Using your definition of [pal] from the previous exercise, prove
    that
     forall l, l = rev l -> pal l.
Theorem list_munger: forall X: Type, forall l: list X, forall x0 x1: X,
    x1 :: l = (snoc l x0)
*)

Theorem empty_rev : forall X : Type, forall l: list X,
    rev l = [] -> l = [].
Proof.
    intros X l.
    intros H.
    destruct l.
    reflexivity.
    simpl in H.
    destruct (rev l).
    inversion H.
    inversion H.
Qed.

Lemma ble_nat_0_implies_0: forall n: nat,
    ble_nat n 0 = true -> n = 0.
Proof. intros n. destruct n. reflexivity.  intros H. inversion H. Qed.

Lemma length_0_implies_nil: forall X: Type, forall l: list X,
    length l = 0 -> l = [].
Proof. intros X l. intros H. destruct l. reflexivity. inversion H. Qed.

Lemma rev_len_ind: forall X: Type, forall l: list X, forall x: X,
    length (snoc l x) = S (length l).
Proof.
    intros X l x.
    induction l.
    reflexivity.
    simpl.
    apply f_equal.
    apply IHl.
Qed.

Lemma rev_len: forall X: Type, forall l: list X,
    length l = length (rev l).
Proof.
    intros X l.
    induction l.
    reflexivity.
    simpl.
    rewrite rev_len_ind.
    apply f_equal.
    apply IHl.
Qed.

Lemma ble_nat_0: forall n : nat, ble_nat n 0 = true -> n = 0.
Proof. intros n. destruct n. reflexivity. intros H. inversion H. Qed.

Lemma smaller_than_trans_1: forall n m: nat,
    ble_nat n m = true -> ble_nat n (S m) = true.
Proof.
    intros n m.
    generalize dependent m.
    induction n.
    intros m.
    reflexivity.

    induction m.
    intros H.
    simpl. inversion H.
    intros H.
    apply IHn.
    apply H.
Qed.

Lemma smaller_than_trans: forall n m: nat,
    ble_nat (S n) m = true -> ble_nat n m = true.
Proof.
    intros n m H.
    inversion H.
    destruct m. inversion H1.
    rewrite H1.

    destruct n.
    reflexivity.
    simpl.
    destruct m.
    inversion H.
    inversion H.
    rewrite H2.
    apply smaller_than_trans_1.
    apply H2.
Qed.

Theorem palindrome_converse_strong: forall X: Type, forall l: list X,
    forall m: nat,
    ble_nat (length l) m = true ->
    l = rev l ->
    pal l.
Proof.
    intros X l m.
    generalize dependent l.
    induction m.

    intros l.
    intros H.
    apply ble_nat_0_implies_0 in H.
    apply length_0_implies_nil in H.
    rewrite H.
    intros.
    apply pal_nil.

    intros l.
    intros Length_H.
    intros Rev_H.

    destruct l.
    apply pal_nil.
    destruct (rev l) eqn:Heq.
    assert (LNIL: l = []).
    apply empty_rev.
    apply Heq.
    rewrite LNIL.
    apply pal_one.
    replace (l) with (rev (rev l)).
    rewrite Heq.
    simpl.
    inversion Rev_H.
    rewrite Heq in H0.
    simpl in H0.
    inversion H0.
    apply pal_add.
    apply IHm.

    inversion Length_H.
    rewrite H3.
    rewrite H2 in H3.
    rewrite rev_len_ind in H3.
    rewrite rev_len. rewrite rev_involutive.
    apply smaller_than_trans.
    apply H3.
    rewrite -> rev_involutive.
    rewrite H2 in Heq.
    rewrite rev_snoc in Heq.
    inversion Heq.
    rewrite -> rev_involutive.
    symmetry. apply H3.
    apply rev_involutive.
Qed.

Theorem palindrome_converse: forall X: Type, forall l: list X,
    l = rev l -> pal l.
Proof.

    intros X.
    intros l.
    apply palindrome_converse_strong with (m:=length l).
    symmetry.
    apply ble_nat_refl.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced (subsequence) *)
(** A list is a _subsequence_ of another list if all of the elements
    in the first list occur in the same order in the second list,
    possibly with some extra elements in between. For example,
    [1,2,3]
    is a subsequence of each of the lists
    [1,2,3]
    [1,1,1,2,2,3]
    [1,2,7,3]
    [5,6,1,9,9,2,7,3,8]
    but it is _not_ a subsequence of any of the lists
    [1,2]
    [1,3]
    [5,6,2,1,7,3,8]

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)

    - Prove that subsequence is reflexive, that is, any list is a
      subsequence of itself.

    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a
      subsequence of [l2], then [l1] is also a subsequence of [l2 ++
      l3].

    - (Optional, harder) Prove that subsequence is transitive -- that
      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence
      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your
      induction carefully!
*)
Inductive subseq:  list nat -> list nat -> Prop :=
| subseq_nil:    subseq [] []
| subseq_space:  forall n: nat, forall l1 l2: list nat, subseq l1 l2 -> subseq l1 (n::l2)
| subseq_add:    forall n: nat, forall l1 l2: list nat, subseq l1 l2 -> subseq (n::l1) (n::l2)
.

Theorem subseq_refl: forall l: list nat, subseq l l.
Proof.
    induction l.
    apply subseq_nil.
    apply subseq_add.
    apply IHl.
Qed.

Lemma app_nil_r: forall X: Type, forall l: list X,
    l ++ [] = l.
Proof. intros X. induction l. reflexivity. simpl. apply f_equal. apply IHl. Qed.

Theorem subseq_nil_x: forall l: list nat, subseq l [] -> l = [].
Proof. intros l. intros H. inversion H. reflexivity. Qed.

Theorem subseq_nil_l: forall l: list nat, subseq [] l.
Proof. induction l. apply subseq_nil. apply subseq_space. apply IHl. Qed.

Theorem subseq_snoc: forall l1 l2: list nat, forall n : nat,
    subseq l1 l2 -> subseq l1 (snoc l2 n).
Proof.
    intros l1 l2 n.
    intros H.
    induction H.
    apply subseq_nil_l.
    simpl.
    apply subseq_space. apply IHsubseq.
    simpl. apply subseq_add. apply IHsubseq.
Qed.

Theorem subseq_app: forall l1 l2 l3: list nat, subseq l1 l2 -> subseq l1 (l2 ++ l3).
    intros l1 l2 l3.
    intros H.
    induction H.
    apply subseq_nil_l.
    simpl. apply subseq_space. apply IHsubseq.
    simpl. apply subseq_add. apply IHsubseq.
Qed.

Lemma subseq_simpl: forall n: nat, forall l1 l2 : list nat, subseq (n::l1) l2 ->
    subseq l1 l2.
Proof.
    intros n l1 l2.
    induction l2.
    intros H.
    inversion H.
    intros H.
    inversion H.
    apply subseq_space. apply IHl2. apply H2.
    apply subseq_space. apply H1.
Qed.

Lemma subseq_move: forall n : nat, forall l1 l2 : list nat, subseq (n::l1) (n::l2) ->
    subseq l1 l2.
Proof. intros n l1 l2.
    intros H.
    inversion H.
    apply subseq_simpl in H2.
    apply H2.
    apply H1.
Qed.

Theorem beq_nat_false_subseq: forall l1 l2: list nat, forall n1 n2: nat,
    beq_nat n1 n2 = false ->
    subseq (n1::l1) (n2::l2) ->
    subseq (n1::l1) l2.
Proof.
    intros l1 l2 n1 n2.
    intros beq H.

    inversion H.
    apply H2.
    rewrite H3 in beq.
    rewrite <- beq_nat_refl in beq.
    inversion beq.
Qed.

(**
*               1       2
*       0     0 1     0 2 0 0 0
*   9 9 0 9 9 0 1 9 9 0 2 0 0 0 9 9
* *)
Theorem subseq_transitive: forall l1 l2 l3: list nat, subseq l1 l2 -> subseq l2 l3 ->
    subseq l1 l3.
Proof.
    intros l1 l2 l3.
    intros H1 H2.
    generalize dependent l1.
    generalize dependent l2.
    induction l3.
    intros. apply subseq_nil_x in H2. rewrite H2 in H1. apply H1.
    intros. inversion H2.
    Case "FOO".
    subst. apply subseq_space.
    apply IHl3 with (l2:=l2). apply H3. apply H1.
    subst. inversion H1. subst. apply subseq_space. apply IHl3 with (l2:=l0). apply H3. apply H4.
    subst. apply subseq_add.
    apply IHl3 with (l2:=l0). apply H3. apply H4.
Qed.
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 2 stars, optional (R_provability) *)
(** Suppose we give Coq the following definition:
    Inductive R : nat -> list nat -> Prop :=
      | c1 : R 0 []
      | c2 : forall n l, R n l -> R (S n) (n :: l)
      | c3 : forall n l, R (S n) l -> R n l.
    Which of the following propositions are provable?

    - [R 2 [1,0]]
    - [R 1 [1,2,1,0]]
    - [R 6 [3,2,1,0]]
*)
Inductive R : nat -> list nat -> Prop :=
  | c1 : R 0 []
  | c2 : forall n l, R n l -> R (S n) (n :: l)
  | c3 : forall n l, R (S n) l -> R n l.

Example R1: R 2 [1;0]. Proof.  apply c2. apply c2. apply c1.  Qed.
Example R2: R 1 [1;2;1;0]. Proof. apply c3. apply c2. apply c3. apply c3. apply c2.
    apply c2. apply c2. apply c1. Qed.
(** [] *)

(* ####################################################### *)
(** * Relations *)

(** A proposition parameterized by a number (such as [ev] or
    [beautiful]) can be thought of as a _property_ -- i.e., it defines
    a subset of [nat], namely those numbers for which the proposition
    is provable.  In the same way, a two-argument proposition can be
    thought of as a _relation_ -- i.e., it defines a set of pairs for
    which the proposition is provable. *)

Module LeModule.

(** One useful example is the "less than or equal to"
    relation on numbers. *)

(** The following definition should be fairly intuitive.  It
    says that there are two ways to give evidence that one number is
    less than or equal to another: either observe that they are the
    same number, or give evidence that the first is less than or equal
    to the predecessor of the second. *)

Inductive le : nat -> nat -> Prop :=
  | le_n : forall n, le n n
  | le_S : forall n m, (le n m) -> (le n (S m)).

Notation "m <= n" := (le m n).

(** Proofs of facts about [<=] using the constructors [le_n] and
    [le_S] follow the same patterns as proofs about properties, like
    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]
    goals (e.g., to show that [3<=3] or [3<=6]), and we can use
    tactics like [inversion] to extract information from [<=]
    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)

(** *** *)
(** Here are some sanity checks on the definition.  (Notice that,
    although these are the same kind of simple "unit tests" as we gave
    for the testing functions we wrote in the first few lectures, we
    must construct their proofs explicitly -- [simpl] and
    [reflexivity] don't do the job, because the proofs aren't just a
    matter of simplifying computations.) *)

Theorem test_le1 :
  3 <= 3.
Proof.
  (* WORKED IN CLASS *)
  apply le_n.  Qed.

Theorem test_le2 :
  3 <= 6.
Proof.
  (* WORKED IN CLASS *)
  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.

Theorem test_le3 :
  (2 <= 1) -> 2 + 2 = 5.
Proof.
  (* WORKED IN CLASS *)
  intros H. inversion H. inversion H2.  Qed.

(** *** *)
(** The "strictly less than" relation [n < m] can now be defined
    in terms of [le]. *)

End LeModule.

Definition lt (n m:nat) := le (S n) m.

Notation "m < n" := (lt m n).

(** Here are a few more simple relations on numbers: *)

Inductive square_of : nat -> nat -> Prop :=
  sq : forall n:nat, square_of n (n * n).

Inductive next_nat (n:nat) : nat -> Prop :=
  | nn : next_nat n (S n).

Inductive next_even (n:nat) : nat -> Prop :=
  | ne_1 : ev (S n) -> next_even n (S n)
  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).

(** **** Exercise: 2 stars (total_relation) *)
(** Define an inductive binary relation [total_relation] that holds
    between every pair of natural numbers. *)
Inductive total_relation: nat -> nat -> Prop :=
    | arb: forall n m: nat, total_relation n m.

Example tr_1: total_relation 10 20. apply arb. Qed.
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 2 stars (empty_relation) *)
(** Define an inductive binary relation [empty_relation] (on numbers)
    that never holds. *)
Inductive empty_relation: nat -> nat -> Prop :=
.
Theorem empty_relation_implies_False: forall n m: nat,
    empty_relation n m -> False.
Proof.
    intros.
    inversion H.
Qed.
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 2 stars, optional (le_exercises) *)
(** Here are a number of facts about the [<=] and [<] relations that
    we are going to need later in the course.  The proofs make good
    practice exercises. *)
Lemma le_0_implies_0 : forall n: nat, n <= 0 -> n = 0.
Proof.
    intros n.
    destruct n. reflexivity. intros H. inversion H.
Qed.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
    induction n. apply le_n. apply le_S. apply IHn. Qed.

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
    intros.
    generalize dependent m.
    generalize dependent n.
    induction o.
    intros. inversion H0. subst. inversion H. apply le_n.
    intros. inversion H0. subst. apply H.
            subst. apply le_S. apply IHo with (n:=n).
            apply H2. apply H.
Qed.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
    intros.
    induction H. apply le_n. apply le_S. apply IHle.
Qed.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
    intros.
    inversion H. apply le_n.
    apply le_trans with (n:=S n).
    apply le_S. apply le_n.
    apply H1.
Qed.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
    intros a b.
    induction b.
    assert(a = a + 0). symmetry. apply plus_0_r.
    symmetry in H. rewrite H. apply le_n.
    assert(S(a + b) = a + S b).
    apply plus_n_Sm.
    symmetry in H.
    rewrite H.
    apply le_S.
    apply IHb.
Qed.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
 unfold lt.
 intros.
 split.
 apply le_trans with (n:= S(n1+n2)).
 apply n_le_m__Sn_le_Sm.
 apply le_plus_l. apply H.
 apply le_trans with (n:= S(n1+n2)).
 rewrite plus_comm.
 apply n_le_m__Sn_le_Sm.
 apply le_plus_l.
 apply H.
Qed.

Theorem lt_S : forall n m,
  n < m ->
  n < S m.
Proof.
    intros.
    apply le_S. unfold lt in H. apply H.
Qed.

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
 intros.
 generalize dependent n.
 induction m. destruct n. intros. inversion H. apply le_n. intros. inversion H.
 destruct n. intros. apply O_le_n.
 intros.
 inversion H.
 apply n_le_m__Sn_le_Sm.
 apply IHm.
 apply H1.
Qed.

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
    intros. generalize dependent n.
    induction m.
    intros. inversion H. reflexivity.
    intros.
    destruct n.
    reflexivity.
    simpl. apply IHm. apply Sn_le_Sm__n_le_m. apply H.
Qed.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
    intros.
    apply le_ble_nat.
    apply le_trans with (n:=m).
    apply ble_nat_true. apply H.
    apply ble_nat_true. apply H0.
Qed.

(** **** Exercise: 2 stars, optional (ble_nat_false) *)
Theorem ble_nat_false : forall n m,
  ble_nat n m = false -> ~(n <= m).
Proof.
 intros.
 intros H1.
 apply le_ble_nat in H1.
 destruct (ble_nat n m).
 inversion H. inversion H1.
Qed.
(** [] *)

(** **** Exercise: 3 stars (R_provability2) *)
Module R.
(** We can define three-place relations, four-place relations,
    etc., in just the same way as binary relations.  For example,
    consider the following three-place relation on numbers: *)

Inductive R : nat -> nat -> nat -> Prop :=
   | c1 : R 0 0 0
   | c2 : forall m n o, R m n o -> R (S m) n (S o)
   | c3 : forall m n o, R m n o -> R m (S n) (S o)
   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o
   | c5 : forall m n o, R m n o -> R n m o.

(** - Which of the following propositions are provable?
      - [R 1 1 2]
      - [R 2 2 6]

    - If we dropped constructor [c5] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

    - If we dropped constructor [c4] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

(* FILL IN HERE *)
[]
*)
Example r_1: R 1 1 2. Proof. apply c2. apply c3. apply c1. Qed.

(** **** Exercise: 3 stars, optional (R_fact) *)
(** Relation [R] actually encodes a familiar function.  State and prove two
    theorems that formally connects the relation and the function.
    That is, if [R m n o] is true, what can we say about [m],
    [n], and [o], and vice versa?
*)
Theorem nat_R: forall n m o :nat, n + m = o -> R n m o.
Proof.
    intros.
    generalize dependent m.
    generalize dependent o.
    induction n.
    simpl. intros. subst. induction o. apply c1. apply c3. apply IHo.
    intros.
    destruct o. inversion H.
    apply c2. apply IHn. inversion H. reflexivity.
Qed.

Theorem R_nat: forall n m o: nat, R n m o -> (n + m = o). Proof.
 intros m n o. intro H.
 induction H. reflexivity.
 rewrite  plus_Sn_m. apply f_equal. apply IHR.
 rewrite <- plus_n_Sm. apply f_equal. apply IHR.
 inversion IHR.
 rewrite  <- plus_n_Sm  in H1.
 inversion H1.
 reflexivity.
 rewrite plus_comm. apply IHR.
Qed.

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

(** As we have seen, a _proposition_ is a statement expressing a factual claim,
    like "two plus two equals four."  In Coq, propositions are written
    as expressions of type [Prop]. . *)

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

Check (ble_nat 3 2 = false).
(* ===> ble_nat 3 2 = false : Prop *)

Check (beautiful 8).
(* ===> beautiful 8 : Prop *)

(** *** *)
(** Both provable and unprovable claims are perfectly good
    propositions.  Simply _being_ a proposition is one thing; being
    _provable_ is something else! *)

Check (2 + 2 = 5).
(* ===> 2 + 2 = 5 : Prop *)

Check (beautiful 4).
(* ===> beautiful 4 : Prop *)

(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions
    of type [Prop]. *)

(** *** *)
(** We've mainly seen one place that propositions can appear in Coq: in
    [Theorem] (and [Lemma] and [Example]) declarations. *)

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

(** But they can be used in many other ways.  For example, we have also seen that
    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've seen several ways of constructing propositions.

       - We can define a new proposition primitively using [Inductive].

       - Given two expressions [e1] and [e2] of the same type, we can
         form the proposition [e1 = e2], which states that their
         values are equal.

       - We can combine propositions using implication and
         quantification. *)
(** *** *)
(** We have also seen _parameterized propositions_, such as [even] and
    [beautiful]. *)

Check (even 4).
(* ===> even 4 : Prop *)
Check (even 3).
(* ===> even 3 : Prop *)
Check even.
(* ===> even : nat -> Prop *)

(** *** *)
(** The type of [even], i.e., [nat->Prop], can be pronounced in
    three equivalent ways: (1) "[even] is a _function_ from numbers to
    propositions," (2) "[even] is a _family_ of propositions, indexed
    by a number [n]," or (3) "[even] is a _property_ of numbers."  *)

(** Propositions -- including parameterized propositions -- are
    first-class citizens in Coq.  For example, we can define functions
    from numbers to propositions... *)

Definition between (n m o: nat) : Prop :=
  andb (ble_nat n o) (ble_nat o m) = true.

(** ... and then partially apply them: *)

Definition teen : nat->Prop := between 13 19.

(** We can even pass propositions -- including parameterized
    propositions -- as arguments to functions: *)

Definition true_for_zero (P:nat->Prop) : Prop :=
  P 0.

(** *** *)
(** Here are two more examples of passing parameterized propositions
    as arguments to a function.

    The first function, [true_for_all_numbers], takes a proposition
    [P] as argument and builds the proposition that [P] is true for
    all natural numbers. *)

Definition true_for_all_numbers (P:nat->Prop) : Prop :=
  forall n, P n.

(** The second, [preserved_by_S], takes [P] and builds the proposition
    that, if [P] is true for some natural number [n'], then it is also
    true by the successor of [n'] -- i.e. that [P] is _preserved by
    successor_: *)

Definition preserved_by_S (P:nat->Prop) : Prop :=
  forall n', P n' -> P (S n').

(** *** *)
(** Finally, we can put these ingredients together to define
a proposition stating that induction is valid for natural numbers: *)

Definition natural_number_induction_valid : Prop :=
  forall (P:nat->Prop),
    true_for_zero P ->
    preserved_by_S P ->
    true_for_all_numbers P.

(** **** 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]. As its result, it should return a new 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)  (n: nat): Prop :=
    (oddb n = true -> Podd n)   /\
    (oddb n = false -> Peven n).

(** To test your definition, see whether you can 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.
    unfold combine_odd_even.
    destruct (oddb n).
    split. apply H.  apply H0.
    split. apply H. apply H0.
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.
  apply H.
  apply 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.
  apply H. apply H0.
Qed.
(** [] *)

(* ##################################################### *)
(** One more quick digression, for adventurous souls: if we can define
    parameterized propositions using [Definition], then can we also
    define them using [Fixpoint]?  Of course we can!  However, this
    kind of "recursive parameterization" doesn't correspond to
    anything very familiar from everyday mathematics.  The following
    exercise gives a slightly contrived example. *)

(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)
(** Define a recursive function
    [true_upto_n__true_everywhere] that makes
    [true_upto_n_example] work. *)

Fixpoint true_upto_n__true_everywhere (n: nat) (f: nat->Prop): Prop :=
    match n with
    | S n' => f n -> (true_upto_n__true_everywhere n' f)
    | 0 => forall m: nat, f m
    end.
(* FILL IN HERE *)

Example true_upto_n_example :
    (true_upto_n__true_everywhere 3 (fun n => even n))
  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).
Proof. unfold true_upto_n__true_everywhere. reflexivity.  Qed.
(** [] *)

(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)


(* week_39a_binary_trees.v *)
(* dIFP 2014-2015, Q1, Week 38 *)
(* Olivier Danvy <danvy@cs.au.dk> *)

(* ********** *)

Require Import Arith Bool unfold_tactic.

(* ********** *)

Inductive binary_tree_nat : Type :=
  | Leaf : nat -> binary_tree_nat
  | Node : binary_tree_nat -> binary_tree_nat -> binary_tree_nat.

Definition bt_0 :=
  Leaf 42.

Definition bt_1 :=
  Node (Leaf 10)
       (Leaf 20).

Definition bt_2 :=
  Node (Node (Leaf 10)
             (Leaf 20))
       (Leaf 30).

(*
Print bt_2.
bt_2 = Node (Node (Leaf 10) (Leaf 20)) (Leaf 30)
     : binary_tree_nat
*)

(* ********** *)

(* A unit test: *)

Notation "A =n= B" := (beq_nat A B) (at level 70, right associativity).

Definition unit_test_for_number_of_leaves (candidate : binary_tree_nat -> nat) :=
  (candidate bt_0 =n= 1)
  &&
  (candidate bt_1 =n= 2)
  &&
  (candidate bt_2 =n= 3)
  &&
  (candidate (Node bt_1 bt_2) =n= 5)
  .

Definition specification_of_number_of_leaves (number_of_leaves : binary_tree_nat -> nat) :=
  (forall n : nat,
     number_of_leaves (Leaf n) = 1)
  /\
  (forall t1 t2 : binary_tree_nat,
     number_of_leaves (Node t1 t2) = (number_of_leaves t1) + (number_of_leaves t2)).

Theorem there_is_only_one_number_of_leaves :
  forall f g : binary_tree_nat -> nat,
    specification_of_number_of_leaves f ->
    specification_of_number_of_leaves g ->
    forall t : binary_tree_nat,
      f t = g t.
Proof.
  intros f g.
  unfold specification_of_number_of_leaves.
  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].
  intro t.
  induction t as [n | t1 IHt1 t2 IHt2].

  rewrite -> Hf_leaf.
  rewrite -> Hg_leaf.
  reflexivity.

  rewrite -> Hf_node.
  rewrite -> Hg_node.
  rewrite -> IHt1.
  rewrite -> IHt2.
  reflexivity.
Qed.

Fixpoint number_of_leaves_ds (t : binary_tree_nat) : nat :=
  match t with
    | Leaf n =>
      1
    | Node t1 t2 =>
      (number_of_leaves_ds t1) + (number_of_leaves_ds t2)
  end.

Lemma unfold_number_of_leaves_ds_leaf :
  forall n : nat,
    number_of_leaves_ds (Leaf n) = 1.
Proof.
  unfold_tactic number_of_leaves_ds.
Qed.

Lemma unfold_number_of_leaves_ds_node :
  forall t1 t2 : binary_tree_nat,
    number_of_leaves_ds (Node t1 t2) =
    (number_of_leaves_ds t1) + (number_of_leaves_ds t2).
Proof.
  unfold_tactic number_of_leaves_ds.
Qed.

Definition number_of_leaves_v0 (t : binary_tree_nat) : nat :=
  number_of_leaves_ds t.

Compute unit_test_for_number_of_leaves number_of_leaves_v0.
(*
     = true
     : bool
*)

(* Homework:
   write a version number_of_leaves_v1
   that uses an accumulator.
*)

(* ********** *)

(* Exercise:
   do the same as above for computing the number of nodes
   of a binary tree.
*)

(* ********** *)

(* end of week_39a_binary_trees.v *)