From discprob.basic Require Import base sval order monad bigop_ext nify seq_ext.
Require Import Reals Psatz Omega.

Require ClassicalEpsilon.
From mathcomp Require Import ssrfun ssreflect eqtype ssrbool seq fintype choice.
Global Set Bullet Behavior "Strict Subproofs".
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype seq div choice fintype finset finfun bigop.
Require Import stdpp.tactics.

Local Open Scope R_scope.
From discprob.idxval Require Import ival pival ival_dist pival_dist pidist_singleton extrema pidist_post_cond.
From discprob.prob Require Import prob countable finite stochastic_order.

Import Lub.

Local Set Printing Coercions.

Lemma general_markov_inequality {X} (f: X → R) (Is: pidist X) (h: R → R) (a: R)
      (Hmono: ∀ x y, x <= y → h x <= h y) (Hpos: ∀ x, 0 <= x → 0 <= h x)
      (Hapos: 0 <= a) (Hhapos: 0 < h a):
  is_finite (Ex_max (λ x, h (Rabs (f x))) Is) →
  ex_Ex_extrema (λ x, h (Rabs (f x))) Is →
  Rbar_le (Pr_max (λ x, f x > a) Is)
          (Rbar_mult (/(h a)) (Ex_max (λ x, h (Rabs (f x))) Is)).
Proof.
  intros Hfin Hex.
  rewrite -Ex_max_scale_const; last first.
  { apply Rle_ge; left. apply Rinv_0_lt_compat; auto. }
  apply Ex_max_le_ext.
  - intros x.  destruct (ClassicalEpsilon.excluded_middle_informative _) => //=.
    * cut (h a <= h (Rabs (f x))).
      { intros. apply (Rmult_le_reg_l (h a)); try nra.
        field_simplify; nra. }
      apply Hmono. transitivity (f x); first nra.
      apply Rle_abs.
    * apply Rmult_le_pos; try nra.
      { left. apply Rinv_0_lt_compat; auto. }
      apply Hpos; auto with *.
  - apply ex_Ex_extrema_scale_const_l; auto.
Qed.

Lemma markov_inequality {X} (f: X → R) (Is: pidist X) (a: R):
  a > 0 →
  is_finite (Ex_max f Is) →
  ex_Ex_extrema f Is →
  pspec Is (λ x, f x >= 0) →
  Rbar_le (Pr_max (λ x, f x > a) Is)
          (Rbar_mult (/a) (Ex_max (λ x, f x) Is)).
Proof.
  intros Hgt0 Hfin Hex Hnonneg.
  assert (Ex_max (λ x, Rabs (f x)) Is =
            Ex_max f Is) as Heq.
  { eapply Ex_max_eq_ext_supp. intros; rewrite Rabs_right; auto. }
  etransitivity; first eapply (general_markov_inequality f Is id a); try auto; try nra.
  * rewrite Heq //=.
  * eapply ex_Ex_extrema_proper_supp; try eassumption.
    intros; rewrite Rabs_right; auto.
  * rewrite Heq //.
Qed.

Lemma Rabs_gt_iff_square x k:
  k > 0 →
  (Rabs x > k ↔ x^2 > k^2).
