Require Import Base.
Require Import Monad.

(* classical non-empty subset monad *)
Section NonemptyPowersetMonad.
  Definition NPset : Type -> Type := fun A => {P : A ->  Prop | exists x, P x}.
  Definition NPset_fun_map : forall A B (f : A -> B), NPset A -> NPset B.
  Proof.
    intros A B f [x e].
    exists (fun b => exists a, x a /\ b = f a).
    destruct e as [x0 H].
    exists (f x0).
    exists x0.
    auto.
  Defined.

  Definition NPset_functorial_comp : forall A B C (f : A -> B) (g : B -> C),
      NPset_fun_map _ _ (fun x => g (f x)) = fun x => (NPset_fun_map _ _ g) ((NPset_fun_map _ _ f) x).
  Proof.
    intros.
    apply fun_ext.
    intro.
    unfold NPset_fun_map.
    destruct x.
    destruct e.
    simpl.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    destruct H.
    exists (f x3); auto.
    split.
    exists x3.
    split; auto.
    destruct H; auto.
    destruct H; auto.
    intro.
    destruct H.
    destruct H.
    destruct H.
    exists x4.
    destruct H.
    rewrite H0.
    rewrite H1.
    auto.
  Defined.

    Definition NPset_functorial_id :  forall A, (fun x : NPset A => x) = NPset_fun_map A A (fun x => x).
    Proof.
      intros.
      apply fun_ext.
      intro.
      unfold NPset_fun_map.
      destruct x.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      destruct e.
      exists x0; auto.
      intro.
      destruct H.
      destruct H.
      rewrite H0; auto.
    Defined.

    (* monad has unit and mult *)
    Definition NPset_unit : forall A : Type, A -> NPset A.
    Proof.
      intros.
      exists (fun a => a = X).
      exists X; auto.
    Defined.

    Definition NPset_mult : forall A : Type, NPset (NPset A) -> NPset A.
    Proof.
      intros.
      destruct X.
      exists (fun a => exists X, x X /\  projP1 _ _ X a).
      destruct e.
      destruct x0.
      destruct e.
      exists x1.
      exists (exist _ x0 (ex_intro _ x1 x2)).
      split.
      assert ((exist (fun P : A -> Prop => exists x : A, P x) x0 (ex_intro (fun x : A => x0 x) x1 x2)) = (exist (ex (A:=A)) x0 (ex_intro x0 x1 x2))).
      apply sigma_eqP2; auto.
      rewrite <- H0; auto.
      simpl; auto.
    Defined.

    (* unit and mult are nat. trans.  *)
    Definition NPset_unit_ntrans : forall A B (f : A -> B) x, (NPset_fun_map A B f) (NPset_unit A x) = NPset_unit B (f x).
    Proof.
      intros.
      unfold NPset_unit.
      unfold NPset_fun_map.
      apply sigma_eqP2.
      apply fun_ext; intro.
      apply Prop_ext.
      intro.
      destruct H.
      destruct H.
      rewrite H in H0.
      exact H0.
      intro.
      rewrite H.
      exists x; auto.
    Defined.

    Definition NPset_mult_ntrans : forall A B (f : A -> B) x, NPset_mult B ((NPset_fun_map (NPset A) (NPset B) (NPset_fun_map A B f)) x) = (NPset_fun_map A B f) (NPset_mult A x).
    Proof.
      intros.
      unfold NPset_mult.
      unfold NPset_fun_map.
      destruct x.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      destruct e.
      destruct x1.
      destruct e.
      destruct H.
      destruct H.
      destruct H.
      destruct H.
      destruct x5.
      rewrite H2 in H1.
      simpl in H1.
      destruct H1.
      destruct H1.
      exists x6.
      split; auto.
      exists (exist _ x5 (ex_intro _ x6 H1)).
      simpl.
      split; auto.
      assert ((exist (ex (A:=A)) x5 (ex_intro x5 x6 H1)) = (exist (fun P : A -> Prop => exists x : A, P x) x5 e)).
      apply sigma_eqP2.
      auto.
      rewrite H4; auto.
      intro.
      destruct H.
      destruct H.
      destruct H.
      destruct H.
      exists (NPset_fun_map _ _ f x2).
      split.
      exists x2.
      split; auto.
      unfold NPset_fun_map.
      destruct x2.
      simpl.
      exists x1; auto.
    Defined.

    (* coherence conditions *)
    Definition NPset_coh1 : forall A x, NPset_mult A (NPset_unit (NPset A) x) = x.
    Proof.
      intros.
      destruct x.
      unfold NPset_mult.
      unfold NPset_unit.
      apply sigma_eqP2.
      apply fun_ext; intro.
      apply Prop_ext.
      intro.
      destruct H.
      destruct x1.
      simpl in H.
      destruct H.
      apply sigma_eqP_pr1 in H.
      rewrite <- H; auto.
      intro.
      exists (exist _ x (ex_intro _ x0 H)).
      simpl.
      split.
      apply sigma_eqP2; auto.
      auto.
    Defined.

    Definition NPset_coh2 : forall A x, NPset_mult A (NPset_fun_map A (NPset A) (NPset_unit A)  x) = x.
    Proof.
      intros.
      unfold NPset_mult, NPset_fun_map, NPset, NPset_unit.
      destruct x.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      destruct H.
      destruct H.
      destruct H.
      destruct H.
      rewrite H1 in H0.
      simpl in H0.
      rewrite H0; auto.
      intro.

      destruct e.
      exists (exist _ (fun b => b = x0) (ex_intro _ x0 eq_refl)).
      split.
      exists x0.
      split; auto.
      simpl.
      auto.
    Defined.

    Definition NPset_coh3 : forall A x, NPset_mult A (NPset_mult (NPset A) x) = NPset_mult A (NPset_fun_map (NPset (NPset A)) (NPset A) (NPset_mult A) x).
    Proof.
      unfold NPset_mult, NPset_mult, NPset, NPset_fun_map.
      intros.
      destruct x.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      destruct H.
      destruct H.
      destruct H.
      simpl in H.
      destruct x2.
      simpl in H.
      assert (exists a : A, exists X, x2 X /\ projP1 _ _ X  a).
      destruct e0.
      destruct H.
      destruct x1.
      destruct e0.
      destruct x3.
      destruct e0.
      exists x7.
      exists (exist _ x3 (ex_intro _ x7 x8)).
      simpl.
      split; auto.
      exists (exist _ (fun a => exists X, x2 X /\ projP1 _ _ X a) H1).
      split; auto.
      exists (exist _ x2 e0).
      split; auto.
      destruct H.
      exact H.
      apply sigma_eqP2.
      auto.
      simpl.
      exists x1.
      split; auto.
      destruct H; auto.

      intro.
      repeat destruct H.
      destruct x2.
      destruct x1.
      apply (lp _ _ (projP1 _ _ )) in H1.
      simpl in H1.
      simpl in H0.
      rewrite H1 in H0.
      destruct H0.
      exists x3.
      simpl.
      split; auto.
      exists (exist _ x2 e0).
      simpl.
      split; auto.
      destruct H0; auto.
      destruct H0; auto.
    Defined.

    (* classical nonempty powerest monad *)

  #[global] Instance NPset_Monad : Monad NPset := {
    Monad_fun_map := NPset_fun_map;
    Monad_functorial_comp := NPset_functorial_comp;
    Monad_functorial_id := NPset_functorial_id;
    Monad_unit := NPset_unit;
    Monad_mult := NPset_mult;
    Monad_unit_ntrans := NPset_unit_ntrans;
    Monad_mult_ntrans := NPset_mult_ntrans;
    Monad_coh1 := NPset_coh1;
    Monad_coh2 := NPset_coh2;
    Monad_coh3 := NPset_coh3;
  }.

End NonemptyPowersetMonad.

