(* This file implements a number of (endo?)morphisms? *)
Require Import DirectedGraphs.
Require Import Setoid Bool MSetProperties.
(* Need to make sure this doesn't pollute the definitions in bool_scope *)

Open Scope bool.

Module DirectedGraphMorph (DG : DirectedGraphs).
  (* Declare Module Import DG : DirectedGraphs. *)
  Import DG.

    Inductive EqualGraph : t -> t -> Prop :=
    | GraphEQ : forall g1 g2,
                  (enumVertices g1) =V= (enumVertices g2) ->
                  (enumEdges g1) =E= (enumEdges g2) ->
                    EqualGraph g1 g2.

    Definition equalGraph : t -> t -> bool :=
      fun G1 G2 =>
        Vertices.equal (enumVertices G1) (enumVertices G2) &&
        Edges.equal (enumEdges G1) (enumEdges G2).

    Notation "G1 =G= G2" := (EqualGraph G1 G2) (at level 60).

    Definition Respectful (A : Type) (f : t -> A) : Prop :=
      forall G1 G2, G1 =G= G2 -> f G1 = f G2.

    Lemma EqualGraphP G1 G2 : reflect (G1 =G= G2) (equalGraph G1 G2).
    Proof.
      case_eq (equalGraph G1 G2); intros H0;
      unfold equalGraph in H0; constructor;
      [apply andb_true_iff in H0 | apply andb_false_iff in H0; intros H2].
      destruct H0 as [H0 H1]; constructor;
      [apply Vertices.equal_spec | apply Edges.equal_spec]; auto.
      inversion H2. destruct H0 as [H0 | H0];
      [rewrite <- Vertices.equal_spec in H |
       rewrite <- Edges.equal_spec in H1]; congruence.
    Qed.

  (* Lemmas for weakening graph equality *)
    Lemma EqualGraph_weakVertices :
      forall G1 G2, G1 =G= G2 -> (enumVertices G1 =V= enumVertices G2).
    Proof.
      intros G1 G2 H; destruct H as [H0 H1]; auto.
    Qed.

    Lemma EqualGraph_weakEdges :
      forall G1 G2, G1 =G= G2 -> (enumEdges G1 =E= enumEdges G2).
    Proof.
      intros G1 G2 H; destruct H as [H0 H1]; auto.
    Qed.

  (* Relational proofs for easier rewriting *)
    Lemma EqualGraph_equiv : Equivalence EqualGraph.
    Proof.
      do 2 constructor;
      destruct Edges.eq_equiv as [e0 e1 e2];
      destruct Vertices.eq_equiv as [v0 v1 v2].
      apply v0. apply e0.
      destruct H as [H H']; apply v1 ; auto.
      destruct H as [H H']; apply e1 ; auto.
      destruct H as [H H']; destruct H0 as [H0 H0']; apply (v2 _ _ _ H1 H3).
      destruct H as [H H']; destruct H0 as [H0 H0']; apply (e2 _ _ _ H2 H4).
    Qed.

    Add Parametric Relation : t EqualGraph
      reflexivity proved by (Equivalence.equiv_reflexive EqualGraph_equiv)
      symmetry proved by (Equivalence.equiv_symmetric EqualGraph_equiv)
      transitivity proved by (Equivalence.equiv_transitive EqualGraph_equiv)
    as eqGraph.

    Definition destructEdge_eq1 (e1 e2 : edge): Prop :=
      fst (destructEdge e1) =v= fst (destructEdge e2).

    Definition destructEdge_eq2 (e1 e2 : edge) : Prop :=
      snd (destructEdge e1) =v= snd (destructEdge e2).

    Lemma destructEdge_eq1_r : Equivalence destructEdge_eq1.
      Proof.
        constructor;
        unfold destructEdge_eq1; intros x; try reflexivity; auto.
        intros.
        rewrite H.
        reflexivity.
        intros.
        rewrite H.
        rewrite H0.
        reflexivity.
      Qed.

   Lemma destructEdge_eq2_r : Equivalence destructEdge_eq2.
     Proof.
       constructor;
         unfold destructEdge_eq2; intros x; try reflexivity; auto.
       intros.
       rewrite H.
       reflexivity.
       intros.
       rewrite H.
       rewrite H0.
       reflexivity.
     Qed.

    Add Parametric Relation : edge  destructEdge_eq1
        reflexivity proved by (Equivalence.equiv_reflexive destructEdge_eq1_r)
        symmetry proved by (Equivalence.equiv_symmetric destructEdge_eq1_r)
        transitivity proved by (Equivalence.equiv_transitive destructEdge_eq1_r)
          as destruct_eq_r_1.

    Add Parametric Relation : edge  destructEdge_eq2
        reflexivity proved by (Equivalence.equiv_reflexive destructEdge_eq2_r)
        symmetry proved by (Equivalence.equiv_symmetric destructEdge_eq2_r)
        transitivity proved by (Equivalence.equiv_transitive destructEdge_eq2_r)
          as destruct_eq_r_2.

    Add Morphism buildEdge
        with signature Vertices.E.eq ==> Vertices.E.eq ==> Edges.E.eq
          as buildEdge_morph.
    Proof.
      intros.
      apply buildEdge_spec; auto.
    Qed.

    Add Morphism destructEdge
        with signature Edges.E.eq ==> Vertices.E.eq * Vertices.E.eq
                                  as destructEdge_morph.
    Proof.
      intros.
      split.
      apply destructEdge_spec1.
      auto.
      apply destructEdge_spec2.
      auto.
    Qed.

    Add Morphism destructEdge_eq1
        with signature destructEdge_eq1 ==> Edges.E.eq ==> iff
          as destructEdge_eq1_morph.
    Proof.
      intros; split; intros;
      unfold destructEdge_eq1 in *.
      rewrite <- H0;
      rewrite <- H1;
      symmetry.
      auto.
      rewrite H0.
      rewrite H.
      auto.
    Qed.

    Add Morphism destructEdge_eq2
        with signature destructEdge_eq2 ==> Edges.E.eq ==> iff
          as destructEdge_eq2_morph.
    Proof.
      intros; split; intros;
      unfold destructEdge_eq2 in *.
      rewrite <- H0;
      rewrite <- H1;
      symmetry.
      auto.
      rewrite H0.
      rewrite H.
      auto.
    Qed.

    Add Morphism enumVertices
      with signature EqualGraph ==> Vertices.eq
    as enumVertices_morph.
    Proof.
      intros G1 G2 H0; apply EqualGraph_weakVertices in H0; auto.
    Qed.

    Add Morphism enumEdges
      with signature EqualGraph ==> Edges.eq
    as enumEdges_morph.
    Proof.
      intros G1 G2 H0; apply EqualGraph_weakEdges in H0; auto.
    Qed.

    Add Morphism IsVertex
      with signature Vertices.E.eq ==> EqualGraph ==> iff
    as IsVertex_morph.
    Proof.
      intros v1 v2 H0 G1 G2 H1.
      destruct H1 as [H1 H2].
      do 2 rewrite IsVertexEnum.
      rewrite H0. split; intros H4;
      apply H; auto.
    Qed.

    Add Morphism IsEdge
      with signature Edges.E.eq ==> EqualGraph ==> iff
    as IsEdges_morph.
    Proof.
      intros e1 e2 H0 G1 G2 H1.
      destruct H1 as [H1 H2].
      do 2 rewrite IsEdgeEnum.
      rewrite H0. split; intros H4;
      apply H3; auto.
    Qed.

    Add Morphism addVertex
      with signature Vertices.E.eq ==> EqualGraph ==> EqualGraph
    as addVertex_morph.
    Proof.
      intros v1 v2 H0 G1 G2 H1.
      constructor; intros v.
      {
        case (Vertices.E.eq_dec v v1); intros H2.
        {
          rewrite H2. rewrite H0 at 3.
          do 2 rewrite <- IsVertexEnum;
          split; intros _; apply addVertex_spec1.
        }
        {
          do 2 rewrite <- IsVertexEnum.
          split; intros H3; apply addVertex_spec2;
          apply addVertex_spec2 in H3; auto.
          rewrite <- H0; auto. rewrite <- H1; auto.
          rewrite <- H0; auto. rewrite H1; auto.
          rewrite <- H0; auto.
        }
      }
      {
        do 2 rewrite <- IsEdgeEnum;
        do 2 rewrite <- addVertex_spec3;
        rewrite H1. split; auto.
      }
    Qed.

    Add Morphism addEdge
      with signature Edges.E.eq ==> EqualGraph ==> EqualGraph
    as addEdge_morph.
    Proof.
      intros e1 e2 H0 G1 G2 H1.
      constructor; intros e.
      {
        do 2 rewrite <- IsVertexEnum;
        do 2 rewrite <- addEdge_spec3;
        rewrite H1. split; auto.
      }
      {
        do 2 rewrite <- IsEdgeEnum.
        case (Edges.E.eq_dec e e1); intros H2.
        {
          rewrite H2. split; intros H3;
          [rewrite H0; rewrite H0 in H3 at 1 |];
          apply addEdge_spec1.
          apply Edge_exists1 in H3.
          apply addEdge_spec3 in H3.
          rewrite <- H1; auto.
          apply Edge_exists2 in H3.
          apply addEdge_spec3 in H3.
          rewrite <- H1; auto.
          apply Edge_exists1 in H3.
          apply addEdge_spec3 in H3.
          rewrite H1; auto.
          apply Edge_exists2 in H3.
          apply addEdge_spec3 in H3.
          rewrite H1; auto.
        }
        {
          split; intros H3;
          apply addEdge_spec2 in H3; auto. apply addEdge_spec2.
          rewrite <- H0; auto. rewrite <- H1; auto.
          apply addEdge_spec2; auto. rewrite <- H1 in H3; auto.
          rewrite <- H0; auto.
        }
      }
    Qed.

    (* Consider deleting *)
    Add Morphism (fun e g => IsEdge e g /\
                             IsVertex (fst (destructEdge e)) g)
      with signature Edges.E.eq ==> EqualGraph ==> iff
    as EdgeDest1.
    Proof.
      intros e1 e2 H0 G1 G2 H1.
      split; intros [H2 H3]; split.
      + rewrite <- H0, <- H1. auto.
      + rewrite H0, H1 in H2. apply Edge_exists1 in H2; auto.
      + rewrite <- H0, <- H1 in H2. auto.
      + rewrite <- H0, <- H1 in H2. apply Edge_exists1 in H2; auto.
    Qed.

    Add Morphism (fun e g => IsEdge e g /\
                             IsVertex (snd (destructEdge e)) g)
      with signature Edges.E.eq ==> EqualGraph ==> iff
    as EdgeDest2.
    Proof.
      intros e1 e2 H0 G1 G2 H1.
      split; intros [H2 H3]; split.
      + rewrite <- H0, <- H1. auto.
      + rewrite H0, H1 in H2. apply Edge_exists2 in H2; auto.
      + rewrite <- H0, <- H1 in H2. auto.
      + rewrite <- H0, <- H1 in H2. apply Edge_exists2 in H2; auto.
    Qed.

  Module Import VertProperties := OrdProperties Vertices.
  Module Import EdgeProperties := OrdProperties Edges.

Inductive GraphConst1 : t -> Type :=
  | EmptyGraph1 : GraphConst1 empty
  | AddVert1 : forall G v, (GraphConst1 G) -> GraphConst1 (addVertex v G)
  | AddEdge1 : forall G e, (GraphConst1 G) -> GraphConst1 (addEdge e G).

(* These definitions could use to be somewhere else *)
  Definition addVertices V G : t :=
    Vertices.fold (fun v g => addVertex v g) V G.

  Definition addEdges E G : t :=
    Edges.fold (fun e G => addEdge e G) E G.

(* Same for these lemmas *)
  Lemma addVertex_pres :
    forall v1 v2 G, IsVertex v1 G ->
      IsVertex v1 (addVertex v2 G).
  Proof.
    intros v1 v2 G H.
    case (Vertices.E.eq_dec v1 v2); intros H2.
    rewrite H2. apply addVertex_spec1.
    apply addVertex_spec2; auto.
  Qed.

  Lemma addVertices_pres :
    forall v V G, IsVertex v G ->
      IsVertex v  (addVertices V G).
  Proof.
    intros v V G H.
    unfold addVertices.
    apply VertProperties.P.fold_rec_weak; try (auto; fail).
    intros x a s s' H0. apply addVertex_pres; auto.
  Qed.

  Lemma addEdge_pres :
    forall e1 e2 G, IsEdge e1 G ->
      IsEdge e1 (addEdge e2 G).
  Proof.
    intros e1 e2 G H0.
    case (Edges.E.eq_dec e1 e2); intros H2.
    rewrite H2. apply addEdge_spec1.
    apply Edge_exists1. rewrite <- H2; auto.
    apply Edge_exists2. rewrite <- H2; auto.
    apply addEdge_spec2; auto.
  Qed.

  Lemma transposeAddVertex :
    transpose EqualGraph (fun (v0 : Vertices.elt) (G0 : t) => addVertex v0 G0).
  Proof.
    intros v1 v2 G. constructor.
    + intros v. do 2 rewrite <- IsVertexEnum.
      split; intros.
      case (Vertices.E.eq_dec v v2); intros.
        rewrite e. apply addVertex_spec1.
        apply addVertex_spec2; auto.
          case (Vertices.E.eq_dec v v1); intros.
          rewrite e. apply addVertex_spec1.
          apply addVertex_spec2; auto.
          do 2 apply addVertex_spec2 in H; auto.
      case (Vertices.E.eq_dec v v1); intros.
        rewrite e. apply addVertex_spec1.
        apply addVertex_spec2; auto.
          case (Vertices.E.eq_dec v v2); intros.
          rewrite e. apply addVertex_spec1.
          apply addVertex_spec2; auto.
          do 2 apply addVertex_spec2 in H; auto.
    + intros e. do 2 rewrite <- IsEdgeEnum. split; intros;
      do 2 apply addVertex_spec3 in H; do 2 apply addVertex_spec3; auto.
  Qed.

  Lemma transposeAddEdge :
    transpose EqualGraph (fun (e0 : Edges.elt) (G0 : t) => addEdge e0 G0).
  Proof.
    split. unfold Vertices.eq.
    + split; intros; try rewrite <- IsVertexEnum in *;
      try do 2 rewrite <- addEdge_spec3 in *; auto.
    + split; intros; rewrite <- IsEdgeEnum in *.
      case (Edges.E.eq_dec a y); intros.
      rewrite e in H |-*.
      - assert (IsVertex (fst (destructEdge y)) z) as H0.
          apply Edge_exists1 in H; do 2 rewrite <- addEdge_spec3 in H; auto.
        assert (IsVertex (snd (destructEdge y)) z) as H1.
          apply Edge_exists2 in H; do 2 rewrite <- addEdge_spec3 in H; auto.
        apply addEdge_spec1; apply addEdge_spec3; auto.
      - apply addEdge_spec2; auto. case (Edges.E.eq_dec a x); intros.
        rewrite e in H |-*.  apply addEdge_spec1;
        [apply Edge_exists1 in H | apply Edge_exists2 in H];
        do 2 apply addEdge_spec3 in H; auto. do 2 apply addEdge_spec2 in H; auto.
        apply addEdge_spec2; auto.
      - case (Edges.E.eq_dec a x); intros.
        rewrite e in H |-*.
        * assert (IsVertex (fst (destructEdge x)) z) as H0.
            apply Edge_exists1 in H; do 2 rewrite <- addEdge_spec3 in H; auto.
          assert (IsVertex (snd (destructEdge x)) z) as H1.
            apply Edge_exists2 in H; do 2 rewrite <- addEdge_spec3 in H; auto.
          apply addEdge_spec1; auto; apply addEdge_spec3; auto.
        * apply addEdge_spec2; auto. case (Edges.E.eq_dec a y); intros.
        rewrite e in H |-*.  apply addEdge_spec1;
        [apply Edge_exists1 in H | apply Edge_exists2 in H];
        do 2 apply addEdge_spec3 in H; auto. do 2 apply addEdge_spec2 in H; auto.
        apply addEdge_spec2; auto.
  Qed.

  Lemma addEdges_pres :
    forall e E G, IsEdge e G ->
      IsEdge e (addEdges E G).
  Proof.
    intros. unfold addEdges. apply EdgeProperties.P.fold_rec_weak;
    try solve [auto | split; auto].
    intros e1 g V H0 H1. apply addEdge_pres; auto.
  Qed.

  Lemma addEdges_spec2 :
    forall v E G, IsVertex v (addEdges E G) <-> IsVertex v G.
  Proof.
    intros v E G. unfold addEdges. apply P.fold_rec_weak.
    auto. split; auto.
    intros. rewrite <- H0. symmetry. apply addEdge_spec3.
  Qed.
(*
  Lemma addEdges_morph_aux1 :
    forall E1 E2 G, E1 =E= E2 -> addEdges E1 G =G= addEdges E2 G.
  Proof.
    intros. split.
    + intros v; split; intros H0; rewrite <- IsVertexEnum in *;
      apply addEdges_spec2 in H0; apply addEdges_spec2; auto.
    + intros e; split; intros H0; rewrite <- IsEdgeEnum in *;
      unfold addEdges in *. admit. admit.
  Admitted.
*)
  Lemma addEdges_morph_aux2 :
    forall E G1 G2, G1 =G= G2 -> addEdges E G1 =G= addEdges E G2.
  Proof.
    intros. split.
    + intros v; split; intros H0; rewrite <- IsVertexEnum in *;
      apply addEdges_spec2 in H0; apply addEdges_spec2;
      [rewrite <- H | rewrite H]; auto.
    + unfold addEdges. intros v. do 2 rewrite <- IsEdgeEnum.
      induction E using P.set_induction.
      - split; intros; rewrite P.fold_1b in *; auto;
        [rewrite <- H | rewrite H]; auto.
      - intros. rewrite (@P.fold_2 E1 E2 x); auto. rewrite (@P.fold_2 E1 E2 x); auto.
        case (Edges.E.eq_dec v x); intros.
        * rewrite e. split; intros; apply addEdge_spec1; apply addEdges_spec2;
          [apply Edge_exists1 in H2 | apply Edge_exists2 in H2 |
           apply Edge_exists1 in H2 | apply Edge_exists2 in H2];
          apply addEdge_spec3 in H2; apply addEdges_spec2 in H2;
          [rewrite <- H | rewrite <- H | rewrite H | rewrite H]; auto.
        * split; intros H2; apply addEdge_spec2; auto;
          apply addEdge_spec2 in H2; auto; apply IHE1; auto.
        * apply EqualGraph_equiv.
        * intros e1 e2 H2 Ga Gb H3. rewrite H3, H2. apply EqualGraph_equiv.
        * apply transposeAddEdge.
        * apply EqualGraph_equiv.
        * intros e1 e2 H2 Ga Gb H3. rewrite H3, H2. apply EqualGraph_equiv.
        * apply transposeAddEdge.
  Qed.

  Add Morphism addEdges
      with signature Edges.eq ==> EqualGraph ==> EqualGraph
  as addEdges_morph.
  Proof.
    intros. assert (addEdges y x0 =G= addEdges x x0) as H1.
    unfold addEdges. apply P.fold_equal. apply EqualGraph_equiv.
    intros e1 e2 H1 g1 g2 H2. rewrite H2, H1. apply EqualGraph_equiv.
    apply transposeAddEdge. symmetry. apply H. rewrite <- H1.
    apply addEdges_morph_aux2. auto.
  Qed.

 (* Is there a term for possessing the added elements? *)
  Lemma addVertices_spec1 :
    forall v V G, Vertices.In v V -> IsVertex v (addVertices V G).
  Proof.
    intros v V G. unfold addVertices.
    apply VertProperties.P.fold_rec_weak.
    intros s s' H0 H1 H2 H3. rewrite H1 in H2. apply H2; auto.
    intros H. apply Vertices.empty_spec in H; contradiction.
    intros x a s H0 H1 H2. case (Vertices.E.eq_dec v x); intros H3.
    rewrite H3; apply addVertex_spec1.
    apply addVertex_spec2; auto. apply H1. apply Vertices.add_spec in H2.
    case H2; auto. intros H4. apply H3 in H4. contradiction.
  Qed.

  Lemma addVertices_spec2 :
    forall e V G, IsEdge e (addVertices V G) <-> IsEdge e G.
  Proof.
    intros e V G.
    unfold addVertices.
    apply VertProperties.P.fold_rec_weak; try solve [auto | split; auto].
    intros s s' G1 H0 H1; auto. rewrite <- H1.
    rewrite <- addVertex_spec3; split; auto.
  Qed.

  Lemma addEdges_spec1 :
    forall E e G, (IsVertex (fst (destructEdge e)) G) ->
                (IsVertex (snd (destructEdge e)) G) ->
                Edges.In e E -> IsEdge e (addEdges E G).
  Proof.
    intros E. induction E using P.set_induction_bis.
    + intros. rewrite <- H in H2. specialize (IHE1 e G H0 H1 H2).
      assert (addEdges E1 G =G= addEdges E2 G) as H3. rewrite H.
      reflexivity. rewrite <- H. auto.
    + intros. apply Edges.empty_spec in H1. contradiction.
    + intros. unfold addEdges. rewrite P.fold_add.
      apply Edges.add_spec in H2. case H2; intros.
      - rewrite <- H3. apply addEdge_spec1; apply addEdges_spec2; auto.
      - apply (IHE _ _ H0 H1) in H3. apply addEdge_pres. auto.
      - apply EqualGraph_equiv.
      - unfold respectful. unfold Proper. intros. rewrite H3, H4.
        apply EqualGraph_equiv.
      - apply transposeAddEdge.
      - auto.
  Qed.

  (* Rebuilds the graph according to the graph const *)
  Definition rebuildGraph_GraphConst1 G : t :=
    addEdges (enumEdges G) (addVertices (enumVertices G) empty).

  Lemma addVertices_bleh :
    forall v V, Vertices.In v V -> Vertices.In v (enumVertices (addVertices V empty)).
  Proof.
    intros. rewrite <- IsVertexEnum.
    apply addVertices_spec1; auto.
  Qed.

  Lemma emptyVerts : forall G, IsEmpty G -> forall v, ~ IsVertex v G.
  Proof.

  Admitted.

  Lemma emptyEdges : forall G, IsEmpty G -> forall e, ~ IsEdge e G.
  Proof.

  Admitted.

  Lemma rebuildGraph_GraphConst1_spec1 :
    forall G, (rebuildGraph_GraphConst1 G) =G= G.
  Proof.
    intros G. constructor.
    + unfold rebuildGraph_GraphConst1. intros v.
      do 2 rewrite <- IsVertexEnum. rewrite addEdges_spec2.
      - do 2 rewrite IsVertexEnum.
        induction (enumVertices G) using VertProperties.P.set_induction.
        * unfold addVertices. rewrite VertProperties.P.fold_1b.
          generalize (Empty); intros. apply emptyVerts with (v := v) in H0.
          split; intros. rewrite <- IsVertexEnum in H1. contradiction.
          apply H in H1. contradiction. auto.
        * split; intros.
            unfold addVertices in H1.
            rewrite (@VertProperties.P.fold_2 t0_1 t0_2 x) in H1; auto.
            case (Vertices.E.eq_dec v x); intros H3. rewrite H3. apply H0.
            left. reflexivity. apply H0. right. apply IHt0_1.
            rewrite <- IsVertexEnum in H1. apply addVertex_spec2 in H1; auto.
            rewrite <- IsVertexEnum. apply H1. apply EqualGraph_equiv.
            intros a b H' c d H''. rewrite H', H''. reflexivity.
            apply transposeAddVertex. rewrite <- IsVertexEnum.
            apply addVertices_spec1. auto.
    + unfold rebuildGraph_GraphConst1.
      intros e. do 2 rewrite <- IsEdgeEnum. split.
      - intros. rewrite IsEdgeEnum.
        remember (enumEdges G).
        induction (t0) using EdgeProperties.P.set_induction.
        * unfold addEdges in H. rewrite EdgeProperties.P.fold_1b in H.
          rewrite addVertices_spec2 in H. generalize Empty; intros H1.
          apply emptyEdges with (e := e) in H1. contradiction. auto.
        * apply P.Add_Equal in H1. rewrite H1. unfold addEdges in H.
          admit. (* still needs some work *)
          (* rewrite (@EdgeProperties.P.fold_2 t1_1 t1_2 e) in H; auto.
          admit. apply EqualGraph_equiv.
          intros e1 e2 H' g1 g2 H''. rewrite H', H''. reflexivity.
          apply transposeAddEdge. *)
      - intros H. apply addEdges_spec1;
        try (apply addVertices_spec1; rewrite <- IsVertexEnum).
        apply Edge_exists1; auto. apply Edge_exists2; auto.
        rewrite <- IsEdgeEnum; auto.
  Admitted.

  Lemma rebuildGraph_GraphConst1_spec2 :
    forall G, GraphConst1 (rebuildGraph_GraphConst1 G).
  Proof.
    intros G. unfold rebuildGraph_GraphConst1, addEdges, addVertices.
    apply EdgeProperties.P.fold_rec_weak;
      try apply VertProperties.P.fold_rec_weak; try constructor; auto.
  Qed.

  Lemma ind1 (P : t -> Prop) (H0 : Respectful Prop P) :
    P empty ->
    (forall x g, P g -> P (addVertex x g)) ->
    (forall x g, P g -> P (addEdge x g)) ->
      forall g, P g.
  Proof.
    intros.
    unfold Respectful in H0.
    rewrite <- (H0 (rebuildGraph_GraphConst1 g) g).
    induction (rebuildGraph_GraphConst1_spec2 g);
    auto. apply rebuildGraph_GraphConst1_spec1.
  Qed.

  Lemma rec1 (P : t -> Set) ( H0 : Respectful _ P) :
    P empty ->
    (forall x g, P g -> P (addVertex x g)) ->
    (forall x g, P g -> P (addEdge x g)) ->
      forall g, P g.
  Proof.
    intros.
    unfold Respectful in H0.
    rewrite <- (H0 (rebuildGraph_GraphConst1 g) g).
    induction (rebuildGraph_GraphConst1_spec2 g);
    auto.
    apply rebuildGraph_GraphConst1_spec1.
  Qed.

  Lemma rect1 :
    forall (P : t -> Type) (H0 : Respectful _ P),
      P empty ->
      (forall x g, P g -> P (addVertex x g)) ->
      (forall x g, P g -> P (addEdge x g)) ->
        forall g, P g.
  Proof.
    intros.
    unfold Respectful in H0.
    rewrite <- (H0 (rebuildGraph_GraphConst1 g) g).
    induction (rebuildGraph_GraphConst1_spec2 g);
    auto.
    apply rebuildGraph_GraphConst1_spec1.
  Qed.
Module Import vOTF := OrderedTypeFacts Vertices.E.
Module Import eOTF := OrderedTypeFacts Edges.E.

  Definition neighborhood_ind : vertex -> t -> Vertices.t.
  Proof.
    intros. apply rect1.
    constructor. apply Vertices.empty.
    intros. apply X1.
    intros. apply destructEdge in x. destruct x.
    apply (if vOTF.eqb e X
                then (Vertices.add e0 X1)
                else  X1). exact X0.
  Defined.

  Print neighborhood_ind.

  Definition neighborhood_fold (v : Vertices.E.t) (G : t): Vertices.t :=
    Edges.fold (fun edge e =>
                  if vOTF.eqb (fst (destructEdge edge)) v then Vertices.add (snd (destructEdge edge)) e
                  else e) (enumEdges G) Vertices.empty.

  Definition rmvNeighbors (v : Vertices.E.t) (G : t) (l : Vertices.t) := Vertices.fold (fun v' l' =>
                        if isEdge (buildEdge v v') G then l'
                        else (Vertices.add v' l')) (enumVertices G) Vertices.empty.

  Inductive GraphConst2 : t -> Type :=
  | Empty : GraphConst2 empty
  | GrowGraph : forall G,
      GraphConst2 G ->
      forall v1 E,
        (* We require v1 to be a new vertex *)
        ~ IsVertex v1 G ->
        (* All edges in E have v1 as one of their members *)
        (forall e, Edges.In e E ->
          ((fst (destructEdge e)) =v= v1 \/
          (snd (destructEdge e)) =v= v1)) ->
        (* All edges in E have a vertex of the parent graph as a member *)
        (forall e, Edges.In e E ->
          (IsVertex (fst (destructEdge e)) G \/
           IsVertex (snd (destructEdge e)) G)) ->
       GraphConst2 (addEdges E (addVertex v1 G)).

  (* Generates the edges that need to be added to a graph GN, in order to
      satisfy GraphConst2, with the end goal of reconstructing G, given a vertex v1 *)
  Definition addEdges_GC2 (v1 : vertex) (G : t) (GN : t): Edges.t :=
    Edges.fold
      (fun (e : edge) E =>
            (* Check to see which edges have a source/sink in the graph GN *)
         if ((Vertices.mem (fst (destructEdge e)) (enumVertices GN) ||
             Vertices.mem (snd (destructEdge e)) (enumVertices GN)))
            &&
            (* Ensures that either the source/sink is equal to v1 *)
            (vOTF.eqb v1 (fst (destructEdge e)) ||
            (vOTF.eqb v1 (snd (destructEdge e))))
         then Edges.add e E
         else E)
      (enumEdges G) Edges.empty.

  Definition rebuildGraph_GraphConst2 (G : t) : t :=
    Vertices.fold (fun (v : vertex) (G0 : t) =>
                     addEdges (addEdges_GC2 v G G0) (addVertex v G0))
                  (enumVertices G) empty.

    Lemma rebuildGraph_GraphConst2_spec1 :
    forall G, (rebuildGraph_GraphConst2 G) =G= G.
  Proof.
    intros G. constructor.
    {
      constructor; intros H.
      unfold rebuildGraph_GraphConst2 in H.
      rewrite <- IsVertexEnum. rewrite <- IsVertexEnum in H.
      Admitted.

  Hint Constructors GraphConst2.

  Lemma rebuildGraph_GraphConst2_spec2 :
    forall G, GraphConst2 (rebuildGraph_GraphConst2 G).
  Proof.
    Admitted.

  Lemma ind2 (P : t -> Type) (H0 : Respectful _ P) :
    P empty ->
    (forall G, P G ->
      (forall v1 E,
        ~ IsVertex v1 G ->
          (forall e, Edges.In e E ->
            ((fst (destructEdge e)) =v= v1 \/
            (snd (destructEdge e)) =v= v1)) ->
          (forall e, Edges.In e E ->
            (IsVertex (fst (destructEdge e)) G \/
             IsVertex (snd (destructEdge e)) G)) ->
        P (addEdges E (addVertex v1 G)))) ->
     forall g, P g.
  Proof.
    intros H H1 g.
    rewrite <- (H0 (rebuildGraph_GraphConst2 g) g).
    induction (rebuildGraph_GraphConst2_spec2 g); auto.
    apply rebuildGraph_GraphConst2_spec1.
  Qed.

  Lemma ind3 (P : t -> Type) (H0 : Respectful _ P) :
    (forall G, Vertices.cardinal (enumVertices G) = 0 -> P G) ->
    (forall G n, Vertices.cardinal (enumVertices G) = n ->
      (P G) ->
      (forall G', Vertices.cardinal (enumVertices G') = S n -> P G')) ->
    forall G, P G.
  Proof.
    intros. apply ind2; auto.
    apply X. auto.
    admit.
    intros.
    specialize (X0 G0 (Vertices.cardinal (enumVertices G0))).
    apply X0; auto. admit.
  Admitted.

  Lemma ind4 (P : t -> Type) (H0 : Respectful _ P) :
    (forall G, Vertices.cardinal (enumVertices G) = 0 -> P G) ->
    (forall G G',
      (Vertices.cardinal (enumVertices G) <= Vertices.cardinal (enumVertices G')) ->
      (P G) ->
        (P G')) ->
    forall G, P G.
  Proof.
    intros. apply ind3; auto.
    intros. apply X0 with (G:= G0). rewrite H, H1; auto.
    auto.
  Qed.

End DirectedGraphMorph.


Definition fact : nat -> nat.
Proof.
  fix fact 1.
  intro x.
  case x.
  apply (S 0).
  intro y.
  apply (x * fact y).
Qed.

Eval compute in fact 2.


Require Import Coq.Strings.String.

Inductive idType : Type :=
| idTerm : idType. (* Term id *)

Inductive id : idType -> Type :=
| makeId : forall (idT : idType), string -> id idT.

Definition termId := id idTerm.

Inductive type : Type :=
| tunit : type
| tarrow : type -> type -> type.

Inductive term : Type :=
| eunit : term
| evar : termId -> term
| eabs : termId -> type -> term -> term
| eapp : term -> term -> term.

Inductive context : Type :=
| cempty : context
| cextend : context -> termId -> type -> context.


Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.
Require Import path choice fintype tuple finfun finset bigop.
Require Import Reals Fourier.
Require Import Reals_ext log2 ssr_ext Rbigop proba entropy aep typ_seq natbin Rssr ceiling v_source_code.

Set Implicit Arguments.
Import Prenex Implicits.

Local Open Scope tuple_ext_scope.
Local Open Scope typ_seq_scope.
Local Open Scope proba_scope.
Local Open Scope reals_ext_scope.
Local Open Scope entropy_scope.

Section Rsum_lemma.
Variable (X : finType) (n : nat).
Variable f : X -> R.
Hypothesis n_pos : (0 < n)%nat.
Variable S : {set  X}.

Lemma rsum_type_set :
  \rsum_(x in X) f(x) = \rsum_(x in [set : X]) f(x).
Proof.
by apply eq_bigl=>i; first rewrite in_setT.
Qed.

Lemma rsum_S_not_S:
  \rsum_(x| x \in [set : X]) f x =
  \rsum_(x| x \in S ) f x
                 + \rsum_(x| x \in ~: S) f x.
Proof.
apply: rsum_union; first by rewrite disjoints_subset setCS.
by apply/setP=> ?; rewrite !inE orbN.
Qed.

Lemma log_pow k:
  log(INR (n ^ k)) = (INR k) * log (INR n).
Proof.
elim: k => [| k IH].
  by rewrite mul0R expn0 log_1.
rewrite expnS -multE mult_INR log_mult; last first.
  apply lt_0_INR; apply/ltP; by rewrite expn_gt0 /orb n_pos.
  apply lt_0_INR; by apply/ltP.
by rewrite IH -addn1 plus_INR mulRDl addRC mul1R.
Qed.

End Rsum_lemma.

Section lemma_enc_dec.
Variable (X : finType) (n' : nat).
Let n := n'.+1.
Variable P : dist X.
Variable epsilon : R.
Hypothesis ep_pos : 0 < epsilon.

Lemma Xcard : 1 <= INR #|X|.
Proof.
rewrite (_ : 1 = INR 1) //.
apply le_INR.
by apply /leP; first apply (dist_support_not_empty P).
Qed.

Definition L0 := ceil (INR n * (`H P + epsilon)).

Lemma L0_pos: 0 < IZR L0.
Proof.
rewrite /L0.
apply (Rlt_le_trans _ (INR n * (`H P + epsilon))); last by apply ceil_bottom.
rewrite -(mulR0 0).
apply (Rmult_le_0_lt_compat _ _ _ _ (Rle_refl _) (Rle_refl _)).
apply lt_0_INR; by apply/ltP.
by apply (Rplus_le_lt_0_compat _ _ (entropy_pos P) ep_pos).
Qed.

Definition L1 :=  ceil (log (INR #| [set : n.-tuple X]|)).

Lemma L1_nonneg: 0 <= IZR L1.
Proof.
apply (Rle_trans _ (log (INR #|[set: n.-tuple X]|))); last by apply ceil_bottom.
rewrite -log_1.
apply (log_increasing_le Rlt_0_1).
rewrite cardsT card_tuple -INR_pow_expn.
by apply pow_R1_Rle, Xcard.
Qed.

Lemma IZR_INR_to_nat z: 0 <= IZR z -> IZR z = INR (Zabs_nat z).
Proof.
move => H.
rewrite -INR_Zabs_nat ;last by apply le_IZR.
by rewrite Zabs2Nat.abs_nat_nonneg //; first apply le_IZR.
Qed.

Lemma card_TS_le_L0 : INR #| `TS P n epsilon | <= INR #|[ set : (Zabs_nat L0).-tuple bool]|.
Proof.
apply (Rle_trans _ _ _ (TS_sup _ _ _)).
rewrite cardsT /= card_tuple /= card_bool -exp2_pow2.
apply exp2_le_increasing.
rewrite -IZR_INR_to_nat; last apply RltW, L0_pos.
by apply ceil_bottom.
Qed.

Lemma card_tuple_le_L1 : INR #| [set: n.-tuple X]| <= INR #| [set: (Zabs_nat L1).-tuple bool]|.
Proof.
rewrite /L1 cardsT card_tuple.
rewrite {1}(_ :  INR (#|X| ^ n) = exp2 (log ( INR (#|X|^n)))); last first.
  rewrite exp2_log //; last rewrite -INR_pow_expn.
  apply pow_lt.
  apply (Rlt_le_trans _ 1 _ Rlt_0_1 Xcard).
rewrite cardsT card_tuple card_bool -exp2_pow2.
apply exp2_le_increasing.
rewrite /L1 -IZR_INR_to_nat; last first.
  apply (Rle_trans _ (log (INR (#|X|^n)))); last by apply ceil_bottom.
  rewrite -log_1.
  apply log_increasing_le; first by apply Rlt_0_1.
  rewrite -INR_pow_expn.
  by apply pow_R1_Rle, Xcard.
by apply (Rle_trans _ _ _ (Rle_refl _) (ceil_bottom _)).
Qed.

End lemma_enc_dec.

Section enc_dec_def.
Local Open Scope nat_scope.

Variable (X : finType) (n' : nat).
Let n := n'.+1.
Variable P : dist X.
Variable epsilon : R.
Hypothesis ep_pos : (0 < epsilon)%R.

Local Notation "'L0'" := (L0 n' P epsilon).
Local Notation "'L1'" := (L1 X n').

Lemma le_n_L1_tuple :
  #|[finType of n.-tuple X] | <= #|[finType of (Zabs_nat L1).-tuple bool]|.
Proof.
rewrite -!cardsT.
by apply /leP; apply (INR_le _ _ (card_tuple_le_L1 n' P)).
Qed.

Definition not_enc_typ x := enum_val (widen_ord le_n_L1_tuple (enum_rank x)).

Lemma inj_not_enc_typ : injective not_enc_typ.
Proof.
by move=> a1 a2 [] /enum_val_inj [] /ord_inj/enum_rank_inj.
Qed.

Definition enc_typ x :=
 let i := seq.index x (enum (`TS P n epsilon))
 in Tuple (size_nat2bin i (Zabs_nat L0)).

(* Definition enc_typ x := *)
(*  let i := seq.index x (enum (`TS P n epsilon)) *)
(*  in nat2bin i (Zabs_nat L0). *)

Definition f : var_enc X n := fun x =>
  if x \in `TS P n epsilon then
    true :: enc_typ x
  else
    false :: not_enc_typ x.

Lemma f_inj : injective f.
Proof.
move=> t1 t2.
rewrite /f.
case/boolP : (t1 == t2); first by move=> /eqP.
move=> t1t2.
case: ifP => Ht1.
  case: ifP => Ht2 //.
  case => H.
  have {H}H : seq.index t1 (enum (`TS P n epsilon)) =
              seq.index t2 (enum (`TS P n epsilon)).
    apply (nat2bin_inj (Zabs_nat L0)) => //.
    apply leq_trans with #|`TS P n epsilon|.
      apply seq_index_enum_card => //; first by exact: enum_uniq.
      apply/leP.
      apply INR_le.
      move: (card_TS_le_L0 n' P ep_pos).
      by rewrite {1}cardsT card_tuple /= card_bool.
    apply leq_trans with #|`TS P n epsilon|.
      apply seq_index_enum_card => //; first by exact: enum_uniq.
      apply/leP.
      apply INR_le.
      move: (card_TS_le_L0 n' P ep_pos).
      by rewrite {1}cardsT card_tuple /= card_bool.
  rewrite -(@nth_index _ t1 t1 (enum (`TS P n epsilon))); last by rewrite mem_enum.
  rewrite -(@nth_index _ t1 t2 (enum (`TS P n epsilon))); last by rewrite mem_enum.
  by rewrite H.
case: ifP => Ht2 //.
case => H.
apply (inj_not_enc_typ t1 t2).
by apply val_inj.
Qed.

Definition phi_def : n.-tuple X.
move: (dist_support_not_empty P) => H.
move Hpick : [pick x | x \in [set: X] ] => p.
move: Hpick.
case: (pickP _).
  move=> x _ _.
  exact [tuple of nseq n x].
move=> abs H'.
suff : False by done.
move: H.
rewrite -cardsT card_gt0.
case/set0Pn => ?.
by rewrite abs.
Defined.

Definition phi y := if [ pick x | f x == y ] is Some x then x else phi_def.

Lemma phi_f x : phi (f x) = x.
Proof.
rewrite /phi.
case: (pickP _) => [x0 /eqP | H].
  by apply f_inj.
move: (H x).
by rewrite eqxx.
Qed.

Definition extension (enc : var_enc X n) (x : seq (n.-tuple X)) :=
flatten (map enc x).

Lemma uniquely_decodable : injective (extension f).
Proof.
move =>t1.
elim t1=>[t2|a la H t2].
by case t2=>[|a la] //; rewrite /extension /f /=; case: ifP.
case t2=>[|b lb]; [by rewrite /extension /f /=; case: ifP | rewrite /extension /= /f ].
case: ifP=> [ainT | aninT].
  case: ifP=> binT //.
  move /eqP.
  rewrite  -/f eqseq_cat; last by rewrite /= !/nat2bin !size_pad_seqL.
  case /andP=>[/eqP eq_ab ] /eqP /H ->.
  congr (_ :: _); by apply f_inj; rewrite /f ainT binT.
case: ifP=> bninT //.
move /eqP.
rewrite  -/f eqseq_cat; last by rewrite !size_tuple.
case /andP=>[/eqP eq_ab ] /eqP /H ->.
congr (_ :: _); by apply f_inj; rewrite /f aninT bninT.
Qed.

End enc_dec_def.

Section exp_len_cw_def.
Variable (X : finType) (n :nat).
Variable f : var_enc X n.
Variable P : dist X.

Definition exp_len_cw := `E (mkRvar (P `^ n) (fun x => INR (size (f x)))).

End exp_len_cw_def.

Section main_pre.
Variable (X : finType) (n' : nat).
Let n := n'.+1.
Variable P : dist X.
Variable epsilon:R.
Hypothesis ep_pos: 0 < epsilon.
Hypothesis aepbound : aep_bound P epsilon <= INR n.

Local Notation "'L0'" := (L0 n' P epsilon).
Local Notation "'L1'" := (L1 X n').

Lemma fdef_in x : x \in `TS P n epsilon -> INR (size (f P epsilon x)) = (IZR L0) + 1.
Proof.
move => H.
rewrite /f H /= size_pad_seqL IZR_INR_to_nat; last by apply RltW, L0_pos.
by rewrite -addn1; first rewrite plus_INR.
Qed.

Lemma fdef_notin x : x \in ~: `TS P n epsilon -> INR (size (f P epsilon x)) = (IZR L1) + 1.
Proof.
rewrite /f in_setC.
move/negbTE ->.
rewrite /= -addn1 size_tuple plus_INR.
by rewrite -IZR_INR_to_nat; last apply L1_nonneg.
Qed.

Lemma Hexp_len_cw :
  exp_len_cw (f (n':=n') P epsilon) P
  = \rsum_(x in [finType of n.-tuple X])( P`^n(x) * (INR (size (f P epsilon x)))).
Proof.
apply eq_bigr => /= x _.
by rewrite mulRC.
Qed.

Lemma f_typ_in :
  \rsum_(x| x \in `TS P n epsilon) P `^ n (x) * (INR (size (f P epsilon x)) ) =
  \rsum_(x| x \in `TS P n epsilon) P `^ n (x) * (IZR L0 + 1).
Proof.
apply eq_bigr=> i H.
apply Rmult_eq_compat_l.
by apply fdef_in.
Qed.

Lemma f_typ_notin:
  \rsum_(x| x \in ~:(`TS P n epsilon)) P `^ n (x) * (INR (size (f P epsilon x)) )
  = \rsum_(x| x \in ~:(`TS P n epsilon)) P `^ n (x) * (IZR L1 + 1) .
Proof.
apply eq_bigr=> i H.
apply Rmult_eq_compat_l.
by apply fdef_notin.
Qed.

Lemma theorem_helper : \rsum_(x| x \in (`TS P n epsilon)) P `^ n (x) * (IZR L0 + 1)
                       +  \rsum_(x| x \in ~:(`TS P n epsilon)) P `^ n (x) * (IZR L1 + 1)
                       <=  (IZR L0 + 1) + epsilon * (IZR L1 + 1) .
Proof.
rewrite -!(big_morph _ (morph_mulRDl _) (mul0R _)) mulRC.
rewrite (_ : \rsum_(i | i \in ~: `TS P n epsilon) P `^ n i = 1 - \rsum_(i | i \in `TS P n epsilon) P `^ n i); last first.
  rewrite -(pmf1 P`^n) rsum_type_set (rsum_S_not_S _ (`TS P n epsilon)) ; field.
apply Rplus_le_compat.
  rewrite -[X in _ <= X]mulR1.
  apply Rmult_le_compat_l.
    apply Rplus_le_le_0_compat; by [apply RltW, L0_pos| apply Rle_0_1].
  rewrite -(pmf1 P`^ n).
  apply Rle_big_f_X_Y=> //; first move=> ?; apply pmf.
apply Rmult_le_compat_r.
  by apply (Rplus_le_le_0_compat _ _ (L1_nonneg _ P) Rle_0_1).
apply Rminus_le.
rewrite /Rminus addRC addRA.
apply Rle_minus.
rewrite addRC.
by apply Rge_le; apply Pr_TS_1.
Qed.

End main_pre.

Section main.
Variable (X : finType) (n' : nat).
Let n := n'.+1.
Variable P : dist X.
Variable epsilon : R.
Hypothesis ep_pos : 0 < epsilon .
Definition epsilon':= epsilon / (3 + (3 * log (INR #|X|))).
Definition n0 := maxn (Zabs_nat (ceil (INR 2 / (INR 1 + log (INR #|X|)))))
                     (maxn (Zabs_nat (ceil (8 / epsilon)))
                     (Zabs_nat (ceil (aep_sigma2 P/ epsilon' ^ 3)))).
Hypothesis n0_n : (n0 < n)%coq_nat.

Lemma n1_le_n : (Zabs_nat (ceil (INR 2 / (INR 1 + log (INR #|X|)))) < n)%coq_nat.
Proof.
move/ltP : n0_n.
rewrite /n0 gtn_max.
by case/andP => /ltP.
Qed.

Lemma n2_le_n : (Zabs_nat (ceil (8 / epsilon)) < n)%coq_nat.
Proof.
move/ltP : n0_n.
do 2 rewrite /n0 gtn_max.
case/andP=> H.
case/andP=> H1 H2.
by apply /ltP.
Qed.

Lemma n3_le_n : (Zabs_nat (ceil (aep_sigma2 P / epsilon' ^ 3 )) < n)%coq_nat.
Proof.
move/ltP : n0_n.
do 2 rewrite /n0 gtn_max.
case/andP=> H.
case/andP=> H1 H2.
by apply /ltP.
Qed.

Lemma n_non0 : INR n <> 0.
Proof.
apply nesym, Rlt_not_eq.
by apply lt_0_INR; apply/ltP.
Qed.

Lemma n0_n_helper1: 1 + log (INR #|X|) <> 0.
Proof.
apply nesym, Rlt_not_eq, Rplus_lt_le_0_compat; first by apply Rlt_0_1.
rewrite -log_1.
apply log_increasing_le; first by apply Rlt_0_1.
by apply Xcard.
Qed.

Lemma n0_n_helper2 : INR n <> 0 /\ 1 + log (INR #|X|) <> 0.
Proof.
split.
apply n_non0.
apply n0_n_helper1.
Qed.

Lemma n0_n_1 :  2 * (epsilon / (3 * (1 + log (INR #|X|)))) / INR n < epsilon / 3.
Proof.
rewrite (_ : 2 * _ / _ = epsilon * (2 /  (3 * (1 + log (INR #|X|))) / INR n)); last first.
  field; by case: n0_n_helper2.
apply Rmult_lt_compat_l; first by apply ep_pos.
apply (Rmult_lt_reg_l 3); first by fourier.
rewrite (_ : 3 * _ = 2 * 3 / 3 / (1 + log (INR #|X|)) * / INR n); last first.
  field; by case: n0_n_helper2.
rewrite /Rdiv Rinv_r_simpl_l; last by move=> ?; fourier.
apply (Rmult_lt_reg_l (INR n)); first by apply lt_0_INR; apply/ltP.
rewrite (_ : _ * _ = (2 * / (1 + log (INR #|X|)) * INR n  * / INR n)); last first.
  field; by case: n0_n_helper2.
rewrite (Rinv_r_simpl_l _ _ n_non0).
apply (Rle_lt_trans _ _ _ (ceil_bottom _)).
rewrite IZR_INR_to_nat; last first.
  apply (Rle_trans _ (2 * / (1 + log (INR #|X|)))); last by apply ceil_bottom.
  apply (Rmult_le_reg_l (1 + log (INR #|X|))); last first.
    rewrite (_ : _ * (_ * / _) =
                 2 * (1 + log (INR #|X|)) * / (1 + log (INR #|X|))); last first.
      field; exact n0_n_helper1.
    rewrite (Rinv_r_simpl_l _ _ n0_n_helper1).
    rewrite mulR0; fourier.
  apply (Rplus_lt_le_0_compat _ _ Rlt_0_1).
  rewrite -log_1.
  apply log_increasing_le; first by fourier.
  apply (Xcard P).
rewrite Rinv_r; last by move=> ?; fourier.
rewrite mulR1.
apply (lt_INR _ _ n1_le_n).
Qed.

Lemma n0_n_2 :  2 * / INR n  < epsilon / 4.
Proof.
apply (Rmult_lt_reg_l 4); first fourier.
rewrite /Rdiv (mulRC epsilon (/ 4)) mulRA mulRA Rinv_r ; last by move => ? ; fourier.
apply (Rmult_lt_reg_l (INR n)); first by apply lt_0_INR; apply /ltP.
rewrite (_ : _ * (_ * _ * / _) = 8 * INR n * / INR n); last by field; exact n_non0.
rewrite (Rinv_r_simpl_l _ _ n_non0).
apply (Rmult_lt_reg_l ( / epsilon)).
  apply (Rmult_lt_reg_l epsilon _ _ ep_pos).
  rewrite Rinv_r; first by rewrite mulR0; apply Rlt_0_1.
  by apply nesym, Rlt_not_eq, ep_pos.
rewrite mul1R (mulRC (/ epsilon) (INR n * epsilon)).
rewrite Rinv_r_simpl_l; last by apply nesym, Rlt_not_eq, ep_pos.
rewrite mulRC.
apply (Rle_lt_trans _ (IZR (ceil (8 * / epsilon))) _ (ceil_bottom _)).
rewrite IZR_INR_to_nat; first by apply lt_INR, n2_le_n.
eapply Rle_trans;  last by apply ceil_bottom.
apply (Rmult_le_reg_l epsilon _ _ ep_pos).
rewrite (mulRC 8  (/ epsilon)) mulRA Rinv_r; last by apply nesym, Rlt_not_eq, ep_pos.
rewrite mulR0; fourier.
Qed.

Lemma ep'_pos : 0 < epsilon'.
Proof.
rewrite /epsilon' /Rdiv.
rewrite -(mulR0 epsilon).
apply (Rmult_lt_compat_l _ _ _ ep_pos).
rewrite -(mul1R ( / (3 + 3 * log (INR #|X|)))).
apply (Rlt_mult_inv_pos _ _ Rlt_0_1).
apply Rplus_lt_le_0_compat; first by apply Rlt_zero_pos_plus1, Rlt_R0_R2.
apply Rmult_le_pos; first by apply Rle_zero_pos_plus1, Rle_zero_pos_plus1, Rle_0_1.
rewrite -log_1.
by apply (log_increasing_le Rlt_0_1 (Xcard P)).
Qed.

Lemma n0_n_3 : aep_bound P epsilon' <= INR n.
Proof.
rewrite /aep_bound .
eapply (Rle_trans _ _ _ (ceil_bottom _)).
rewrite IZR_INR_to_nat; last first.
  apply (Rle_trans _ (aep_sigma2 P / epsilon' ^ 3)); last by apply (ceil_bottom _).
  apply (Rmult_le_reg_l ( epsilon' ^ 3) _ _ (pow_gt0 ep'_pos 3)).
  rewrite (_ : _ * ( _ / _) = aep_sigma2 P * epsilon' ^ 3  * / (epsilon' ^ 3)); last first.
    by field; apply nesym, Rlt_not_eq, ep'_pos.
  rewrite Rinv_r_simpl_l; last by apply nesym, Rlt_not_eq, pow_gt0, ep'_pos.
  rewrite mulR0.
  by apply aep_sigma2_pos.
by apply RltW, lt_INR, n3_le_n.
Qed.

Lemma v_scode_helper : exists (f : var_enc X n) (phi : var_dec X n) ,
                         (forall x, phi (f x) = x) /\
                         (exp_len_cw f P) / (INR n) < (`H P + epsilon).
Proof.
exists (f P epsilon') .
exists (phi n' P epsilon').
split=> [ x |]; first  by apply (phi_f _ ep'_pos).
apply (Rmult_lt_reg_r (INR n)); first by apply lt_0_INR; apply /ltP.
rewrite /Rdiv -mulRA -(mulRC (INR n)).
rewrite (Rinv_r _ n_non0).
rewrite mulR1 Hexp_len_cw rsum_type_set (rsum_S_not_S _ (`TS P n epsilon')).
rewrite f_typ_notin f_typ_in; last apply ep'_pos.
eapply Rle_lt_trans.
  apply (theorem_helper _  ep'_pos).
  by apply n0_n_3.
rewrite /L0 /L1.
eapply Rle_lt_trans.
  apply Rplus_le_compat.
    by apply Rplus_le_compat; by [apply RltW, ceil_upper | apply Rle_refl].
  apply Rmult_le_compat_l; first by apply Rlt_le, ep'_pos.
  by apply Rplus_le_compat; by [apply RltW, ceil_upper | apply Rle_refl].
rewrite cardsT card_tuple.
rewrite log_pow; last by apply (dist_support_not_empty P).
rewrite (_ : _ * _ + _ + _ + _ *( _ * _ + _ + _) =
             INR n * (`H P + epsilon') + 2 +
             epsilon' * (INR n * log (INR #|X|) + 2)); last first.
  rewrite /n.
  by field.
rewrite  -(Rinv_r_simpl_l (INR n) 2); last by apply n_non0.
rewrite (_ :  _ * _ + _ * _ / _ =
              INR n * (`H P + epsilon' + 2 / INR n)) ;last first.
  field; by apply n_non0.
rewrite (_ :  _ * _ * / _ = INR n * (2  / INR n)); last first.
  field; by apply n_non0.
rewrite (_ :  INR n * _ + INR n * _ =
                (INR n * (log (INR #|X|) + (2 / INR n)))); last first.
  field; by apply n_non0.
rewrite (_ :   _ * _ + _ * _ =
               INR n * (`H P + epsilon' + 2 / INR n +  epsilon' * (log (INR #|X|) + 2 / INR n))); last first.
  field; by apply n_non0.
rewrite mulRC.
apply Rmult_lt_compat_r.
  by apply lt_0_INR; apply /ltP.
do 2 rewrite -addRA.
apply Rplus_lt_compat_l.
rewrite (_ : epsilon' * _ =
               epsilon' * (log (INR #|X|)) + epsilon' * 2 / INR n); last first.
  field; by apply n_non0.
rewrite (_ :   _ + (_ / _ + _) =
               2 / INR n +
               epsilon' * (1 + log (INR #|X|)) + epsilon' * 2 / INR n) ; last first.
  field; by apply n_non0.
rewrite (_ : _ * _ / _ = 2 * epsilon' / INR n); last first.
  field; by apply n_non0.
rewrite /epsilon'.
rewrite (_ : (3 + 3 * _ = 3 * (1 + log (INR #|X|)))); last field.
rewrite {1}(_ : epsilon / _ =
                epsilon / 3 / (1 + log (INR #|X|) )); last first.
  field; by apply n0_n_helper1.
rewrite (_ : _ / _ / _ * _ =
             epsilon  * (1 + log (INR #|X|))/ (1 + log (INR #|X|)) /3); last first.
  field; by apply n0_n_helper1.
rewrite /Rdiv (Rinv_r_simpl_l _ _ n0_n_helper1).
eapply Rle_lt_trans.
  apply Rplus_le_compat; last by apply RltW, n0_n_1.
    by apply Rplus_le_compat; by [apply RltW, n0_n_2 | apply Rle_refl].
rewrite (_ : _ / _ + _ / _ + _ / _ = epsilon * ( / 4 + / 3 + / 3)) ; last field.
rewrite -{2}(mulR1 epsilon).
apply (Rmult_lt_compat_l _ _ _ ep_pos).
fourier.
Qed.

End main.

Section variable_length_source_coding.

Variable (X : finType) (n' : nat).
Let n := n'.+1.
Variable P : dist X.
Variable epsilon : R.
Hypothesis ep_pos : 0 < epsilon .
(*Definition n0 := maxn
          (Z.to_nat (ceil (INR 2 / (INR 1 + log (INR #|X|)))))
          (maxn (Z.to_nat (ceil (8 / epsilon)))
          (Z.to_nat (ceil (aep_sigma2 P/ epsilon' ^ 3)))).*)
Local Notation "'n0'" := (n0 P epsilon).

Theorem vscode : (n0 < n)%nat ->
  exists f : var_enc X n,
    injective f /\
    exp_len_cw f P / INR n < `H P + epsilon.
Proof.
move/ltP.
case/v_scode_helper => // f [phi [fphi ccl]].
exists f.
split => //.
by apply can_inj with phi.
Qed.

End variable_length_source_coding.


Require Export LaugwitzSchmieden.

Module LSn2 <: Num_w.

Include LS.
(* Definitions in LS are available here thanks to the module type declaration for LS - see above - *)

Definition w :A := fun (n:nat) => Z_of_nat (n*n).

Lemma n_n2 : beta <A w.
unfold beta,w; unfold_intros.
exists 2%nat.
intros.
apply inj_lt.
setoid_replace n with (n*1)%nat at 1 by ring.
apply mult_lt_compat_l; omega.
Qed.

Lemma n_n2bis : forall n, (Z_of_nat n <= Z_of_nat (n*n))%Z.
Proof.
induction n.
simpl; omega.
rewrite Nat2Z.inj_mul.
setoid_replace (Z.of_nat (S n)) with (Z.of_nat (S n)* 1)%Z at 1 by ring.
apply Zmult_le_compat_l.
rewrite Nat2Z.inj_succ.
omega.
omega.
Qed.

Lemma lim_lt_w : forall a:A, lim a/\ leA 0 a -> ltA a w.
Proof.
intros.
apply lt_le_trans with beta.
apply lim_lt_beta.
assumption.
apply lt_le; apply n_n2.
Qed.

Lemma ANS3 : ~lim w.
Proof.
intro H; unfold lim in *.
elim H; clear H; intros p (Hstdp,(Hle0p,Hwp)).
unfold ltA,a0 in *.
elim Hstdp.
intros b Hb.
elim Hwp.
intros a Ha.
elim Hle0p.
intros c Hc.
(* w (p (a+b+c+1) + a + b + c + 1) = p (a+b+c+1) + a+b+c+1 *)
(* p (p (a+b+c+1) + a + b + c + 1) = p (a + b + c + 1) because p(a+b+c+1)>=0 et Hb: p is std *)
pose (px:=p (a+b+c+1)%nat).
assert (0<= px)%Z.
apply Hc.
omega.
pose (x:=((Z.abs_nat px)+a+b+c+1)%nat).
assert ((|w |) (x) < p (x))%Z.
apply Ha.
unfold px,x in *.
omega.

assert  ((|w |) (x) >= p (x))%Z.
apply Z.le_ge.
apply Z.le_trans with  (((|fun n => Z_of_nat n|) (x))%Z).
unfold absA in *.
unfold w.
unfold x.
replace (p (Z.abs_nat px + a + b + c + 1)%nat)%Z with
(p (a+b+c+1)%nat)%Z.
rewrite Z.abs_eq.
replace (Z.abs_nat px + a + b + c + 1)%nat with (Z.abs_nat (px + (Z_of_nat (a + b + c + 1))))%nat.
rewrite inj_Zabs_nat.
rewrite Z.abs_eq.
unfold px.
omega.
omega.
rewrite Zabs_nat_Zplus.
rewrite Zabs_nat_Z_of_nat.
ring.
unfold px; apply Hc.
omega.
solve [auto with zarith].
solve [auto with zarith].
apply Hb.
omega.
omega.
unfold w, absA.
rewrite Z.abs_eq.
rewrite Z.abs_eq.
apply n_n2bis.
apply Zle_0_nat.
apply Zle_0_nat.
omega.
Qed.

Lemma Aw : 0 <A w.
Proof.
unfold ltA.
exists 0%nat.
intros;unfold a0, w.
rewrite Nat2Z.inj_mul.
setoid_replace 0%Z with (Z.of_nat n * 0)%Z by ring.
assert (0<Z.of_nat n)%Z by omega.
apply Zmult_lt_compat_l; assumption.
Qed.

Lemma div_modw2 : forall a, w*(a/w) =A a + - (a mod% w).
Proof.
intros; apply div_mod2.
left; apply Aw.
Qed.

Lemma div_modw3 : forall a, |(a mod% w)| <A w.
Proof.
intros; apply div_mod3.
apply Aw.
Qed.

End LSn2.


Require Import Coq.Logic.Classical_Pred_Type.
Require Import mathcomp.ssreflect.all_ssreflect.
Require Import mathcomp.algebra.all_algebra.
Require Import mathcomp.ssreflect.bigop.
Import GRing.Theory Num.Theory.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Require Import Filter.
Require Import Dominated.

Definition filter_nat_base : filter nat :=
  fun P => exists n0, forall n, le n0 n -> P n.

Definition mixin_filter_nat : filterMixin filter_nat_base.
Proof.
  constructor; unfold filter_nat_base.
  - exists O. eauto.
  - intros ? [? ?]. eauto.
  - { intros P1 P2 P [n1 H1] [n2 H2] I. exists (max n1 n2).
      intros. apply I.
      - apply H1. apply Max.max_lub_l with n2. eauto.
      - apply H2. apply Max.max_lub_r with n1. eauto. }
Qed.

Definition filter_nat := FilterType mixin_filter_nat.
Definition filter_nat_nat := filter_product filter_nat filter_nat.

Definition dominated_forall := dominated filter_nat_nat.

Section Hat.

Variable B : numDomainType.

Definition hat_nat (f: nat -> B): nat -> B :=
  fun n => \big[Num.max/0]_(0 <= i < n+1) f i.

Definition hat_nat_nat (f: nat * nat -> B) : nat * nat -> B :=
  fun p =>
    let (n1, n2) := p in
    \big[Num.max/0]_(0 <= i < n1+1) \big[Num.max/0]_(0 <= j < n2+1) f (i, j).

SearchAbout Num.max.

Lemma hat_nat_ge : forall f, forall n, f n <= hat_nat f n.
Proof.
  intros. unfold hat_nat. rewrite big_nat_recr.
Admitted.

(* nondecr f -> hat f = f *)

End Hat.


Require Import Grammar.
Require Import Coq.Lists.List.
Require Import Coq.Strings.String.
Import ListNotations.

Inductive nonterminal : Type :=
| NT : string -> nonterminal.

Inductive terminal : Type :=
| Te : string -> terminal.

Definition production : Type := terminal * list nonterminal.
Definition grammar : Type := (nonterminal -> production).

Definition a : string := "a".
Definition b : string := "b".
Definition c : string := "c".

Definition simple_grammar : grammar :=
  fun s =>
    match s with
    | NT "S" => ((Te "a"),[(NT "B");(NT "B")])
    | NT "B" => ((Te "b"),[])
    | _ => ((Te ""), [])
    end.

Fixpoint check (g : grammar) (tokens : list string) (nt : nonterminal) : bool * list string :=
  match tokens, g nt with
  | token :: ts, (Te x, []) => if string_dec token x then (true, ts) else (false, [])
  | token :: ts, (Te x, ns) =>
    if string_dec token x then
      fold_left (fun ts' nt =>
                   match ts' with
                   | (true, tmp) => check g tmp nt
                   | (false, _) => (false, [])
                   end) ns (true, ts)
    else (false, [])
  | _, _ => (false, [])
  end.


(** * MoreCoq: More About Coq's Tactics *)

Require Export Poly.

(** This chapter introduces several more proof strategies and
    tactics that, together, allow us to prove theorems about the
    functional programs we have been writing. In particular, we'll
    reason about functions that work with natural numbers and lists.

    In particular, we will see:
    - how to use auxiliary lemmas, in both forwards and backwards reasoning;
    - how to reason about data constructors, which are injective and disjoint;
    - how to create a strong induction hypotheses (and when
      strengthening is required); and
    - 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 above. But 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] binding 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 thm fact.
  apply thm.
  apply fact.
Qed.
(** [] *)

(** 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.
  rewrite -> H.
  symmetry.
  apply rev_involutive.
Qed.
(** [] *)

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  Are there 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
    abstract 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 eq1 eq2.
  apply trans_eq with (m).
  apply eq2.
  apply eq1.
Qed.
(** [] *)

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

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is clear 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 other facts:

    - The constructor [S] is _injective_.  That is, the only way we can
      have [S n = S m] is if [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 unequal.  (Since neither [true]
    nor [false] take any arguments, their injectivity is not an issue.) *)

(** Coq provides a tactic called [inversion] that allows us to exploit
    these principles in proofs.

    The [inversion] tactic is used like this.  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] instructs Coq to "invert" this
    equality to extract the information it contains about these terms:

    - If [c] and [d] are the same constructor, then we know, by the
      injectivity of this constructor, 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.  That is, a false assumption has crept
      into the context, and this means that any goal whatsoever is
      provable!  In this case, [inversion H] marks the current goal as
      completed and pops it off the goal stack. *)

(** The [inversion] tactic is probably easier to understand by
    seeing it in action than from general descriptions like the above.
    Below you will find example theorems that demonstrate the use of
    [inversion] and exercises to test your understanding. *)

Theorem eq_add_S : forall (n m : nat),
     S n = S m ->
     n = m.
Proof.
  intros n m eq. inversion eq. reflexivity.  Qed.

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

(** As a convenience, the [inversion] tactic can also
    destruct equalities between complex values, binding
    multiple variables as it goes. *)

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

(** **** Exercise: 1 star (sillyex1)  *)
Example sillyex1 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = z :: j ->
     y :: l = x :: j ->
     x = y.
Proof.
  intros X x y z l j eq1 eq2.
  inversion eq2.
  reflexivity.
Qed.
(** [] *)

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

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

(** **** Exercise: 1 star (sillyex2)  *)
Example sillyex2 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = [] ->
     y :: l = z :: j ->
     x = z.
Proof.
  intros X x y z l j eq1.
  inversion eq1.
Qed.
(** [] *)

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

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.

(** **** Exercise: 2 stars, optional (practice)  *)
(** A couple more nontrivial but not-too-complicated proofs to work
    together in class, or for you to work as exercises. *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  intros n H.
  destruct n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    inversion H.
Qed.

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  intros n H.
  destruct n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    inversion H.
Qed.
(** [] *)

(* ###################################################### *)
(** * 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, the tactic [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
    gives us 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, Coq tends to favor backward reasoning, but in some
    situations the forward style can be easier to use or to think
    about.  *)

(** **** Exercise: 3 stars (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise. *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      inversion H.
  Case "n = S n'".
    intros m.
    destruct m as [| m'].
    SCase "m = 0".
      intros H.
      inversion H.
    SCase "m = S m'".
      intros H.
      rewrite <- plus_n_Sm in H.
      rewrite <- plus_n_Sm in H.
      inversion H.
      apply f_equal.
      apply IHn'.
      apply H1.
Qed.
(** [] *)

(* ###################################################### *)
(** * 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 little bit delicate: if we
    begin it 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'].
  Case "n = O". simpl. intros eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'". intros eq. destruct m as [| m'].
    SCase "m = O". inversion eq.
    SCase "m = S m'".  apply f_equal.
      (* Here we are stuck.  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 _this 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 that
    the proposition

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

    holds for all [n] by showing

      - [P O]

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

      - [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 with proving [R]!  (If we
    tried to prove [R] from [Q], we would say 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 at this point.) *)

(** 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
    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'].
  Case "n = O". simpl. intros m eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'".
    (* Notice that both the goal and the induction
       hypothesis have changed: 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 choose a particular [m] and introduce the
       assumption that [double n = double m].  Since we
       are doing a case analysis on [n], we need a case
       analysis on [m] to keep the two "in sync." *)
    destruct m as [| m'].
    SCase "m = O".
      (* The 0 case is trivial *)
      inversion eq.
    SCase "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 at this point is actually the
         predecessor of the one 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
         [m'] that we are talking about right now (this
         instantiation is performed automatically by
         [apply]), then [IHn'] gives us exactly what we
         need to finish the proof. *)
      apply IHn'. inversion eq. reflexivity. Qed.

(** What this teaches us 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 proof of this theorem (left as an exercise) has to be treated similarly: *)

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  induction n as [| n'].
  Case "n = 0".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      inversion H.
  Case "n = S n'".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      inversion H.
    SCase "m = S m'".
      apply IHn' in H.
      rewrite -> H.
      reflexivity.
Qed.
(** [] *)

(** **** 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] doesn't
    always work directly; 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'].
  Case "m = O". simpl. intros eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "n = S n'".  apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem 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 mangle 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, taking them 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'].
  Case "m = O". simpl. intros n eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros n eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "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 this is what we wanted to show.  Otherwise, if [n = S
    n'] for some [n'], we derive a contradiction: by the definition of
    [double] we would have [double n = S (S (double n'))], but this
    contradicts the assumption that [double n = 0].

  - Otherwise, 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. [] *)

(** Here's another illustration of [inversion] and using an
    appropriately general induction hypothesis.  This is a slightly
    roundabout way of stating a fact that we have already proved
    above.  The extra equalities force us to do a little more
    equational reasoning and exercise some of the tactics we've seen
    recently. *)

Theorem length_snoc' : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l. induction l as [| v' l'].

  Case "l = []".
    intros n eq. rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    intros n eq. simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.

(** It might be tempting to start proving the above theorem
    by introducing [n] and [eq] at the outset.  However, this leads
    to an induction hypothesis that is not strong enough.  Compare
    the above to the following (aborted) attempt: *)

Theorem length_snoc_bad : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l n eq. induction l as [| v' l'].

  Case "l = []".
    rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)

(** As in the double examples, the problem is that by
    introducing [n] before doing induction on [l], the induction
    hypothesis is specialized to one particular natural number, namely
    [n].  In the induction case, however, we need to be able to use
    the induction hypothesis on some other natural number [n'].
    Retaining the more general form of the induction hypothesis thus
    gives us more flexibility.

    In general, a good rule of thumb is to make the induction hypothesis
    as general as possible. *)

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

Theorem index_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     index n l = None.
Proof.
  intros n X l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros n H.
    reflexivity.
  Case "l = h :: t".
    intros n H.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      inversion H.
      apply IHt.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)
(** Write an informal proof corresponding to your Coq proof
    of [index_after_last]:

     _Theorem_: For all sets [X], lists [l : list X], and numbers
      [n], if [length l = n] then [index n l = None].

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

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

Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : list X),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros n X v l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros n H.
    simpl in H.
    rewrite <- H.
    reflexivity.
  Case "l = h :: t".
    intros n H.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      apply IHt.
      inversion H.
      reflexivity.
Qed.
(** [] *)

(** **** 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.
  intros X l1.
  induction l1 as [| h t].
  Case "l1 = []".
    intros.
    rewrite <- H.
    reflexivity.
  Case "l1 = h :: t".
    intros.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      apply IHt with (x).
      inversion H.
      reflexivity.
Qed.
(** [] *)

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

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  assert (forall (X : Type) (l1 l2 : list X) (x : X) (n : nat),
    length (l1 ++ l2) = n -> length (l1 ++ (x :: l2)) = S n
  ) as app_length_cons'.
  Case "Proof of assertion".
    intros X l1.
    induction l1 as [| h t].
    SCase "l = nil".
      intros.
      rewrite <- H.
      reflexivity.
    SCase "l = h :: t".
      intros.
      destruct n as [| n'].
      SSCase "n = 0".
        inversion H.
      SSCase "n = S n'".
        simpl.
        apply f_equal.
        apply IHt.
        inversion H.
        reflexivity.
  intros X n l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros.
    rewrite <- H.
    reflexivity.
  Case "l = h :: t".
    intros.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      rewrite <- plus_n_Sm.
      apply app_length_cons'.
      apply IHt.
      inversion H.
      reflexivity.
Qed.
(** [] *)

(** **** 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.
  intros P H.
  induction m as [| m'].
  Case "m = 0".
    induction n as [| n'].
    SCase "n = 0".
      apply H.
    SCase "n = S n'".
      apply H1.
      apply IHn'.
  Case "m = S m'".
    induction n as [| n'].
    SCase "n = 0".
      apply H0.
      apply IHm'.
    SCase "n = S n'".
      apply H2.
      apply IHm'.
Qed.
(** [] *)

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

(** We have seen many examples where the [destruct] tactic 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).
    Case "beq_nat n 3 = true". reflexivity.
    Case "beq_nat n 3 = false". destruct (beq_nat n 5).
      SCase "beq_nat n 5 = true". reflexivity.
      SCase "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 ...].  Well,
    either [n] is equal to [3] or it isn't, so we 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: 1 star (override_shadow)  *)
Theorem override_shadow : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  (override (override f k1 x2) k1 x1) k2 = (override f k1 x1) k2.
Proof.
  intros.
  unfold override.
  destruct (beq_nat k1 k2).
  Case "beq_nat k1 k2 = true".
    reflexivity.
  Case "beq_nat k1 k2 = false".
    reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
(** Complete the proof below *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y l.
  induction l as [| (x, y) t].
  Case "l = []".
    intros l1 l2 H.
    inversion H.
    reflexivity.
  Case "l = (x, y) :: t".
    intros l1 l2 H.
    simpl in H.
    destruct (split t) as [xs ys].
    destruct l1 as [| h1 t1].
    SCase "l1 = []".
      inversion H.
    SCase "l1 = h1 :: t1".
      destruct l2 as [| h2 t2].
      SSCase "l2 = []".
        inversion H.
      SSCase "l2 = h2 :: t2".
        assert ((xs, ys) = (t1, t2)).
        SSSCase "Proof of assertion".
          inversion H.
          reflexivity.
        apply IHt in H0.
        rewrite <- H0.
        simpl.
        inversion H.
        reflexivity.
Qed.
(** [] *)

(** Sometimes, doing a [destruct] on a compound expression (a
    non-variable) will 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.

(** And suppose that we want to convince Coq of the rather
    obvious observation 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, in this branch of the case
    analysis, [beq_nat n 3 = true], 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 (with whatever
    name 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. *)
    Case "e3 = true". apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    Case "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.
        SCase "e5 = true".
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        SCase "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.
  intros f.
  destruct b.
  Case "b = true".
    destruct (f true) eqn:Htrue.
    SCase "f true = true".
      rewrite -> Htrue.
      apply Htrue.
    SCase "f true = false".
      destruct (f false) eqn:Hfalse.
      SSCase "f false = true".
        apply Htrue.
      SSCase "f false = false".
        apply Hfalse.
  Case "b = false".
      destruct (f false) eqn:Hfalse.
      SCase "f false = true".
        destruct (f true) eqn:Htrue.
        SSCase "f true = true".
          apply Htrue.
        SSCase "f true = false".
          apply Hfalse.
      SCase "f false = false".
        rewrite -> Hfalse.
        apply Hfalse.
Qed.

(** **** Exercise: 2 stars (override_same)  *)
Theorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),
  f k1 = x1 ->
  (override f k1 x1) k2 = f k2.
Proof.
  intros X x1 k1 k2 f H.
  unfold override.
  destruct (beq_nat k1 k2) eqn:Heq.
  Case "beq_nat k1 k2 = true".
   apply beq_nat_true in Heq.
   rewrite <- Heq.
   symmetry.
   apply H.
  Case "beq_nat k1 k2 = false".
    reflexivity.
Qed.
(** [] *)

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

(** We've now seen a bunch of Coq's fundamental tactics.  We'll
    introduce a few more as we go along through the coming lectures,
    and later in the course we'll introduce some more powerful
    _automation_ tactics that make Coq do more of the low-level work
    in many cases.  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.
  induction n as [| n'].
  Case "n = 0".
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      reflexivity.
  Case "n = S n'".
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      simpl.
      apply IHn'.
Qed.
(** [] *)

(** **** 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.
  intros n m p eqnm eqmp.
  apply beq_nat_true in eqnm.
  apply beq_nat_true in eqmp.
  rewrite -> eqnm.
  rewrite <- eqmp.
  symmetry.
  apply beq_nat_refl.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We have just proven 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 :=
  forall (X Y : Type) (l1 : list X) (l2 : list Y),
  length l1 = length l2 -> split (combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
  intros X Y.
  induction l1 as [| h1 t1].
  Case "l1 = []".
    destruct l2 as [| h2 t2].
    SCase "l2 = []".
      intros H.
      reflexivity.
    SCase "l2 = h2 :: t2".
      intros contra.
      inversion contra.
  Case "l1 = h1 :: t1".
    destruct l2 as [| h2 t2].
    SCase "l2 = []".
      intros contra.
      inversion contra.
    SCase "l2 = h2 :: t2".
      intros H.
      simpl in H.
      inversion H.
      apply IHt1 in H1.
      simpl.
      rewrite -> H1.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars (override_permute)  *)
Theorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  intros.
  unfold override.
  destruct (beq_nat k1 k3) eqn:eq13.
  Case "beq_nat k1 k3 = true".
    destruct (beq_nat k2 k3) eqn:eq12.
    SCase "beq_nat k2 k3 = true".
      apply beq_nat_true in eq13.
      apply beq_nat_true in eq12.
      rewrite -> eq12 in H.
      rewrite -> eq13 in H.
      rewrite <- beq_nat_refl in H.
      inversion H.
    SCase "beq_nat k2 k3 = false".
      reflexivity.
  Case "beq_nat k1 k3 = false".
    destruct (beq_nat k2 k3) eqn:eq12.
    SCase "beq_nat k2 k3 = true".
      reflexivity.
    SCase "beq_nat k2 k3 = false".
      reflexivity.
Qed.
(** [] *)

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

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  intros X test.
  induction l as [| h t].
  Case "l = []".
    intros lf contra.
    inversion contra.
  Case "l = h :: t".
    intros lf H.
    simpl in H.
    destruct (test h) eqn:Htest.
    SCase "test h = true".
      inversion H.
      rewrite <- H1.
      apply Htest.
    SCase "test h = false".
      apply IHt with (lf).
      apply H.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced (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].

    Prove theorem [existsb_existsb'] that [existsb'] and [existsb] have
    the same behavior.
*)

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => true
  | h :: t => if test h
              then forallb test t
              else false
  end.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => false
  | h :: t => if test h
              then true
              else existsb test t
  end.

Function existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=
  negb (forallb (fun (x : X) => negb (test x)) l).

Theorem existsb_existsb' :
  forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof.
  intros X test.
  induction l as [| h t].
  Case "l = []".
    reflexivity.
  Case "l = h :: t".
    simpl.
    destruct (test h) eqn:H.
    SCase "test h = true".
      unfold existsb'.
      simpl.
      rewrite -> H.
      reflexivity.
    SCase "test h = false".
      unfold existsb'.
      simpl.
      rewrite -> H.
      rewrite -> IHt.
      reflexivity.
Qed.
(** [] *)

(** $Date: 2014-12-31 16:01:37 -0500 (Wed, 31 Dec 2014) $ *)