Proof.
  intros Hgt.
  split.
  - assert (x^2 = (Rabs x)^2) as ->.
    { rewrite //=. apply Rabs_case; nra. }
    nra.
  - intros. apply Rlt_gt.
    replace k with (Rabs k) by (rewrite Rabs_right; nra).
    rewrite -?sqrt_Rsqr_abs.
    apply sqrt_lt_1; rewrite /Rsqr; intros; nra.
Qed.

Lemma chebyshev_inequality {X} (f: X → R) (Is: pidist X) (k: R) (μ: R):
  k > 0 →
  is_finite (Ex_max (λ x, (f x - μ)^2) Is) →
  ex_Ex_extrema (λ x, (f x - μ)^2) Is →
  Rbar_le (Pr_max (λ x, Rabs (f x - μ) > k) Is)
          (Rbar_mult (/(k^2)) (Ex_max (λ x, (f x - μ)^2) Is)).
Proof.
  intros.
  transitivity (Pr_max (λ x, (f x - μ)^2 > k^2) Is).
  - refl_right. apply Ex_max_eq_ext.
    intros x.
    destruct ClassicalEpsilon.excluded_middle_informative as [r|n] => //=;
    destruct ClassicalEpsilon.excluded_middle_informative as [r'|n'] => //=.
    * rewrite Rabs_gt_iff_square in r *; nra.
    * rewrite -Rabs_gt_iff_square in r' *; nra.
  - eapply markov_inequality; try nra; eauto.
    intros ??. apply Rle_ge, pow2_ge_0.
Qed.

Lemma ex_Ex_ivd_max_const {X} (f: X → R) I r:
  ex_Ex_ivd f I ↔ ex_Ex_ivd (λ x, Rmax r (Rabs (f x))) I.
Proof.
  split.
  - intros Hex%ex_Ex_ival_to_Rabs.
    eapply (ex_Ex_ivd_plus_const _ _ (Rabs r)) in Hex.
    eapply ex_Ex_ival_le; last eassumption.
    intros. rewrite Rabs_right; last first.
    { apply Rle_ge. setoid_rewrite <-Rmax_r. apply Rabs_pos. }
    rewrite [a in _ <= a]Rabs_right; last first.
    { specialize (Rabs_pos (f x)). specialize (Rabs_pos r). nra. }
    specialize (Rle_abs r) => Habs.
    specialize (Rabs_pos (f x)) => Hpos.
    specialize (Rabs_pos r) => Hpos'.
    apply Rmax_case; nra.
  - intros. eapply ex_Ex_ival_le; last eassumption.
    intros. rewrite //=. setoid_rewrite <-RRle_abs at 2.
    apply Rmax_r.
Qed.

Lemma ex_Ex_ivd_moments {X} (f: X → R) (I: ivdist X) m n:
  (m <= n)%nat →
  ex_Ex_ivd (λ x, (f x)^n) I →
  ex_Ex_ivd (λ x, (f x)^m) I.
Proof.
  intros Hle.
  rewrite (ex_Ex_ivd_max_const _ _ 1) => Hex.
  rewrite (ex_Ex_ivd_max_const _ _ 1).
  eapply ex_Ex_ival_le; last eassumption.
  intros x => //=.
  rewrite Rabs_right; last first.
  { apply Rle_ge. setoid_rewrite <-Rmax_r. apply Rabs_pos. }
  rewrite [a in _ <= a]Rabs_right; last first.
  { apply Rle_ge. setoid_rewrite <-Rmax_r. apply Rabs_pos. }
  destruct (Rge_dec (Rabs (f x)) 1).
  - apply Rmax_le_compat; first done.
    rewrite -?RPow_abs. apply Rle_pow; auto. nra.
  - rewrite ?Rmax_left; first done.
    * rewrite -RPow_abs.
      destruct n; first by auto.
       left. apply pow_lt_1_compat; last by omega.
       split; try nra.
       apply Rabs_pos.
    * rewrite -RPow_abs.
      destruct m; first by auto.
       left. apply pow_lt_1_compat; last by omega.
       split; try nra.
       apply Rabs_pos.
Qed.

Lemma ex_Ex_ivd_moments_1 {X} (f: X → R) (I: ivdist X) n:
  (1 <= n)%nat →
  ex_Ex_ivd (λ x, (f x)^n) I →
  ex_Ex_ivd f I.
Proof.
  intros. eapply ex_Ex_ival_proper'; last first.
  { eapply (ex_Ex_ivd_moments f I 1); eauto. }
  { reflexivity. }
  rewrite //= => ?. ring.
Qed.

Lemma ex_Ex_extrema_moments {X} (f: X → R) (Is: pidist X) m n:
  (m <= n)%nat →
  ex_Ex_extrema (λ x, (f x)^n) Is →
  ex_Ex_extrema (λ x, (f x)^m) Is.
Proof.
  intros Hle Hex I Hin.
  eapply (ex_Ex_ivd_moments f ({| ivd_ival := I; val_sum1 := all_sum1 _ _ Hin |})); eauto.
  eapply Hex; eauto.
Qed.

Lemma ex_Ex_extrema_moments_1 {X} (f: X → R) (Is: pidist X) n:
  (1 <= n)%nat →
  ex_Ex_extrema (λ x, (f x)^n) Is →
  ex_Ex_extrema f Is.
Proof.
  intros Hle Hex I Hin.
  eapply (ex_Ex_ivd_moments_1 f ({| ivd_ival := I; val_sum1 := all_sum1 _ _ Hin |})); eauto.
  eapply Hex; eauto.
Qed.

Lemma is_Ex_ival_variance {X} (f: X → R) (I: ivdist X) (μ: R):
  ex_Ex_ival (λ x, (f x)^2) I →
  is_Ex_ival (λ x, (f x - μ)^2) I (Ex_ival (λ x, (f x)^2) I - 2 * μ * Ex_ival f I + μ^2).
Proof.
  intros Hex.
  eapply (is_Ex_ival_proper' (λ x, (f x)^2 - 2 * μ * (f x) + μ^2)).
  { rewrite //= => ?. field. }
  { reflexivity. }
  apply is_Ex_ival_sum; last apply is_Ex_ivd_const.
  apply is_Ex_ival_sum.
  - apply Ex_ival_correct; auto.
  - apply: is_Ex_ival_negate.
    apply: is_Ex_ival_scal_l.
    apply Ex_ival_correct. apply: ex_Ex_ivd_moments_1; try eassumption. omega.
Qed.

Lemma Finite_Rplus x y:
  Finite (x + y) = Rbar_plus (Finite x) (Finite y).
Proof. done. Qed.

Lemma Finite_Rmult x y:
  Finite (x * y) = Rbar_mult (Finite x) (Finite y).
Proof. done. Qed.

Lemma Finite_Ropp x:
  Finite (- x) = Rbar_opp (Finite x).
Proof. done. Qed.

Lemma Rbar_mult_finite_le_compat_l :
  ∀ (r: R) (r1 r2 : Rbar), 0 <= r → Rbar_le r1 r2 → Rbar_le (Rbar_mult r r1) (Rbar_mult r r2).
Proof.
  intros. destruct r1, r2 => //=; try destruct Rle_dec; try auto; try nra.
  * apply Rmult_le_compat_l; eauto.
  * destruct Rle_lt_or_eq_dec; eauto; subst => //=. nra.
  * destruct Rle_lt_or_eq_dec; eauto; subst => //=. nra.
  * destruct Rle_lt_or_eq_dec; eauto; subst => //=.
Qed.

Lemma Rabs_pow2 (x: R):
  Rabs (x^2) = x^2.
Proof.
  rewrite  Rabs_mult Rmult_1_r. apply Rabs_case; nra.
Qed.

Lemma bounded_psupp_variance_moment1 {X} (f: X → R) Is μ:
  bounded_fun_on (λ x, (f x - μ) ^ 2) (λ x, In_psupport x Is) ↔
  bounded_fun_on f (λ x, In_psupport x Is).
Proof.
  split.
  - intros (c&Hmax). exists (sqrt c + Rabs μ).
    intros x Hin. specialize (Hmax x Hin).
    assert (0 <= c).
    { etransitivity; last eauto. apply Rabs_pos. }
    apply sqrt_le_1_alt in Hmax.
    replace (Rabs ((f x - μ)^2)) with ((Rabs (f x - μ))^2) in Hmax; last first.
    { rewrite pow2_abs Rabs_pow2 //=. }
    rewrite sqrt_pow2 in Hmax; last apply Rabs_pos.
    move: Hmax. repeat apply Rabs_case; nra.
  - intros (c&Hmax). exists (c^2 + 2 * c * Rabs μ + μ^2).
    intros x Hin. specialize (Hmax x Hin).
    rewrite Rabs_pow2. ring_simplify.
    cut (f x ^2 ≤ c^2 + 2 * c * Rabs μ + 2 * f x * μ); first by nra.
    specialize (pow_maj_Rabs _ _ 2 Hmax) => H.
    cut (0 <= 2 * c * Rabs μ + 2 * f x * μ); first nra.
    move: Hmax. do 2 apply Rabs_case; nra.
Qed.

Lemma bounded_psupp_moment1_moment2 {X} (f: X → R) Is:
  bounded_fun_on f (λ x, In_psupport x Is)
  ↔ bounded_fun_on (λ x, (f x) ^ 2) (λ x, In_psupport x Is).
Proof.
  split.
  - intros (c&Hmax). exists (c^2).
    intros x Hin. specialize (Hmax x Hin).
    rewrite Rabs_pow2.
    specialize (pow_maj_Rabs _ _ 2 Hmax) => H; nra.
  - intros (c&Hmax). exists (sqrt c).
    intros x Hin. specialize (Hmax x Hin).
    rewrite ?Rabs_mult in Hmax. replace (Rabs 1) with 1 in Hmax by (rewrite Rabs_right; nra).
    apply sqrt_le_1_alt in Hmax. rewrite (sqrt_pow2 (Rabs (f x))) in Hmax; auto using Rabs_pos.
Qed.

Lemma bounded_psupp_variance_moment2 {X} (f: X → R) Is μ:
  bounded_fun_on (λ x, (f x - μ) ^ 2) (λ x, In_psupport x Is)
  ↔ bounded_fun_on (λ x, (f x) ^ 2) (λ x, In_psupport x Is).
Proof.
  rewrite bounded_psupp_variance_moment1.
  apply bounded_psupp_moment1_moment2.
Qed.

Lemma Ex_max_variance {X} (f: X → R) (Is: pidist X) (μ: R):
  ex_Ex_extrema (λ x, (f x)^2) Is →
  μ >= 0 →
  Rbar_le (Ex_max (λ x, (f x - μ)^2) Is)
          (Rbar_plus (Ex_max (λ x, (f x)^2) Is)
                     (Rbar_plus (Rbar_mult (- 2 * μ) (Ex_min f Is)) (Finite (μ^2)))).
Proof.
  intros Hex Hpos.
  apply Ex_max_spec2. intros r Hin.
  destruct Hin as (I&Hin&His).
  erewrite (is_Ex_ival_unique' (λ x, (f x - μ)^2) I r); auto; last first.
  { apply (is_Ex_ival_variance _ {| ivd_ival := I; val_sum1 := all_sum1 _ _ Hin |}).
    eapply Hex. eauto. }
  rewrite Rplus_assoc.
  rewrite ?Finite_Rplus.
  apply Rbar_plus_le_compat.
  { apply Ex_max_spec1'; eauto. }
  apply Rbar_plus_le_compat; last done.
  rewrite Finite_Ropp.
  rewrite -Ropp_mult_distr_l.
  rewrite Finite_Ropp.
  rewrite Rbar_mult_opp_l.
  apply Rbar_opp_le.
  rewrite [a in Rbar_le _ a]Finite_Rmult.
  apply Rbar_mult_finite_le_compat_l; try nra.
  apply Ex_min_spec1'; eauto.
  eapply ex_Ex_extrema_moments_1 in Hex; eauto.
Qed.


Require Import Coq.Bool.Bool.

Inductive Sig (a:Type) (p:a -> Type) : Type :=
| Ex : forall (x:a), p x -> Sig a p
.

Arguments Sig {a}.
Arguments Ex {a} {p}.

Definition prj1 (a:Type) (p:a -> Type) (q:Sig p) : a :=
    match q with
    | Ex x _    => x
    end.

Arguments prj1 {a} {p}.

Definition prj2 (a:Type) (p:a -> Type) (q:Sig p) : p (prj1 q) :=
    match q with
    | Ex _ r    => r
    end.

Arguments prj2 {a} {p}.

(* f is a decider for p                                                         *)
Definition Decider (a:Type) (f:a -> bool) (p:a -> Prop) : Prop :=
    forall (x:a), p x <-> f x = true.

Arguments Decider {a}.

Definition Decidable (a:Type) (p:a -> Prop) : Prop :=
    exists (f:a -> bool), Decider f p.

Arguments Decidable {a}.

(* f is a semi-decider for p                                                    *)
Definition SemiDecider (a:Type) (p:a -> Prop) (f:a -> nat -> bool) : Prop :=
    forall (x:a), p x <-> exists (n:nat), f x n = true.

Arguments SemiDecider {a}.

Definition SemiDecidable (a:Type) (p:a -> Prop) : Prop :=
    exists (f:a -> nat -> bool), SemiDecider p f.

Arguments SemiDecidable {a}.

Lemma L1 : forall (a:Type) (p:a -> Prop), Decidable p -> SemiDecidable p.
Proof.
    intros a p. unfold Decidable, SemiDecidable, Decider, SemiDecider.
    intros [f H1]. exists (fun x _ => f x). intros x. split.
    - intros H2. exists 0. apply H1. assumption.
    - intros [_ H2]. apply H1. assumption.
Qed.

Definition tsat (f: nat -> bool) : Prop := exists (n:nat), f n = true.

Lemma L2 : SemiDecidable tsat.
Proof.
    unfold SemiDecidable, tsat, SemiDecider. exists (fun g n => g n).
    intros f. split; auto.
Qed.

(* semi-decision type S(X) associated with proposition X.                       *)
Definition S (X:Prop) : Type := Sig (fun f => X <-> tsat f).

Definition D (X:Prop) : Type := {X} + {~X}.

Definition toSemi : forall (X:Prop), D X -> S X.
Proof.
    unfold D, S. intros X [q|q].
    - remember (fun (n:nat) => true) as f eqn:F. assert (X <-> tsat f) as H1.
        { split.
            { intros H1. exists 0. rewrite F. reflexivity. }
            { intros H1. assumption. }}
      exact (Ex f H1).
    - remember (fun (n:nat) => false) as f eqn:F. assert (X <-> tsat f) as H1.
        { split.
            { intros H1. apply q in H1. contradiction. }
            { intros [n H1]. rewrite F in H1. inversion H1. }}
      exact (Ex f H1).
Defined.

Definition transport : forall (X Y:Prop), (X <-> Y) -> S X -> S Y.
Proof.
    intros X Y [H1 H2] [f [H3 H4]]. assert (Y <-> tsat f) as H5.
        { split.
            { intros H5. apply H3, H2. assumption. }
            { intros H5. apply H1, H4. assumption. }}
    exact (Ex f H5).
Defined.

Definition toSemiOr : forall (X Y:Prop), S X -> S Y -> S (X \/ Y).
Proof.
    intros X Y [f [H1 H2]] [g [G1 G2]].
    remember (fun n => orb (f n) (g n)) as h eqn:H.
    assert (X \/ Y <-> tsat h) as H3.
        { split.
            { intros [H3|H3].
                { apply H1 in H3. destruct H3 as [n H3].
                  exists n. rewrite H, H3. reflexivity. }
                { apply G1 in H3. destruct H3 as [n H3].
                  exists n. rewrite H, H3. destruct (f n); reflexivity. }}
            { intros [n H3]. destruct (f n) eqn:F; destruct (g n) eqn:G.
                { left. apply H2. exists n. assumption. }
                { left. apply H2. exists n. assumption. }
                { right. apply G2. exists n. assumption. }
                { rewrite H in H3. rewrite F in H3. rewrite G in H3. inversion H3. }}}
    exact (Ex h H3).
Defined.

Variable toNat : nat * nat -> nat.
Variable fromNat : nat -> nat * nat.

Axiom toNatFromNat : forall (n:nat), toNat (fromNat n) = n.
Axiom fromNatToNat : forall (p:nat*nat), fromNat (toNat p) = p.

Definition fromNat1 (n:nat) : nat := fst (fromNat n).
Definition fromNat2 (n:nat) : nat := snd (fromNat n).

Definition toSemiAnd : forall (X Y:Prop), S X -> S Y -> S (X /\ Y).
Proof.
    intros X Y [f [H1 H2]] [g [G1 G2]].
    remember (fun n => andb (f (fromNat1 n)) (g (fromNat2 n))) as h eqn:E.
    apply Ex with h. split.
    - intros [H3 H4]. apply H1 in H3. apply G1 in H4.
      destruct H3 as [n H3]. destruct H4 as [m H4]. exists (toNat (n,m)).
      rewrite E. unfold fromNat1, fromNat2. rewrite fromNatToNat. simpl.
      rewrite H3, H4. reflexivity.
    - intros [n H3]. rewrite E in H3. apply andb_true_iff in H3.
      destruct H3 as [H3 H4]. split.
        + apply H2. exists (fromNat1 n). assumption.
        + apply G2. exists (fromNat2 n). assumption.
Qed.

(* Certifying semi-decider                                                      *)
Definition CertSemiDecider (a:Type) (p:a -> Prop) : Type := forall (x:a), S (p x).

Arguments CertSemiDecider {a}.

Definition fromCertSD : forall (a:Type) (p:a -> Prop),
    CertSemiDecider p ->
    Sig (fun (F:a -> nat -> bool) => forall (x:a), p x <-> tsat (F x)).
Proof.
    unfold CertSemiDecider. intros a p q.
    remember (fun (x:a) (n:nat) => prj1 (q x) n) as F eqn:E. exists F.
    intros x. remember (prj2 (q x)) as H1 eqn:E'. clear E'. simpl in H1.
    rewrite E. assumption.
Defined.

Arguments fromCertSD {a} {p}.

Definition toCertSD : forall (a:Type) (p:a -> Prop),
    Sig (fun (F:a -> nat -> bool) => forall (x:a), p x <-> tsat (F x)) ->
    CertSemiDecider p.
Proof.
    unfold CertSemiDecider. intros a p [F H1] x. apply (Ex (F x)), H1.
Defined.

Lemma L3 : forall (a:Type) (p:a -> Prop),
    SemiDecidable p <-> exists (q:CertSemiDecider p), True.
Proof.
    unfold SemiDecidable, SemiDecider, CertSemiDecider.
    intros a p. split; intros H1.
    - destruct H1 as [F H1]. exists (fun x => Ex (F x) (H1 x)). trivial.
    - destruct H1 as [q _]. exists (prj1 (fromCertSD q)).
      exact (prj2 (fromCertSD q)).
Qed.

Definition Fact_13_1_9_1 :
    (forall (X:Prop), S X -> D X) -> (forall (f:nat -> bool), D (tsat f)).
Proof.
    intros q f. apply q. apply (Ex f). split; auto.
Defined.

Definition Fact_13_1_9_2 :
    (forall (f:nat -> bool), D(tsat f)) -> (forall (X:Prop), S X -> D X).
Proof.
    intros q X [f [H1 H2]]. destruct (q f) as [H3|H3].
    - left. apply H2. assumption.
    - right. intros H4. apply H3, H1. assumption.
Qed.

Definition Markov : Prop := forall (f:nat -> bool),
    ~(forall n, f n = false) -> exists n, f n = true.

Definition Post : Type := forall (X:Prop), S X -> S (~X) -> D X.

Definition Fact_13_2_1_1 : Post -> forall (X:Prop), D X -> S X * S (~X).
Proof.
    unfold Post. intros H1 X H2. split.
    - destruct H2 as [H3|H3].
        + apply (Ex (fun n => true)). split; intros H4; try assumption.
          exists 0. reflexivity.
        + apply (Ex (fun n => false)). split; intros H4.
            { apply H3 in H4. contradiction. }
            { destruct H4 as [n H4]. inversion H4. }
    - destruct H2 as [H3|H3].
        + apply (Ex (fun n => false)). split; intros H4.
            { apply H4 in H3. contradiction. }
            { destruct H4 as [n H4]. inversion H4. }
        + apply (Ex (fun n => true)). split; intros H4; try assumption.
          exists 0. reflexivity.
Defined.

Definition Fact_13_2_1_2 : Post -> forall (X:Prop), S X * S (~X) -> D X.
Proof.
    unfold Post. intros H1 X [H2 H3]. apply H1; assumption.
Qed.

Lemma Markov2Post : Markov -> Post.
Proof.
    unfold Markov, Post. intros H1 X H2 H3.
    destruct H2 as [f H2]. destruct H3 as [g H3].
    unfold tsat in H2. unfold tsat in H3.
Show.


(* Copyright (c) 2008-2012, Adam Chlipala
 *
 * This work is licensed under a
 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
 * Unported License.
 * The license text is available at:
 *   http://creativecommons.org/licenses/by-nc-nd/3.0/
 *)

(* begin hide *)
Require Import List.

Require Import CpdtTactics.

Set Implicit Arguments.

(* Extra definitions to get coqdoc to choose the right fonts. *)

(* begin thide *)
Inductive unit := tt.
Inductive Empty_set := .
Inductive bool := true | false.
Inductive sum := .
Inductive prod := .
Inductive and := conj.
Inductive or := or_introl | or_intror.
Inductive ex := ex_intro.
Inductive eq := eq_refl.
Reset unit.
(* end thide *)
(* end hide *)

(** %\chapter{Inductive Predicates}% *)

(** The so-called %\index{Curry-Howard correspondence}``%#"#Curry-Howard correspondence#"#%''~\cite{Curry,Howard}% states a formal connection between functional programs and mathematical proofs.  In the last chapter, we snuck in a first introduction to this subject in Coq.  Witness the close similarity between the types [unit] and [True] from the standard library: *)

Print unit.
(** %\vspace{-.15in}%[[
  Inductive unit : Set :=  tt : unit
]]
*)

Print True.
(** %\vspace{-.15in}%[[
  Inductive True : Prop :=  I : True
  ]]

Recall that [unit] is the type with only one value, and [True] is the proposition that always holds.  Despite this superficial difference between the two concepts, in both cases we can use the same inductive definition mechanism.  The connection goes further than this.  We see that we arrive at the definition of [True] by replacing [unit] by [True], [tt] by [I], and [Set] by [Prop].  The first two of these differences are superficial changes of names, while the third difference is the crucial one for separating programs from proofs.  A term [T] of type [Set] is a type of programs, and a term of type [T] is a program.  A term [T] of type [Prop] is a logical proposition, and its proofs are of type [T].  Chapter 12 goes into more detail about the theoretical differences between [Prop] and [Set].  For now, we will simply follow common intuitions about what a proof is.

The type [unit] has one value, [tt].  The type [True] has one proof, [I].  Why distinguish between these two types?  Many people who have read about Curry-Howard in an abstract context but who have not put it to use in proof engineering answer that the two types in fact _should not_ be distinguished.  There is a certain aesthetic appeal to this point of view, but I want to argue that it is best to treat Curry-Howard very loosely in practical proving.  There are Coq-specific reasons for preferring the distinction, involving efficient compilation and avoidance of paradoxes in the presence of classical math, but I will argue that there is a more general principle that should lead us to avoid conflating programming and proving.

The essence of the argument is roughly this: to an engineer, not all functions of type [A -> B] are created equal, but all proofs of a proposition [P -> Q] are.  This idea is known as%\index{proof irrelevance}% _proof irrelevance_, and its formalizations in logics prevent us from distinguishing between alternate proofs of the same proposition.  Proof irrelevance is compatible with, but not derivable in, Gallina.  Apart from this theoretical concern, I will argue that it is most effective to do engineering with Coq by employing different techniques for programs versus proofs.  Most of this book is organized around that distinction, describing how to program, by applying standard functional programming techniques in the presence of dependent types; and how to prove, by writing custom Ltac decision procedures.

With that perspective in mind, this chapter is sort of a mirror image of the last chapter, introducing how to define predicates with inductive definitions.  We will point out similarities in places, but much of the effective Coq user's bag of tricks is disjoint for predicates versus "datatypes."  This chapter is also a covert introduction to dependent types, which are the foundation on which interesting inductive predicates are built, though we will rely on tactics to build dependently typed proof terms for us for now.  A future chapter introduces more manual application of dependent types. *)

(** * Propositional Logic *)

(** Let us begin with a brief tour through the definitions of the connectives for propositional logic.  We will work within a Coq section that provides us with a set of propositional variables.  In Coq parlance, these are just variables of type [Prop]. *)

Section Propositional.
  Variables P Q R : Prop.

  (** In Coq, the most basic propositional connective is implication, written [->], which we have already used in almost every proof.  Rather than being defined inductively, implication is built into Coq as the function type constructor.

We have also already seen the definition of [True].  For a demonstration of a lower-level way of establishing proofs of inductive predicates, we turn to this trivial theorem. *)

  Theorem obvious : True.
(* begin thide *)
    apply I.
(* end thide *)
  Qed.

  (** We may always use the [apply] tactic to take a proof step based on applying a particular constructor of the inductive predicate that we are trying to establish.  Sometimes there is only one constructor that could possibly apply, in which case a shortcut is available:%\index{tactics!constructor}% *)

(* begin thide *)
  Theorem obvious' : True.
    constructor.
  Qed.

(* end thide *)

  (** There is also a predicate [False], which is the Curry-Howard mirror image of [Empty_set] from the last chapter. *)

  Print False.
  (** %\vspace{-.15in}%[[
  Inductive False : Prop :=
  ]]

  We can conclude anything from [False], doing case analysis on a proof of [False] in the same way we might do case analysis on, say, a natural number.  Since there are no cases to consider, any such case analysis succeeds immediately in proving the goal. *)

  Theorem False_imp : False -> 2 + 2 = 5.
(* begin thide *)
    destruct 1.
(* end thide *)
  Qed.

  (** In a consistent context, we can never build a proof of [False].  In inconsistent contexts that appear in the courses of proofs, it is usually easiest to proceed by demonstrating the inconsistency with an explicit proof of [False]. *)

  Theorem arith_neq : 2 + 2 = 5 -> 9 + 9 = 835.
(* begin thide *)
    intro.

    (** At this point, we have an inconsistent hypothesis [2 + 2 = 5], so the specific conclusion is not important.  We use the %\index{tactics!elimtype}%[elimtype] tactic.  For a full description of it, see the Coq manual.  For our purposes, we only need the variant [elimtype False], which lets us replace any conclusion formula with [False], because any fact follows from an inconsistent context. *)

    elimtype False.
    (** [[
  H : 2 + 2 = 5
  ============================
   False

   ]]

   For now, we will leave the details of this proof about arithmetic to [crush]. *)

    crush.
(* end thide *)
  Qed.

  (** A related notion to [False] is logical negation. *)

  (* begin hide *)
  Definition foo := not.
  (* end hide *)

  Print not.
  (** %\vspace{-.15in}% [[
    not = fun A : Prop => A -> False
      : Prop -> Prop
     ]]

     We see that [not] is just shorthand for implication of [False].  We can use that fact explicitly in proofs.  The syntax [~ P] %(written with a tilde in ASCII)% expands to [not P]. *)

  Theorem arith_neq' : ~ (2 + 2 = 5).
(* begin thide *)
    unfold not.
    (** [[
  ============================
   2 + 2 = 5 -> False
   ]]
   *)

    crush.
(* end thide *)
  Qed.

  (** We also have conjunction, which we introduced in the last chapter. *)

  Print and.
(** %\vspace{-.15in}%[[
    Inductive and (A : Prop) (B : Prop) : Prop :=  conj : A -> B -> A /\ B
  ]]

  The interested reader can check that [and] has a Curry-Howard equivalent called %\index{Gallina terms!prod}%[prod], the type of pairs.  However, it is generally most convenient to reason about conjunction using tactics.  An explicit proof of commutativity of [and] illustrates the usual suspects for such tasks.  The operator [/\] is an infix shorthand for [and]. *)

  Theorem and_comm : P /\ Q -> Q /\ P.

(* begin thide *)
    (** We start by case analysis on the proof of [P /\ Q]. *)

    destruct 1.
    (** [[
  H : P
  H0 : Q
  ============================
   Q /\ P

   ]]

    Every proof of a conjunction provides proofs for both conjuncts, so we get a single subgoal reflecting that.  We can proceed by splitting this subgoal into a case for each conjunct of [Q /\ P].%\index{tactics!split}% *)

    split.
(** [[
2 subgoals

  H : P
  H0 : Q
  ============================
   Q

subgoal 2 is

   P

 ]]

 In each case, the conclusion is among our hypotheses, so the %\index{tactics!assumption}%[assumption] tactic finishes the process. *)

    assumption.
    assumption.
(* end thide *)
  Qed.

  (** Coq disjunction is called %\index{Gallina terms!or}%[or] and abbreviated with the infix operator [\/]. *)

  Print or.
(** %\vspace{-.15in}%[[
  Inductive or (A : Prop) (B : Prop) : Prop :=
    or_introl : A -> A \/ B | or_intror : B -> A \/ B
]]

We see that there are two ways to prove a disjunction: prove the first disjunct or prove the second.  The Curry-Howard analogue of this is the Coq %\index{Gallina terms!sum}%[sum] type.  We can demonstrate the main tactics here with another proof of commutativity. *)

  Theorem or_comm : P \/ Q -> Q \/ P.

(* begin thide *)
    (** As in the proof for [and], we begin with case analysis, though this time we are met by two cases instead of one. *)

    destruct 1.
(** [[
2 subgoals

  H : P
  ============================
   Q \/ P

subgoal 2 is

 Q \/ P

 ]]

 We can see that, in the first subgoal, we want to prove the disjunction by proving its second disjunct.  The %\index{tactics!right}%[right] tactic telegraphs this intent. *)

    right; assumption.

    (** The second subgoal has a symmetric proof.%\index{tactics!left}%

       [[
1 subgoal

  H : Q
  ============================
   Q \/ P
   ]]
   *)

    left; assumption.

(* end thide *)
  Qed.

(* begin hide *)
(* In-class exercises *)

  Theorem contra : P -> ~P -> R.
(* begin thide *)
    unfold not.
    intros.
    elimtype False.
    apply H0.
    assumption.
(* end thide *)
  Admitted.

  Theorem and_assoc : (P /\ Q) /\ R -> P /\ (Q /\ R).
(* begin thide *)
    intros.
    destruct H.
    destruct H.
    split.
    assumption.
    split.
    assumption.
    assumption.
(* end thide *)
  Admitted.

  Theorem or_assoc : (P \/ Q) \/ R -> P \/ (Q \/ R).
(* begin thide *)
    intros.
    destruct H.
    destruct H.
    left.
    assumption.
    right.
    left.
    assumption.
    right.
    right.
    assumption.
(* end thide *)
  Admitted.

(* end hide *)

  (** It would be a shame to have to plod manually through all proofs about propositional logic.  Luckily, there is no need.  One of the most basic Coq automation tactics is %\index{tactics!tauto}%[tauto], which is a complete decision procedure for constructive propositional logic.  (More on what "constructive" means in the next section.)  We can use [tauto] to dispatch all of the purely propositional theorems we have proved so far. *)

  Theorem or_comm' : P \/ Q -> Q \/ P.
(* begin thide *)
    tauto.
(* end thide *)
  Qed.

  (** Sometimes propositional reasoning forms important plumbing for the proof of a theorem, but we still need to apply some other smarts about, say, arithmetic.  The tactic %\index{tactics!intuition}%[intuition] is a generalization of [tauto] that proves everything it can using propositional reasoning.  When some further facts must be established to finish the proof, [intuition] uses propositional laws to simplify them as far as possible.  Consider this example, which uses the list concatenation operator %\coqdocnotation{%#<tt>#++#</tt>#%}% from the standard library. *)

  Theorem arith_comm : forall ls1 ls2 : list nat,
    length ls1 = length ls2 \/ length ls1 + length ls2 = 6
    -> length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2.
(* begin thide *)
    intuition.

    (** A lot of the proof structure has been generated for us by [intuition], but the final proof depends on a fact about lists.  The remaining subgoal hints at what cleverness we need to inject. *)

    (** [[
  ls1 : list nat
  ls2 : list nat
  H0 : length ls1 + length ls2 = 6
  ============================
   length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2

   ]]

   We can see that we need a theorem about lengths of concatenated lists, which we proved last chapter and is also in the standard library. *)

    rewrite app_length.
    (** [[
  ls1 : list nat
  ls2 : list nat
  H0 : length ls1 + length ls2 = 6
  ============================
   length ls1 + length ls2 = 6 \/ length ls1 = length ls2

   ]]

   Now the subgoal follows by purely propositional reasoning.  That is, we could replace [length ls1 + length ls2 = 6] with [P] and [length ls1 = length ls2] with [Q] and arrive at a tautology of propositional logic. *)

    tauto.
(* end thide *)
  Qed.

  (** The [intuition] tactic is one of the main bits of glue in the implementation of [crush], so, with a little help, we can get a short automated proof of the theorem. *)

(* begin thide *)
  Theorem arith_comm' : forall ls1 ls2 : list nat,
    length ls1 = length ls2 \/ length ls1 + length ls2 = 6
    -> length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2.
    Hint Rewrite app_length.

    crush.
  Qed.
(* end thide *)

End Propositional.

(** Ending the section here has the same effect as always.  Each of our propositional theorems becomes universally quantified over the propositional variables that we used. *)

(** * What Does It Mean to Be Constructive? *)

(** One potential point of confusion in the presentation so far is the distinction between [bool] and [Prop].  The datatype [bool] is built from two values [true] and [false], while [Prop] is a more primitive type that includes among its members [True] and [False].  Why not collapse these two concepts into one, and why must there be more than two states of mathematical truth, [True] and [False]?

The answer comes from the fact that Coq implements%\index{constructive logic}% _constructive_ or%\index{intuitionistic logic|see{constructive logic}}% _intuitionistic_ logic, in contrast to the%\index{classical logic}% _classical_ logic that you may be more familiar with.  In constructive logic, classical tautologies like [~ ~ P -> P] and [P \/ ~ P] do not always hold.  In general, we can only prove these tautologies when [P] is%\index{decidability}% _decidable_, in the sense of %\index{computability|see{decidability}}%computability theory.  The Curry-Howard encoding that Coq uses for [or] allows us to extract either a proof of [P] or a proof of [~ P] from any proof of [P \/ ~ P].  Since our proofs are just functional programs which we can run, a general %\index{law of the excluded middle}%law of the excluded middle would give us a decision procedure for the halting problem, where the instantiations of [P] would be formulas like "this particular Turing machine halts."

A similar paradoxical situation would result if every proposition evaluated to either [True] or [False].  Evaluation in Coq is decidable, so we would be limiting ourselves to decidable propositions only.

Hence the distinction between [bool] and [Prop].  Programs of type [bool] are computational by construction; we can always run them to determine their results.  Many [Prop]s are undecidable, and so we can write more expressive formulas with [Prop]s than with [bool]s, but the inevitable consequence is that we cannot simply "run a [Prop] to determine its truth."

Constructive logic lets us define all of the logical connectives in an aesthetically appealing way, with orthogonal inductive definitions.  That is, each connective is defined independently using a simple, shared mechanism.  Constructivity also enables a trick called%\index{program extraction}% _program extraction_, where we write programs by phrasing them as theorems to be proved.  Since our proofs are just functional programs, we can extract executable programs from our final proofs, which we could not do as naturally with classical proofs.

We will see more about Coq's program extraction facility in a later chapter.  However, I think it is worth interjecting another warning at this point, following up on the prior warning about taking the Curry-Howard correspondence too literally.  It is possible to write programs by theorem-proving methods in Coq, but hardly anyone does it.  It is almost always most useful to maintain the distinction between programs and proofs.  If you write a program by proving a theorem, you are likely to run into algorithmic inefficiencies that you introduced in your proof to make it easier to prove.  It is a shame to have to worry about such situations while proving tricky theorems, and it is a happy state of affairs that you almost certainly will not need to, with the ideal of extracting programs from proofs being confined mostly to theoretical studies. *)

(** * First-Order Logic *)

(** The %\index{Gallina terms!forall}%[forall] connective of first-order logic, which we have seen in many examples so far, is built into Coq.  Getting ahead of ourselves a bit, we can see it as the dependent function type constructor.  In fact, implication and universal quantification are just different syntactic shorthands for the same Coq mechanism.  A formula [P -> Q] is equivalent to [forall x : P, Q], where [x] does not appear in [Q].  That is, the "real" type of the implication says "for every proof of [P], there exists a proof of [Q]."

%\index{existential quantification}\index{Gallina terms!exists}\index{Gallina terms!ex}%Existential quantification is defined in the standard library. *)

  Print ex.
(** %\vspace{-.15in}%[[
  Inductive ex (A : Type) (P : A -> Prop) : Prop :=
    ex_intro : forall x : A, P x -> ex P
    ]]

  (Note that here, as always, each [forall] quantifier has the largest possible scope, so that the type of [ex_intro] could also be written [forall x : A, (P x -> ex P)].)

  The family [ex] is parameterized by the type [A] that we quantify over, and by a predicate [P] over [A]s.  We prove an existential by exhibiting some [x] of type [A], along with a proof of [P x].  As usual, there are tactics that save us from worrying about the low-level details most of the time.

  Here is an example of a theorem statement with existential quantification.  We use the equality operator [=], which, depending on the settings in which they learned logic, different people will say either is or is not part of first-order logic.  For our purposes, it is. *)

Theorem exist1 : exists x : nat, x + 1 = 2.
(* begin thide *)
  (** remove printing exists *)
  (** We can start this proof with a tactic %\index{tactics!exists}%[exists], which should not be confused with the formula constructor shorthand of the same name.  %In the version of this document that you are reading, the reverse ``E'' appears instead of the text ``exists'' in formulas.% *)

  exists 1.

  (** The conclusion is replaced with a version using the existential witness that we announced.

     [[
  ============================
   1 + 1 = 2
   ]]
   *)

  reflexivity.
(* end thide *)
Qed.

(** printing exists $\exists$ *)

(** We can also use tactics to reason about existential hypotheses. *)

Theorem exist2 : forall n m : nat, (exists x : nat, n + x = m) -> n <= m.
(* begin thide *)
  (** We start by case analysis on the proof of the existential fact. *)

  destruct 1.
  (** [[
  n : nat
  m : nat
  x : nat
  H : n + x = m
  ============================
   n <= m

   ]]

   The goal has been replaced by a form where there is a new free variable [x], and where we have a new hypothesis that the body of the existential holds with [x] substituted for the old bound variable.  From here, the proof is just about arithmetic and is easy to automate. *)

  crush.
(* end thide *)
Qed.

(* begin hide *)
(* In-class exercises *)

Theorem forall_exists_commute : forall (A B : Type) (P : A -> B -> Prop),
  (exists x : A, forall y : B, P x y) -> (forall y : B, exists x : A, P x y).
(* begin thide *)
  intros.
  destruct H.
  exists x.
  apply H.
(* end thide *)
Admitted.

(* end hide *)

(** The tactic [intuition] has a first-order cousin called %\index{tactics!firstorder}%[firstorder], which proves many formulas when only first-order reasoning is needed, and it tries to perform first-order simplifications in any case.  First-order reasoning is much harder than propositional reasoning, so [firstorder] is much more likely than [intuition] to get stuck in a way that makes it run for long enough to be useless. *)

(** * Predicates with Implicit Equality *)

(** We start our exploration of a more complicated class of predicates with a simple example: an alternative way of characterizing when a natural number is zero. *)

Inductive isZero : nat -> Prop :=
| IsZero : isZero 0.

Theorem isZero_zero : isZero 0.
(* begin thide *)
  constructor.
(* end thide *)
Qed.

(** We can call [isZero] a%\index{judgment}% _judgment_, in the sense often used in the semantics of programming languages.  Judgments are typically defined in the style of%\index{natural deduction}% _natural deduction_, where we write a number of%\index{inference rules}% _inference rules_ with premises appearing above a solid line and a conclusion appearing below the line.  In this example, the sole constructor [IsZero] of [isZero] can be thought of as the single inference rule for deducing [isZero], with nothing above the line and [isZero 0] below it.  The proof of [isZero_zero] demonstrates how we can apply an inference rule.  (Readers not familiar with formal semantics should not worry about not following this paragraph!)

The definition of [isZero] differs in an important way from all of the other inductive definitions that we have seen in this and the previous chapter.  Instead of writing just [Set] or [Prop] after the colon, here we write [nat -> Prop].  We saw examples of parameterized types like [list], but there the parameters appeared with names _before_ the colon.  Every constructor of a parameterized inductive type must have a range type that uses the same parameter, whereas the form we use here enables us to choose different arguments to the type for different constructors.

For instance, our definition [isZero] makes the predicate provable only when the argument is [0].  We can see that the concept of equality is somehow implicit in the inductive definition mechanism.  The way this is accomplished is similar to the way that logic variables are used in %\index{Prolog}%Prolog (but worry not if not familiar with Prolog), and it is a very powerful mechanism that forms a foundation for formalizing all of mathematics.  In fact, though it is natural to think of inductive types as folding in the functionality of equality, in Coq, the true situation is reversed, with equality defined as just another inductive type!%\index{Gallina terms!eq}\index{Gallina terms!refl\_equal}% *)

Print eq.
(** %\vspace{-.15in}%[[
  Inductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : x = x
  ]]

  Behind the scenes, uses of infix [=] are expanded to instances of [eq].  We see that [eq] has both a parameter [x] that is fixed and an extra unnamed argument of the same type.  The type of [eq] allows us to state any equalities, even those that are provably false.  However, examining the type of equality's sole constructor [eq_refl], we see that we can only _prove_ equality when its two arguments are syntactically equal.  This definition turns out to capture all of the basic properties of equality, and the equality-manipulating tactics that we have seen so far, like [reflexivity] and [rewrite], are implemented treating [eq] as just another inductive type with a well-chosen definition.  Another way of stating that definition is: equality is defined as the least reflexive relation.

Returning to the example of [isZero], we can see how to work with hypotheses that use this predicate. *)

Theorem isZero_plus : forall n m : nat, isZero m -> n + m = n.
(* begin thide *)
  (** We want to proceed by cases on the proof of the assumption about [isZero]. *)

  destruct 1.
  (** [[
  n : nat
  ============================
   n + 0 = n

   ]]

   Since [isZero] has only one constructor, we are presented with only one subgoal.  The argument [m] to [isZero] is replaced with that type's argument from the single constructor [IsZero].  From this point, the proof is trivial. *)

  crush.
(* end thide *)
Qed.

(** Another example seems at first like it should admit an analogous proof, but in fact provides a demonstration of one of the most basic gotchas of Coq proving. *)

Theorem isZero_contra : isZero 1 -> False.
(* begin thide *)
  (** Let us try a proof by cases on the assumption, as in the last proof. *)

  destruct 1.
  (** [[
  ============================
   False

   ]]

   It seems that case analysis has not helped us much at all!  Our sole hypothesis disappears, leaving us, if anything, worse off than we were before.  What went wrong?  We have met an important restriction in tactics like [destruct] and [induction] when applied to types with arguments.  If the arguments are not already free variables, they will be replaced by new free variables internally before doing the case analysis or induction.  Since the argument [1] to [isZero] is replaced by a fresh variable, we lose the crucial fact that it is not equal to [0].

     Why does Coq use this restriction?  We will discuss the issue in detail in a future chapter, when we see the dependently typed programming techniques that would allow us to write this proof term manually.  For now, we just say that the algorithmic problem of "logically complete case analysis" is undecidable when phrased in Coq's logic.  A few tactics and design patterns that we will present in this chapter suffice in almost all cases.  For the current example, what we want is a tactic called %\index{tactics!inversion}%[inversion], which corresponds to the concept of inversion that is frequently used with natural deduction proof systems.  (Again, worry not if the semantics-oriented terminology from this last sentence is unfamiliar.) *)

  Undo.
  inversion 1.
(* end thide *)
Qed.

(** What does [inversion] do?  Think of it as a version of [destruct] that does its best to take advantage of the structure of arguments to inductive types.  In this case, [inversion] completed the proof immediately, because it was able to detect that we were using [isZero] with an impossible argument.

Sometimes using [destruct] when you should have used [inversion] can lead to confusing results.  To illustrate, consider an alternate proof attempt for the last theorem. *)

Theorem isZero_contra' : isZero 1 -> 2 + 2 = 5.
  destruct 1.
  (** [[
  ============================
   1 + 1 = 4

   ]]

   What on earth happened here?  Internally, [destruct] replaced [1] with a fresh variable, and, trying to be helpful, it also replaced the occurrence of [1] within the unary representation of each number in the goal.  Then, within the [O] case of the proof, we replace the fresh variable with [O].  This has the net effect of decrementing each of these numbers. *)

Abort.

(** To see more clearly what is happening, we can consider the type of [isZero]'s induction principle. *)

Check isZero_ind.
(** %\vspace{-.15in}% [[
isZero_ind
     : forall P : nat -> Prop, P 0 -> forall n : nat, isZero n -> P n
   ]]

   In our last proof script, [destruct] chose to instantiate [P] as [fun n => S n + S n = S (S (S (S n)))].  You can verify for yourself that this specialization of the principle applies to the goal and that the hypothesis [P 0] then matches the subgoal we saw generated.  If you are doing a proof and encounter a strange transmutation like this, there is a good chance that you should go back and replace a use of [destruct] with [inversion]. *)

(* begin hide *)
(* In-class exercises *)

(* EX: Define an inductive type capturing when a list has exactly two elements.  Prove that your predicate does not hold of the empty list, and prove that, whenever it holds of a list, the length of that list is two. *)

(* begin thide *)
Section twoEls.
  Variable A : Type.

  Inductive twoEls : list A -> Prop :=
  | TwoEls : forall x y, twoEls (x :: y :: nil).

  Theorem twoEls_nil : twoEls nil -> False.
    inversion 1.
  Qed.

  Theorem twoEls_two : forall ls, twoEls ls -> length ls = 2.
    inversion 1.
    reflexivity.
  Qed.
End twoEls.
(* end thide *)

(* end hide *)

(** * Recursive Predicates *)

(** We have already seen all of the ingredients we need to build interesting recursive predicates, like this predicate capturing even-ness. *)

Inductive even : nat -> Prop :=
| EvenO : even O
| EvenSS : forall n, even n -> even (S (S n)).

(** Think of [even] as another judgment defined by natural deduction rules.  The rule [EvenO] has nothing above the line and [even O] below the line, and [EvenSS] is a rule with [even n] above the line and [even (S (S n))] below.

The proof techniques of the last section are easily adapted. *)

Theorem even_0 : even 0.
(* begin thide *)
  constructor.
(* end thide *)
Qed.

Theorem even_4 : even 4.
(* begin thide *)
  constructor; constructor; constructor.
(* end thide *)
Qed.

(** It is not hard to see that sequences of constructor applications like the above can get tedious.  We can avoid them using Coq's hint facility, with a new [Hint] variant that asks to consider all constructors of an inductive type during proof search.  The tactic %\index{tactics!auto}%[auto] performs exhaustive proof search up to a fixed depth, considering only the proof steps we have registered as hints. *)

(* begin thide *)
Hint Constructors even.

Theorem even_4' : even 4.
  auto.
Qed.

(* end thide *)

(** We may also use [inversion] with [even]. *)

Theorem even_1_contra : even 1 -> False.
(* begin thide *)
  inversion 1.
(* end thide *)
Qed.

Theorem even_3_contra : even 3 -> False.
(* begin thide *)
  inversion 1.
  (** [[
  H : even 3
  n : nat
  H1 : even 1
  H0 : n = 1
  ============================
   False

   ]]

   The [inversion] tactic can be a little overzealous at times, as we can see here with the introduction of the unused variable [n] and an equality hypothesis about it.  For more complicated predicates, though, adding such assumptions is critical to dealing with the undecidability of general inversion.  More complex inductive definitions and theorems can cause [inversion] to generate equalities where neither side is a variable. *)

  inversion H1.
(* end thide *)
Qed.

(** We can also do inductive proofs about [even]. *)

Theorem even_plus : forall n m, even n -> even m -> even (n + m).
(* begin thide *)
  (** It seems a reasonable first choice to proceed by induction on [n]. *)

  induction n; crush.
  (** [[
  n : nat
  IHn : forall m : nat, even n -> even m -> even (n + m)
  m : nat
  H : even (S n)
  H0 : even m
  ============================
   even (S (n + m))

   ]]

   We will need to use the hypotheses [H] and [H0] somehow.  The most natural choice is to invert [H]. *)

  inversion H.
  (** [[
  n : nat
  IHn : forall m : nat, even n -> even m -> even (n + m)
  m : nat
  H : even (S n)
  H0 : even m
  n0 : nat
  H2 : even n0
  H1 : S n0 = n
  ============================
   even (S (S n0 + m))

   ]]

  Simplifying the conclusion brings us to a point where we can apply a constructor. *)

  simpl.
  (** [[
  ============================
   even (S (S (n0 + m)))
   ]]
   *)

  constructor.

(** [[
  ============================
   even (n0 + m)

   ]]

   At this point, we would like to apply the inductive hypothesis, which is:

   [[
  IHn : forall m : nat, even n -> even m -> even (n + m)

  ]]

  Unfortunately, the goal mentions [n0] where it would need to mention [n] to match [IHn].  We could keep looking for a way to finish this proof from here, but it turns out that we can make our lives much easier by changing our basic strategy.  Instead of inducting on the structure of [n], we should induct _on the structure of one of the [even] proofs_.  This technique is commonly called%\index{rule induction}% _rule induction_ in programming language semantics.  In the setting of Coq, we have already seen how predicates are defined using the same inductive type mechanism as datatypes, so the fundamental unity of rule induction with "normal" induction is apparent.

  Recall that tactics like [induction] and [destruct] may be passed numbers to refer to unnamed lefthand sides of implications in the conclusion, where the argument [n] refers to the [n]th such hypothesis. *)

Restart.

  induction 1.
(** [[
  m : nat
  ============================
   even m -> even (0 + m)
]]

%\noindent \coqdockw{subgoal} 2 \coqdockw{is}:%#<tt>subgoal 2 is</tt>#
[[
 even m -> even (S (S n) + m)

 ]]

 The first case is easily discharged by [crush], based on the hint we added earlier to try the constructors of [even]. *)

  crush.

  (** Now we focus on the second case: *)

  intro.
  (** [[
  m : nat
  n : nat
  H : even n
  IHeven : even m -> even (n + m)
  H0 : even m
  ============================
   even (S (S n) + m)

   ]]

   We simplify and apply a constructor, as in our last proof attempt. *)

  simpl; constructor.

(** [[
  ============================
   even (n + m)

   ]]

   Now we have an exact match with our inductive hypothesis, and the remainder of the proof is trivial. *)

  apply IHeven; assumption.

  (** In fact, [crush] can handle all of the details of the proof once we declare the induction strategy. *)

Restart.

  induction 1; crush.
(* end thide *)
Qed.

(** Induction on recursive predicates has similar pitfalls to those we encountered with inversion in the last section. *)

Theorem even_contra : forall n, even (S (n + n)) -> False.
(* begin thide *)
  induction 1.
  (** [[
  n : nat
  ============================
   False
]]

%\noindent \coqdockw{subgoal} 2 \coqdockw{is}:%#<tt>subgoal 2 is</tt>#
[[
 False

 ]]

 We are already sunk trying to prove the first subgoal, since the argument to [even] was replaced by a fresh variable internally.  This time, we find it easier to prove this theorem by way of a lemma.  Instead of trusting [induction] to replace expressions with fresh variables, we do it ourselves, explicitly adding the appropriate equalities as new assumptions. *)

Abort.

Lemma even_contra' : forall n', even n' -> forall n, n' = S (n + n) -> False.
  induction 1; crush.

  (** At this point, it is useful to consider all cases of [n] and [n0] being zero or nonzero.  Only one of these cases has any trickiness to it. *)

  destruct n; destruct n0; crush.

  (** [[
  n : nat
  H : even (S n)
  IHeven : forall n0 : nat, S n = S (n0 + n0) -> False
  n0 : nat
  H0 : S n = n0 + S n0
  ============================
   False

   ]]

  At this point it is useful to use a theorem from the standard library, which we also proved with a different name in the last chapter.  We can search for a theorem that allows us to rewrite terms of the form [x + S y]. *)

  SearchRewrite (_ + S _).
(** %\vspace{-.15in}%[[
  plus_n_Sm : forall n m : nat, S (n + m) = n + S m
     ]]
     *)

  rewrite <- plus_n_Sm in H0.

  (** The induction hypothesis lets us complete the proof, if we use a variant of [apply] that has a %\index{tactics!with}%[with] clause to give instantiations of quantified variables. *)

  apply IHeven with n0; assumption.

  (** As usual, we can rewrite the proof to avoid referencing any locally generated names, which makes our proof script more readable and more robust to changes in the theorem statement.  We use the notation [<-] to request a hint that does right-to-left rewriting, just like we can with the [rewrite] tactic. *)

  Restart.

  Hint Rewrite <- plus_n_Sm.

  induction 1; crush;
    match goal with
      | [ H : S ?N = ?N0 + ?N0 |- _ ] => destruct N; destruct N0
    end; crush.
Qed.

(** We write the proof in a way that avoids the use of local variable or hypothesis names, using the %\index{tactics!match}%[match] tactic form to do pattern-matching on the goal.  We use unification variables prefixed by question marks in the pattern, and we take advantage of the possibility to mention a unification variable twice in one pattern, to enforce equality between occurrences.  The hint to rewrite with [plus_n_Sm] in a particular direction saves us from having to figure out the right place to apply that theorem.

The original theorem now follows trivially from our lemma, using a new tactic %\index{tactics!eauto}%[eauto], a fancier version of [auto] whose explanation we postpone to Chapter 13. *)

Theorem even_contra : forall n, even (S (n + n)) -> False.
  intros; eapply even_contra'; eauto.
Qed.

(** We use a variant %\index{tactics!apply}%[eapply] of [apply] which has the same relationship to [apply] as [eauto] has to [auto].  An invocation of [apply] only succeeds if all arguments to the rule being used can be determined from the form of the goal, whereas [eapply] will introduce unification variables for undetermined arguments.  In this case, [eauto] is able to determine the right values for those unification variables, using (unsurprisingly) a variant of the classic algorithm for _unification_ %\cite{unification}%.

By considering an alternate attempt at proving the lemma, we can see another common pitfall of inductive proofs in Coq.  Imagine that we had tried to prove [even_contra'] with all of the [forall] quantifiers moved to the front of the lemma statement. *)

Lemma even_contra'' : forall n' n, even n' -> n' = S (n + n) -> False.
  induction 1; crush;
    match goal with
      | [ H : S ?N = ?N0 + ?N0 |- _ ] => destruct N; destruct N0
    end; crush.

  (** One subgoal remains:

     [[
  n : nat
  H : even (S (n + n))
  IHeven : S (n + n) = S (S (S (n + n))) -> False
  ============================
   False

   ]]

   We are out of luck here.  The inductive hypothesis is trivially true, since its assumption is false.  In the version of this proof that succeeded, [IHeven] had an explicit quantification over [n].  This is because the quantification of [n] _appeared after the thing we are inducting on_ in the theorem statement.  In general, quantified variables and hypotheses that appear before the induction object in the theorem statement stay fixed throughout the inductive proof.  Variables and hypotheses that are quantified after the induction object may be varied explicitly in uses of inductive hypotheses. *)

Abort.

(** Why should Coq implement [induction] this way?  One answer is that it avoids burdening this basic tactic with additional heuristic smarts, but that is not the whole picture.  Imagine that [induction] analyzed dependencies among variables and reordered quantifiers to preserve as much freedom as possible in later uses of inductive hypotheses.  This could make the inductive hypotheses more complex, which could in turn cause particular automation machinery to fail when it would have succeeded before.  In general, we want to avoid quantifiers in our proofs whenever we can, and that goal is furthered by the refactoring that the [induction] tactic forces us to do. *)
(* end thide *)

(* begin hide *)
(* In-class exercises *)

(* EX: Define a type [prop] of simple Boolean formulas made up only of truth, falsehood, binary conjunction, and binary disjunction.  Define an inductive predicate [holds] that captures when [prop]s are valid, and define a predicate [falseFree] that captures when a [prop] does not contain the "false" formula.  Prove that every false-free [prop] is valid. *)

(* begin thide *)
Inductive prop : Set :=
| Tru : prop
| Fals : prop
| And : prop -> prop -> prop
| Or : prop -> prop -> prop.

Inductive holds : prop -> Prop :=
| HTru : holds Tru
| HAnd : forall p1 p2, holds p1 -> holds p2 -> holds (And p1 p2)
| HOr1 : forall p1 p2, holds p1 -> holds (Or p1 p2)
| HOr2 : forall p1 p2, holds p2 -> holds (Or p1 p2).

Inductive falseFree : prop -> Prop :=
| FFTru : falseFree Tru
| FFAnd : forall p1 p2, falseFree p1 -> falseFree p2 -> falseFree (And p1 p2)
| FFNot : forall p1 p2, falseFree p1 -> falseFree p2 -> falseFree (Or p1 p2).

Hint Constructors holds.

Theorem falseFree_holds : forall p, falseFree p -> holds p.
  induction 1; crush.
Qed.
(* end thide *)

(* EX: Define an inductive type [prop'] that is the same as [prop] but omits the possibility for falsehood.  Define a proposition [holds'] for [prop'] that is analogous to [holds].  Define a function [propify] for translating [prop']s to [prop]s.  Prove that, for any [prop'] [p], if [propify p] is valid, then so is [p]. *)

(* begin thide *)
Inductive prop' : Set :=
| Tru' : prop'
| And' : prop' -> prop' -> prop'
| Or' : prop' -> prop' -> prop'.

Inductive holds' : prop' -> Prop :=
| HTru' : holds' Tru'
| HAnd' : forall p1 p2, holds' p1 -> holds' p2 -> holds' (And' p1 p2)
| HOr1' : forall p1 p2, holds' p1 -> holds' (Or' p1 p2)
| HOr2' : forall p1 p2, holds' p2 -> holds' (Or' p1 p2).

Fixpoint propify (p : prop') : prop :=
  match p with
    | Tru' => Tru
    | And' p1 p2 => And (propify p1) (propify p2)
    | Or' p1 p2 => Or (propify p1) (propify p2)
  end.

Hint Constructors holds'.

Lemma propify_holds' : forall p', holds p' -> forall p, p' = propify p -> holds' p.
  induction 1; crush; destruct p; crush.
Qed.

Theorem propify_holds : forall p, holds (propify p) -> holds' p.
  intros; eapply propify_holds'; eauto.
Qed.
(* end thide *)

(* end hide *)


Require Import Coq.ZArith.ZArith.
Require Import Coq.micromega.Lia.
Require Import Coq.Relations.Relations.
Require Import Coq.Classes.Morphisms.
Require Import Crypto.Util.Bool.Reflect.
Require Import Crypto.Util.Decidable.

Module Level.
  Local Coercion is_true : bool >-> Sortclass.
  Local Set Boolean Equality Schemes.
  Local Set Decidable Equality Schemes.
  Inductive Level :=
  | neg_inf
  | level (lvl : Z)
  | pos_inf
  .
  Notation t := Level (only parsing).
  Module Export Exports1.
    Delimit Scope level_scope with level.
    Bind Scope level_scope with Level.
    Global Coercion level : Z >-> Level.
  End Exports1.
  Local Open Scope level_scope.

  Definition of_nat (n : nat) : Level := Z.of_nat n.
  Definition of_N (n : N) : Level := Z.of_N n.
  Definition of_pos (n : positive) : Level := Z.pos n.

  Module Export Exports2.
    Global Coercion of_nat : nat >-> Level.
    Global Coercion of_N : N >-> Level.
    Global Coercion of_pos : positive >-> Level.
  End Exports2.

  (** next tighter level *)
  Definition next (l : Level) : Level
    := match l with
       | neg_inf => neg_inf
       | level lvl => level (Z.pred lvl)
       | pos_inf => pos_inf
       end.
  (** previous looser level *)
  Definition prev (l : Level) : Level
    := match l with
       | neg_inf => neg_inf
       | level lvl => level (Z.succ lvl)
       | pos_inf => pos_inf
       end.

  Notation eqb := Level_beq.
  Lemma eqb_eq x y : eqb x y = true <-> x = y.
  Proof. split; [ apply internal_Level_dec_bl | apply internal_Level_dec_lb ]. Qed.
  Lemma eqb_neq x y : eqb x y = false <-> x <> y.
  Proof. rewrite <- eqb_eq; destruct (eqb x y); split; congruence. Qed.
  Lemma eqb_refl x : eqb x x = true.
  Proof. rewrite eqb_eq; reflexivity. Qed.
  Lemma eqb_sym x y : eqb x y = eqb y x.
  Proof. destruct (eqb x y) eqn:?, (eqb y x) eqn:?; rewrite ?eqb_eq, ?eqb_neq in *; subst; congruence. Qed.
  Lemma eqb_spec : reflect_rel eq eqb.
  Proof. intros x y; destruct (eqb x y) eqn:?; constructor; rewrite ?eqb_eq, ?eqb_neq in *; assumption. Qed.
  Definition dec_eq_Level : DecidableRel (@eq Level) := dec_rel_of_bool_dec_rel eqb internal_Level_dec_bl internal_Level_dec_lb.
  Lemma eqb_compat : Proper (eq ==> eq ==> eq) eqb.
  Proof. repeat intro; subst; reflexivity. Qed.

  Definition compare (l1 l2 : Level) : comparison
    := match l1, l2 with
       | neg_inf, neg_inf => Eq
       | neg_inf, _ => Lt
       | _, neg_inf => Gt
       | pos_inf, pos_inf => Eq
       | pos_inf, _ => Gt
       | _, pos_inf => Lt
       | level l1, level l2 => Z.compare l1 l2
       end.
  Definition ltb (l1 l2 : Level) : bool
    := match compare l1 l2 with
       | Lt => true
       | _ => false
       end.
  Definition leb (l1 l2 : Level) : bool
    := orb (eqb l1 l2) (ltb l1 l2).
  Definition le : relation Level := leb.
  Definition lt : relation Level := ltb.
  Module Export Exports3.
    Global Arguments le _ _ / .
    Global Arguments lt _ _ / .
    Global Arguments ltb !_ !_ / .
    Global Arguments leb !_ !_ / .
    Global Arguments compare !_ !_ / .
  End Exports3.

  Module Import Notations1.
    Notation "-∞" := neg_inf.
    Notation "∞" := pos_inf.
    Infix "?=" := compare : level_scope.
    Infix "=?" := eqb : level_scope.
    Infix "<=?" := leb : level_scope.
    Infix "<?" := ltb : level_scope.
    Infix "<=" := le : level_scope.
    Infix "<" := lt : level_scope.
    Notation "l1 >=? l2" := (leb l2 l1) (only parsing) : level_scope.
    Notation "l1 >? l2" := (ltb l2 l1) (only parsing) : level_scope.
    Notation "l1 >= l2" := (le l2 l1) (only parsing) : level_scope.
    Notation "l1 > l2" := (lt l2 l1) (only parsing) : level_scope.
  End Notations1.
  Lemma compare_spec x y : CompareSpec (x = y) (x < y) (y < x) (x ?= y).
  Proof.
    destruct x as [|x|], y as [|y|]; cbv [lt ltb compare]; try destruct (Z.compare_spec x y), (Z.compare_spec y x); constructor;
      subst; try reflexivity; try lia.
  Qed.
  Lemma compare_refl x : (x ?= x) = Eq.
  Proof. destruct x; cbn; try reflexivity; now rewrite Z.compare_refl. Qed.
  Lemma compare_antisym x y : (y ?= x) = CompOpp (x ?= y).
  Proof. destruct x, y; cbn; try reflexivity; now rewrite Z.compare_antisym. Qed.
  Lemma compare_eq x y : (x ?= y) = Eq -> x = y.
  Proof. destruct x, y; cbn; try congruence; intro; now apply f_equal, Z.compare_eq. Qed.
  Lemma compare_eq_iff x y : (x ?= y) = Eq <-> x = y.
  Proof. destruct x, y; cbn; rewrite ?Z.compare_eq_iff; split; congruence. Qed.

  Module Export Notations.
    Export Notations1.
  End Notations.

  Module Export Exports.
    Export Exports1.
    Export Exports2.
    Export Exports3.
    Global Existing Instances eqb_spec dec_eq_Level eqb_compat | 10.
  End Exports.
End Level.
Export Level.Notations.
Export Level.Exports.
Notation Level := Level.Level.

Inductive Associativity := LeftAssoc | RightAssoc | NoAssoc | FullyAssoc | ExplicitAssoc (l r : Level).


Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.montgomery64_2e141m9_3limbs.Synthesis.

(* TODO : change this to field once field isomorphism happens *)
Definition mul :
  { mul : feBW_small -> feBW_small -> feBW_small
  | forall a b, phiM_small (mul a b) = F.mul (phiM_small a) (phiM_small b) }.
Proof.
  Set Ltac Profiling.
  Time synthesize_mul ().
  Show Ltac Profile.
Time Defined.

Print Assumptions mul.


Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.montgomery64_2e321m9_6limbs.Synthesis.

(* TODO : change this to field once field isomorphism happens *)
Definition mul :
  { mul : feBW_small -> feBW_small -> feBW_small
  | forall a b, phiM_small (mul a b) = F.mul (phiM_small a) (phiM_small b) }.
Proof.
  Set Ltac Profiling.
  Time synthesize_mul ().
  Show Ltac Profile.
Time Defined.

Print Assumptions mul.


(**
We show that the path space of the circle is the integers
 *)
Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.
Require Import UniMath.NumberSystems.Integers.

Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.Core.NaturalTransformations.
Require Import UniMath.CategoryTheory.Groupoids.
Require Import UniMath.CategoryTheory.Core.Isos.
Require Import UniMath.Bicategories.Core.Bicat.
Import Bicat.Notations.
Require Import UniMath.Bicategories.Morphisms.Adjunctions.
Require Import UniMath.Bicategories.Core.Examples.OneTypes.
Require Import UniMath.Bicategories.Colimits.Initial.

Require Import UniMath.Bicategories.PseudoFunctors.Display.Base.
Require Import UniMath.Bicategories.PseudoFunctors.Display.Map1Cells.
Require Import UniMath.Bicategories.PseudoFunctors.Display.Map2Cells.
Require Import UniMath.Bicategories.PseudoFunctors.Display.Identitor.
Require Import UniMath.Bicategories.PseudoFunctors.Display.Compositor.
Require Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.
Require Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.
Require Import UniMath.Bicategories.Transformations.PseudoTransformation.

Require Import prelude.all.
Require Import signature.hit_signature.
Require Import signature.hit.
Require Import algebra.one_types_polynomials.
Require Import algebra.one_types_endpoints.
Require Import algebra.one_types_homotopies.
Require Import algebra.groupoid_polynomials.
Require Import algebra.groupoid_endpoints.
Require Import algebra.groupoid_homotopies.
Require Import displayed_algebras.displayed_algebra.
Require Import initial_grpd_alg.W_poly.
Require Import initial_grpd_alg.initial_groupoid_algebra.
Require Import initial_grpd_alg.is_initial.
Require Import existence.hit_existence.
Require Import examples.circle.

Require Import fundamental_groups.loops.

Local Open Scope cat.
Local Open Scope hz.

(**
Initial groupoid algebra for the circle constructed in a special way.
We will use this conclude that the fundamental group of the circle is the integers
 *)
Definition circle_initial_algebra_precategory_data
  : precategory_data.
Proof.
  use make_precategory_data.
  - use make_precategory_ob_mor.
    + exact unit.
    + exact (λ _ _, hz).
  - exact (λ _, hzzero).
  - exact (λ _ _ _, hzplus).
Defined.

Definition circle_initial_algebra_is_precategory
  : is_precategory circle_initial_algebra_precategory_data.
Proof.
  use make_is_precategory.
  - exact (λ _ _, hzplusl0).
  - exact (λ _ _, hzplusr0).
  - exact (λ _ _ _ _ x y z, ! hzplusassoc x y z).
  - exact (λ _ _ _ _, hzplusassoc).
Qed.

Definition circle_initial_algebra_precategory
  : precategory.
Proof.
  use make_precategory.
  - exact circle_initial_algebra_precategory_data.
  - exact circle_initial_algebra_is_precategory.
Defined.

Definition circle_initial_algebra_homsets
  : has_homsets circle_initial_algebra_precategory.
Proof.
  intros x y.
  apply isasetsetquot.
Qed.

Definition circle_initial_algebra_category
  : category.
Proof.
  use make_category.
  - exact circle_initial_algebra_precategory.
  - exact circle_initial_algebra_homsets.
Defined.

Definition circle_initial_algebra_is_pregroupoid
  : is_pregroupoid circle_initial_algebra_category.
Proof.
  intros tt1 tt2 z.
  use make_is_z_isomorphism.
  - exact (hzsign z).
  - split.
    + exact (hzrminus z).
    + exact (hzlminus z).
Defined.

Definition circle_initial_algebra_carrier
  : groupoid.
Proof.
  use make_groupoid.
  - exact circle_initial_algebra_category.
  - exact circle_initial_algebra_is_pregroupoid.
Defined.

(** It forms a groupoid algebra *)
Definition circle_initial_algebra_base_data
  : functor_data
      (⦃ point_constr circle_signature ⦄ circle_initial_algebra_carrier : groupoid)
      (circle_initial_algebra_carrier).
Proof.
  use make_functor_data.
  - exact (λ x, x).
  - exact (λ _ _ _, hzzero).
Defined.

Definition circle_initial_algebra_base_is_functor
  : is_functor circle_initial_algebra_base_data.
Proof.
  split.
  - exact (λ _, idpath _).
  - exact (λ _ _ _ _ _, ! hzplusr0 _).
Qed.

Definition circle_initial_algebra_base
  : (⦃ point_constr circle_signature ⦄ circle_initial_algebra_carrier : groupoid)
    ⟶
    circle_initial_algebra_carrier.
Proof.
  use make_functor.
  - exact circle_initial_algebra_base_data.
  - exact circle_initial_algebra_base_is_functor.
Defined.

Definition circle_initial_prealgebra
  : hit_prealgebra_grpd circle_signature.
Proof.
  use make_hit_prealgebra_grpd.
  - exact circle_initial_algebra_carrier.
  - exact circle_initial_algebra_base.
Defined.

Definition circle_initial_algebra_loop_data
  : nat_trans_data
      (sem_endpoint_grpd_data_functor_data constr circle_initial_prealgebra)
      (sem_endpoint_grpd_data_functor_data constr circle_initial_prealgebra)
  := λ _, hzone.

Definition circle_initial_algebra_loop_is_nat_trans
  : is_nat_trans
      _ _
      circle_initial_algebra_loop_data.
Proof.
  exact (λ _ _ _, hzplusl0 _ @ ! hzplusr0 _).
Qed.

Definition circle_initial_algebra_loop
  : sem_endpoint_grpd_data_functor_data constr circle_initial_prealgebra
    ⟹
    sem_endpoint_grpd_data_functor_data constr circle_initial_prealgebra.
Proof.
  use make_nat_trans.
  - exact circle_initial_algebra_loop_data.
  - exact circle_initial_algebra_loop_is_nat_trans.
Defined.

Definition circle_initial_path_algebra
  : hit_path_algebra_grpd circle_signature.
Proof.
  use make_hit_path_algebra_grpd.
  - exact circle_initial_prealgebra.
  - exact (λ _, circle_initial_algebra_loop).
Defined.

Definition circle_initial_algebra
  : hit_algebra_grpd circle_signature.
Proof.
  use make_algebra_grpd.
  - exact circle_initial_path_algebra.
  - abstract (intro j ; induction j).
Defined.

(** The UMP for 1-cells *)
Local Notation "f ^ z" := (morph_power f z).

Section CircleInitialAlgUMPOne.
  Variable (G : hit_algebra_grpd circle_signature).

  Local Notation "'Gloop'" := (pr1 (alg_path_grpd G loop) tt).

  Definition circle_initial_algebra_ump_1_carrier_data_0
    : alg_carrier_grpd G
    := alg_constr_grpd G tt.

  Definition circle_initial_algebra_ump_1_carrier_data_1
             (z : hz)
    : alg_carrier_grpd G ⟦ circle_initial_algebra_ump_1_carrier_data_0 ,
                           circle_initial_algebra_ump_1_carrier_data_0 ⟧
    := Gloop ^ z.

  Definition circle_initial_algebra_ump_1_carrier_data
    : functor_data
        circle_initial_algebra_precategory_data
        (alg_carrier_grpd G).
  Proof.
    use make_functor_data.
    - exact (λ _, circle_initial_algebra_ump_1_carrier_data_0).
    - exact (λ _ _, circle_initial_algebra_ump_1_carrier_data_1).
  Defined.

  Definition circle_initial_algebra_ump_1_carrier_is_functor
    : is_functor circle_initial_algebra_ump_1_carrier_data.
  Proof.
    split.
    - exact (λ _, idpath _).
    - intros ? ? ?.
      cbn -[hz] ; unfold circle_initial_algebra_ump_1_carrier_data_1.
      intros f g.
      exact (morph_power_plus Gloop f g).
  Qed.

  Definition circle_initial_algebra_ump_1_carrier
    : circle_initial_algebra_carrier ⟶ alg_carrier_grpd G.
  Proof.
    use make_functor.
    - exact circle_initial_algebra_ump_1_carrier_data.
    - exact circle_initial_algebra_ump_1_carrier_is_functor.
  Defined.

  Definition circle_initial_algebra_ump_1_commute_data
    : nat_trans_data
        (functor_composite_data
           circle_initial_algebra_base_data
           circle_initial_algebra_ump_1_carrier_data)
        (functor_composite_data
           (poly_act_functor
              circle_point_constr
              circle_initial_algebra_ump_1_carrier)
           (alg_constr_grpd G)).
  Proof.
    intros x.
    induction x ; simpl.
    apply id₁.
  Defined.

  Definition circle_initial_algebra_ump_1_commute_is_nat_trans
    : is_nat_trans
        _ _
        circle_initial_algebra_ump_1_commute_data.
  Proof.
    intros x y f.
    induction x, y.
    simpl.
    cbn.
    rewrite !id_left.
    assert (f = idpath _) as p.
    { apply isapropunit. }
    rewrite p.
    exact (!(functor_id (alg_constr_grpd G : _ ⟶ _) _)).
  Qed.

  Definition circle_initial_algebra_ump_1_commute
    : functor_composite_data
        circle_initial_algebra_base_data
        circle_initial_algebra_ump_1_carrier_data
      ⟹
      functor_composite_data
        (poly_act_functor
           circle_point_constr
           circle_initial_algebra_ump_1_carrier)
        (alg_constr_grpd G).
  Proof.
    use make_nat_trans.
    - exact circle_initial_algebra_ump_1_commute_data.
    - exact circle_initial_algebra_ump_1_commute_is_nat_trans.
  Defined.

  Definition circle_initial_prealgebra_ump_1
    : pr11 circle_initial_algebra --> pr11 G.
  Proof.
    use make_hit_prealgebra_mor.
    - exact circle_initial_algebra_ump_1_carrier.
    - exact circle_initial_algebra_ump_1_commute.
  Defined.

  (** Might need to change once the definitions can be unfolded more *)
  Definition circle_initial_algebra_ump_1_path
             (j : path_label circle_signature)
             (x : unit)
    : # (pr11 circle_initial_prealgebra_ump_1)
        (circle_initial_algebra_loop_data x)
      · (pr112 circle_initial_prealgebra_ump_1) x
      =
      (pr112 circle_initial_prealgebra_ump_1) x · pr1 ((pr21 G) j) x.
  Proof.
    cbn.
    induction x, j.
    cbn.
    rewrite !id_right, id_left.
    apply idpath.
  Qed.

  Definition circle_initial_algebra_ump_1
    : circle_initial_algebra --> G.
  Proof.
    use make_algebra_map_grpd.
    use make_hit_path_alg_map_grpd.
    - exact circle_initial_prealgebra_ump_1.
    - exact circle_initial_algebra_ump_1_path.
  Defined.
End CircleInitialAlgUMPOne.

Definition morph_is_a_power_morph
           (f : circle_initial_algebra_carrier ⟦ tt , tt ⟧)
  : f = (hzone : circle_initial_algebra_carrier ⟦ _ , _ ⟧) ^ f.
Proof.
  revert f.
  use hz_ind.
  - cbn ; apply idpath.
  - simpl.
    intros n IHn.
    rewrite !nattohzandS.
    etrans.
    {
      apply maponpaths.
      exact IHn.
    }
    rewrite morph_power_plus.
    apply maponpaths_2.
    cbn ; apply idpath.
  - simpl.
    intros n IHn.
    rewrite !toℤneg_S.
    etrans.
    {
      apply maponpaths_2.
      exact IHn.
    }
    unfold hzminus.
    rewrite morph_power_plus.
    refine (maponpaths (λ z, z + _) _).
    apply idpath.
Qed.

Definition circle_alg_mor_on_loop
           {G₁ G₂ : hit_algebra_grpd circle_signature}
           (F : G₁ --> G₂)
  : # (pr111 F : _ ⟶ _) (alg_path_grpd G₁ loop tt) · (pr112 (pr11 F)) tt
    =
    (pr112 (pr11 F)) tt · alg_path_grpd G₂ loop tt.
Proof.
  pose (pr21 F loop) as m.
  simpl in m.
  pose (nat_trans_eq_pointwise m tt) as p.
  exact p.
Qed.

Section CircleInitialAlgUMPTwo.
  Variable (G : hit_algebra_grpd circle_signature)
           (F₁ F₂ : circle_initial_algebra --> G).

  Definition circle_initial_algebra_ump_2_carrier_data
    : nat_trans_data (pr111 (pr1 F₁)) (pr111 (pr1 F₂))
    := λ x, pr11 (pr211 F₁) x · grpd_inv (pr11 (pr211 F₂) x).

  Definition circle_initial_algebra_ump_2_is_nat_trans
    : is_nat_trans _ _ circle_initial_algebra_ump_2_carrier_data.
  Proof.
    intros x y.
    induction x, y.
    unfold circle_initial_algebra_ump_2_carrier_data.
    intro f.
    refine (assoc _ _ _ @ _).
    refine (!_) ; use move_grpd_inv_left.
    etrans.
    {
      apply maponpaths_2.
      etrans.
      {
        apply maponpaths.
        exact (morph_is_a_power_morph f).
      }
      apply functor_on_morpower.
    }
    etrans.
    {
      exact (power_swap (circle_alg_mor_on_loop F₁) f).
    }
    do 2 refine (_ @ assoc _ _ _).
    apply maponpaths.
    refine (!_).
    etrans.
    {
      apply maponpaths.
      etrans.
      {
        apply maponpaths_2.
        etrans.
        {
          apply maponpaths.
          exact (morph_is_a_power_morph f).
        }
        apply functor_on_morpower.
      }
      exact (power_swap (circle_alg_mor_on_loop F₂) f).
    }
    refine (assoc _ _ _ @ _ @ id_left _).
    apply maponpaths_2.
    refine (!_).
    use move_grpd_inv_right.
    exact (!(id_right _)).
  Qed.

  Definition circle_initial_algebra_ump_2_carrier
    : pr111 (pr1 F₁) ⟹ pr111 (pr1 F₂).
  Proof.
    use make_nat_trans.
    - exact circle_initial_algebra_ump_2_carrier_data.
    - exact circle_initial_algebra_ump_2_is_nat_trans.
  Defined.

  Definition circle_initial_algebra_ump_2
    : F₁ ==> F₂.
  Proof.
    simple refine (((_ ,, _) ,, λ _, tt) ,, tt).
    - exact circle_initial_algebra_ump_2_carrier.
    - abstract
        (use nat_trans_eq ;
         [ apply (pr1 (pr111 G))
         | simpl ;
           intro x ;
           unfold circle_initial_algebra_ump_2_carrier_data ;
           rewrite <- assoc ;
           apply maponpaths ;
           rewrite (functor_id (pr21 (pr1 G))) ;
           refine (!_) ;
           apply move_grpd_inv_right ;
           rewrite id_right ;
           apply idpath]).
  Defined.
End CircleInitialAlgUMPTwo.

Section CircleInitialAlgUMPEq.
  Variable (G : hit_algebra_grpd circle_signature)
           (F₁ F₂ : circle_initial_algebra --> G)
           (τ₁ τ₂ : F₁ ==> F₂).

  Definition circle_ump_eq
    : τ₁ = τ₂.
  Proof.
    use subtypePath.
    { intro ; apply isapropunit. }
    use subtypePath.
    { intro ; use impred ; intro ; apply isapropunit. }
    use subtypePath.
    { intro ; apply grpd_bicat. }
    use nat_trans_eq.
    { apply (pr1 (pr111 G)). }
    intro x ; induction x.
    pose (nat_trans_eq_pointwise (pr211 τ₁) tt) as p.
    pose (nat_trans_eq_pointwise (pr211 τ₂) tt) as q.
    cbn in p, q.
    rewrite (functor_id (pr21 (pr1 G))), id_right in p.
    rewrite (functor_id (pr21 (pr1 G))), id_right in q.
    pose (maponpaths (λ z, z · grpd_inv (pr11 (pr211 F₂) tt)) (p @ !q)) as r.
    simpl in r.
    refine (_ @ r @ _).
    - rewrite <- assoc.
      refine (!(id_right _) @ _).
      apply maponpaths.
      apply move_grpd_inv_left.
      rewrite id_left.
      apply idpath.
    - rewrite <- assoc.
      refine (!_).
      refine (!(id_right _) @ _).
      apply maponpaths.
      apply move_grpd_inv_left.
      rewrite id_left.
      apply idpath.
  Qed.
End CircleInitialAlgUMPEq.

Definition circle_initial_algebra_unique_maps
  : is_biinitial circle_initial_algebra.
Proof.
  use make_is_biinitial.
  - exact circle_initial_algebra_ump_1.
  - intros G f g.
    use make_invertible_2cell.
    + exact (circle_initial_algebra_ump_2 G f g).
    + apply hit_alg_is_invertible_2cell.
  - exact circle_ump_eq.
Defined.

(** Path space of the circle at base *)
Definition circle_path_space_base
  : UU
  := ((pr111 (initial_groupoid_algebra circle_signature) : groupoid)
        ⟦ poly_initial_alg circle_point_constr tt
        , poly_initial_alg circle_point_constr tt ⟧).

Definition circle_path_space_base_is_Z
  : circle_path_space_base ≃ hz.
Proof.
  pose (left_adjoint_equivalence_grpd_algebra_is_fully_faithful
          (biinitial_unique_adj_eqv
             circle_initial_algebra_unique_maps
             (initial_groupoid_algebra_is_initial _))
          (poly_initial_alg circle_point_constr tt)
          (poly_initial_alg circle_point_constr tt))
    as f.
  exact (make_weq _ f).
Defined.

Definition circle_path_space_encode_decode
  : circle_base circle = circle_base circle
    ≃
    circle_path_space_base
  := hit_path_space
       circle_signature
       (poly_initial_alg circle_point_constr tt)
       (poly_initial_alg circle_point_constr tt).

Definition circle_path_space_is_Z
  : circle_base circle = circle_base circle ≃ hz
  := (circle_path_space_base_is_Z ∘ circle_path_space_encode_decode)%weq.


Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.montgomery32_2e130m5_5limbs.Synthesis.

(* TODO : change this to field once field isomorphism happens *)
Definition mul :
  { mul : feBW_small -> feBW_small -> feBW_small
  | forall a b, phiM_small (mul a b) = F.mul (phiM_small a) (phiM_small b) }.
Proof.
  Set Ltac Profiling.
  Time synthesize_mul ().
  Show Ltac Profile.
Time Defined.

Print Assumptions mul.


Require Import rt.util.all.
Require Import rt.model.arrival.basic.arrival_sequence rt.model.arrival.basic.task rt.model.arrival.basic.task_arrival rt.model.arrival.basic.job.
Require Import rt.implementation.uni.susp.dynamic.task
               rt.implementation.uni.susp.dynamic.job.
From mathcomp Require Import ssreflect ssrbool ssrfun ssrnat eqtype seq div.

Module ConcreteArrivalSequence.

  Import Job ArrivalSequence ConcreteTask ConcreteJob SporadicTaskset TaskArrival.

  Section PeriodicArrivals.

    Variable ts: concrete_taskset.

    (* At any time arr_time, we release Some job of tsk if t is a multiple of the period,
       otherwise we release None. *)
    Definition add_job (arr_time: time) (tsk: concrete_task) :=
      if task_period tsk %| arr_time  then
        Some (Build_concrete_job (arr_time %/ task_period tsk) arr_time
                                 (task_cost tsk) (task_deadline tsk) tsk)
      else
        None.

    (* The arrival sequence at any time t is simply the partial map of add_job. *)
    Definition periodic_arrival_sequence (t: time) := pmap (add_job t) ts.

  End PeriodicArrivals.

  Section Proofs.

    (* Let ts be any concrete task set with valid parameters. *)
    Variable ts: concrete_taskset.
    Hypothesis H_valid_task_parameters:
      valid_sporadic_taskset task_cost task_period task_deadline ts.

    (* Regarding the periodic arrival sequence built from ts, we prove that...*)
    Let arr_seq := periodic_arrival_sequence ts.

    (* ... arrival times are consistent, ... *)
    Theorem periodic_arrivals_are_consistent:
      arrival_times_are_consistent job_arrival arr_seq.
    Proof.
      move => j t ARRj.
      rewrite /arrives_at mem_pmap in ARRj.
      move: ARRj => /mapP ARRj; destruct ARRj as [tsk IN SOME].
      by unfold add_job in *; desf.
    Qed.

    (* ... every job comes from the task set, ... *)
    Theorem periodic_arrivals_all_jobs_from_taskset:
      forall j,
        arrives_in arr_seq j ->
        job_task j \in ts.
    Proof.
      move => j [t ARRj].
      rewrite mem_pmap in ARRj.
      move: ARRj => /mapP ARRj; destruct ARRj as [tsk IN SOME].
      by unfold add_job in *; desf.
    Qed.

    (* ..., jobs have valid parameters, ... *)
    Theorem periodic_arrivals_valid_job_parameters:
      forall j,
        arrives_in arr_seq j ->
        valid_sporadic_job task_cost task_deadline job_cost job_deadline job_task j.
    Proof.
      rename H_valid_task_parameters into PARAMS.
      unfold valid_sporadic_taskset, is_valid_sporadic_task in *.
      move => j [t ARRj].
      rewrite mem_pmap in ARRj; move: ARRj => /mapP [tsk IN SOME].
      unfold add_job in SOME; desf.
      specialize (PARAMS tsk IN); des.
      unfold valid_sporadic_job, valid_realtime_job, job_cost_positive.
      by repeat split; try (by done); apply leqnn.
    Qed.

    (* ... job arrivals satisfy the sporadic task model, ... *)
    Theorem periodic_arrivals_are_sporadic:
      sporadic_task_model task_period job_arrival job_task arr_seq.
    Proof.
      move => j j' /eqP DIFF [arr ARR] [arr' ARR'] SAMEtsk LE.
      rewrite eqE /= /job_eqdef negb_and /= SAMEtsk eq_refl orbF in DIFF.
      rewrite 2!mem_pmap in ARR ARR'.
      move: ARR ARR' => /mapP [tsk_j INj SOMEj] /mapP [tsk_j' INj' SOMEj'].
      unfold add_job in SOMEj, SOMEj'; desf; simpl in *;
      move: Heq0 Heq => /dvdnP [k DIV] /dvdnP [k' DIV'].
      {
        rewrite DIV DIV' -mulSnr.
        rewrite leq_eqVlt in LE; move: LE => /orP [/eqP EQ | LESS].
        {
          exfalso; move: DIFF => /negP DIFF; apply DIFF.
          by subst; rewrite EQ !eq_refl.
        }
        subst; rewrite leq_mul2r; apply/orP; right.
        by rewrite ltn_mul2r in LESS; move: LESS => /andP [_ LT].
      }
    Qed.

    (* ... and the arrival sequence has no duplicate jobs. *)
    Theorem periodic_arrivals_is_a_set:
      arrival_sequence_is_a_set arr_seq.
    Proof.
      intros t.
      unfold arr_seq, periodic_arrival_sequence.
      apply (pmap_uniq) with (g := job_task); last by destruct ts.
      by unfold add_job, ocancel; intro tsk; desf.
    Qed.

  End Proofs.

End ConcreteArrivalSequence.


Require Export Basics.

(* ((Naming Cases)) *)

Require String. Open Scope string_scope.

Ltac move_to_top x :=
  match reverse goal with
    | H : _ |- _ => try move x after H
  end.

Tactic Notation "assert_eq" ident(x) constr(v) :=
  let H := fresh in
  assert (x = v) as H by reflexivity;
  clear H.

Tactic Notation "Case_aux" ident(x) constr(name) :=
  first [
    set (x := name); move_to_top x
  | assert_eq x name; move_to_top x
  | fail 1 "because we are working on a different case" ].

Tactic Notation "Case" constr(name) := Case_aux Case name.
Tactic Notation "SCase" constr(name) := Case_aux SCase name.
Tactic Notation "SSCase" constr(name) := Case_aux SSCase name.
Tactic Notation "SSSCase" constr(name) := Case_aux SSSCase name.
Tactic Notation "SSSSCase" constr(name) := Case_aux SSSSCase name.
Tactic Notation "SSSSSCase" constr(name) := Case_aux SSSSSCase name.
Tactic Notation "SSSSSSCase" constr(name) := Case_aux SSSSSSCase name.
Tactic Notation "SSSSSSSCase" constr(name) := Case_aux SSSSSSSCase name.

(* Exercise: 2 stars (andb_true_elim2) *)

Theorem andb_true_elim2 :
  forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros b c H.
  destruct c.
  Case "c = true".
    reflexivity.
  Case "c = false".
    rewrite <- H.
    destruct b.
      SCase "b = true".
        reflexivity.
      SCase "b = false".
        reflexivity.
Qed.

(* END andb_true_elim2. *)

(* ((Proof by Induction)) *)

Theorem plus_0_r : forall n : nat,
  n + 0 = n.
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite -> IHn'.
    reflexivity.
Qed.

(* Exercise: 2 stars (basic_induction) *)

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

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

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros n m.
  induction m as [|m'].
  Case "m = 0".
    rewrite -> plus_0_r.
    reflexivity.
  Case "m = S m'".
    simpl.
    rewrite <- IHm'.
    rewrite <- plus_n_Sm.
    reflexivity.
Qed.

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

(* END basic_induction. *)

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

(* Exercies: 2 starts (double_plus) *)

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

(* END double_plus. *)

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

(* Exercise: 2 stars, optional (evenb_S) *)

Lemma evenb_S_helper : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b.
  destruct b.
  - reflexivity.
  - reflexivity.
Qed.

Theorem evenb_S : forall n : nat,
  evenb (S n) = negb (evenb n).
Proof.
  intro n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    destruct n' as [|n''].
      reflexivity.
      rewrite -> IHn'.
      rewrite -> evenb_S_helper.
      reflexivity.
Qed.

(* END evenb_S. *)

(* Exercise: 1 star (destruct_induction) *)

(* `induction` is useful when dealing with inductive types: after proving the
* induction base, user is provided with a statement which assumes the
* correctness of the initial statement for a case of the previous inductive
* step. *)

(* END destruct_induction *)

(* Exercise: 4 stars (mult_comm) *)

Theorem plus_swap : forall n m p : nat,
   n + (m + p) = m + (n + p).
Proof.
   intros n m p.
   assert (H1: m + (n + p) = n + p + m).
     rewrite -> plus_comm.
     reflexivity.
   rewrite -> H1.
   assert (H2: m + p = p + m).
     rewrite -> plus_comm.
     reflexivity.
   rewrite -> H2.
   rewrite -> plus_assoc.
   reflexivity.
Qed.

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

Theorem mult_comm : forall m n : nat,
  m * n = n * m.
Proof.
  intros m n.
  induction m as [|m'].
  Case "m = 0".
    rewrite -> mult_0_r.
    reflexivity.
  Case "m = S m'".
    simpl.
    rewrite -> IHm'.
    rewrite -> mult_n_Sm.
    reflexivity.
Qed.

(* END mult_comm. *)

(* Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)

Theorem evenb_n__oddb_Sn : forall n : nat,
  evenb n = negb (evenb (S n)).
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite -> IHn'.
    rewrite -> negation_fn_applied_twice.
    reflexivity.
    SCase "negb x = negb x".
      reflexivity.
Qed.

(* END evenb_n__oddb_Sn. *)

(* (( More Excercises )) *)

(* Exercise: 3 stars, optional (more_exercises) *)

Theorem ble_nat_refl : forall n : nat,
  true = ble_nat n n.
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite <- IHn'.
    reflexivity.
Qed.

Theorem zero_nbeq_S : forall n : nat,
  beq_nat O (S n) = false.
Proof.
  reflexivity.
Qed.

Theorem andb_false_r : forall b : bool,
  andb b false = false.
Proof.
  destruct b.
  Case "b = true".
    reflexivity.
  Case "b = false".
    reflexivity.
Qed.

Theorem plus_ble_compat_l : forall n m p : nat,
  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.
Proof.
  intros n m p.
  intros H.
  induction p as [|p'].
  Case "p = 0".
    simpl.
    rewrite -> H.
    reflexivity.
  Case "p = S p'".
    simpl.
    rewrite -> IHp'.
    reflexivity.
Qed.

Theorem S_nbeq_0 : forall n : nat,
  beq_nat (S n) 0 = false.
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite <- IHn'.
    reflexivity.
Qed.

Theorem mult_1_l : forall n : nat,
  1 * n = n.
Proof.
  intros n.
  simpl.
  rewrite <- plus_0_r.
  reflexivity.
Qed.

Theorem excluded_middle : forall b : bool,
  orb b (negb b) = true.
Proof.
  destruct b.
  Case "b = true".
    reflexivity.
  Case "b = false".
    reflexivity.
Qed.

Theorem all3_spec : forall b c : bool,
  orb (andb b c) (orb (negb b) (negb c)) = true.
Proof.
  intros b c.
  destruct b.
  Case "b = true".
    simpl.
    rewrite -> excluded_middle.
    reflexivity.
  Case "b = false".
    reflexivity.
Qed.

Theorem mult_plus_distr_r : forall n m p : nat,
  (n + m) * p = (n * p) + (m * p).
Proof.
  intros n m p.
  induction p as [|p'].
  Case "p = 0".
    rewrite -> mult_0_r.
    rewrite -> mult_0_r.
    rewrite -> mult_0_r.
    reflexivity.
  Case "p = S p'".
    rewrite -> mult_n_Sm.
    rewrite -> mult_n_Sm.
    rewrite -> mult_n_Sm.
    rewrite -> IHp'.
    assert (H : m + (n * p' + m * p') = n * p' + (m + m * p')).
      rewrite -> plus_swap.
      reflexivity.
    rewrite <- plus_assoc.
    rewrite -> H.
    rewrite -> plus_assoc.
    reflexivity.
Qed.

Theorem mult_assoc : forall n m p : nat,
  n * (m * p) = (n * m) * p.
Proof.
  intros n m p.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite -> mult_plus_distr_r.
    rewrite -> IHn'.
    reflexivity.
Qed.

(* END more_exercises. *)

(* Exercise: 2 stars, optional (beq_nat_refl) *)

Theorem beq_nat_refl : forall n : nat,
  true = beq_nat n n.
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite <- IHn'.
    reflexivity.
Qed.

(* END beq_nat_refl. *)

(* Exercise: 2 stars, optional (plus_swap') *)

Theorem plus_swap' : forall n m p : nat,
   n + (m + p) = m + (n + p).
Proof.
   intros n m p.
   assert (H1: m + (n + p) = n + p + m).
     rewrite -> plus_comm.
     reflexivity.
   rewrite -> H1.
   replace (m + p) with (p + m).
   Case "continuing the proof".
     rewrite -> plus_assoc.
     reflexivity.
   Case "replacement m + p -> p + m".
     rewrite -> plus_comm.
     reflexivity.
Qed.

(* END plus_swap'. *)

(* Exercise: 3 stars (binary_commute) *)

Theorem bin_to_nat_pres_incr : forall b : bin,
  bin_to_nat (incr b) = S (bin_to_nat b).
Proof.
  intros b.
  induction b as [|p'|p'].
  Case "b = bO".
    reflexivity.
  Case "b = bD p'".
    reflexivity.
  Case "b = bT p'".
    simpl.
    rewrite -> IHp'.
    rewrite <- plus_n_Sm.
    reflexivity.
Qed.

(* END binary_commute. *)

(* Exercise: 5 stars, advanced (binary_inverse) *)

(* a) *)

Fixpoint nat_to_bin (n : nat) : bin :=
  match n with
    | O    => bO
    | S p' => incr (nat_to_bin p')
  end.

Theorem nat_to_bin_bin_to_nat_eq : forall n : nat,
  bin_to_nat (nat_to_bin n) = n.
Proof.
  intros n.
  induction n as [|n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite -> bin_to_nat_pres_incr.
    rewrite -> IHn'.
    reflexivity.
Qed.

(* b) *)

(* The problem lies in the fact that bO = bD bO = bD .. bD bO which creates a
* non-linear mapping from natural to binary numbers. *)

(* c) *)

Fixpoint dbl (b : bin) : bin :=
  match b with
    | bO => bO
    | b' => bD b'
  end.

Fixpoint normalize (b : bin) : bin :=
  match b with
    | bO => bO
    | bD p' => dbl (normalize p')
    | bT p' => bT (normalize p')
  end.

Theorem bin_normalize : forall b : bin,
  nat_to_bin (bin_to_nat b) = normalize b.
Proof.
  intros b.
  induction b as [|b'|b'].
  Case "b = bO".
    reflexivity.
  Case "b = bD b'".
    simpl.
    rewrite <- IHb'.
    assert (dbl_doubles : forall n : nat,
            nat_to_bin (n + n) = dbl (nat_to_bin n)).
      intros n.
      induction n as [|n'].
      SCase "n = 0".
        reflexivity.
      SCase "n = S n'".
        simpl.
        rewrite <- plus_n_Sm.
        simpl.
        rewrite -> IHn'.
        assert (H : forall b : bin, incr (incr (dbl b)) = dbl (incr b)).
          induction b as [|p|p].
          SSCase "b = bO".
            reflexivity.
          SSCase "b = bD p".
            reflexivity.
          SSCase "b = bT p".
            reflexivity.
        rewrite -> H.
        reflexivity.
    rewrite -> dbl_doubles.
    reflexivity.
  Case "b = bT b'".
    simpl.
    rewrite <- IHb'.
    assert (H: forall n : nat, incr (nat_to_bin (n + n)) = bT (nat_to_bin n)).
      induction n as [|n'].
      SCase "n = 0".
        reflexivity.
      SCase "n = S n'".
        rewrite <- plus_n_Sm.
        simpl.
        rewrite -> IHn'.
        reflexivity.
    rewrite -> H.
    reflexivity.
Qed.

(* END binary_inverse. *)


Load LFindLoad.
From lfind Require Import LFind.
Unset Printing Notations.
Set Printing Implicit.

Require Import Arith.

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

Inductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.

Inductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.

Inductive Pair : Type := mkpair : natural -> natural -> Pair
with Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.

Fixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst
           := match append_arg0, append_arg1 with
              | Nil, x => x
              | Cons x y, z => Cons x (append y z)
              end.

Fixpoint eqb (n m: natural) : bool :=
  match n, m with
    | Zero, Zero => true
    | Zero, Succ _ => false
    | Succ _, Zero => false
    | Succ n', Succ m' => eqb n' m'
  end.
Fixpoint mem  (mem_arg1 : lst) (mem_arg0 : natural)
:= match mem_arg0, mem_arg1 with
  | x, Nil => false
  | x, Cons y z => orb (eqb x y) (mem z x)
  end.

Theorem goal36 : forall (x : natural) (y : lst) (z : lst), mem y x = true -> mem (append y z) x = true.
Proof.
   intros.
   induction y.
   - simpl. destruct H.
Admitted.
      (* + auto.
      + apply IHy in H. auto.
   - contradiction.
Qed. *)

Theorem goal37 : forall (x : natural) (y : lst) (z : lst), mem z x = true -> mem (append y z) x = true.
Proof.
   intros.
   induction y.
   - simpl. rewrite IHy. apply Bool.orb_true_r.
   - auto.
Qed.

Theorem theorem0 : forall (x : natural) (y : lst) (z : lst), mem y x = true \/ mem z x = true -> mem (append y z) x = true.
Proof.
   intros.
   destruct H.
   -
lfind.  assumption.
Admitted.