Section NablaMonad.
  Definition Nabla : Type -> Type := fun A => {P : A -> Prop | exists! a, P a}.
  Definition Nabla_fun_map : forall A B (f : A -> B), Nabla A -> Nabla B.
  Proof.
    intros.
    destruct X.
    exists (fun b => exists a : A, x a /\ b = f a).
    destruct e.
    exists (f x0).
    split.
    exists x0.
    destruct H.
    split; auto.
    intros.
    destruct H0.
    destruct H0.
    destruct H.
    induction (H2 _ H0).
    auto.
  Defined.

  Definition Nabla_functorial_comp : forall A B C (f : A -> B) (g : B -> C),
      Nabla_fun_map _ _ (fun x => g (f x)) = fun x => (Nabla_fun_map _ _ g) ((Nabla_fun_map _ _ f) x).
  Proof.
    intros.
    apply fun_ext.
    intro.
    unfold NPset_fun_map.
    destruct x.
    destruct e.
    simpl.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    destruct H.
    exists (f x2); auto.
    split.
    exists x2.
    split; auto.
    destruct H; auto.
    destruct H; auto.
    intro.
    destruct H.
    destruct H.
    destruct H.
    exists x3.
    destruct H.
    rewrite H0.
    rewrite H1.
    auto.
  Defined.

  Definition Nabla_functorial_id :  forall A, (fun x : Nabla A => x) = Nabla_fun_map A A (fun x => x).
  Proof.
    intros.
    apply fun_ext.
    intro.
    (* unfold NPset_fun_map. *)
    destruct x.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    destruct e.
    exists x0; auto.
    intro.
    destruct H.
    destruct H.
    rewrite H0; auto.
  Defined.

  Definition Nabla_unit : forall A : Type, A -> Nabla A.
  Proof.
    intros.
    exists (fun a => a = X).
    exists X.
    split.
    exact (eq_refl _).
    intros.
    induction H.
    exact (eq_refl _).
  Defined.

  Definition Nabla_mult : forall A : Type, Nabla (Nabla A) -> Nabla A.
  Proof.
    intros.
    destruct X.

    exists (fun a => x (Nabla_unit A a)).
    destruct e.
    destruct x0.
    destruct e.
    exists x1.
    split.
    destruct u.
    destruct H.
    unfold Nabla_unit.
    assert (
        (exist (fun P : A -> Prop => exists ! a : A, P a) x0
                (ex_intro (unique (fun a : A => x0 a)) x1 (conj x2 e)))
        =
           (exist (fun P : A -> Prop => exists ! a : A, P a) (fun a : A => a = x1)
           (ex_intro (unique (fun a : A => a = x1)) x1
                 (conj eq_refl (fun (x' : A) (H1 : x' = x1) => eq_ind x' (fun X : A => X = x') eq_refl x1 H1))))
      ).
    assert (x0 = (fun a : A => a = x1)).
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    pose proof (e _ H1).
    rewrite H2; auto.
    intro.
    rewrite H1.
    exact x2.
    apply (sigma_eqP _ _ _ _ _ _ H1).
    apply irrl.
    rewrite<- H1.
    exact H.

    intros.
    destruct H.
    pose proof (H1 _ H0).
    unfold Nabla_unit in H2.
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H2).
    apply (lp _ _ (fun f => f x1)) in H3.
    rewrite <- H3.
    destruct u.
    auto.
  Defined.

  Definition Nabla_unit_ntrans : forall A B (f : A -> B) x, (Nabla_fun_map A B f) (Nabla_unit A x) = Nabla_unit B (f x).
  Proof.
    intros.
    apply eq_sym.
    unfold Nabla_fun_map.
    case_eq (Nabla_unit _ x); intros.
    unfold Nabla_unit.
    assert ((fun a : B => a = f x) =  (fun b : B => exists a : A, x0 a /\ b = f a)).
    apply fun_ext.
    intros.
    apply Prop_ext.
    intros.
    exists x.
    split; auto.

    unfold Nabla_unit in H.
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H).
    apply (lp _ _ (fun f => f x)) in H1.
    rewrite <- H1; apply eq_refl.
    intro.
    repeat destruct H0.
    rewrite H1; clear H1.
    unfold Nabla_unit in H.
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H).
    apply (lp _ _ (fun f => f x)) in H1.
    assert (x0 x) by (rewrite <- H1; apply eq_refl).
    destruct e.
    destruct u.
    pose proof (e _ H0).
    pose proof (e _ H2).
    rewrite <- H3, <- H4.
    auto.
    apply (sigma_eqP _ _ _ _ _ _ H0).
    apply irrl.
  Qed.

  Definition Nabla_mult_ntrans : forall A B (f : A -> B) x, Nabla_mult B ((Nabla_fun_map (Nabla A) (Nabla B) (Nabla_fun_map A B f)) x) = (Nabla_fun_map A B f) (Nabla_mult A x).
  Proof.
      intros.
      unfold Nabla_mult.
      unfold Nabla_fun_map.
      destruct x.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      destruct H.
      destruct H.
      destruct x1.
      destruct e0.
      unfold Nabla_unit in H0.
      apply sigma_eqP_pr1 in H0.
      apply (lp _ _ (fun g => g x0)) in H0.
      assert ( (exists a : A, x1 a /\ x0 = f a)) by (rewrite <- H0; auto).
      destruct H1.
      exists x3; auto.
      split; auto.
      assert ((Nabla_unit A x3) = (exist (fun P : A -> Prop => exists ! a : A, P a) x1 (ex_intro (unique (fun a : A => x1 a)) x2 u))).
      unfold Nabla_unit.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      rewrite H2.
      destruct H1; auto.
      intro.
      destruct u.
      destruct H1.
      rewrite <- (e0 _ H1).
      rewrite <- (e0 _ H2).
      auto.
      rewrite H2; auto.
      destruct H1; auto.
      intro.
      destruct e.
      exists x1.
      destruct H0.
      split; auto.
      destruct x1.
      apply sigma_eqP2.
      apply fun_ext.
      intro.
      apply Prop_ext.
      intro.
      rewrite H2.
      destruct H.
      exists x3.
      split; auto.
      destruct H.
      pose proof (H1 _ H).
      apply sigma_eqP_pr1 in H4.
      rewrite H4; auto.
      destruct H; auto.
      intro.
      destruct H2.
      destruct H2.
      rewrite H3.
      destruct H.
      destruct H.
      pose proof (H1 _ H).
      apply sigma_eqP_pr1 in H5.
      rewrite H4.
      apply (lp _ _ (fun g => g x3)) in H5.
      assert (x3 = x4) by (rewrite <- H5; auto).
      rewrite H6; auto.
  Defined.

  (* coherence conditions *)
  Definition Nabla_coh1 : forall A x, Nabla_mult A (Nabla_unit (Nabla A) x) = x.
  Proof.
    intros.
    destruct x.
    apply sigma_eqP2.
    apply fun_ext; intro.
    apply Prop_ext.
    intro.
    apply sigma_eqP_pr1 in H.
    apply (lp _ _ (fun g => g x0)) in H.
    rewrite <- H; auto.
    intro.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    rewrite H0; auto.
    intro.
    destruct e.
    destruct H1.
    rewrite <- (H2 _ H).
    rewrite <- (H2 _ H0).
    auto.
  Defined.

  Definition Nabla_coh2 : forall A x, Nabla_mult A (Nabla_fun_map A (Nabla A) (Nabla_unit A)  x) = x.
  Proof.
    intros.
    destruct x.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    destruct H.
    destruct H.
    apply sigma_eqP_pr1 in H0.
    apply (lp _ _ (fun g => g x0)) in H0.
    assert (x0 = x1) by (rewrite <- H0; auto).
    rewrite H1; auto.
    intro.
    exists x0.
    split; auto.
  Defined.

  Lemma nabla_eq_at : forall A (a b : Nabla A), projP1 _  _ a = projP1 _ _ b -> a = b.
  Proof.
    intros.
    destruct a, b.
    simpl in H.
    apply (sigma_eqP _ _ _ _ _ _ H).
    apply irrl.
  Qed.

  Definition Nabla_unit_mult_inverse : forall A, (forall x : Nabla A, Nabla_mult _ (Nabla_unit _ x) = x) /\
                                                 (forall x : Nabla (Nabla A), Nabla_unit _ (Nabla_mult _ x) = x).
  Proof.
    intro.
    split.
    intro.
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    rewrite <- H.
    simpl.
    exact eq_refl.
    intro.
    destruct x.
    simpl in H.
    destruct e.
    destruct u.
    pose proof (e _ H).
    induction H0.
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    induction H0.
    exact H.
    intro.
    rewrite (e _ H0); auto.

    intro.
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    rewrite H.

    destruct x.

    destruct e.
    destruct u.
    assert (x1 = (Nabla_mult A
                             (exist (fun P : Nabla A -> Prop => exists ! a : Nabla A, P a) x
                                    (ex_intro (unique (fun a : Nabla A => x a)) x1 (conj x2 e))))).
    simpl.
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    destruct x1.
    simpl in H0.
    destruct e0.
    destruct u.
    pose proof (e0 _ H0).
    induction H1.
    assert (
        (exist (fun P : A -> Prop => exists ! a : A, P a) x1
               (ex_intro (unique (fun a : A => x1 a)) x4 (conj x5 e0)))
        =
        Nabla_unit A x4).
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    pose proof (e0 _ H1).
    rewrite (H2).
    apply eq_refl.
    intro.
    rewrite H1.
    exact H0.
    clear H.
    rewrite H1 in x2.
    exact x2.
    intro.
    clear H.
    destruct x1.
    simpl.
    destruct e0.
    destruct u.
    assert (
        (exist (fun P : A -> Prop => exists ! a : A, P a) x1
               (ex_intro (unique (fun a : A => x1 a)) x4 (conj x5 e0)))
        =

        (Nabla_unit A x3)).
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.

    intro.
    pose proof ( e _ H0).
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H1).
    apply (lp _ _ (fun k => k x3)) in H2.
    assert (x1 x3) by (rewrite H2; auto).
    pose proof (e0 _ H3).
    pose proof (e0 _  H).
    rewrite <- H4, <- H5.
    auto.

    intro.
    rewrite H.
    pose proof ( e _ H0).
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H1).
    rewrite H2.
    auto.

    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H).
    rewrite H1.
    auto.
    rewrite <- H0.
    simpl.
    exact x2.

    intros.
    destruct x.
    simpl in H.
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    assert (x0 = (Nabla_unit A x1)).
    apply nabla_eq_at.
    simpl.
    apply fun_ext.
    intros.
    apply Prop_ext.
    intros.
    destruct x0.
    simpl in H0, H1.
    destruct e0.
    destruct u.
    pose proof (e0 _ H0).

    pose proof (e0 _ H1).
    induction H2.
    induction H3.
    auto.

    intros.
    destruct x0.
    simpl.
    simpl in H, H0.
    rewrite H1.
    exact H0.
    rewrite <- H1.
    exact H.

    intro.
    destruct x0.
    simpl.
    destruct e0.
    destruct u.
    destruct e.

    destruct H1.
    pose proof (H2 _ H0).
    pose proof (H2 _ H).
    rewrite H3 in H4.
    pose proof (sigma_eqP_pr1 _ _ _ _ _ _ H4).
    apply (lp _ _ (fun l => l x1)) in H5.
    rewrite <- H5.
    auto.
  Defined.

  Definition Nabla_coh3 : forall A x, Nabla_mult A (Nabla_mult (Nabla A) x) = Nabla_mult A (Nabla_fun_map (Nabla (Nabla A)) (Nabla A) (Nabla_mult A) x).
  Proof.
    intros.
    destruct x.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    exists (Nabla_unit _ (Nabla_unit _ x0)).
    split; auto.
    apply sigma_eqP2.
    apply fun_ext.
    intro.
    apply Prop_ext.
    intro.
    rewrite H0; auto.
    intro.
    apply sigma_eqP_pr1 in H0.
    apply (lp _ _ (fun g => g x1)) in H0.
    rewrite <- H0; auto.
    intro.
    destruct H.
    destruct H.
    rewrite H0.
    assert ((Nabla_unit (Nabla A) (Nabla_mult A x1)) = x1).
    apply (proj2   (Nabla_unit_mult_inverse A)).
    rewrite H1; auto.
  Defined.

  Lemma test : forall P : Prop, Nabla P -> P.
  Proof.
    intros.
    destruct X.
    destruct e.
    exact x0.
  Defined.

  Lemma Props_are_modal : forall P : Prop, is_equiv (Nabla_unit P).
  Proof.
    intros.
    exists (test P).
    unfold fc, id; split.
    apply fun_ext.
    intro.
    apply irrl.
    apply fun_ext; intro.
    apply nabla_eq_at.
    simpl.
    destruct x.
    simpl.
    destruct e.
    apply fun_ext; intro.
    apply Prop_ext; intro.

    induction H.
    destruct u; auto.
    destruct u.
    induction (H1 _ H); auto.
  Defined.

  #[global] Instance Nabla_Monad : Monad Nabla := {
    Monad_fun_map := Nabla_fun_map;
    Monad_functorial_comp := Nabla_functorial_comp;
    Monad_functorial_id := Nabla_functorial_id;
    Monad_unit := Nabla_unit;
    Monad_mult := Nabla_mult;
    Monad_unit_ntrans := Nabla_unit_ntrans;
    Monad_mult_ntrans := Nabla_mult_ntrans;
    Monad_coh1 := Nabla_coh1;
    Monad_coh2 := Nabla_coh2;
    Monad_coh3 := Nabla_coh3;
  }.

