Require Import Ensembles ssrfun Description Relations_1 IndefiniteDescription
  Classical_Prop.

Require Import base.

(* 群的第一定义 *)
Module group_first.

Record class_of {A : Type} (X : Ensemble A) := Class {
  base :> assoc_law X;
  _ : exists_solution base X;
}.

Structure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.

Notation Group_Fst := type.
Notation Group_Fst_Class := class_of.

Definition is_fst_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=
  binary_operation op G /\ associative op /\ exists_solution op G /\ notEmpty G.

End group_first.

Export group_first.

(* 群的第二定义 *)
Module group_second.

Record class_of {A : Type} (X : Ensemble A) := Class {
  base :> assoc_law X;
  zero : A;
  inv : A -> A;
  _ : left_id zero base; (* 左单位元 *)
  _ : left_inverse zero inv base;  (* 左逆元 *)
}.

Structure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.

Notation Group_Snd := type.
Notation Group_Snd_Class := class_of.

Definition is_snd_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=
  binary_operation op G /\ associative op /\ notEmpty G /\
  exists (zero: A), left_id zero op /\ exists (inv: A -> A), left_inverse zero inv op.

End group_second.

Export group_second.

Module group.

Record class_of {A : Type} (X : Ensemble A) := Class {
  base :> assoc_law X;
  zero : A;
  inv : A -> A;
  _ : left_id zero base; (* 左单位元 *)
  _ : right_id zero base;
  _ : left_inverse zero inv base;  (* 左逆元 *)
  _ : right_inverse zero inv base;
}.

Structure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.

Notation Group := type.
Notation Group_Class := class_of.

Definition is_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=
  binary_operation op G /\ associative op /\ notEmpty G /\
  exists (zero: A), left_id zero op /\ right_id zero op /\
  exists (inv: A -> A), left_inverse zero inv op /\ right_inverse zero inv op.

End group.

Export group.

Arguments group.Pack {A}.
Arguments group.Class {A}.

(* 可证 *)
Lemma groupfsttosnd {A: Type} (G : Ensemble A) (op: A -> A -> A) :
  is_fst_group G op <-> is_snd_group G op.
Proof.
  split.
  - intros. destruct H, H0, H1. red in H, H, H0, H1, H2.
    split; auto. split; auto. split; auto.
    assert (exists zero : A, left_id zero op).
    { destruct H2. generalize H1 H2; intros.
      specialize (H1 x x). destruct H1, H1, H5.
      exists x1. red; intros.
      specialize (H3 x x2). destruct H3, H3, H6.
      rewrite <- H3. specialize (H0 x1 x x3).
      rewrite  H0. rewrite H5; auto. }
    destruct H3. exists x. split; auto.
    rename x into e. unfold left_inverse.
    assert (forall a, {a' : A | op a' a = e}).
    { intros. apply constructive_indefinite_description.
      specialize (H1 a e). destruct H1; auto. }
    exists (fun a => proj1_sig (X a)); eauto.
    intros.
    pose proof (X x). destruct (X x). simpl; auto.
  - intros. destruct H,H0, H1, H2, H2, H3.
    rename x into e; rename x0 into inv.
    red in H, H, H0, H2, H3. split; auto.
    split; auto. split; auto. red. intros.
Admitted.

(* 可证 *)
Lemma groupsndto {A: Type} (G : Ensemble A) (op: A -> A -> A) :
  is_snd_group G op <-> is_group G op.
Proof.
  split.
  - admit.
  - intros. destruct H, H0, H1, H2, H2, H3, H4, H4.
    repeat split; auto. exists x; split; auto.
    exists x0; auto.
Admitted.

(* 子群 *)
Section subgroups.

Variable A : Type.

Definition grouptoclass (G : @Group A) := let: group.Pack _ imp as G' := G
  return Group_Class G' in imp.

Definition zeroG (G : @Group A) := zero G (grouptoclass G).

Definition invG (G : @Group A) := inv G (grouptoclass G).

Definition addG (G : @Group A) := add G (grouptoclass G).

Structure sub_group (G : @Group A) := sub_Group{
  subGens :> Ensemble A;
  _ : notEmpty subGens;
  _ : Included subGens G;
  _ : is_group subGens (addG G);
}.

(* 由子群作成的群 *)
Definition subgrouptogroup (G : @Group A) (H : sub_group G) : @Group A.
  destruct H, i0, H0. destruct H1 as [K H1].
  clear H1. unfold addG, grouptoclass in H,H0.
  destruct G, c, base0. simpl in *.
  Check (Assoc A subGens0 add0 H H0 K).
  Check (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0).
  Check (group.Pack subGens0 (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0)).
  exact (group.Pack subGens0 (group.Class subGens0 (Assoc A subGens0 add0 H H0 n) zero0 inv0 l r l0 r0)).
Defined.

End subgroups.

Arguments grouptoclass {A}.
Arguments zeroG {A}.
Arguments invG {A}.
Arguments addG {A}.
Arguments sub_group {A}.

Section groupTheorem.
Variable A : Type.
Variable G : @Group A.

Axiom invG_pro : forall a, In G a -> In G (invG G a).

Lemma group_assoc : forall (a b c : A), addG G a (addG G b c) = addG G (addG G a b) c.
Proof.
  intros.
  unfold addG; unfold grouptoclass.
  destruct G, c0, base0; simpl; auto.
Qed.
Lemma group_bin : binary_operation (addG G) G.
Proof.
  red; red. unfold addG, grouptoclass.
  destruct G, c, base0; simpl.
  red in b, b; auto.
Qed.

Lemma group_operation_pro : forall a b, invG G (addG G a (invG G b)) = addG G b (invG G a).
Admitted.

Lemma group_operation_pro1 : forall x y z,
  (addG G (addG G x (invG G y)) (addG G y (invG G z))) = addG G x (invG G z).
Admitted.

Lemma group_operation_pro2 : forall x, (addG G x (invG G x)) = zeroG G.
Proof.
  unfold addG, invG, zeroG, grouptoclass.
  destruct G, c; simpl; auto.
Qed.

End groupTheorem.

Hint Rewrite group_assoc.

Section II_8_Theorem.

Variable A : Type.

Variable G : @Group A.

(* H是G的子群 则有如下性质 (1) 任意a b属于H 则 add a b 属于H
                        (2) a属于H，-> inv a 属于H *)
Theorem theorem_II_8_1to (H : sub_group G) :
  (forall a b, In H a -> In H b -> In H (addG G a b)) /\
  (forall a, In H a -> In H (invG G a)).
Proof.
  split.
  - destruct H, i0; simpl; auto. red in b, b. intros.
    apply (b a0 b0) in H; auto.
    destruct H, H. rewrite H1; auto.
  - intros. generalize invG_pro; intros.
    specialize (H1 A (subgrouptogroup A G H) a).
    destruct H; simpl in *; auto.
    destruct i0; simpl in *; auto.
    destruct a0; simpl in *; auto.
    destruct a1; simpl in *; auto.
    destruct G; simpl in *; auto.
    destruct c; simpl in *; auto.
    destruct base0; simpl in *; auto.
Qed.

(* 集合X有如下性质 *)
Theorem theorem_II_8_1from (X : Ensemble A) : notEmpty X -> Included X G ->
  (forall a b, In X a -> In X b -> In X (addG G a b)) /\ (forall a, In X a -> In X (invG G a)) ->
  is_snd_group X (addG G).
Proof.
  intros. destruct H1. split.
  red; red. intros. exists (addG G x y). split; auto.
  split. red. unfold addG, grouptoclass.
  unfold addG, grouptoclass in H1, H2; simpl.
  destruct G, c, base0; simpl; auto.
  split; auto. unfold addG, grouptoclass.
  destruct G, c; simpl; auto.
  exists zero0; split; auto. exists inv0; auto.
Qed.

Lemma inference_II_8' (H : sub_group G) : In H (zeroG G) /\ zeroG (subgrouptogroup A G H) = zeroG G.
Proof.
  split.
  - generalize (theorem_II_8_1to H); intros. destruct H0.
    destruct H; simpl. destruct n; simpl.
    simpl in H1, H0. generalize i1; intros. apply H1 in i1.
    apply (H0 x (invG G x)) in i2; auto.
    rewrite group_operation_pro2 in i2; auto.
  - unfold subgrouptogroup. destruct H; simpl in *; auto.
    destruct i0; simpl in *; auto. destruct a; simpl in *; auto.
    destruct a0; simpl in *; auto. destruct G; simpl in *; auto.
    destruct c; simpl in *; auto. destruct base0; simpl in *; auto.
Qed.

Lemma inference_II_8'' (H : sub_group G) : forall a, In H a -> invG (subgrouptogroup A G H) a = invG G a.
Proof.
  intros.
  unfold subgrouptogroup. destruct H; simpl in *; auto.
  destruct i0; simpl in *; auto.
  destruct a0; simpl in *; auto.
  destruct a1; simpl in *; auto.
  destruct G; simpl in *; auto.
  destruct c; simpl in *; auto.
  destruct base0; simpl in *; auto.
Qed.

(* 子群的充要条件 可证 *)
Theorem theorem_II_8_2to (H : sub_group G) : forall a b, In H a -> In H b -> In H (addG G a (invG G b)).
Admitted.

(* 可证 *)
Theorem theorem_II_8_2from (X : Ensemble A) : notEmpty X -> Included X G ->
  (forall a b, In X a -> In X b -> In X (addG G a (invG G b))) ->
  is_snd_group X (addG G).
Admitted.

End II_8_Theorem.

Section coset.

Inductive right_coset {A : Type} (G : @Group A) (H : sub_group G) (a : A) : Ensemble A :=
  right_coset_intro : forall b, In H (addG G a (invG G b)) -> In (right_coset G H a) b.

Inductive left_coset {A : Type} (G : @Group A) (H : sub_group G) (a : A) : Ensemble A :=
  left_coset_intro : forall b,  In H (addG G (invG G b) a ) -> In (left_coset G H a) b.
End coset.

Section normal_subgroups.

Variable A : Type.

Structure normal_subgroup (G : @Group A) := normal_SubGroup{
  normalSubGens :> sub_group G ;
  _ : forall a, Same_set (right_coset G normalSubGens a) (left_coset G normalSubGens a);
}.

End normal_subgroups.

Arguments normal_subgroup {A}.
Arguments normal_SubGroup {A}.

Section quotient_groups.

(* 陪集 *)
Variable A : Type.

(* G是一个群，H是G的不变子群，给一个元素repr；返回其一个陪集类型 *)
Structure coset (G: @Group A) (H: normal_subgroup G) : Type := makeCoset{
  repr : A ;
}.

(* 提取出代表元 *)
Definition coset_to_repr G H (a : coset G H) : A.
  destruct a as [a].
  exact a.
Defined.

(* 元间的关系 即 a与b等价 <-> a*b逆 属于H  *)
Definition right_coset_element_relation (G: @Group A) (H: sub_group G) (a b : A) :=
  In H (addG G a (invG G b)).

(* 该关系是一个等价关系 *)
Lemma right_coset_relation_is_equivalence (G: @Group A) (H: sub_group G) :
  Equivalence (right_coset_element_relation G H).
Proof.
  split.
  - red. red. intros. generalize inference_II_8'; intros.
    specialize (H0 A G H). destruct H0. unfold addG, invG, grouptoclass.
    destruct G, c; simpl. red in r0. remember r0; clear Heqe.
    specialize (r0 x). rewrite r0; auto.
  - red. unfold right_coset_element_relation.
    intros.
    generalize theorem_II_8_1to; intros. specialize (H2 A G H).
    destruct H2.
    apply (H2 (addG G x (invG G y)) (addG G y (invG G z))) in H0; auto.
    rewrite group_operation_pro1 in H0; auto.
  - red. unfold right_coset_element_relation. intros.
    generalize theorem_II_8_1to; intro H2. specialize (H2 A G H).
    destruct H2. apply H2 in H0.
    rewrite group_operation_pro in H0; auto.
Qed.

(* coset 相等 *)
Definition coset_eq (G: @Group A) (H: normal_subgroup G) (a b : coset G H) :=
  exists c, In (right_coset G H c) (coset_to_repr G H a) /\
            In (right_coset G H c) (coset_to_repr G H b).

(* coest相等的外延公理 *)
Axiom coset_eq_axiom : forall (G: @Group A) (H: normal_subgroup G) (a b : coset G H),
  a = b <-> coset_eq G H a b.

(* 两个陪集相等 那么他们的代表元等价 即 addG a invG b 属于 H *)
Lemma coset_pro1 (G: @Group A) (H: normal_subgroup G) (a b : coset G H) :
  coset_eq G H a b <-> In H (addG G (coset_to_repr G H a) (invG G (coset_to_repr G H b))).