End NablaMonad.


(** * Tactics: More Basic Tactics *)

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

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

(*Importar o devido do Poly.v para conseguir executar isso aqu*)

Set Warnings "-notation-overridden,-parsing".
(*From LF Require Export Poly.*)

(*Como não é possível importar do Poly, importar o necessário abaixo:*)

(*############## IMPORTS NECESSARIOS ##############*)

Module NatList.
From Coq Require Export String.

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

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

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

Notation "x =? y" := (eqb x y) (at level 70) : nat_scope.
Notation "x <=? y" := (leb x y) (at level 70) : nat_scope.
Notation "x :: y" := (cons x y) (at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y []) ..).
Notation "x ++ y" := (app x y) (at level 60, right associativity).

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

Definition oddb (n:nat) : bool   :=   negb (evenb n). (*para aux na countodd abaixo*)
(*Fim Basics.v*)

(*Inicio Induction.v*)
(*Exercício 2 da aula 13/07: *)
Fixpoint double (n:nat) :=
  match n with
  | O => O
  | S n' => S (S (double n'))
  end.

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

(*Lista 3 - questão 3 - disponível no arq Lista3-Q3-double_plus.v*)
Lemma double_plus : forall n, double n = n + n .
Proof.
  intros n. induction n as [ | n' IHn'].
  - reflexivity.  (* caso 0 = 0 * 0*)
  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. (* 2 * N = N + N*)
Qed.
(*Fim Induction.v*)

(*Inicio Lists.v*)
Definition eqb_id (x1 x2 : id) :=
  match x1, x2 with
  | Id n1, Id n2 => n1 =? n2
  end.
(*Fim Lists.v*)

(*Inicio Poly.v*)
Fixpoint rev {X:Type} (l:list X) : list X :=
  match l with
  | nil      => nil
  | cons h t => app (rev t) (cons h nil)
  end.

Theorem app_nil_r : forall (X:Type), forall l:list X,
  l ++ [] = l.
Proof.
    intros X l. induction l as [ | h t IH]. (*ou induction l.*)
  - reflexivity.
  - simpl. rewrite -> IH. reflexivity.
 Qed.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  intros A l m n. induction l as [ | h t IH]. (*Preciso do tipo A*)
  - reflexivity.
  - simpl. rewrite <- IH. reflexivity.
Qed.

Theorem rev_app_distr: forall X (l1 l2 : list X),
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  intros X l1 l2. induction l1 as [ | h t IH].
  - rewrite -> app_nil_r. simpl. reflexivity.
  - simpl. rewrite IH. rewrite <- app_assoc. reflexivity.
 Qed.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  intros X l. induction l as [ | h t IH].
  - simpl. reflexivity.
  - simpl. rewrite rev_app_distr. rewrite -> IH. reflexivity.
Qed.

Definition app_list_pair {X Y : Type} (listp1 :
  (list X) * (list Y)) (listp2 : (list X) * (list Y)) : (list X) * (list Y) :=
  (app (fst listp1) (fst listp2), app (snd listp1) (snd listp2)).

Fixpoint split {X Y : Type} (l : list (X*Y)) : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (h1, h2) :: t => app_list_pair ([h1], [h2]) (split t)
  end.

(*Fim Poly.v*)