Proof.
  split.
  - intros. destruct H0, H0.
    generalize right_coset_relation_is_equivalence; intros.
    specialize (H2 G H). destruct H2.
    red in H2, H3, H4. unfold right_coset_element_relation in H3, H4.
    destruct a, b; simpl.
    simpl in H0, H1. destruct H0, H1.
    apply H4 in H0. apply (H3 b x b0) in H0; auto.
  - destruct a, b; simpl. intros.
    red. exists repr0. split.
    + apply right_coset_intro; simpl.
      rewrite group_operation_pro2. generalize (inference_II_8' A G H); intros.
      tauto.
    + apply right_coset_intro in H0. auto.
Qed.

(* 给一个a 返回包含a的陪集 *)
Definition quotient_mapping (G: @Group A) (H: normal_subgroup G) (a: A) : coset G H.
  exact (makeCoset G H a).
Defined.

Definition quotient_z G H : coset G H.
    apply (makeCoset _ _ (zeroG G)).
Defined.

Definition quotient_add G H : coset G H -> coset G H -> coset G H.
    intros a b.
    (* this is dumb,but basically we just don't care about the coset repr *)
    destruct a as [a].
    destruct b as [b].
    exact (makeCoset _ _ ((addG G) a b)).
Defined.

Definition quotient_inv G H: coset G H -> coset G H.
  intros a.
  destruct a as [a].
  exact (makeCoset _ _ ((invG G) a)).
Defined.

Inductive quotient_ens G H : Ensemble (coset G H) :=
  quotient_ens_intro : forall a, In G a -> In (quotient_ens G H) (makeCoset G H a).

Lemma quotient_pro G H : binary_operation (quotient_add G H) (quotient_ens G H).
Proof.
  red; red; intros.
  destruct H0, H1.
  destruct G; simpl.
  unfold addG, grouptoclass.
  destruct c, base0. red in b, b.
  apply (b a a0) in H0; auto.
  destruct H0, H0.
  exists (makeCoset (Pack sort0 (Class sort0 (Assoc A sort0 add0 b a1 n) zero0 inv0 l r l0 r0)) H x).
  split. apply quotient_ens_intro; auto.
  simpl. rewrite H2; auto.
Qed.

Definition quotient_assoc_law (G: @Group A) (H: normal_subgroup G) : assoc_law (quotient_ens G H).
  apply (base.Assoc _ _ (quotient_add G H)).
  generalize group_bin; intros.
  specialize (H0 A G).
  red; red. intros. destruct H1, H2.
  red in H0, H0. apply (H0 a a0) in H1; auto.
  destruct H1, H1.
  exists (makeCoset G H x).
  split; auto. apply quotient_ens_intro; auto.
  unfold quotient_add; auto. rewrite H3; auto.
  red. intros [x] [y] [z].
  unfold quotient_add. autorewrite with core; auto.
  red. destruct G, c, base0, n; simpl.
  exists (makeCoset (Pack sort0 (Class sort0 (Assoc A sort0 add0 b a (ex_intro [eta In sort0] x i)) zero0 inv0 l r l0 r0)) H x).
  apply quotient_ens_intro; auto.
Defined.

(* 可证 *)
Definition quotient_Group_Class (G: @Group A) (H:  normal_subgroup G) : Group_Class (quotient_ens G H).
  apply (group.Class _ (quotient_assoc_law G H) (quotient_z G H) (quotient_inv G H)).
  - red; intros. unfold quotient_z. destruct x; simpl.
    unfold addG, zeroG, grouptoclass.
    destruct G, c; simpl; auto. red in l.
    pose proof (l repr0). rewrite H0; auto.
  - red; intros. unfold quotient_z. destruct x; simpl.
    unfold addG, zeroG, grouptoclass.
    destruct G, c; simpl; auto. red in r.
    pose proof (r repr0). rewrite H0; auto.
  - red; intros. unfold quotient_z, quotient_inv. destruct x; simpl.
    unfold addG, invG, zeroG, grouptoclass; simpl; auto.
    destruct G, c; simpl; auto.
    red in l0. pose proof (l0 repr0).
    rewrite H0; auto.
  - red; intros. unfold quotient_z, quotient_inv. destruct x; simpl.
    unfold addG, invG, zeroG, grouptoclass; simpl; auto.
    destruct G, c; simpl; auto.
    red in r0. pose proof (r0 repr0).
    rewrite H0; auto.
Defined.

(* 商群  可证 *)
Definition quotient_group (G: @Group A) (H: normal_subgroup G) : @Group (coset G H).
    apply (group.Pack _ (quotient_Group_Class G H)).
Defined.

End quotient_groups.

Arguments coset {A}.
Arguments makeCoset {A}.

(* 加群 *)
Module group_add.

Record class_of {A : Type} (X : Ensemble A) := Class {
  base :> Group_Class X;
  _ : commutative base;
}.

Structure type {A : Type} := Pack {sort :> Ensemble A; _ : class_of sort}.

Notation Group_Add := type.
Notation Group_Add_Class := class_of.

Definition is_add_group {A: Type} (G : Ensemble A) (op: A -> A -> A) :=
  is_group G op /\ commutative op.

End group_add.

Export group_add.


(***************************************************************************)
(*   This is part of FA_3rdCalculus, it is distributed under the terms     *)
(*         of the GNU Lesser General Public License version 3              *)
(*                (see file LICENSE for more details)                      *)
(*                                                                         *)
(*            Copyright 2020-2022: Yaoshun Fu and Wensheng Yu.             *)
(***************************************************************************)

Require Export DCF.

Definition additivity S a b:=
  ∀ u v w, u ∈ [a|b] -> v ∈ [a|b] -> w ∈ [a|b] -> S u v + S v w = S u w.

Definition intermed S f a b :=
  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> v > u ->
  ∃ p q, p ∈ [u|v] /\ q ∈ [u|v] /\ f(p)·(v-u) ≦ S u v /\ S u v ≦ f(q)·(v-u).

Definition integralsystem S f a b := additivity S a b /\ intermed S f a b.

Definition integrable S f a b :=
  ∀ S', integralsystem S' f a b ->
  (∀ x y, x ∈ [a|b] -> y ∈ [a|b] -> S x y = S' x y).

Definition definiteiInt S f a b := integralsystem S f a b /\ integrable S f a b.

Notation " S =∫ f " := (definiteiInt S f)(at level 10).

Theorem Int_med : ∀ {S f a b},
  integralsystem S f a b -> ∀ c, c ∈ [a|b] -> diff_quo_median (S c) f a b.
Proof.
  intros. destruct H. red; intros.
  pose proof (H _ _ _ H0 H2 H3). rewrite <- H4; Simpl_R.
  destruct (H1 _ _ H2 H3 (Theorem182_1 _ _ l)) as [p [q [H5 [H6 [H7]]]]].
  exists p, q. split; auto. split; auto.
  split; apply LeTi_R2 with (z:=v-u); Simpl_R.
Qed.

Theorem Med_Int : ∀ {F f a b},
  diff_quo_median F f a b -> integralsystem F# f a b.
Proof.
  intros. split; red; intros.
  - unfold input2Mi. rewrite <- (Theorem181 (F v)); Simpl_R.
    rewrite Mi_R'. Simpl_R. apply Theorem181.
  - apply Theorem182_1' in H2.
    destruct (H _ _ H2 H0 H1) as [p [q [H3 [H4 [H5]]]]].
    apply LeTi_R1 with (z:=v-u) in H5; Simpl_Rin H5.
    apply LeTi_R1 with (z:=v-u) in H6; Simpl_Rin H6. exists p, q; auto.
Qed.

Theorem Int_DefInt : ∀ {S f a b}, S =∫ f a b ->
  ∀ c, c ∈ [a|b] -> ∀ F, diff_quo_median F f a b ->
  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> (S c)# u v = F# u v.
Proof.
  intros. destruct H. pose proof (Int_med H _ H0).
  destruct H. pose proof (Med_Int H1). rewrite <- (H4 _ H7); auto.
  unfold input2Mi; apply Theorem188_2 with (Θ:=S c u); Simpl_R.
  rewrite Theorem175. rewrite H; auto.
Qed.

Theorem DefInt_Int : ∀ {F f a b} , diff_quo_median F f a b ->
  (∀ F', diff_quo_median F' f a b ->
  ∀ u v, u ∈ [a|b] -> v ∈ [a|b] -> F# u v = F'# u v) -> F# =∫ f a b.
Proof.
  intros. split; [apply Med_Int; auto|red; intros].
  pose proof (Int_med H1 _ H2). destruct H1.
  rewrite (H0 _ H4 _ _ H2 H3). unfold input2Mi.
  pattern (S' x y) at 1. rewrite <- (H1 x x y); Simpl_R.
Qed.


(******************************************************************************)
(* Dr Daniel Kirk (c) 2021                                                    *)
(******************************************************************************)
(* Let R : ringType                                                           *)
(******************************************************************************)
(* freeLmodType R == a record consisting of an lmodType R 'sort' and          *)
(*                   a (lmodBasisType sort)                                   *)
(*                   M : freeLmodType M coerces to its underlying lmodType    *)
(******************************************************************************)
(* Let M : freeLmodType R                                                     *)
(* basis M             == underlying lmodBasisType object of M                *)
(* \freeBasisCoef_(b) x == \basisProj_b^(basis M) x                           *)
(******************************************************************************)
(* fdFreeLmodType R == a record consisting of an lmodType R 'sort' and        *)
(*                     a (lmodFinBasisType sort)                              *)
(*                     M : fdFreeLmodType M coerces to its underlying         *)
(*                     lmodType but not to freeLmodType                       *)
(******************************************************************************)
(* Let M : fdFreeLmodType R                                                   *)
(*                fdBasis M == underlying lmodFinBasisType object of M        *)
(* fdFreeLmod_to_freeLmod M == converts to underlying lmodBasisType           *)
(*   \fdFreeBasisCoef_(b) x == \finBasisProj_b^(fdBasis M) x                  *)
(******************************************************************************)
(* null_fdFreeLmod R == the fdFreeLmodType structure for null_lmodType:       *)
(*                        the trivial module over R. It has the null basis.   *)
(* unit_fdFreeLmod R == the fdFreeLmodType structure for unit_lmodType:       *)
(*                        R as a module over itself. It has a basis with one  *)
(*                        element (unit).                                     *)
(* matrix_fdFreeLmod R n m == the fdFreeLmodType structure for                *)
(*                            matrix_lmodType n m: the matrix objects defined *)
(*                            in mathcomp matrix.v. It has a basis 'I_n*'I_m  *)
(* vector_fdFreeLmod R n   == the fdFreeLmodType structure for                *)
(*                            matrix_lmodType 1 n, the row matrix objects.    *)
(*                            It has a basis 'I_n                             *)
(*        R\lmod^n         == alias for vector_fdFreeLmod R n                 *)
(* poly_fdFreeLmod R n     == the fdFreeLmodType structure for                *)
(*                            poly_lmodType n. [TODO]                         *)
(******************************************************************************)
(* freeLinear.to_row   == linIsomType mapping a fdFreeLmod with basis         *)
(*                        number n to R\lmod^n                                *)
(* freeLinear.to_map   == function mapping {linear M -> N} to the equivalent  *)
(*                        {linear R\lmod^m -> R\lmod^n} where M and N have    *)
(*                        basis numbers m and n respectively                  *)
(* freeLinear.from_map == inverse of freeLinear.to_map                        *)
(******************************************************************************)
(*        M1 \foplus M2  == the fdFreeLmodType given by M1 \oplus M2 and      *)
(*                          Pair.basis M1 M2                                  *)
(*                          Pair.basis M1 M2 == finBasisType with index-set   *)
(*                          (fdBasis M1) + (fdBasis M2) and                   *)
(*                          elem x := match x with                            *)
(*                            |inl y => (B1 y, 0)                             *)
(*                            |inr y => (0, B2 y)                             *)
(*                          end                                               *)
(* \fbigoplus_(f in L) I == the fdFreeLmodType given by \bigoplus_(f in L) I  *)
(*                          and Seq.basis I L                                 *)
(*                          Seq.basis I nil has                               *)
(*                            index-set == null_finType                       *)
(*                            elem x    == tt                                 *)
(*                          Seq.basis I a::L has                              *)
(*                            index-set ==                                    *)
(*                              Pair.basis (fdBasis (I a)) (Seq.basis I L)    *)
(*                            elem x    ==  match x with                      *)
(*                                          |inl y => (fdBasis (I a) y, 0)    *)
(*                                          |inr y => (0, Seq.basis I L y)    *)
(*                                          end                               *)
(*       \fbigoplus_F I == equivalent to \fbigoplus_(f : F) I                 *)
(*         \fbigoplus I == equivalent to \fbigoplus_(f : F) I                 *)
(*                         where I : F -> lmodType R                          *)
(******************************************************************************)
(* FreeModule_UniversalProperty == [TODO] *)
(******************************************************************************)

Require Import Coq.Program.Tactics.
Require Import Coq.Logic.ProofIrrelevance.
Require Import Coq.Logic.FunctionalExtensionality.
From mathcomp Require Import ssreflect ssrfun seq.
From mathcomp Require Import eqtype fintype bigop matrix poly.

Set Warnings "-parsing". (* Some weird bug in ssrbool throws out parsing warnings*)
  From mathcomp Require Import ssrbool ssrnat.
Set Warnings "parsing".

Set Warnings "-ambiguous-paths". (* Some weird bug in ssralg throws out coercion warnings*)
    From mathcomp Require Import ssralg.
Set Warnings "ambiguous-paths".

Require Import Modules Linears DirectSum FiniteSupport lmodLC Basis.
Set Implicit Arguments.
Unset Strict Implicit.
Open Scope ring_scope.

Include GRing.

Open Scope lmod_scope.
(*
  Definitions of the Free and Finite Dimensional Free Module Types
    *)

Module freeLmod.
  Section Def.
    Variable (R : ringType).
    Record mixin (M : lmodType R) := Mixin { basis : lmodBasisType M; }.
    Record type := Pack { sort : _ ;  class_of : mixin sort; }.
    Definition Build {M : lmodType R} (B : lmodBasisType M) := Pack (Mixin B).
  End Def.

  Module Exports.
    Coercion sort : type >-> lmodType.
    Coercion class_of : type >-> mixin.
    Notation freeLmodType := type.
    Notation basis := basis.
    Notation freeLmodPack := Build.
    Notation coef := (fun (R : ringType) (M : type R) b => \basisProj_b^(basis M)).
    Notation "\freeBasisCoef_( b ) x" := (@coef _ _ b x) (at level 36) : lmod_scope.
  End Exports.
End freeLmod.
Export freeLmod.Exports.

(* Finite dimenisonal free modules are compatible with finite direct sums
   That is they can be built-up and have corresponding proj and inj morphisms *)
Module fdFreeLmod.
  Section Def.
    Variable (R : ringType).
    Record mixin (M : lmodType R) := Mixin { fdBasis : lmodFinBasis.type M; }.
    Record type := Pack { sort : _ ;  class_of : mixin sort; }.
    Definition Build {M : lmodType R} (B : lmodFinBasis.type M) := Pack (Mixin B).

    Definition to_arb (F : type) := freeLmod.Build (lmodFinBasis.to_lmodBasis (fdBasis (class_of F))).
    Definition erefl (B : type) := erefl (size (enum (to_FinType (fdBasis (class_of B))))).
    Definition eqBn (B : type) (n : nat) := size (enum (to_FinType (fdBasis (class_of B)))) = n.
    Definition eqnB (B : type) (n : nat) := n = size (enum (to_FinType (fdBasis (class_of B)))).
  End Def.

  Module Exports.
    Coercion sort : type >-> lmodType.
    Coercion class_of : type >-> mixin.
    Notation fdFreeLmodType := type.
    Notation fdBasis := fdBasis.
    Notation fdFreeLmodPack := Build.

    Notation coef := (fun (R : ringType) (M : type R) b => \basisProj_b^(fdBasis M)).
    Notation "\fdFreeBasisCoef_( b ) x" := (@coef _ _ b x) (at level 36) : lmod_scope.
    Notation fdFreeLmod_to_freeLmod := to_arb.
  End Exports.
End fdFreeLmod.
Export fdFreeLmod.Exports.

(*
  Free Module Types of:
    the trivial modules (null basis)
    the ring as a module over itself (unit basis)
    matrix modules over a ring
    polynomial modules over a ring
    *)

Module fdFreeLmodNull.
  Section Def.
    Variable (R : ringType).

    Definition nullBasis_fn := fun x : void => match x with end : (lmodZeroType R).

    Lemma null_injective : injective nullBasis_fn.
    Proof. by move=>x; destruct x. Qed.

    Lemma null_nondeg : non_degenerate nullBasis_fn.
    Proof. by move=>x; destruct x. Qed.

    Definition null_set := lmodFinSet.Build null_injective null_nondeg.

    Lemma null_li : lmodBasis.li null_set.
    Proof. move=>C H.
      rewrite lmodLC.eqFSFun/=.
      apply functional_extensionality=>b.
      destruct C as [coef [s [U E]]].
      by induction s.
    Qed.

    Lemma null_sp : lmodBasis.span null_set.
    Proof. move=>m;
      apply (exist _ (nullFSType R null_set) (lmodLC.null_sumsTo _)).
    Qed.
    Definition basis := lmodFinBasis.Build null_li null_sp.
  End Def.
  Module Exports.
    Canonical null_fdFreeLmod (R : ringType) := Eval hnf in @fdFreeLmodPack R _ (fdFreeLmodNull.basis R).
  End Exports.
End fdFreeLmodNull.
Export fdFreeLmodNull.Exports.

Module freeRingModule.
  Section Def.
    Variable (R : ringType).
    Definition fn := fun _ : unit_eqType => (GRing.one R) : (ringModType R).
    Lemma fn_injective : injective fn.
      Proof. by move=>x y; destruct x, y. Qed.
    Lemma fn_nondegen : non_degenerate fn.
      Proof. rewrite /fn=>x; apply GRing.oner_neq0. Qed.

    Definition bset := lmodFinSet.Build fn_injective fn_nondegen.

    Lemma bset_li : lmodBasis.li bset.
    Proof. move=>/=C S.
      rewrite lmodLC.eqFSFun/=.
      apply functional_extensionality=>/=b.
      destruct S as [s [U [H S]]]; move: s U H S.
      rewrite /bset/==>s U H S.
      case(C b == 0) as []eqn:E.
        by move/eqP in E.

        move/negbT in E.
        destruct s; [by move:(H _ E); rewrite in_nil|destruct s=>//].
          rewrite big_seq1/fn/(scale _)/= mulr1 in S; move/eqP in S;
          by destruct b, u.
    Qed.

    Lemma bset_spanning : lmodBasis.span bset.
    Proof. move=>x.
      refine (exist _ (unitFSType (B:= bset) tt x) _).
      move: (lmodLC.unit_sumsTo (B:=bset) tt x).
      by rewrite /scale/= mulr1.
    Qed.

    Definition basis : lmodFinBasisType (ringModType R) := lmodFinBasis.Build bset_li bset_spanning.
  End Def.
  Module Exports.
    Canonical unit_fdFreeLmod (R : ringType) := Eval hnf in @fdFreeLmodPack R (ringModType R) (freeRingModule.basis R).
  End Exports.
End freeRingModule.
Export freeRingModule.Exports.

Module freeLmodMatrix.
  Section Def.
    Variable (R : ringType) (m n : nat).
    Definition fn pp := @delta_mx R m n pp.1 pp.2.
    Lemma fn_injective : injective fn.
      Proof. rewrite/fn=>x y; rewrite /delta_mx -matrixP/eqrel=>H.
        move:(H y.1 y.2); clear H; rewrite !mxE !eq_refl/==>H.
        have: (y.1 == x.1) by
          case(y.1 == x.1) as []eqn:E=>//; move: H;
          rewrite !E !(rwP eqP) eq_sym oner_eq0.
        have: (y.2 == x.2) by
          case(y.2 == x.2) as []eqn:E=>//; move: H;
          rewrite E andbC !(rwP eqP) eq_sym oner_eq0.
        destruct x, y; rewrite -!(rwP eqP)=>/=H1 H2.
        by rewrite H1 H2.
      Qed.

      Lemma fn_nondegen : non_degenerate fn.
      Proof. rewrite /fn=>x; rewrite /delta_mx -(rwP negP)-(rwP eqP)-matrixP=>H.
        by move:(H x.1 x.2); rewrite !mxE !eq_refl (rwP eqP) oner_eq0.
      Qed.

      Definition fn_bset := lmodFinSet.Build fn_injective fn_nondegen.

      Lemma big_or (T : finType) (M : zmodType) (F : T -> M)  P1 P2 : \sum_(i | P1 i || P2 i)F i = \sum_(i | P1 i)F i + \sum_(i |P2 i)F i - \sum_(i | P1 i && P2 i)F i.
      Proof.
        rewrite !big_mkcond !(big_mkcond P1) !(big_mkcond P2) !(big_mkcond (fun i => P1 i && P2 i)) -!big_enum-!big_mkcond.
        induction (enum _).
        by rewrite !big_nil subr0 addr0.
        rewrite !big_cons.
        case(P1 a) as []eqn:E1.
        case(P2 a) as []eqn:E2=>/=.
        rewrite (addrC _ (\sum_(j <- _| P2 j) _)) !addrA.
        by rewrite addrKA IHl !addrA/=.
        by rewrite IHl/= !addrA.
        case(P2 a) as []eqn:E2=>//=.
        by rewrite !addrA (addrC (\sum_(j <- _| P1 j) _) _) IHl !addrA/=.
      Qed.

      Lemma seq_basis (c : 'I_m*'I_n -> R) (x : seq ('I_m*'I_n)) (U : uniq x) : \sum_(b <- x) c b *: delta_mx b.1 b.2 =  \sum_(i < m) \sum_(j < n) (if(i,j) \in x then c (i,j) else 0) *: delta_mx i j.
      Proof.
        rewrite pair_big.
        symmetry; under eq_bigr do rewrite (lmod_ifthenelse_sum (fun p => c p) (fun p => delta_mx p.1 p.2) (fun p => p \in x)); symmetry.
        simpl fst; simpl snd.
        rewrite -big_mkcond/=.
        induction x.
        rewrite big_nil.
        under eq_bigl do rewrite in_nil.
        by rewrite big_pred0.

        simpl in U; move/andP in U.
        rewrite big_cons (IHx (proj2 U)).
        symmetry; under eq_bigl do rewrite in_cons;symmetry.
        rewrite big_or -(IHx (proj2 U)) (big_pred1 a).
        destruct a as [a1 a2]=>/=.
        rewrite (big_mkcond (fun _ => _ && (_ \in _)))/=
                (big1 _ _ (fun i => if _ then _ else _));
        [by rewrite subr0|move=>i _].
        case((i.1, i.2) == (a1, a2)) as []eqn:E1=>//.
        case((i.1, i.2) \in x) as []eqn:E2.
        by move/eqP in E1; rewrite -E1 E2/= in U; destruct U.
        by rewrite E2.
        move=>i; destruct a as [a1 a2]=>//.
      Qed.

      Lemma fn_li : lmodBasis.li fn_bset.
      Proof. rewrite/fn_bset/lmodFinSet.to_set/==>c H.
        destruct c as [c V].
        destruct H as [h [U [H S]]].
        simpl in H, S, c, h; rewrite fsFun.eqFSFun/=; clear V.
        rewrite /fn(seq_basis _ U) in S.
        move:(matrix_sum_delta (\matrix_(i < m, j < n)(if (i, j) \in h then c (i, j) else 0))).
        under eq_bigr do under eq_bigr do rewrite mxE.
        move=>A. move/eqP in S; move:S.
        rewrite -A -matrixP/eqrel=>/=S.
        apply functional_extensionality=>b.
        move:(S b.1 b.2)=>/=.
        rewrite !mxE.
        case(c b == 0) as []eqn:E.
        by move/eqP in E.
        move/negbT in E.
        by destruct b=>/=; rewrite (H _ E).
      Qed.

    Lemma fn_spanning : lmodBasis.span fn_bset.
    Proof. move=>A.
      move:(matrix_sum_delta A)=>W.
      rewrite pair_big/= in W.

      have HS : hasSupport (fun i => A i.1 i.2) (index_enum (prod_finType (ordinal_finType m) (ordinal_finType n))) by
      move=>b X; apply (mem_index_enum b).

      have E : finSuppE (fun i => A i.1 i.2) by
      refine (ex_intro _ _ (conj _ HS)); rewrite (index_enum_uniq _).

      refine(exist _ (fsFun.Pack E) _).
      refine (ex_intro _ _ (ex_intro _ (index_enum_uniq _) (ex_intro _ HS _))).
      by rewrite {2}W/=/fn eq_refl.
    Qed.

    Definition basis : lmodFinBasisType (matrix_lmodType R m n) := lmodFinBasis.Build fn_li fn_spanning.
  End Def.
  Module Exports.
    Canonical Structure fdFreeLmod_matrix (R : ringType) (m n : nat) := Eval hnf in fdFreeLmodPack (basis R m n).
  End Exports.
End freeLmodMatrix.
Export freeLmodMatrix.Exports.

Definition vector_lmodType R n := matrix_lmodType R 1 n.
Module freeLmodVector.
  Section Def.
    Variable (R : ringType) (n : nat).
    Notation ord0 := (Ordinal (ltn0Sn 0)).

    Definition fn pp := @delta_mx R 1 n ord0 pp.
    Lemma fn_injective : injective fn.
      Proof. move: (@freeLmodMatrix.fn_injective R 1 n).
        rewrite /injective/freeLmodMatrix.fn/fn=>H x y P.
        move: (H (ord0, x) (ord0, y) P).
        by rewrite !(rwP eqP).
      Qed.

      Lemma fn_nondegen : non_degenerate fn.
      Proof. move: (@freeLmodMatrix.fn_nondegen R 1 n).
        rewrite /non_degenerate/freeLmodMatrix.fn/fn=>H i.
        by move: (H (ord0, i)).
      Qed.

      Definition fn_bset := lmodFinSet.Build fn_injective fn_nondegen.

      Section Bijection.
        Lemma n_sizen : n = size (enum 'I_n).
        Proof. by rewrite -cardT !card_ord. Qed.
        (*ord_to_finBasis n_sizen (finBasis_to_ord n_size1n x).*)

        Lemma n_size1n : n = size (enum (prod_finType (ordinal_finType 1) (ordinal_finType n))).
        Proof. by rewrite -cardT card_prod !card_ord mul1n. Qed.
        Definition vect_to_mat : fn_bset -> (@freeLmodMatrix.fn_bset R 1 n) := fun x =>
        (ord0, x).
        Definition mat_to_vect : (@freeLmodMatrix.fn_bset R 1 n) -> fn_bset :=
          fun x => x.2.

        Lemma vect_to_matK : cancel mat_to_vect vect_to_mat.
        Proof. rewrite /vect_to_mat/mat_to_vect=>x.
          destruct x as [x1 x2]=>/=.
          destruct x1.
          by induction m; [rewrite -(proof_irrelevance _ _ (ltn0Sn 0)) |inversion i].
        Qed.

        Lemma mat_to_vectK : cancel vect_to_mat mat_to_vect.
        Proof. by rewrite /vect_to_mat/mat_to_vect=>x. Qed.
      End Bijection.

      Lemma vector_to_matrix : forall i, fn (mat_to_vect i) = freeLmodMatrix.fn_bset R 1 n i.
      Proof. rewrite/fn=>i; rewrite/freeLmodMatrix.fn_bset/freeLmodMatrix.fn.
        destruct i, s as [s S], s=>//=.
      Qed.

      Lemma fn_li : lmodBasis.li fn_bset.
      Proof. move: (@freeLmodMatrix.fn_li R 1 n)=>W C S.
        rewrite /lmodBasis.li in W.
        destruct C as [coef C].
        destruct S as [s [U [H S]]].
        move: s U H S.
        rewrite/==>s U H S.
        rewrite fsFun.eqFSFun/=; clear C.
        pose(s' := map (fun i => (Ordinal (ltn0Sn 0),i)) s).

        have U' : uniq s'.
        rewrite map_inj_in_uniq=>//.
        move=>x y X Y E.
        by inversion E.

        have H' : hasSupport (coef \o snd) s'.
        move=>b X.
        destruct b as [b' b]; simpl in X.
        rewrite /s'.

        have BB: b' == ord0 by
        destruct b'; rewrite /eq_op/=; destruct m=>//.
        move/eqP in BB; destruct BB.

        apply (map_f (fun b=> (b', b))).
        apply (H _ X).

        have Q: fsFun.finSuppE (B:= prod_eqType (ordinal_eqType 1) _) (coef \o snd) by
        refine(ex_intro _ s' _)=>//.

        move:(W (fsFun.Pack Q))=>T.
        have Y: lmodLCSumsTo (B:=freeLmodMatrix.fn_bset R 1 n) {| fsFun.sort := coef \o snd; fsFun.hasFiniteSupport := Q |} 0.

        rewrite /lmodLC.li.
        refine(ex_intro _ s' (ex_intro _ U' (ex_intro _ H' _))).
        rewrite/=/s' big_map/=/freeLmodMatrix.fn/=.
        by rewrite /fn in S.
        move:(T Y).
        rewrite fsFun.eqFSFun/=/comp/==>O.
        apply functional_extensionality=>b.
        by move: (equal_f O (ord0,b)).
      Qed.

    Lemma fn_spanning : lmodBasis.span fn_bset.
    Proof. move=>/=A.
      move: (@freeLmodMatrix.fn_spanning R 1 n A)=>C;destruct C as [C S].
      have E: fsFun.finSuppE (C \o vect_to_mat). clear S.
      destruct C as [coef [c [U H]]].
      refine(ex_intro _ (map mat_to_vect c) _);split.
      rewrite -(map_inj_in_uniq (f:=mat_to_vect)) in U=>//.
      move=>[x1 x2] [y1 y2] X Y Z.
      rewrite/mat_to_vect/= in Z.
      destruct x1, y1; destruct m,m0=>//.
      by rewrite Z (proof_irrelevance _ i i0).
      move=>b X.
      rewrite/comp/vect_to_mat in X.
      rewrite -(rwP mapP).
      refine(ex_intro2 _ _ (ord0,b) (H _ X) _)=>//.

      refine(exist _ (fsFun.Pack E) _).
      destruct S as [s [U [H S]]].
      refine(ex_intro _ (map mat_to_vect s) _).
      rewrite -(map_inj_in_uniq (f:=mat_to_vect)) in U.
      refine(ex_intro _ U _).
      have HS:hasSupport (C \o vect_to_mat) [seq mat_to_vect i | i <- s].
      move=> b X.
      rewrite/comp/vect_to_mat in X.
      rewrite -(rwP mapP).
      refine(ex_intro2 _ _ (ord0,b) (H _ X) _)=>//.
      refine(ex_intro _ HS _).
      rewrite big_map/=.
      under eq_bigr do rewrite vect_to_matK.
      rewrite /freeLmodMatrix.fn_bset/=/freeLmodMatrix.fn in S.
      move/eqP in S.
      rewrite/fn/mat_to_vect -S -(rwP eqP).
      apply eq_bigr=>i _.
      destruct i as [[i1 I1] i2]=>/=.
      destruct ord0 as [o1 O1].
      destruct i1, o1=>//.
      move=>[x1 x2] [y1 y2] _ _ Z.
      rewrite/mat_to_vect/= in Z.
      destruct x1, y1.
      destruct m,m0=>//.
      by rewrite Z (proof_irrelevance _ i i0).
    Qed.

    Definition basis : lmodFinBasisType (vector_lmodType R n) := lmodFinBasis.Build fn_li fn_spanning.
  End Def.

  Module Exports.
    Canonical fdFreeLmod_vector (R : ringType) (n : nat) := Eval hnf in fdFreeLmodPack (basis R n).
  End Exports.
End freeLmodVector.
Export freeLmodVector.Exports.

Module freeLinear.
  Section Def.
    Variable (R : ringType).
    Section VectorConversion.
    Variable (M : fdFreeLmodType R) (n : nat) (E : fdFreeLmod.eqnB M n).

      Definition to_row_raw : M -> vector_lmodType R n  := fun x =>
      \row_(i < n)
        \fdFreeBasisCoef_(lmodFinSet.from_ord E i) x.

      Definition from_row_raw : vector_lmodType R n -> M  := fun x =>
        \sum_(b : fdBasis M)
          x (Ordinal (ltn0Sn 0)) (lmodFinSet.to_ord E b) *: (fdBasis M b).

      Lemma from_row_lin : linear to_row_raw /\ linear from_row_raw.
      Proof. split; rewrite/from_row_raw/to_row_raw=>r x y.
      rewrite -matrixP /eqrel=>i j.
      by rewrite !mxE linearP.
      rewrite scaler_sumr -big_split.
      apply eq_bigr=>i _.
      by rewrite mxE mxE scalerDl scalerA. Qed.

      Lemma from_rowK : cancel to_row_raw from_row_raw /\ cancel from_row_raw to_row_raw.
      Proof. split=>x; rewrite/from_row_raw/to_row_raw.
        move:(lmodBasis.hasSpanEq (fdBasis M) x)=>H.
        destruct H as [s [U [H S]]]; move/eqP in S.
        rewrite (eqLCSumsTo H (@lmodFinBasis.hasSupport_enum _ _ (fdBasis M) x) U (enum_uniq _)) in S.
        rewrite -big_enum-S.
        apply eq_bigr=>i _.
        rewrite mxE.
        rewrite linear_sum ord_to_finBasisK scaler_suml.
        by rewrite (lmodBasis.sum_trivialises (B:=fdBasis M) (enum_uniq _) i (lmodFinBasis.hasSupport_enum (x:=x))).

        rewrite -matrixP=>i j.
        rewrite mxE linear_sum.
        under eq_bigr do rewrite linearZ (lmodBasis.orthonormP (B:=fdBasis M) (ord_to_finBasis E j)) eq_sym.
        have Q: forall k (_ : true),
          (x (Ordinal (ltn0Sn 0)) (finBasis_to_ord E k) * (if k == ord_to_finBasis E j then 1 else 0))
            = if k == ord_to_finBasis E j then
                x (Ordinal (ltn0Sn 0)) (finBasis_to_ord E k)
              else
                0
        by move=>k _; case(k == ord_to_finBasis E j); [rewrite mulr1|rewrite mulr0].
        rewrite (eq_bigr _ Q) -big_mkcond big_pred1_eq finBasis_to_ordK.
        destruct i as [i I]; destruct i=>//.
        by rewrite (proof_irrelevance _ (ltn0Sn 0) I).
      Qed.
      Definition to_row := linIsomBuildPack from_row_lin from_rowK.
    End VectorConversion.

    Section MatrixConversion.
      Variable (M N : fdFreeLmodType R)
      (m : nat) (Em : fdFreeLmod.eqnB M m)
      (n : nat) (En : fdFreeLmod.eqnB N n).

      Definition to_map (f : {linear M -> N}) : {linear (vector_lmodType R m) -> (vector_lmodType R n)}
      := (to_row En) \oLin f \oLin inv(to_row Em).

      Definition from_map (f : {linear (vector_lmodType R m) -> (vector_lmodType R n)}) : {linear M -> N}
        := inv(to_row En) \oLin f \oLin (to_row Em).

      Lemma from_mapK : cancel to_map from_map.
      Proof. rewrite/from_map/to_map=>/=f.
        rewrite !linear_eq.
        apply functional_extensionality=>x.
        by rewrite -!linCompChain !(isomlK _).
      Qed.

      Lemma to_mapK : cancel from_map to_map.
      Proof. rewrite/from_map/to_map=>f.
        rewrite !linear_eq.
        apply functional_extensionality=>x.
        by rewrite -!linCompChain !(isomKl _).
      Qed.
    End MatrixConversion.
  End Def.
End freeLinear.

(*

  Direct Sums of Free Modules

    *)

Module dsFdFreeLmod.
  Module Pair.
    Section Def.
      Variable (R : ringType).
      Variable (M1 M2 : lmodType R) (B1 : lmodFinBasisType M1) (B2 : lmodFinBasisType M2).

      Section FiniteSuppSums.
        Import FiniteSupport.
        Lemma LCsumsTo_sums (C1 : lmodLCType B1) (C2 : lmodLCType B2) m1 m2 : lmodLC.sumsTo C1 m1 -> lmodLC.sumsTo C2 m2
        -> lmodLC.sumsTo (lmodLC.sum C1 C2) (m1,m2).
        Proof. move=>H1 H2.
          destruct H1 as [s1 [U1 [H1 S1]]].
          destruct H2 as [s2 [U2 [H2 S2]]].
          refine(ex_intro _ (fsFun.sum_seq s1 s2) _).
          refine(ex_intro _ (fsFun.sum_uniq U1 U2) _).
          refine(ex_intro _ (fsFun.hasFunSupp_sum H1 H2) _).
          rewrite big_cat/= !big_map/lmodSet.elem_sum.
          under (eq_bigr (r:=s1)) do rewrite /(scale _)/=/scale_pair/= scaler0.
          under (eq_bigr (r:=s2)) do rewrite /(scale _)/=/scale_pair/= scaler0.
          by rewrite dsLmod.pair_eq_seq S1 S2.
        Qed.

        Lemma LCsumsTo_sumsI (C : lmodLCType (lmodSet.sum B1 B2)) m1 m2 : lmodLC.sumsTo C (m1,m2)
            -> (lmodLC.sumsTo (fsFun.foldFSl C) m1 /\ lmodLC.sumsTo (fsFun.foldFSr C) m2).
        Proof. move=>H; split;destruct H as [h [U [E H]]].
          refine(ex_intro _ (fsFun.foldL h) _).
          refine(ex_intro _ (fsFun.foldL_uniq U) _).
          refine(ex_intro _ (fsFun.foldL_fs E) _).
          clear E U. move: m1 m2 H.
          induction h=>//m1 m2.
          rewrite !big_nil {1}/eq_op/= -(rwP andP)=>H;
          apply (proj1 H).
          destruct a; [rewrite fsFun.foldL_consl|rewrite fsFun.foldL_consr];
            rewrite !big_cons /(scale _)/=/scale_pair/= scaler0 addrC eq_sym -subr_eq /(add _)/=/add_pair/= subr0 eq_sym=>H;
            move: (IHh _ _ H)=> G//.
            by rewrite eq_sym subr_eq eq_sym addrC in G.

          refine(ex_intro _ (fsFun.foldR h) _).
          refine(ex_intro _ (fsFun.foldR_uniq U) _).
          refine(ex_intro _ (fsFun.foldR_fs E) _).
          clear E U; move: m1 m2 H.
          induction h=>//m1 m2.
          rewrite !big_nil {1}/eq_op/= -(rwP andP)=>H;
          apply (proj2 H).
          destruct a; [rewrite fsFun.foldR_consl|rewrite fsFun.foldR_consr];
            rewrite !big_cons;
            rewrite /(scale _)/=/scale_pair/= scaler0 addrC eq_sym -subr_eq /(add _)/=/add_pair/= subr0 eq_sym=>H;
            move: (IHh _ _ H) => G//.
            by rewrite eq_sym subr_eq eq_sym addrC in G.
        Qed.
      End FiniteSuppSums.

      Lemma pair_li : lmodBasis.li (lmodSet.sum B1 B2).
      Proof. move=>c H.
        apply (LCsumsTo_sumsI) in H. destruct H as [H1 H2].
        move: (lmodBasis.hasLI (B:=B1) H1).
        move: (lmodBasis.hasLI (B:=B2) H2).
        rewrite !lmodLC.eqFSFun/==>Z2 Z1.
        apply functional_extensionality=>b.
        destruct b;[apply (equal_f Z1 s)|apply (equal_f Z2 s)].
      Qed.
      Lemma pair_sp : lmodBasis.span (lmodSet.sum B1 B2).
      Proof. move=> m.
        move: (lmodBasis.hasSpanEq B1 m.1)=>E1.
        move: (lmodBasis.hasSpanEq B2 m.2)=>E2.
        move:(LCsumsTo_sums E1 E2)=>E.
        apply(exist _ (lmodLC.sum (lmodBasis.hasSpanLC B1 m.1) (lmodBasis.hasSpanLC B2 m.2)) E).
      Qed.

      Definition basis : lmodFinBasisType (pair_lmodType M1 M2) := lmodFinBasis.Build pair_li pair_sp.
    End Def.

    Definition fdFreeLmod (R : ringType) (m1 m2 : fdFreeLmodType R) := fdFreeLmodPack (basis (fdBasis m1) (fdBasis m2)).
    Section Results.
      Variable (R : ringType).
      Variable (M1 M2 : fdFreeLmodType R).
      Definition incl1 : {linear M1 -> fdFreeLmod M1 M2} := dsLmod.Pair.incl1 M1 M2.
      Definition incl2 : {linear M2 -> fdFreeLmod M1 M2} := dsLmod.Pair.incl2 M1 M2.

      Definition proj1 : {linear fdFreeLmod M1 M2 -> M1} := dsLmod.Pair.proj1 M1 M2.
      Definition proj2 : {linear fdFreeLmod M1 M2 -> M2} := dsLmod.Pair.proj2 M1 M2.
    End Results.

    Module Exports.
      Canonical fdFreeLmod.
    End Exports.
  End Pair.
  Export Pair.Exports.

  Module Seq.
    Section Def.
      Variable (R : ringType) (T : eqType) (I : T -> (fdFreeLmodType R)).
      Fixpoint basis (L : seq T) := match L with
      |nil    => fdBasis (null_fdFreeLmod R) : lmodFinBasisType (dsLmod.Seq.DS I nil)
      |a::L'  => (Pair.basis (fdBasis (I a)) (basis L')) : lmodFinBasisType (dsLmod.Seq.DS I (a::L'))
      end.
    End Def.

    Definition fdFreeLmod (R : ringType) (T : eqType) (I : T -> (fdFreeLmodType R)) (L : seq T) := fdFreeLmodPack (basis I L).

    Module Exports.
      Canonical fdFreeLmod.
    End Exports.
  End Seq.

  Section Def.
    Variable (R : ringType) (F : finType) (I : F -> (fdFreeLmodType R)).
    Definition type := Seq.fdFreeLmod I (enum F).
  End Def.
  Export Seq.Exports.
End dsFdFreeLmod.

Reserved Notation "\fbigoplus_ i F"
  (at level 36, F at level 36, i at level 0,
    right associativity,
          format "'[' \fbigoplus_ i '/ ' F ']'").

Reserved Notation "\fbigoplus F"
  (at level 36, F at level 36,
    right associativity,
          format "'[' \fbigoplus F ']'").

Reserved Notation "\fbigoplus_ ( i <- r ) F"
  (at level 36, F at level 36, i, r at level 50,
          format "'[' \fbigoplus_ ( i <- r ) '/ ' F ']'").

Reserved Notation "\fbigoplus_ ( i : t ) F"
  (at level 36, F at level 36, i at level 50,
          format "'[' \fbigoplus_ ( i : t ) '/ ' F ']'").

Reserved Notation "\fbigoplus_ ( i 'in' A ) F"
  (at level 36, F at level 36, i, A at level 50,
          format "'[' \fbigoplus_ ( i 'in' A ) '/ ' F ']'").

Infix "\lmod^"  := (vector_lmodType) (at level 30) : lmod_scope.
Infix "\foplus" := (dsFdFreeLmod.Pair.fdFreeLmod) (at level 36) : lmod_scope.
Notation "\fbigoplus_ i F" := (dsFdFreeLmod.type (fun i => F)) : lmod_scope.
Notation "\fbigoplus F" := (dsFdFreeLmod.type F) : lmod_scope.
Notation "\fbigoplus_ ( i : t ) F" := (dsFdFreeLmod.type (fun i : t => F)) : lmod_scope.
Notation "\fbigoplus_ ( i 'in' A ) F" := (dsFdFreeLmod.Seq.fdFreeLmod (filter F (fun i => i \in A))) : lmod_scope.

Export dsFdFreeLmod.Pair.Exports.
Export dsFdFreeLmod.Seq.Exports.
(*
Theorem FreeModule_UniversalProperty (R : ringType) (M : fdFreeLmodType R)
    : forall (N : lmodType R) (f : (fdBasis M) -> N),
      exists (g : {linear M -> N}),
        f = g \o (fdBasis M).
  Proof.
  Admitted.
  *)

Close Scope ring_scope.
Close Scope lmod_scope.


Require Import PropLang.
Require Import List.

Require Import Coq.Lists.List.
Import ListNotations.

Section SequentCalculus.

Context {atom : Type}.

Reserved Notation "Γ1 ---> Γ2" (no associativity, at level 62).

Inductive G : list (prop atom) -> list (prop atom) -> Prop :=
| leave_everything {Γ1 Γ2 Γ3 Γ4 X} :
  [X] ---> [X] ->
  Γ1 ++ [X] ++ Γ2 ---> Γ3 ++ [X] ++ Γ4
| switch_arrow {Γ1 Γ2 Γ3 Γ4 X Y} :
  Γ1 ++[Y] ++ Γ2 ++ [X] ++ Γ3 ---> Γ4 ->
  Γ1 ++ [X] ++ Γ2 ++ [Y] ++ Γ3 ---> Γ4
| arrow_switch {Γ1 Γ2 Γ3 Γ4 X Y} :
  Γ1 ---> Γ2 ++ [Y] ++ Γ3 ++ [X] ++ Γ4 ->
  Γ1 ---> Γ2 ++ [X] ++ Γ3 ++ [Y] ++ Γ4
| axioma {X} : [X] ---> [X]
| arrow_impl {Γ1 Γ2 X Y} :
  [X] ++ Γ1 ---> [Y] ++ Γ2 ->
  Γ1 ---> [X ⊃ Y] ++ Γ2
| arrow_conj {Γ1 Γ2 X Y} :
  Γ1 ---> [X] ++ Γ2 ->
  Γ1 ---> [Y] ++ Γ2 ->
  Γ1 ---> [X ∧ Y] ++ Γ2
| arrow_disj {Γ1 Γ2 X Y} :
  Γ1 ---> [X] ++ [Y] ++ Γ2 ->
  Γ1 ---> [X ∨ Y] ++ Γ2
| arrow_neg {Γ1 Γ2 X} :
  [X] ++ Γ1 ---> Γ2 ->
  Γ1 ---> [¬ X] ++ Γ2
| impl_arrow {Γ1 Γ2 X Y} :
  Γ1 ---> [X] ++ Γ2 ->
  [Y] ++ Γ1 ---> Γ2 ->
  [X ⊃ Y] ++ Γ1 ---> Γ2
| conj_arrow {Γ1 Γ2 X Y} :
  [X] ++ [Y] ++ Γ1 ---> Γ2 ->
  [X ∧ Y] ++ Γ1 ---> Γ2
| disj_arrow {Γ1 Γ2 X Y} :
  [X] ++ Γ1 ---> Γ2 ->
  [Y] ++ Γ1 ---> Γ2 ->
  [X ∨ Y] ++ Γ1 ---> Γ2
| neg_arrow {Γ1 Γ2 X} :
  Γ1 ---> [X] ++ Γ2 ->
  [¬ X] ++ Γ1 ---> Γ2
where "Γ1 ---> Γ2" := (G Γ1 Γ2).

Theorem addNilInSeq_L (Γ1: list (prop atom)) (Γ2 : list (prop atom)) :
  nil ++ Γ1 ---> Γ2 = Γ1 ---> Γ2.
Proof.
  rewrite app_nil_l.
  reflexivity.
Qed.

Theorem addNilInSeq_R (Γ1 : list (prop atom)) (Γ2 : list (prop atom)) :
  Γ1 ---> nil ++ Γ2 = Γ1 ---> Γ2.
Proof.
  rewrite app_nil_l.
  reflexivity.
Qed.

Example example1 {A B C} :
  [A] ++ [B] ++ [¬C] ---> [¬C] ++ [¬A] ++ [A ∧ B].
Proof.
  apply @arrow_neg with (X := C).
  rewrite <- addNilInSeq_L.
  apply @switch_arrow with (X := C) (Y := ¬C) (Γ1 := []) (Γ2 := [A]++[B]) (Γ3 := []).
  apply @neg_arrow with (X := C).
  rewrite <- addNilInSeq_R.
  apply @leave_everything with (X := C).
  apply @axioma.
Qed.

Example example2 {A B C} :
  [A] ++ [B] ++ [¬C] ---> [¬C] ++ [¬A] ++ [A ∧ B].
Proof.
  rewrite <- addNilInSeq_R.
  apply @arrow_switch with (X := ¬C) (Y := A ∧ B).
  apply @arrow_conj with (X := A) (Y := B).
  + rewrite <- addNilInSeq_R.
    rewrite <- addNilInSeq_L.
    apply @leave_everything with (X := A).
    apply @axioma.
  + rewrite <- addNilInSeq_R.
    rewrite <- addNilInSeq_L.
    apply @leave_everything with (X := B).
    apply @axioma.
Qed.

(*\subset- implikálás*)
Example example3 {A B}:
  [¬(A ⊃ B)] ---> [¬A ∨ ¬B].
Proof.
  apply @neg_arrow with(X:= A ⊃ B).
  apply @arrow_impl with (X := A) (Y:= B).
  rewrite <- addNilInSeq_R.
  apply @arrow_switch with (X := B) (Y:= ¬A ∨ ¬B).
  apply @arrow_disj with (X:= ¬A) (Y := ¬B).
  rewrite <- addNilInSeq_R.
  apply @arrow_switch with (X:= ¬A) (Y:= ¬B).
  apply @arrow_neg with (X:= B).
  rewrite <- addNilInSeq_L.
  apply @leave_everything with (X := B).
  apply @axioma.
Qed.

Example example4 {A B C} :
  [(A ∨ B) ⊃ C] ---> [(A ⊃ C) ∧ (B ⊃ C)].

Example example5 {A B} :
  [¬(A ⊃ B)] ---> [¬A ∨ ¬B].

(*\lnot!!*)
Example nyomozos {F K A} :
  [F ⊃ K] ++ [K ⊃ A] ++ [¬A] ---> [¬F].


(** * Tactics: More Basic Tactics *)

Require Export Poly.

(** This chapter introduces several more proof strategies and
    tactics that allow us to prove more interesting properties of
    functional programs.  We will see:

    - how to use auxiliary lemmas in both "forward-style" and
      "backward-style" proofs;
    - how to reason about data constructors (in particular, how to use
      the fact that they are injective and disjoint);
    - how to create a strong induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis.
 *)

(* ###################################################### *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    exactly the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.

(** At this point, we could finish with "[rewrite -> eq2.
    reflexivity.]" as we have done several times before.  We can
    achieve the same effect in a single step by using the [apply]
    tactic instead: *)

  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
     n = m  ->
     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that binds some _universal variables_.  When
    Coq matches the current goal against the conclusion of [H], it
    will try to find appropriate values for these variables.  For
    example, when we do [apply eq2] in the following proof, the
    universal variable [q] in [eq2] gets instantiated with [n] and [r]
    gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** **** Exercise: 2 stars, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  intros H1 H2.
  apply H1. apply H2.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal exactly -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  simpl.
  (* Here we cannot use [apply] directly *)
Abort.

(** In this case we can use the [symmetry] tactic, which switches the
    left and right sides of an equality in the goal. *)

Theorem silly3 : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  symmetry.
  simpl. (* Actually, this [simpl] is unnecessary, since
            [apply] will perform simplification first. *)
  apply H.  Qed.

(** **** Exercise: 3 stars (apply_exercise1)  *)
(** (_Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [SearchAbout] is
    your friend.) *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  intros l l' H.
  symmetry.
  rewrite H.
  apply rev_involutive.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied?

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

(* ###################################################### *)
(** * The [apply ... with ...] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a,b]] to [[e,f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.

(** Since this is a common pattern, we might like to pull it out
    as a lemma recording, once and for all, the fact that equality is
    transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
  reflexivity.  Qed.

(** Now, we should be able to use [trans_eq] to prove the above
    example.  However, to do this we need a slight refinement of the
    [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.

(** If we simply tell Coq [apply trans_eq] at this point, it can
    tell (by matching the goal against the conclusion of the lemma)
    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
    [o] with [[e,f]].  However, the matching process doesn't determine
    an instantiation for [m]: we have to supply one explicitly by
    adding [with (m:=[c,d])] to the invocation of [apply]. *)

  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.

(** Actually, we usually don't have to include the name [m] in
    the [with] clause; Coq is often smart enough to figure out which
    instantiation we're giving. We could instead write: [apply
    trans_eq with [c;d]]. *)

(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros n m o p H1 H2.
  rewrite H2. apply H1.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * The [inversion] tactic *)

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition (and in our
    informal understanding of how datatype declarations work in other
    programming languages) are two more facts:

    - The constructor [S] is _injective_.  That is, if [S n = S m], it
      must be the case that [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n]. *)

(** Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since neither
    [true] nor [false] take any arguments, their injectivity is not an
    issue.)  And so on. *)

(** Coq provides a tactic called [inversion] that allows us to
    exploit these principles in proofs. To see how to use it, let's
    show explicitly that the [S] constructor is injective: *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [inversion H] at this point, we ask Coq to
    generate all equations that it can infer from [H] as additional
    hypotheses, replacing variables in the goal as it goes. In the
    present example, this amounts to adding a new hypothesis [H1 : n =
    m] and replacing [n] by [m] in the goal. *)

  inversion H. reflexivity.  Qed.

(** Here's a more interesting example that shows how multiple
    equations can be derived at once. *)

Theorem inversion_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H. inversion H. reflexivity. Qed.

(** It is possible to name the equations that [inversion]
    generates with an [as ...] clause: *)

Theorem inversion_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n o H. inversion H as [Hno]. reflexivity.  Qed.

(** **** Exercise: 1 star (inversion_ex3)  *)
Example inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  y :: l = x :: j ->
  x = y.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** While the injectivity of constructors allows us to reason
    that [forall (n m : nat), S n = S m -> n = m], the converse of
    this implication is an instance of a more general fact about
    constructors and functions, which we will find useful below: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately. To see why this makes sense, consider the
    following proof: *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'].
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming
    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
    clearly contradictory!  The way forward lies in the assumption.
    After simplifying the goal state, we see that [beq_nat 0 (S n') =
    true] has become [false = true]: *)

  - (* n = S n' *)
    simpl.

(** If we use [inversion] on this hypothesis, Coq notices that
    the subgoal we are working on is impossible, and therefore removes
    it from further consideration. *)

    intros H. inversion H. Qed.

(** This is an instance of a general logical principle known as
    the _principle of explosion_, which asserts that a contradiction
    entails anything, even false things.  For instance: *)

Theorem inversion_ex4 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. inversion contra. Qed.

Theorem inversion_ex5 : forall (n m : nat),
  false = true ->
  [n] = [m].
Proof.
  intros n m contra. inversion contra. Qed.

(** If you find the principle of explosion confusing, remember
    that these proofs are not actually showing that the conclusion of
    the statement holds.  Rather, they are arguing that the situation
    described by the premise can never arise, so the implication is
    vacuous.  We'll explore the principle of explosion of more detail
    in the next chapter. *)

(** **** Exercise: 1 star (inversion_ex6)  *)
Example inversion_ex6 : forall (X : Type)
                          (x y z : X) (l j : list X),
  x :: y :: l = [] ->
  y :: l = z :: j ->
  x = z.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To summarize this discussion, suppose [H] is a hypothesis in the
    context or a previously proven lemma of the form
      c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] has the following effect:

    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know that [a1 = b1], [a2 =
      b2], etc.; [inversion H] adds these facts to the context, and
      tries to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory, and the current goal doesn't have to be
      considered. In this case, [inversion H] marks the current goal
      as completed and pops it off the goal stack. *)

(* ###################################################### *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic [simpl in H] performs simplification in
    the hypothesis named [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     beq_nat (S n) (S m) = b  ->
     beq_nat n m = b.
Proof.
  intros n m b H. simpl in H. apply H.  Qed.

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]
    against [L1] and, if successful, replaces it with [L2].

    In other words, [apply L in H] gives us a form of "forward
    reasoning": from [L1 -> L2] and a hypothesis matching [L1], it
    produces a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning": it says that if we know [L1->L2] and we are
    trying to prove [L2], it suffices to prove [L1].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly3' : forall (n : nat),
  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
  true = beq_nat n 5  ->
  true = beq_nat (S (S n)) 7.
Proof.
  intros n eq H.
  symmetry in H. apply eq in H. symmetry in H.
  apply H.  Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise.  (Hint: use
    [plus_n_Sm].) *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that the [double] function is injective -- i.e.,
    that it always maps different arguments to different results:
    Theorem double_injective: forall n m,
      double n = double m -> n = m.
    The way we _start_ this proof is a bit delicate: if we begin with
      intros n. induction n.
    all is well.  But if we begin it with
      intros n m. induction n.
    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *) intros eq. destruct m as [| m'].
    + (* m = O *) inversion eq.
    + (* m = S m' *)  apply f_equal.

(** At this point, the induction hypothesis, [IHn'], does not give us
    [n' = m'] -- there is an extra [S] in the way -- so the goal is
    not provable. *)

      Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _these particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition

      - [P n] = "if [double n = double m], then [n = m]"

    holds, by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]") and

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: it says that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular [m] --
    say, [5].  The statement is then saying that, if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help at all with proving
    [R]!  (If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing about
    whether [double n] is [10], so [Q] is useless.) *)

(** To summarize: Trying to carry out this proof by induction on [n]
    when [m] is already in the context doesn't work because we are
    then trying to prove a relation involving _every_ [n] but just a
    _single_ [m]. *)

(** The good proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.

  - (* n = S n' *) simpl.

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., to prove the statement for _every_ [m]), but the IH
    is correspondingly more flexible, allowing us to choose any [m] we
    like when we apply the IH. *)

    intros m eq.

(** Now we've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'].
    + (* m = O *) simpl.

(** The 0 case is trivial: *)

      inversion eq.

    + (* m = S m' *)
      apply f_equal.

(** At this point, since we are in the second branch of the [destruct
    m], the [m'] mentioned in the context is the predecessor of the
    [m] we started out talking about.  Since we are also in the [S]
    branch of the induction, this is perfect: if we instantiate the
    generic [m] in the IH with the current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. inversion eq. reflexivity. Qed.

(** What you should take away from all this is that we need to be
    careful about using induction to try to prove something too
    specific: If we're proving a property of [n] and [m] by induction
    on [n], we may need to leave [m] generic. *)

(** The following exercise requires the same pattern. *)

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)

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

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    a little _rearrangement_ of quantified variables is needed.
    Suppose, for example, that we wanted to prove [double_injective]
    by induction on [m] instead of [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *)  apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem here is that, to do induction on [m], we must first
    introduce [n].  (If we simply say [induction m] without
    introducing anything first, Coq will automatically introduce [n]
    for us!)  *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    will work, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them -- we want to state them in the most clear and
    natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables out of the context and putting them
    back at the beginning of the goal.  The [generalize dependent]
    tactic does this. *)

Theorem double_injective_take2 : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. inversion eq. reflexivity. Qed.

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

    _Theorem_: For any nats [n] and [m], if [double n = double m], then
      [n = m].

    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
      any [n], if [double n = double m] then [n = m].

      - First, suppose [m = 0], and suppose [n] is a number such
        that [double n = double m].  We must show that [n = 0].

        Since [m = 0], by the definition of [double] we have [double n =
        0].  There are two cases to consider for [n].  If [n = 0] we are
        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']
        for some [n'], we derive a contradiction: by the definition of
        [double], we can calculate [double n = S (S (double n'))], but
        this contradicts the assumption that [double n = 0].

      - Second, suppose [m = S m'] and that [n] is again a number such
        that [double n = double m].  We must show that [n = S m'], with
        the induction hypothesis that for every number [s], if [double s =
        double m'] then [s = m'].

        By the fact that [m = S m'] and the definition of [double], we
        have [double n = S (S (double m'))].  There are two cases to
        consider for [n].

        If [n = 0], then by definition [double n = 0], a contradiction.

        Thus, we may assume that [n = S n'] for some [n'], and again by
        the definition of [double] we have [S (S (double n')) =
        S (S (double m'))], which implies by inversion that [double n' =
        double m'].  Instantiating the induction hypothesis with [n'] thus
        allows us to conclude that [n' = m'], and it follows immediately
        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just
        what we wanted to show. [] *)

(** Before we close this section and move on to some exercises, let's
    digress briefly and use [beq_nat_true] to prove a similar property
    about identifiers that we'll need in later chapters: *)

Theorem beq_id_true : forall x y,
  beq_id x y = true -> x = y.
Proof.
  intros [m] [n]. simpl. intros H.
  assert (H' : m = n). { apply beq_nat_true. apply H. }
  rewrite H'. reflexivity.
Qed.

(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     nth_error l n = None.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (app_length_cons)  *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, optional (app_length_twice)  *)
(** Prove this by induction on [l], without using [app_length] from [Lists]. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (double_induction)  *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a Definition
    so that we can manipulate its right-hand side.  For example, if we
    define *)

Definition square n := n * n.

(** and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we get stuck: [simpl] doesn't simplify anything at this point,
    and since we haven't proved any other facts about [square], there
    is nothing we can [apply] or [rewrite] with.

    To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these facts it is not
    hard to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
  { rewrite mult_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, a slightly deeper discussion of unfolding and
    simplification is in order.

    You may already have observed that tactics like [simpl],
    [reflexivity], and [apply] will often unfold the definitions of
    functions automatically when it allows them to make progress.  For
    example, if we define [foo m] to be the constant [5], *)

Definition foo (x: nat) := 5.

(** then the [simpl] in the following proof (or the [reflexivity], if
    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and
    then further simplify this expression to just [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** However, this automatic unfolding is rather conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  (It is not smart enough to notice that the
    two branches of the [match] are identical.)  So it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that, itself, cannot be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone.

    At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress.

    A more straightforward way to finish the proof is to explicitly
    tell Coq to unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m.
  - reflexivity.
  - reflexivity.
Qed.

(* ###################################################### *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  But
    sometimes we need to reason by cases on the result of some
    _expression_.  We can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (beq_nat n 3).
    - (* beq_nat n 3 = true *) reflexivity.
    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).
      + (* beq_nat n 5 = true *) reflexivity.
      + (* beq_nat n 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat
    n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c]. *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** However, [destruct]ing compound expressions requires a bit of
    care, as such [destruct]s can sometimes erase information we need
    to complete a proof. *)
(** For example, suppose we define a function [sillyfun1] like
    this: *)

Definition sillyfun1 (n : nat) : bool :=
  if beq_nat n 3 then true
  else if beq_nat n 5 then true
  else false.

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact that [sillyfun1 n] yields [true] only when [n] is
    odd.  By analogy with the proofs we did with [sillyfun] above, it
    is natural to start the proof like this: *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3).
  (* stuck... *)
Abort.

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution peformed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat n 3], but we need to keep some
    memory of this expression and how it was destructed, because we
    need to be able to reason that, since [beq_nat n 3 = true] in this
    branch of the case analysis, it must be that [n = 3], from which
    it follows that [n] is odd.

    What we would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation, giving it a
    name that we choose. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (* When we come to the second equality test in the body
        of the function we are reasoning about, we can use
        [eqn:] again in the same way, allow us to finish the
        proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

(** **** Exercise: 2 stars (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################## *)
(** * Review *)

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  But basically we've got what we need to
    get work done.

    Here are the ones we've seen:

      - [intros]: move hypotheses/variables from goal to context

      - [reflexivity]: finish the proof (when the goal looks like [e =
        e])

      - [apply]: prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]: apply a hypothesis, lemma, or constructor to
        a hypothesis in the context (forward reasoning)

      - [apply... with...]: explicitly specify values for variables
        that cannot be determined by pattern matching

      - [simpl]: simplify computations in the goal

      - [simpl in H]: ... or a hypothesis

      - [rewrite]: use an equality hypothesis (or lemma) to rewrite
        the goal

      - [rewrite ... in H]: ... or a hypothesis

      - [symmetry]: changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]: changes a hypothesis of the form [t=u] into
        [u=t]

      - [unfold]: replace a defined constant by its right-hand side in
        the goal

      - [unfold... in H]: ... or a hypothesis

      - [destruct... as...]: case analysis on values of inductively
        defined types

      - [destruct... eqn:...]: specify the name of an equation to be
        added to the context, recording the result of the case
        analysis

      - [induction... as...]: induction on values of inductively
        defined types

      - [inversion]: reason by injectivity and distinctness of
        constructors

      - [assert (e) as H]: introduce a "local lemma" [e] and call it
        [H]

      - [generalize dependent x]: move the variable [x] (and anything
        else that depends on it) from the context back to an explicit
        hypothesis in the goal formula
*)

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

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

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

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)

Definition split_combine_statement : Prop :=
(* FILL IN HERE *) admit.

Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.

(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:
      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (beq_nat 5) [] = true
    The second checks whether there exists an element in the list that
    satisfies a given predicate:
      existsb (beq_nat 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

      existsb evenb [] = false
    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

    Finally, prove a theorem [existsb_existsb'] stating that
    [existsb'] and [existsb] have the same behavior.
*)

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

(** $Date: 2016-01-30 17:02:58 -0500 (Sat, 30 Jan 2016) $ *)


Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith.
Require Import Crypto.Util.ListUtil.
Require Import Crypto.Util.ZUtil.
Require Crypto.BaseSystem.
Require Import Coq.Lists.List.

Local Open Scope Z_scope.

Section Pow2Base.
  Context (limb_widths : list Z).
  Local Notation "w[ i ]" := (nth_default 0 limb_widths i).

  Fixpoint base_from_limb_widths limb_widths :=
    match limb_widths with
    | nil => nil
    | w :: lw => 1 :: map (Z.mul (two_p w)) (base_from_limb_widths lw)
    end.

  Local Notation base := (base_from_limb_widths limb_widths).

  Definition bounded us := forall i, 0 <= nth_default 0 us i < 2 ^ w[i].

  Definition upper_bound := 2 ^ (sum_firstn limb_widths (length limb_widths)).

  Function decode_bitwise' us i acc :=
    match i with
    | O => acc
    | S i' => decode_bitwise' us i' (Z.lor (nth_default 0 us i') (Z.shiftl acc w[i']))
    end.

  Definition decode_bitwise us := decode_bitwise' us (length us) 0.

  (* i is current index, counts down *)
  Fixpoint encode' z i :=
    match i with
    | O => nil
    | S i' => let lw := sum_firstn limb_widths in
       encode' z i' ++ (Z.shiftr (Z.land z (Z.ones (lw i))) (lw i')) :: nil
    end.

  Definition encodeZ x:= encode' x (length limb_widths).

  (** ** Carrying *)
  Section carrying.
    (** Here we implement addition and multiplication with simple
        carrying. *)
    Notation log_cap i := (nth_default 0 limb_widths i).

    Definition add_to_nth n (x:Z) xs :=
      update_nth n (fun y => x + y) xs.
    Definition carry_single i := fun di =>
      (Z.pow2_mod di (log_cap i),
       Z.shiftr di (log_cap i)).

    (* [fi] is fed [length us] and [S i] and produces the index of
         the digit to which value should be added;
       [fc] modifies the carried value before adding it to that digit *)
    Definition carry_gen fc fi i := fun us =>
      let i := fi i in
      let di := nth_default 0 us      i in
      let '(di', ci) := carry_single i di in
      let us' := set_nth i di' us in
      add_to_nth (fi (S i)) (fc ci) us'.

    (* carry_simple does not modify the carried value, and always adds it
       to the digit with index [S i] *)
    Definition carry_simple := carry_gen (fun ci => ci) (fun i => i).

    Definition carry_simple_sequence is us := fold_right carry_simple us is.

    Fixpoint make_chain i :=
      match i with
      | O => nil
      | S i' => i' :: make_chain i'
      end.

    Definition full_carry_chain := make_chain (length limb_widths).

    Definition carry_simple_full := carry_simple_sequence full_carry_chain.

    Definition carry_simple_add us vs := carry_simple_full (BaseSystem.add us vs).

    Definition carry_simple_sub us vs := carry_simple_full (BaseSystem.sub us vs).

    Definition carry_simple_mul out_base us vs := carry_simple_full (BaseSystem.mul out_base us vs).
  End carrying.

End Pow2Base.


Section ml.
Theorem Exor: forall (A B:Set -> Prop),
(exists x:Set, ((A x) \/ (B x))) ->
(exists x:Set, A x) \/ (exists x:Set, B x).
Proof.
intros F G h0.
elim h0; intros n h1.
elim h1.
intro fn; left; exists n; assumption.
intro gn; right; exists n; assumption.
Qed.
End ml.

Check Exor.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

Inductive nat : Set :=
| O : nat
| S : nat -> nat.

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Definition synth (x : natural) : natural := plus (Succ x) Zero.