(*############ FIM IMPORTS NECESSÁRIOS #########*)

(* ################################################################# *)
(** * 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.

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

  apply eq2.  Qed. (*Usamos o apply quando temos no contexto uma premissa que é exatamente a conclusão do que quero provar*)

(** 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.

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

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

(** **** Exercise: 2 stars, standard, optional (silly_ex)

    Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     oddb 3 = true ->
     evenb 4 = true.
Proof.
  intros eq1 eq2. apply eq2. Qed. (*eq1 é o forall..., oddb 3 = true é o eq2,*)

(** [] *)

(** 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 = (n =? 5)  ->
     (S (S n)) =? 7 = true.
Proof.
  intros n H.

(** Here we cannot use [apply] directly, but we can use the [symmetry]
    tactic, which switches the left and right sides of an equality in
    the goal. *)

  symmetry. (*Ela invrte o lado da igualdade*)
  simpl. (** (This [simpl] is optional, since [apply] will perform
             simplification first, if needed.) *)
  apply H.  Qed.

(** **** Exercise: 3 stars, standard (apply_exercise1)

    (_Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [Search] 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, standard, optional (apply_rewrite)

    Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied? *)

(* FILL IN HERE

    [] *)

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

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

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

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

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

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

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

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

  apply trans_eq with (m:=[c;d]). (*forçando a fazer m substituir por [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, standard, optional (apply_with_exercise)  *)
(*Fazer esse exercício*)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * The [injection] and [discriminate] Tactics *)

(** Recall the definition of natural numbers:

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

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

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

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

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

(** For example, we can prove the injectivity of [S] by using the
    [pred] function defined in [Basics.v]. *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  assert (H2: n = pred (S n)). { reflexivity. } (*forma rápida para criar uma hipótese e permitir usar ela em abaixo*)
  rewrite H2. rewrite H1. reflexivity.
Qed.

(** This technique can be generalized to any constructor by
    writing the equivalent of [pred] for that constructor -- i.e.,
    writing a function that "undoes" one application of the
    constructor. As a more convenient alternative, Coq provides a
    tactic called [injection] that allows us to exploit the
    injectivity of any constructor.  Here is an alternate proof of the
    above theorem using [injection]: *)

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

(** By writing [injection H] at this point, we are asking Coq to
    generate all equations that it can infer from [H] using the
    injectivity of constructors. Each such equation is added as a
    premise to the goal. In the present example, adds the premise
    [n = m]. *)

  injection H. intros Hnm. apply Hnm.
Qed.

(** Here's a more interesting example that shows how [injection] can
    derive multiple equations at once. *)

Theorem injection_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H. intros H1 H2. (*introduzi que é injetora com o injection. Sem uso do as preciso dar o intros*)
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** The "[as]" variant of [injection] permits us to choose names for
    the introduced equations rather than letting Coq do it. *)

Theorem injection_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n m H.
  injection H as Hnm. rewrite Hnm. (*com o uso do as já faz o injection e o intros*)
  reflexivity. Qed.

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

(** So much for injectivity of constructors.  What about disjointness?

    The principle of disjointness says that two terms beginning with
    different constructors (like [O] and [S], or [true] and [false])
    can never be equal.  This means that, any time we find ourselves
    working in a context where we've _assumed_ that two such terms are
    equal, we are justified in concluding anything we want to (because
    the assumption is nonsensical).

    The [discriminate] tactic embodies this principle: It is used on a
    hypothesis involving an equality between different
    constructors (e.g., [S n = O]), and it solves the current goal
    immediately.  For example: *)

Theorem eqb_0_l : forall n,
   0 =? n = true -> n = 0.
Proof.
  intros n.

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

  destruct n as [| n'] eqn:E. (*desmonta o n nas duas possibilidades: 0 ou sucessor de um n'*)
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming [0
    =? (S n') = true], we must show [S n' = 0]!  The way forward is to
    observe that the assumption itself is nonsensical: *)

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

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

    intros H. discriminate H.
Qed.

(** This is an instance of a logical principle known as the _principle
    of explosion_, which asserts that a contradictory hypothesis
    entails anything, even false things! *)

Theorem discriminate_ex1 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. discriminate contra. Qed. (*princípio da explosão, pois a premissa é falsa assim como a implicação*)
  (*usa o discriminate para isso (provar a contradiução), no caso*)

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

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, if the
    nonsensical situation described by the premise did somehow arise,
    then the nonsensical conclusion would follow.  We'll explore the
    principle of explosion of more detail in the next chapter. *)

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

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

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

(* ################################################################# *)
(** * 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),
     (S n) =? (S m) = b  ->
     n =? m = b.
Proof.
  intros n m b H. simpl in H. apply H.  Qed.

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

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

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

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

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.

    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, standard, recommended (plus_n_n_injective)

    Practice using "in" variants in this proof.  (Hint: use
    [plus_n_Sm].) *)

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

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

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that [double] is injective -- i.e., that it maps
    different arguments to different results:

       Theorem double_injective: forall n m,
         double n = double m -> n = m.

    The way we _start_ this proof is a bit delicate: if we begin with

       intros n. induction n.

    all is well.  But if we begin it with

       intros n m. induction n.

    we get stuck in the middle of the inductive case... *)

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

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

      Abort.

(** What went wrong? *)

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

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

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

    holds, by showing

      - [P O]

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

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

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

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

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

    then we can prove

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

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

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

    then we can prove

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

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

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

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

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

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

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

    intros m eq.

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

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

(** The 0 case is trivial: *)

      discriminate eq.

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

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

      apply IHn'. injection eq as goal. apply goal. Qed.

(** What you should take away from all this is that we need to be
    careful, when using induction, that we are not trying to prove
    something too specific: To prove a property of [n] and [m] by
    induction on [n], it is sometimes important to leave [m]
    generic. *)

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

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

(** **** Exercise: 2 stars, advanced (eqb_true_informal)

    Give a careful informal proof of [eqb_true], being as explicit
    as possible about quantifiers. *)

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_informal_proof : option (nat*string) := None.
(** [] *)

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

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* 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
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

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

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

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

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

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

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

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

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

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

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

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

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

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

(** **** Exercise: 3 stars, standard, recommended (gen_dep_practice)

    Prove this by induction on [l]. *)

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

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

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

Definition square n := n * n.

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

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

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

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

  unfold square.

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

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

(** At this point, some discussion of unfolding and simplification is
    in order.

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

Definition foo (x: nat) := 5.

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

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

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

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

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

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

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

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

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

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

(** A more straightforward way to make progress is to explicitly tell
    Coq to unfold [bar]. *)

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

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

  destruct m eqn:E.
  - reflexivity.
  - reflexivity.
Qed.

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

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

    Here are some examples: *)

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

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

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

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

(** **** Exercise: 3 stars, standard, optional (combine_split)

    Here is an implementation of the [split] function mentioned in
    chapter [Poly]: *)

Fixpoint split {X Y : Type} (l : list (X*Y))
               : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (x, y) :: t =>
      match split t with
      | (lx, ly) => (x :: lx, y :: ly)
      end
  end.

(** Prove that [split] and [combine] are inverses in the following
    sense: *)

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

(** The [eqn:] part of the [destruct] tactic is optional: We've chosen
    to include it most of the time, just for the sake of
    documentation, but many Coq proofs omit it.

    When [destruct]ing compound expressions, however, the information
    recorded by the [eqn:] can actually be critical: if we leave it
    out, then [destruct] can sometimes erase information we need to
    complete a proof.

    For example, suppose we define a function [sillyfun1] like
    this: *)

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

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact that [sillyfun1 n] yields [true] only when [n] is
    odd.  If we start the proof like this (with no [eqn:] on the
    destruct)... *)

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

(** ... then we are stuck at this point because the context does
    not contain enough information to prove the goal!  The problem is
    that the substitution performed by [destruct] is quite brutal --
    in this case, it thows away every occurrence of [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 [n =?
    3 = true] in this branch of the case analysis, it must be that [n
    = 3], from which it follows that [n] is odd.

    What we want here is to substitute away all existing occurences of
    [n =? 3], but at the same time add an equation to the context that
    records which case we are in.  This is precisely what the [eqn:]
    qualifier does. *)

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

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

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

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

    Here are the ones we've seen:

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

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

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

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

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

      - [simpl]: simplify computations in the goal

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

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

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

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

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

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

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

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

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

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

      - [injection]: reason by injectivity on equalities
        between values of inductively defined types

      - [discriminate]: reason by disjointness of constructors on
        equalities between values of inductively defined types

      - [assert (H: e)] (or [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, standard (eqb_sym)  *)
Theorem eqb_sym : forall (n m : nat),
  (n =? m) = (m =? n).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)

    Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [(n =? m) = (m =? n)].

   Proof: *)
   (* FILL IN HERE

    [] *)

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

(** **** Exercise: 3 stars, advanced (split_combine)

    We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

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

Definition split_combine_statement : Prop
  (* ("[: Prop]" means that we are giving a name to a
     logical proposition here.) *)
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

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

(* Do not modify the following line: *)
Definition manual_grade_for_split_combine : option (nat*string) := None.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)

    This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

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

(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)

    Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:

      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

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

      forallb (eqb 5) [] = true

    The second checks whether there exists an element in the list that
    satisfies a given predicate:

      existsb (eqb 5) [0;2;3;6] = false

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

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

      existsb evenb [] = false

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

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

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_forallb_1 : forallb oddb [1;3;5;7;9] = true.
Proof. (* FILL IN HERE *) Admitted.

Example test_forallb_2 : forallb negb [false;false] = true.
Proof. (* FILL IN HERE *) Admitted.

Example test_forallb_3 : forallb evenb [0;2;4;5] = false.
Proof. (* FILL IN HERE *) Admitted.

Example test_forallb_4 : forallb (eqb 5) [] = true.
Proof. (* FILL IN HERE *) Admitted.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.
Proof. (* FILL IN HERE *) Admitted.

Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. (* FILL IN HERE *) Admitted.

Example test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.
Proof. (* FILL IN HERE *) Admitted.

Example test_existsb_4 : existsb evenb [] = false.
Proof. (* FILL IN HERE *) Admitted.

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof. (* FILL IN HERE *) Admitted.

(** [] *)

(* Wed Jan 9 12:02:44 EST 2019 *)


(** Calculation of the simple arithmetic language with exceptions
using explicit empty handler. *)

Require Import List.
Require Import Tactics.
Require Import Coq.Program.Equality.
Module Exception (Import mem : Memory).

(** * Syntax *)

Inductive Expr : Set :=
| Val : nat -> Expr
| Add : Expr -> Expr -> Expr
| Throw : Expr
| Catch : Expr -> Expr -> Expr.

(** * Semantics *)

Fixpoint eval (x: Expr) : option nat :=
  match x with
    | Val n => Some n
    | Add x1 x2 => match eval x1 with
                   | Some m => match eval x2 with
                               | Some n => Some (m + n)
                               | None => None
                               end
                   | None => None
                   end
    | Throw => None
    | Catch x h => match eval x with
                   | Some n => Some n
                   | None => eval h
                   end
  end.

(** * Compiler *)

Inductive Code : Set :=
| HALT : Code
| LOAD : nat -> Code -> Code
| STORE : Reg -> Code -> Code
| ADD : Reg -> Code -> Code
| THROW : Code
| MARK : Reg -> Code -> Code -> Code
| UNMARK : Code -> Code.

Fixpoint comp (x : Expr) (r : Reg) (c : Code) : Code :=
  match x with
  | Val n => LOAD n c
  | Add e1 e2 => comp e1 r (STORE r (comp e2 (next r) (ADD r c)))
  | Throw => THROW
  | Catch e1 e2 => MARK r (comp e2 r c) (comp e1 (next r) (UNMARK c))
  end.

Definition compile (x : Expr) : Code := comp x first HALT.

Definition Han : Set := option (Code * Reg).

Inductive RVal : Set :=
| VAL : nat -> RVal
| HAN : Han -> RVal.

(** * Virtual Machine *)

Inductive Conf' : Type :=
| conf : Code -> nat -> Han -> Conf'
| fail : Han -> Conf'.

Definition Conf : Type := Conf' * Mem RVal.

Notation "⟨ x , y , z , s ⟩" := (conf x y z, s).
Notation "⟪ x , s ⟫" := (fail x, s).

Reserved Notation "x ==> y" (at level 80, no associativity).
Inductive VM : Conf -> Conf -> Prop :=
| vm_load n a c s h : ⟨LOAD n c, a , h, s⟩ ==> ⟨c , n, h, s⟩
| vm_store c s a r h : ⟨STORE r c, a, h, s⟩ ==> ⟨c , a, h, s[r:=VAL a]⟩
| vm_add c s a r n h : s[r]=  VAL n -> ⟨ADD r c, a , h, s⟩ ==> ⟨c , n + a, h, s⟩
| vm_throw a s h : ⟨THROW, a, h, s⟩ ==> ⟪h, s⟫
| vm_mark h r s a c c' : ⟨MARK r c' c, a, h, s⟩ ==> ⟨c, a, Some (c', r), s[r:= HAN h]⟩
| vm_unmark h h' r s a c : s[r] = HAN h' ->
                            ⟨UNMARK c, a, Some (h,r), s⟩ ==> ⟨c, a, h', s⟩
| vm_fail  s c r h : s[r] = HAN h -> ⟪ Some (c,r), s⟫ ==> ⟨c, 0, h, s⟩
where "x ==> y" := (VM x y).

Inductive cle : Conf -> Conf -> Prop :=
 | cle_mem  f s s' : s ⊑ s' -> cle (f, s) (f, s').

Hint Constructors cle : core.

(** * Calculation *)

(** Boilerplate to import calculation tactics *)

Module VM <: Machine.
Definition Conf := Conf.
Definition Pre := cle.
Definition Rel := VM.
Lemma monotone : monotonicity cle VM.
prove_monotonicity. Qed.
Lemma preorder : is_preorder cle.
prove_preorder. Qed.
End VM.

Module VMCalc := Calculation mem VM.
Import VMCalc.

(** Specification of the compiler *)

Theorem spec : forall e r c a h s,
  freeFrom r s ->
  ⟨comp e r c, a, h, s⟩
    =|>
    match eval e with
    | Some n => ⟨c , n, h, s⟩
    | None => ⟪h, s⟫
    end.

(** Setup the induction proof *)

Proof.
  induction e;intros.

(** Calculation of the compiler *)

(** - [x = Val n]: *)

  begin
    match eval (Val n) with
    | Some n' => ⟨c , n' ,h, s⟩
    | None => ⟪h, s⟫
    end.
  = {auto}
      ⟨ c, n, h, s⟩.
  <== {apply vm_load}
      ⟨ LOAD n c, a, h, s ⟩.
  [].

(** - [x = Add x1 x2]: *)

  begin
    match eval (Add e1 e2) with
    | Some n => ⟨c , n ,h, s⟩
    | None => ⟪h, s⟫
    end.
  = { auto }
    match eval e1 with
    | Some n => match eval e2 with
                | Some n' => ⟨c , n + n' ,h, s⟩
                | None => ⟪h, s⟫
                end
    | None => ⟪h, s⟫
    end.
  ⊑ { auto }
    match eval e1 with
    | Some n => match eval e2 with
                | Some n' => ⟨c , n + n' ,h, s[r:=VAL n]⟩
                | None => ⟪h, s[r:=VAL n]⟫
                end
    | None => ⟪h, s⟫
    end.
  <== { apply vm_add }
      match eval e1 with
      | Some n => match eval e2 with
                  | Some n' => ⟨ADD r c , n' ,h, s[r:=VAL n]⟩
                  | None => ⟪h, s[r:=VAL n]⟫
                  end
      | None => ⟪h, s⟫
      end.
  <|= { apply IHe2 }
      match eval e1 with
      | Some n => ⟨comp e2 (next r) (ADD r c) , n ,h, s[r:=VAL n]⟩
      | None => ⟪h, s⟫
      end.
  <== { apply vm_store }
      match eval e1 with
      | Some n => ⟨STORE r (comp e2 (next r) (ADD r c)) , n ,h, s⟩
      | None => ⟪h, s⟫
      end.
  <|= { apply IHe1 }
    ⟨comp e1 r (STORE r (comp e2 (next r) (ADD r c))), a,h, s⟩.
  [].

(** - [x = Throw]: *)

  begin
    match eval Throw with
    | Some n => ⟨c , n ,h, s⟩
    | None => ⟪h, s⟫
    end.
  = { auto }
      ⟪h, s⟫.
  <== { apply vm_throw }
      ⟨THROW, a, h, s⟩.
  [].

(** - [x = Catch x1 x2]: *)

  begin
    match eval (Catch e1 e2) with
    | Some n => ⟨c , n ,h, s⟩
    | None => ⟪h, s⟫
    end.
  = { auto }
      match eval e1 with
      | Some n => ⟨c , n ,h, s⟩
      | None => match eval e2 with
                | Some n' => ⟨c , n' ,h, s⟩
                | None => ⟪h, s⟫
                end
      end.
  <|= { apply IHe2 }
      match eval e1 with
      | Some n => ⟨c , n ,h, s⟩
      | None => ⟨comp e2 r c, 0 ,h, s⟩
      end.
  ⊑ { eauto }
      match eval e1 with
      | Some n => ⟨c , n ,h, s⟩
      | None => ⟨comp e2  r c , 0 ,h, s[r:= HAN h]⟩
      end.
  <== {apply vm_fail}
      match eval e1 with
      | Some n => ⟨c, n, h, s⟩
      | None => ⟪Some (comp e2 r c,r), s[r:= HAN h]⟫
      end.
  ⊑ {auto}
      match eval e1 with
      | Some n => ⟨c, n, h, s[r:= HAN h]⟩
      | None => ⟪Some (comp e2 r c,r), s[r:= HAN h]⟫
      end.
  <== {eapply vm_unmark}
      match eval e1 with
      | Some n => ⟨UNMARK c, n, Some (comp e2 r c,r), s[r:= HAN h]⟩
      | None => ⟪Some (comp e2 r c,r), s[r:= HAN h]⟫
      end.
  <|= {apply IHe1}
      ⟨comp e1 (next r) (UNMARK c) , a ,Some (comp e2 r c,r), s[r:= HAN h]⟩.
  <== {apply vm_mark}
      ⟨MARK r (comp e2  r c) (comp e1 (next r) (UNMARK c)) , a ,h, s⟩.
  [].
Qed.

Definition empty := (@empty RVal).

(** Specification of the whole compiler *)

Theorem spec' e a h : ⟨compile e, a, h, empty⟩  =|> match eval e with
                                                      | Some n => ⟨HALT, n, h, empty⟩
                                                      | None => ⟪h, empty⟫
                                                    end.
Proof.
  begin
    match eval e with
    | Some n => ⟨HALT, n, h, empty⟩
    | None => ⟪h, empty⟫
    end.
  <|= {apply spec; apply empty_mem_free}
      ⟨comp e first HALT, a,h, empty⟩.
  [].
Qed.

(** * Soundness *)

(** Since the VM is defined as a small step operational semantics, we *)
(* have to prove that the VM is deterministic and does not get stuck in *)
(* order to derive soundness from the above theorem. *)

Lemma determ_vm : determ VM.
  intros C C1 C2 V. induction V; intro V'; inversion V'; subst;eauto.
  rewrite H in *; dist. rewrite H in H6. dist. rewrite H in H4. dist.
Qed.

Theorem sound x a C :
  ⟨compile x, a, None, empty⟩ =>>! C ->
  ((exists m n, C = ⟨HALT, n, None, m⟩ /\ eval x = Some n) \/ (exists m, C = ⟪None , m⟫ /\ eval x = None)).
Proof.
  intros E.
  pose (spec' x a None). unfold Reach in *. repeat autodestruct.
  pose (determ_trc determ_vm) as D.
  unfold determ in D. inversion H0. subst.
  remember (eval x) as X.
  destruct X.
  - left. inversion H0. subst. inversion H1. subst. eexists. eexists.
    split. eapply D. eapply E. split. apply H. intro Contra. destruct Contra.
    inversion H3. reflexivity.
  - right. inversion H0. subst. inversion H1. subst. eexists.
    split. eapply D. eapply E. split. apply H. intro Contra. destruct Contra.
    inversion H3. reflexivity.
Qed.

End Exception.


(** Formalization of Theorem 3.3 in

   Thierry Coquand, Giovanni Sambin, Jan Smith, Silvio Valentini

   Inductively generated formal topologies

   #http://doai.io/10.1016/S0168-0072(03)00052-6#

   Adapted to distributive lattices. See
   the [FreeFrame] module for more insightful comments
   (this is the same proof, just for finite formal joins
    instead of countable ones). I have some ideas about
   how to refactor the two in the same proof: define the free
   kappa-frame generated by a meet semilattice with axioms,
   where kappa is the appropriate constructive cardinal-like
   object…

 *)

Require Import MathClasses.interfaces.canonical_names.
Require Import BijNat.
Require Import Frame.
Require Import MeetSemiLattice.
Require Import PreorderEquiv.
Require Import DistrLattice.
Require Import Coq.Classes.RelationClasses.
Require Import Coq.Lists.List.
Require Import Coq.Lists.SetoidList.
Require Import EquivlistMap.

Section Definition_Inductive_Locale.

  (** * Definition of the free distributive lattice *)

  (** Generators. *)
  Variable T : Type.
  Variable Tle : Le T.
  Variable Tmsl : @MeetSemiLattice T Tle.
  Existing Instance Tmsl.
  Existing Instance Feq_equiv.
  Existing Instance Feq_equivalence.

  (** For each generator, an index set for its coverings. *)
  Variable Idx : forall t:T, Set.
  (** For each generator and index of covering, an covering. *)
  Variable CovAx : forall t:T, forall i:Idx t, list T.

  (** ** Preliminaries on finite sets with lists *)

  Notation "( a ⊓)" := (fun el => a ⊓ el).

  Definition down (a : T) (U : list T) : list T :=
    map (a ⊓) U.

  Infix "↓" := down (at level 50).

  Infix "↪" := (inclA Feq) (at level 75).
  Instance in_contains : Contains T (list T) := (InA Feq).

  Lemma inclA_app_l : forall u v, u ↪ u ++ v.
  Proof.
    unfold inclA ; intros.
    rewrite InA_app_iff.
    left. assumption.
  Qed.

  Lemma inclA_app_r : forall u v, v ↪ u ++ v.
  Proof.
    unfold inclA ; intros.
    rewrite InA_app_iff.
    right. assumption.
  Qed.

  Instance FeqT_equivalence : Equivalence (Feq : T -> T -> Prop).
  Proof.
    apply (Feq_equivalence msl_preorder).
  Qed.

  Instance InA_Feq_compat : Proper (Feq ==> equivlistA Feq ==> iff) (InA (Feq : Equiv T)) := (InA_compat FeqT_equivalence).

  Definition equiv_listT : list T -> list T -> Prop := equivlistA Feq.
  Add Setoid (list T) equiv_listT (equivlist_equiv FeqT_equivalence) as equiv_listT_setoid.
  Infix "==" := equiv_listT (at level 75).

  (** ** Inductive cover relation
   Here, we need an additional axiom to equate [[]] and
   [[⊥]].
   *)

  Inductive covrel (a : T) : (list T) -> Prop :=
  | cr_bot : forall U, a = ⊥ -> covrel a U
  | cr_refl : forall U, a ∈ U -> covrel a U
  | cr_inf : forall U b, forall i:Idx b, a ≤ b -> (forall x, x ∈ (CovAx b i) -> covrel (a ⊓ x) U) -> covrel a U
  | cr_left : forall U b, a ≤ b -> covrel b U -> covrel a U.
  Infix "◁" := (covrel) (at level 60).

  Lemma covrel_Teq : forall x: T, forall U, (x ◁ U) -> forall y :T,  x = y -> y ◁ U.
  Proof.
    intros.
    destruct H0.
    apply cr_left with (b := x) ; assumption.
  Qed.

  Lemma covrel_proper : Proper ((=) ==> eq ==> iff) covrel.
  Proof.
    unfold Proper, respectful.
    intros.
    split ; intro.

    rewrite <- H0.
    apply (covrel_Teq x x0 H1 y H).

    rewrite H0.
    apply (covrel_Teq y y0 H1 x).
    symmetry. apply H.
  Qed.
  Add Parametric Morphism : covrel with signature ((=) ==> eq ==> iff) as covrel_morphism.
  Proof.
    intros. apply covrel_proper. apply H. reflexivity.
  Qed.

  (** ** Preorder and equivalence between coverings *)

  Definition Covrel (U V : list T) :=
    forall x, x ∈ U -> x ◁ V.
  Instance Covrel_le : Le (list T) := Covrel.
  Ltac unfold_Covrel := unfold le, Covrel_le, Covrel.
  Ltac unfold_Covrel_in a := unfold le, Covrel_le, Covrel in a.

  Lemma cr_trans : forall (a : T) (U W : list T), a ◁ U -> U ≤ W -> a ◁ W.
  Proof.
    intros a U W CR.
    generalize W ; clear W.
    induction CR ; intros.
    - (* cr_bot *)
      destruct W.
      apply cr_bot ; assumption.
      apply cr_left with (b := t).
      rewrite H. apply bot_le.
      apply cr_refl. apply InA_cons_hd. reflexivity.
    - (* cr_refl *)
      unfold_Covrel_in H0.
      apply H0. assumption.
    - (* cr_inf *)
      apply (cr_inf a W b i H).
      intros. apply H1 ; assumption.
    - (* cr_left *)
      apply cr_left with (b := b).
      assumption.
      apply IHCR ; apply H0.
  Qed.

  Lemma Covrel_refl : Reflexive Covrel.
  Proof.
    unfold Reflexive.
    intros.
    unfold Covrel.
    intros. apply cr_refl.
    assumption.
  Qed.

  Lemma Covrel_trans : Transitive Covrel.
  Proof.
    unfold Transitive, Covrel.
    intros.
    apply cr_trans with (U := y).
    apply H. assumption.
    assumption.
  Qed.

  Definition PO_for_FDistrLattice : @Preorder (list T) Covrel :=
    MkPreorder
      (list T)
      Covrel
      Covrel_refl
      Covrel_trans.
  Existing Instance PO_for_FDistrLattice.

  Add Morphism covrel : covrel_morphism2.
  Proof.
    intros x y Heq U W H.
    destruct H as [Hl Hr].
    split ; intro.
    apply cr_left with (b := x).
    rewrite Heq ; apply le_refl.
    apply cr_trans with (U := U) ; auto.

    apply cr_left with (b := y).
    rewrite Heq ; apply le_refl.
    apply cr_trans with (U := W) ; auto.
  Qed.

  Lemma cov_inj_Covrel : forall U W, U ↪ W -> U ≤ W.
  Proof.
    intros.
    unfold le, Covrel_le, Covrel ; intros.
    unfold inclA in H.
    apply cr_refl. apply H. assumption.
  Qed.

  Ltac by_cov_inj :=
    try (apply cov_inj_Covrel) ;
    unfold inclA ;
    intro.

  Lemma covbij_coveq : forall U W : (list T), U == W -> U = W.
  Proof.
    intros.
    unfold equivlistA in H.
    split ; by_cov_inj ; intro ; apply H ; assumption.
  Qed.

  Lemma cr_right : forall a U W, a ◁ U -> U ↪ W -> a ◁ W.
  Proof.
    intros.
    apply cr_trans with (U := U).
    apply H.
    apply cov_inj_Covrel.
    apply H0.
  Qed.

  (** ** Binary join *)

  Instance CJoin : Join (list T) := (@app T).
  Ltac unfold_CJoin := unfold join, CJoin.

  Proposition CJoin_l : forall U V, U ≤ U ⊔ V.
  Proof.
    intros.
    by_cov_inj.
    unfold_CJoin.
    intros.
    rewrite InA_app_iff. left. assumption.
  Qed.

  Proposition CJoin_r : forall U V, V ≤ U ⊔ V.
  Proof.
    intros.
    by_cov_inj. unfold_CJoin. intros.
    rewrite InA_app_iff. right. assumption.
  Qed.

  Proposition CJoin_univ : forall U V W, U ≤ W -> V ≤ W ->
                                    U ⊔ V ≤ W.
  Proof.
    intros.
    unfold_CJoin. unfold_Covrel. intros.
    setoid_rewrite InA_app_iff in H1.
    destruct H1.
    apply H. assumption.
    apply H0. assumption.
  Qed.

  Add Morphism CJoin with signature (equiv_listT ==> equiv_listT ==> equiv_listT) as app_morphism.
  Proof.
    unfold equiv_listT, equivlistA. intros.
    unfold_CJoin. split ; intro ;
    setoid_rewrite InA_app_iff in H1 ;
    setoid_rewrite InA_app_iff.
    rewrite <- H, <- H0.
    assumption.
    rewrite H, H0.
    assumption.
  Qed.

  Lemma CJoin_comm : forall U V : list T, U ++ V == V ++ U.
  Proof.
    intros.
    unfold equivlistA. intros. split ; intros ; (
    setoid_rewrite InA_app_iff in H ;
    setoid_rewrite InA_app_iff ;
    destruct H ;
    [ right ; assumption |
      left ; assumption ]).
  Qed.

  (** We will get this fact for free from the
      distributive lattice structure we will define,
      but we need it before in the definition of the
      meet, so we prove it again here. *)

  Lemma CJoin_le_proper : Proper ((≤) ==> (≤) ==> (≤)) CJoin.
  Proof.
    unfold Proper, respectful.
    unfold_CJoin. intros.
    unfold_Covrel. intros.
    setoid_rewrite InA_app_iff in H1.
    destruct H1.
    - apply cr_right with (U := y).
      apply H. assumption.
      apply inclA_app_l.
    - apply cr_right with (U := y0).
      apply H0. assumption.
      apply inclA_app_r.
  Qed.

  (** Our temporary version of the finite joins: *)

  Definition Vl : list (list T) -> list T := @concat T.

  Lemma Vl_cons : forall u a, Vl (a :: u) = a ⊔ Vl u.
  Proof.
    intros. unfold_CJoin. unfold Vl.
    rewrite concat_cons.
    reflexivity.
  Qed.

  (** ** Binary meet *)

  Proposition cr_loc : forall a b U, a ◁ U -> b ⊓ a ◁ b ↓ U.
  Proof.
    intros a b U HR.
    induction HR as [a | a | a | a].

    - (* cr_bot *)
      rewrite H.
      meetsemilattice.
      simpl.
      apply cr_bot.
      reflexivity.

    - (* cr_refl *)
      apply cr_refl.
      unfold down ; simpl.
      apply map_in with (Qeq := (=)).
      unfold Proper, respectful. intros. rewrite H0. reflexivity.
      assumption.

    - (* cr_inf *)
      apply cr_inf with (b := b0) (i := i).
      apply le_trans with (y := a).
      apply meet_r. assumption.
      intros.
      rewrite <- meet_assoc.
      apply H1. assumption.

    - (* cr_left *)
      apply cr_left with (b := b ⊓ b0).
      apply meet_le_r ; assumption.
      apply IHHR.
  Qed.

  Definition list_prod {A : Type} (f : T -> T -> A) (u v : list T) :=
    fold_left (fun accu x => accu ++ (map (f x) v)) u [].

  Lemma fold_left_concat : forall {A} (f : T -> T -> A) u v ac,
                             fold_left (fun accu x => accu ++ (map (f x) v)) u ac ≡ ac ++ (list_prod f u v).
  Proof.
    intros.
    generalize ac.
    induction u ; intros ; simpl.
    - rewrite app_nil_r. reflexivity.
    - unfold list_prod. simpl.
      rewrite IHu. rewrite IHu.
      rewrite app_assoc.
      reflexivity.
  Qed.

  Lemma list_prod_univ f : forall U V x, x ∈ (list_prod f U V) -> exists a b, a ∈ U /\ b ∈ V /\ x = f a b.
  Proof.
    intros.
    induction U ; simpl in H. inversion H.
    unfold list_prod in H. simpl in H.
    rewrite fold_left_concat in H.
    apply InA_app in H.
    destruct H.
    - apply in_map with (Qeq := Feq) in H.
      destruct H as [y [H G]].
      exists a. exists y. split.
      + apply InA_cons_hd. reflexivity.
      + split ; assumption.
      + exact FeqT_equivalence.
    - apply IHU in H.
      destruct H as (c & d & G & K & L).
      exists c. exists d. split.
      + apply InA_cons_tl. assumption.
      + split ; assumption.
  Qed.

  Lemma list_prod_inj f : Proper (Feq ==> Feq ==> Feq) f -> forall U V a b, a ∈ U -> b ∈ V -> (f a b) ∈ list_prod f U V.
  Proof.
    intros P U V a b H.
    generalize V. clear V.
    induction H ; intros V H' ;
    ( unfold list_prod ; simpl ;
      rewrite fold_left_concat ;
      setoid_rewrite InA_app_iff).
    - left.
      (* Quite tedious rewriting, I might be missing
         an instance somewhere, but where? *)
      assert (f a b = f y b).
      apply P. assumption. reflexivity.
      set (Q := InA_Feq_compat).
      unfold Proper, respectful in Q.
      assert (equivlistA Feq (map (f y) V) (map (f y) V)) as K by reflexivity.
      specialize (Q (f a b) (f y b) H0 (map (f y) V) (map (f y) V) K).
      destruct Q.
      apply H2.
      apply map_in with (Qeq := (=)).
      apply P. reflexivity. assumption.
    - right.
      apply IHInA. assumption.
  Qed.

  Definition CMeet (U W : list T) : list T :=
    list_prod (⊓) U W.

  Instance CMeet_meet : Meet (list T) | 50 := CMeet.
  Ltac unfold_CMeet := unfold meet, CMeet_meet, CMeet.

  Proposition CMeet_l : forall U V : list T, U ⊓ V ≤ U.
  Proof.
    intros.
    unfold_CMeet.
    unfold_Covrel. intros.
    apply list_prod_univ in H.
    destruct H as (a & b & G & K & H).
    rewrite H.
    apply cr_left with (b := a).
    apply meet_l.
    apply cr_refl. assumption.
  Qed.

  Proposition CMeet_r : forall U V : list T, U ⊓ V ≤ V.
  Proof.
    intros.
    unfold_CMeet.
    unfold_Covrel. intros.
    apply list_prod_univ in H.
    destruct H as (a & b & G & K & H).
    rewrite H.
    apply cr_left with (b := b).
    apply meet_r.
    apply cr_refl. assumption.
  Qed.

  Lemma other_Covrel : forall U V : list T, U ≤ V <-> (forall x, x ◁ U -> x ◁ V).
  Proof.
    intros.
    split ; intros.
    - apply cr_trans with (U := U) ; assumption.
    - unfold_Covrel. intros.
      apply H. apply cr_refl. assumption.
  Qed.

  Lemma meet_elem_cov : forall U V x, x ∈ U -> map (x ⊓) V ↪ U ⊓ V.
  Proof.
    intros.
    induction H ; (
    unfold_CMeet ;
      unfold list_prod ; simpl ;
      rewrite fold_left_concat ;
      unfold inclA ; intros ;
      rewrite InA_app_iff).
    - left.
      assert (eqlistA Feq (map (x ⊓) V) (map (y ⊓) V)).
      clear H0.
      induction V. reflexivity.
      simpl. apply eqlistA_cons.
      rewrite H. reflexivity.
      apply IHV.
      rewrite <- H1.
      assumption.
    - right.
      apply IHInA. assumption.
  Qed.

  Lemma meet_covrel : forall x y U, y ◁ U -> x ⊓ y ◁ map (x ⊓) U.
  Proof.
    intros.
    induction H.
    - rewrite H. meetsemilattice.
      simpl.
      apply cr_bot. reflexivity.
    - apply cr_refl. apply map_in with (Qeq := (=)).
      apply meet_morphism_Proper. reflexivity.
      assumption.
    - apply cr_inf with (b := b) (i := i).
      apply le_trans with (y := a).
      apply meet_r. assumption.
      intros. rewrite <- meet_assoc.
      apply H1. assumption.
    - apply cr_left with (b := x ⊓ b).
      apply meet_le_r. assumption.
      assumption.
  Qed.

  Lemma CMeet_univ_internal : forall U V : list T, forall x y,
                                x ◁ U ->
                                y ◁ V ->
                                x ⊓ y ◁ U ⊓ V.
  Proof.
    intros.
    induction H.
    - rewrite H. meetsemilattice.
      apply cr_bot. reflexivity.
    - apply meet_elem_cov with (V := V) in H.
      apply cov_inj_Covrel in H.
      apply cr_trans with (U := map (a ⊓) V).
      apply meet_covrel. assumption.
      assumption.
    - apply cr_inf with (b := b) (i := i).
      apply le_trans with (y0 := a).
      apply meet_l. assumption.
      intros.
      rewrite <- meet_assoc.
      assert (y ⊓ x = x ⊓ y) by (apply meet_comm).
      rewrite H4.
      rewrite meet_assoc.
      apply H2. assumption.
    - apply cr_left with (b := b ⊓ y).
      apply meet_le_l. assumption.
      assumption.
  Qed.

  Proposition CMeet_univ : forall U V W : list T, W ≤ U -> W ≤ V -> W ≤ U ⊓ V.
  Proof.
    setoid_rewrite other_Covrel.
    intros.
    apply H0 in H1 as K.
    apply H in H1 as G.
    assert (x = x ⊓ x) by (rewrite meet_idem ; reflexivity).
    rewrite H2.
    apply CMeet_univ_internal ; assumption.
  Qed.

  (** ** Top and bottom *)

  Instance BotListT : Bottom (list T) := [].

  Lemma Bot_le : forall U, ⊥ ≤ U.
  Proof.
    intro.
    unfold_Covrel. intros.
    inversion H.
  Qed.

  Instance TopListT : Top (list T) := [ ⊤ ].
  Lemma Top_le : forall U : list T, U ≤ ⊤.
  Proof.
    intro.
    unfold_Covrel.
    intros.
    apply cr_left with (b := ⊤).
    apply top_le.
    apply cr_refl.
    apply InA_cons_hd.
    reflexivity.
  Qed.

  Instance MSL_for_FDistrLat : MeetSemiLattice Covrel :=
    MkMSL
      (list T)
      Covrel
      PO_for_FDistrLattice
      TopListT
      Top_le
      BotListT
      Bot_le
      CMeet
      CMeet_l
      CMeet_r
      CMeet_univ.

  (** ** Distributivity of binary meets over joins *)

  Lemma Cdistr_l : forall a b c, a ⊓ (b ⊔ c) ≤ (a ⊓ b) ⊔ (a ⊓ c).
  Proof.
    intros.
    (*assert (a ⊓ (b ⊔ c) = (b ⊔ c) ⊓ a) by (apply meet_comm).
    rewrite H. *)
    unfold meet, msl_meet, MSL_for_FDistrLat.
    unfold_CMeet.
    induction a ; unfold list_prod ; simpl.
    - simpl.
      apply Bot_le.
    - repeat (progress (rewrite fold_left_concat)).
      unfold join, CJoin.
      rewrite app_assoc.
      assert (forall w x y z : list T, (((w ++ x) ++ y) ++ z) = ((w ++ y) ++ (x ++ z))).
      + intros.
        apply covbij_coveq.
        assert ((w ++ x) ++ y == y ++ (w ++ x)) by (apply CJoin_comm).
        rewrite H.
        rewrite app_assoc. rewrite app_assoc.
        assert ((y ++ w) == (w ++ y)) by (apply CJoin_comm).
        rewrite H0.
        reflexivity.
      + rewrite H.
        apply CJoin_le_proper.
        * rewrite map_app.
          apply le_refl.
        * assumption.
  Qed.

  Instance FDistrLat : @DistrLattice (list T) Covrel :=
    MkDistrLattice
      (list T)
      Covrel
      MSL_for_FDistrLat
      CJoin
      CJoin_l
      CJoin_r
      CJoin_univ
      Cdistr_l.

  Definition LFeq := @Feq (list T) Covrel.
  Definition LFeq_setoid := Feq_equivalence PO_for_FDistrLattice.

  (** * Properties of the free distributive lattice *)

  (** ** Injection of generators *)

  Definition inj_gen (t : T) : (list T) := [t].

  Instance inj_gen_mslmorph : MSLMorphism Tmsl MSL_for_FDistrLat inj_gen.
  Proof.
    apply MkMSLMorphism ; unfold inj_gen.
    - apply MkPOMorphism.
      intros.
      unfold le, Covrel. intros.
      inversion H0.
      apply cr_left with (b := y).
      rewrite H2. assumption.
      apply cr_refl. apply InA_cons_hd. reflexivity.
      inversion H2.
    - intros.
      reflexivity.
    - split ; unfold_Covrel ; intros.
      + inversion H.
        rewrite H1.
        apply cr_bot. reflexivity.
        inversion H1.
      + inversion H.
    - reflexivity.
  Qed.

  Lemma Vf_inj_gen : forall u : list T, Vf (map inj_gen u) = u.
  Proof.
    intro.
    induction u.
    - reflexivity.
    - simpl.
      rewrite Vf_cons.
      rewrite IHu.
      reflexivity.
  Qed.

  Lemma inj_gen_le : forall t u, inj_gen t ≤ u <-> t ◁ u.
  Proof.
    intros.
    unfold inj_gen.
    unfold_Covrel.
    split ; intros.
    apply (H t).
    apply InA_cons_hd. reflexivity.
    inversion H0. subst.
    rewrite H2. assumption.
    inversion H2.
  Qed.

  Lemma inj_gen_meet : forall t u, inj_gen t ⊓ u = map (t ⊓) u.
  Proof.
    intros.
    reflexivity.
  Qed.

  (** ** Equalities generated by the axioms *)

  Proposition CovAx_meet_gen :
    forall (b:T), forall (i : Idx b), inj_gen b = (inj_gen b) ⊓ (CovAx b i).
  Proof.
    intros.
    rewrite inj_gen_meet.
    split.
    - rewrite inj_gen_le.
      apply cr_inf with (b := b) (i := i).
      apply le_refl.
      intros.
      apply cr_refl.
      apply map_in with (Qeq := (=)).
      + unfold Proper, respectful. intros.
        rewrite H0. reflexivity.
      + assumption.
    - rewrite <- inj_gen_meet.
      apply meet_l.
  Qed.

  Proposition CovAx_le_eq :
    forall (b:T), forall (i : Idx b), CovAx b i ≤ inj_gen b -> inj_gen b = CovAx b i.
  Proof.
    intros.
    split.
    - rewrite CovAx_meet_gen with (i := i).
      apply meet_r.
    - assumption.
  Qed.

  (** ** Universality *)

  (** Let us assume that we have a meet semilattice
     morphism to an arbitrary distributive lattice [R]. *)
  Context {R : Type}.
  Context {Rle : Le R}.
  Variable RDistrLat : @DistrLattice R Rle.

  Definition Rmsl := @dl_msl R Rle RDistrLat.
  Definition Rpo := @msl_preorder R Rle Rmsl.
  Instance FeqR_equivalence : Equivalence Feq := (Feq_equivalence Rpo).
  Existing Instance FeqT_equivalence.
  Variable f : T -> R.
  Variable mslmorph : MSLMorphism Tmsl Rmsl f.
  Existing Instance mslmorph.

  (** We assume that the morphism respects the axioms
      we have used to generate our free DL. *)
  Definition respects_axioms : Prop :=
    forall t : T, forall i : Idx t, f t ≤ Vf (map f (CovAx t i)).
  Variable resp_ax : respects_axioms.

  (** We define a function from our free DL to R. *)
  Definition fdl_ext (x : list T) : R :=
    Vf (map f x).

  (* We show that this function is a DL morphism. *)
  Existing Instance Covrel_le.

  Lemma eqlist_map_map : forall a l,
                           eqlistA Feq (map (fun x => f (a ⊓ x)) l)
                                   (map (meet (f a)) (map f l)).
  Proof.
    intros.
    induction l.
    + simpl.
      apply eqlistA_nil.
    + apply eqlistA_cons.
      apply mslmorph.
      apply IHl.
  Qed.

  Lemma f_proper : Proper ((=) ==> (=)) f.
  Proof.
    intros.
    apply pomorphism_proper.
    apply (mslmorph_pomorph Tmsl Rmsl).
  Qed.

Lemma dl_covrel : forall a U, a ◁ U -> f a ≤ Vf (map f U).
  Proof.
    intros.
    induction H.
    - rewrite H.
      rewrite mslmorph_bot.
      apply @bot_le.
      exact mslmorph.
    - apply Vf_in_le.
      apply map_in with (Qeq := (=)).
      apply f_proper.
      assumption.
    - unfold respects_axioms in resp_ax.
      specialize (resp_ax b i).
      set (K := Vf (map (fun x => f (a ⊓ x)) (CovAx b i))).
      apply le_trans with (y := K).
      + assert (K = f a ⊓ Vf (map f (CovAx b i))).
        rewrite Vf_meet.
        unfold K.
        apply Vf_proper.
        apply eqlistA_equivlistA.
        apply (Feq_equivalence msl_preorder).
        apply eqlist_map_map.
        rewrite H2.
        rewrite order_then_meet.
        apply le_refl.
        apply le_trans with (y := f b).
        apply pomorph_le.
        assumption.
        assumption.
      + unfold K.
        apply Vf_univ.
        intros.
        apply in_map with (Qeq := Feq) in H2.
        destruct H2.
        destruct H2.
        rewrite H3.
        apply H1.
        assumption.
        exact FeqT_equivalence.
    - apply le_trans with (y := f b).
      apply pomorph_le ; assumption.
      assumption.
  Qed.

  Lemma fdl_pomorph : POMorphism fdl_ext.
  Proof.
    apply MkPOMorphism.
    intros.
    apply Vf_univ ; intros.
    apply in_map with (Qeq := Feq) in H0.
    destruct H0 ; destruct H0.
    unfold le, Covrel in H.
    specialize (H x1).
    rewrite H1.
    apply dl_covrel.
    apply (H H0).
    exact FeqT_equivalence.
  Qed.

  Instance fdl_mor : DLMorphism FDistrLat RDistrLat fdl_ext.
  Proof.
    apply MkDLMorphism.
    - apply MkMSLMorphism.
      + apply fdl_pomorph.
      + intros.
        split.
        * apply meet_univ ;
          apply fdl_pomorph.
          apply meet_l.
          apply meet_r.
        * unfold fdl_ext.
          induction x ; simpl.
          rewrite Vf_nil.
          meetsemilattice.
          apply le_refl.
          rewrite Vf_cons.
          rewrite meet_comm.
          rewrite bdistr_eq.
          rewrite meet_comm in IHx.
          unfold meet, msl_meet, CMeet, list_prod.
          simpl.
          rewrite fold_left_concat.
          rewrite map_app.
          rewrite Vf_app.
          apply join_le.
          rewrite map_map.
          set (K := Vf (map (fun x : T => f (a ⊓ x)) y)).
          assert ((f a) ⊓ (Vf (map f y)) = K).
          rewrite Vf_meet.
          unfold K.
          apply Vf_proper.
          symmetry.
          apply eqlistA_equivlistA.
          exact FeqR_equivalence.
          apply eqlist_map_map.
          rewrite <- H.
          rewrite meet_comm.
          apply le_refl.
          apply IHx.
      + unfold fdl_ext. simpl.
        apply Vf_nil.
      + unfold fdl_ext, Vf ; simpl.
        rewrite mslmorph_top.
        rewrite join_bot_l.
        reflexivity.
        assumption.
    - intros.
      unfold fdl_ext.
      rewrite <- Vf_app.
      rewrite <- map_app.
      reflexivity.
  Qed.

  Definition fdl_mslmorph := dlmorph_mslmorph FDistrLat RDistrLat fdl_ext.
  Proposition fdl_factoring : fdl_ext ∘ inj_gen = f.
  Proof.
    unfold equiv, ext_equiv, respectful.
    intros.
    unfold inj_gen, fdl_ext, compose.
    unfold Vf. simpl.
    rewrite join_bot_l.
    apply f_proper.
    assumption.
  Qed.

  Arguments fdl_factoring : default implicits.

  (* Now the uniqueness part of the universality:
     if we have another such frame morphism,
     then it is equal to fdl_ext *)

  Variable other_fact : (list T) -> R.
  Variable other_morph : DLMorphism FDistrLat RDistrLat other_fact.
  Existing Instance other_morph.
  Instance other_mslmorph : MSLMorphism MSL_for_FDistrLat Rmsl other_fact := dlmorph_mslmorph FDistrLat RDistrLat other_fact.
  Instance other_morph_po : POMorphism other_fact.
  Proof.
    apply (mslmorph_pomorph MSL_for_FDistrLat Rmsl).
  Qed.

  Variable other_commutes : other_fact ∘ inj_gen = f.

  Existing Instance Covrel_le.
  (*  Instance coveq_R : Equiv (nat -> R) := @ext_equiv nat (≡) R (=).*)

  Proposition other_fact_equal : forall u, other_fact u = fdl_ext u.
  Proof.
    intro.
    assert (other_fact u = other_fact (Vf (map inj_gen u))).
    rewrite Vf_inj_gen ; reflexivity.
    rewrite H.
    rewrite morph_Vf.
    rewrite map_map.
    unfold compose in other_commutes.
    assert (pointwise_relation T Feq (fun x => other_fact (inj_gen x)) f).
    unfold pointwise_relation ; intro.
    apply other_commutes.
    reflexivity.
    rewrite H0.
    unfold fdl_ext.
    reflexivity.
    assumption.
  Qed.

End Definition_Inductive_Locale.