Require Import Problem PeanoNat List Omega Permutation.
Import ListNotations.

Fixpoint sorted (xs : list nat) :=
  match xs with
  | nil => True
  | x :: ys =>
    match ys with
    | nil => True
    | y :: zs => x <= y /\ sorted ys
    end
  end.

Definition all (P : nat -> Prop) (xs : list nat) := fold_right and True (map P xs).
Definition upper_bound (n : nat) := all (fun x => x <= n).
Definition lower_bound (n : nat) := all (fun x => n <= x).

Lemma len_0_nil (xs : list nat) : length xs <= 0 -> xs = nil.
Proof.
  intros; apply length_zero_iff_nil; omega.
Qed.

Lemma perm_dig : forall x xs ys, Permutation (A:=nat) (x :: xs) ys -> exists zs ws, ys = zs ++ x :: ws.
Proof.
  intros.
  assert (In x ys) by (refine (Permutation_in _ H _); simpl; auto); clear H.
  induction ys; [inversion H0|].
  simpl in H0.
  destruct H0; [subst a; exists nil; exists ys; auto|].
  apply IHys in H; clear IHys.
  destruct H; destruct H.
  exists (a :: x0); exists x1.
  subst ys.
  auto.
Qed.

Lemma perm_all : forall P xs, all P xs -> forall ys, Permutation xs ys -> all P ys.
Proof.
  induction xs; intros.
  - apply Permutation_nil in H0.
    subst ys; simpl; auto.
  - unfold all in H; simpl in H; fold (all P xs) in H.
    destruct H.
    specialize (IHxs H1); clear H1.
    destruct (perm_dig a xs ys H0); destruct H1.
    subst ys.
    specialize (Permutation_middle x x0 a); intro.
    apply Permutation_sym in H1.
    apply (Permutation_trans H0) in H1; clear H0.
    apply Permutation_cons_inv in H1.
    apply IHxs in H1; clear IHxs.
    induction x; [simpl in H1; split; auto|].
    destruct H1.
    split; [|apply IHx]; auto.
Qed.

Lemma perm_upper : forall n xs, upper_bound n xs -> forall ys, Permutation xs ys -> upper_bound n ys.
Proof.
  intro; apply (perm_all _).
Qed.

Lemma perm_lower : forall n xs, lower_bound n xs -> forall ys, Permutation xs ys -> lower_bound n ys.
Proof.
  intro; apply (perm_all _).
Qed.

Lemma sorted_tail : forall x xs, sorted (x :: xs) -> sorted xs.
Proof.
  destruct xs; [auto|].
  intro H; destruct H.
  auto.
Qed.

Lemma sorted_app : forall xs n ys, upper_bound n xs -> lower_bound n ys ->
                                   sorted xs -> sorted ys -> sorted (xs ++ [n] ++ ys).
Proof.
  intros.
  induction xs; simpl.
  - destruct ys; [auto|].
    destruct H0; split; auto.
  - destruct H.
    destruct xs.
    * simpl.
      clear H3 H1; simpl in IHxs; specialize (IHxs I I).
      split; auto.
    * simpl; simpl in IHxs; simpl in H1.
      destruct H1.
      split; [auto|].
      fold (all (fun x : nat => x <= n) (n0 :: xs)) in H3.
      fold (upper_bound n (n0 :: xs)) in H3.
      apply IHxs; auto.
Qed.

Lemma filter_short (k : nat) (xs : list nat)
  : length xs <= k -> forall P, length (filter P xs) <= k.
Proof.
  intros.
  refine (Nat.le_trans _ _ _ _ H); clear k H.
  induction xs; simpl; [auto|].
  destruct (P a); simpl; omega.
Qed.

Lemma filter_split (P Q : nat -> bool) : (forall x, P x = negb (Q x)) -> forall xs, Permutation xs (filter P xs ++ filter Q xs).
Proof.
  intros.
  induction xs; simpl; [constructor|].
  rewrite H.
  destruct (Q a); simpl; [|apply perm_skip; auto].
  apply (perm_skip a) in IHxs.
  refine (Permutation_trans IHxs _).
  apply Permutation_middle.
Qed.

Definition lt_n (n : nat) := fun x => x <? n.
Definition ge_n (n : nat) := fun x => n <=? x.
Definition le_n (n : nat) := fun x => x <=? n.
Definition gt_n (n : nat) := fun x => n <? x.

Lemma boundary : forall n xs, upper_bound n (filter (lt_n n) xs) /\
                              upper_bound n (filter (le_n n) xs) /\
                              lower_bound n (filter (gt_n n) xs) /\
                              lower_bound n (filter (ge_n n) xs).
Proof.
  unfold upper_bound; unfold lower_bound; unfold all.
  unfold lt_n; unfold le_n; unfold gt_n; unfold ge_n.
  induction xs; simpl; [auto|].
  destruct IHxs; destruct H0; destruct H1.
  assert (C: a = n \/ a > n \/ a < n) by omega.
  destruct C; [subst|destruct H3;repeat rewrite Nat.ltb_antisym]; simpl.
  rewrite Nat.ltb_irrefl; rewrite Nat.leb_refl; simpl.
  repeat split; auto.
  all: repeat rewrite (proj2 (Nat.leb_gt _ _) H3).
  all: repeat rewrite (proj2 (Nat.leb_le _ _) (Nat.lt_le_incl _ _ H3)).
  all: simpl; repeat split; auto; omega.
Qed.

Lemma sort_mid : forall x ys z ws, sorted (x :: ys ++ z :: ws) -> x <= z.
Proof.
  induction ys; intros; destruct H; [auto|].
  destruct ys; [destruct H0; omega|].
  refine (IHys _ ws _); clear IHys.
  destruct H0.
  split; [omega|auto].
Qed.

Lemma qs1_inj : forall xs ys, quicksort1 xs ys -> quicksort1 xs ys \/ quicksort2 xs ys.
Proof.
  auto.
Qed.

Lemma qs2_inj : forall xs ys, quicksort2 xs ys -> quicksort1 xs ys \/ quicksort2 xs ys.
Proof.
  auto.
Qed.

Lemma qs1_split : forall n xs, Permutation xs (filter (lt_n n) xs ++ filter (ge_n n) xs).
Proof.
  intros.
  apply filter_split.
  apply Nat.ltb_antisym.
Qed.

Lemma qs2_split : forall n xs, Permutation xs (filter (le_n n) xs ++ filter (gt_n n) xs).
Proof.
  intros.
  apply filter_split.
  apply Nat.leb_antisym.
Qed.

Lemma qs_perm : forall xs ys, quicksort1 xs ys \/ quicksort2 xs ys -> Permutation xs ys.
Proof.
  intro; remember (length xs) as k.
  assert (length xs <= k) by omega; clear Heqk.
  revert xs H.
  induction k; intros.
  - apply len_0_nil in H; subst xs.
    destruct H0; inversion_clear H; auto.
  - destruct xs; [destruct H0; inversion_clear H0; auto|].
    simpl in H; assert (length xs <= k) by omega; clear H.
    destruct H0; inversion_clear H.
    all: refine (Permutation_trans _ (Permutation_middle _ _ _)).
    all: apply perm_skip.
    1: refine (Permutation_trans (qs1_split n xs) _).
    2: refine (Permutation_trans (qs2_split n xs) _).
    all: refine (Permutation_app _ _).
    all: apply IHk; [apply filter_short|]; auto.
Qed.

Lemma qs1_perm : forall xs ys, quicksort1 xs ys -> Permutation xs ys.
Proof.
  intros; apply qs_perm; auto.
Qed.

Lemma qs2_perm : forall xs ys, quicksort2 xs ys -> Permutation xs ys.
Proof.
  intros; apply qs_perm; auto.
Qed.

Lemma qs_sorted : forall xs ys, quicksort1 xs ys \/ quicksort2 xs ys -> sorted ys.
Proof.
  intro.
  remember (length xs) as k.
  assert (length xs <= k) by omega; clear Heqk.
  revert xs H.
  induction k; intros.
  - apply len_0_nil in H; subst xs.
    destruct H0; inversion_clear H; simpl; auto.
  - destruct xs; [destruct H0; inversion_clear H0; simpl; auto|].
    simpl in H; assert (length xs <= k) by omega; clear H.
    destruct H0; inversion_clear H; apply sorted_app.
    all: try clear l H0; try clear r H2.
    all: try rename l into zs; try rename H0 into H.
    all: try rename r into zs; try rename H2 into H.
    1,2: apply qs1_perm in H.
    5,6: apply qs2_perm in H.
    1,5: apply (perm_upper n) in H; [auto|].
    3,6: apply (perm_lower n) in H; [auto|].
    1-4: apply boundary.
    all: try apply qs1_inj in H; try apply qs2_inj in H.
    all: apply IHk in H; [auto|].
    all: apply filter_short; auto.
Qed.

Lemma low_head : forall x xs, sorted (x :: xs) -> lower_bound x (x :: xs).
Proof.
  unfold lower_bound; unfold all.
  induction xs; simpl; [auto|].
  intro H; destruct H.
  split; [auto|split;[auto|]].
  apply IHxs; clear IHxs.
  destruct xs; simpl; [auto|].
  split; [omega|destruct H0; auto].
Qed.

Lemma sort_uniq : forall xs ys, Permutation xs ys -> sorted xs -> sorted ys -> xs = ys.
Proof.
  induction xs; simpl; intros; [apply Permutation_nil in H; auto|].
  destruct (perm_dig a _ _ H); destruct H2.
  subst ys.
  destruct x.
  - simpl in H; apply Permutation_cons_inv in H.
    apply sorted_tail in H0.
    apply sorted_tail in H1.
    simpl; f_equal.
    apply IHxs; auto.
  - assert (a <= n).
    * specialize (low_head _ _ H0); intro.
      destruct (perm_lower _ _ H2 _ H); auto.
    * rewrite <- app_comm_cons in H1.
      assert (n <= a) by (apply sort_mid in H1; auto).
      assert (n = a) by omega; clear H2 H3.
      subst n; simpl; f_equal.
      apply sorted_tail in H0.
      apply sorted_tail in H1.
      simpl in H; apply Permutation_cons_inv in H.
      apply IHxs; auto.
Qed.

Theorem solution : task.
Proof.
  unfold task.
  intros.
  apply sort_uniq.
  - apply qs1_perm in H.
    apply qs2_perm in H0.
    apply Permutation_sym in H.
    apply (Permutation_trans H H0).
  - apply (qs_sorted x); auto.
  - apply (qs_sorted x); auto.
Qed.


Require Import Setoid.

Inductive mynat := z : mynat | s : mynat -> mynat.

Parameter E : mynat -> mynat -> Prop.
Axiom E_equiv : equiv mynat E.

Add Relation mynat E
 reflexivity proved by (proj1 E_equiv)
 symmetry proved by (proj2 (proj2 E_equiv))
 transitivity proved by (proj1 (proj2 E_equiv))
as E_rel.

Notation "x == y" := (E x y) (at level 70).

Goal z == s z -> s z == z. intros H. setoid_rewrite H at 2. reflexivity. Qed.


(** * MoreInd: More on Induction *)

Require Export "ProofObjects".

(* ##################################################### *)
(** * Induction Principles *)

(** This is a good point to pause and take a deeper look at induction
    principles.

    Every time we declare a new [Inductive] datatype, Coq
    automatically generates and proves an _induction principle_
    for this type.

    The induction principle for a type [t] is called [t_ind].  Here is
    the one for natural numbers: *)

Check nat_ind.
(*  ===> nat_ind :
           forall P : nat -> Prop,
              P 0  ->
              (forall n : nat, P n -> P (S n))  ->
              forall n : nat, P n  *)

(** *** *)
(** The [induction] tactic is a straightforward wrapper that, at
    its core, simply performs [apply t_ind].  To see this more
    clearly, let's experiment a little with using [apply nat_ind]
    directly, instead of the [induction] tactic, to carry out some
    proofs.  Here, for example, is an alternate proof of a theorem
    that we saw in the [Basics] chapter. *)

Theorem mult_0_r' : forall n:nat,
  n * 0 = 0.
Proof.
  apply nat_ind.
  Case "O". reflexivity.
  Case "S". simpl. intros n IHn. rewrite -> IHn.
    reflexivity.  Qed.

(** This proof is basically the same as the earlier one, but a
    few minor differences are worth noting.  First, in the induction
    step of the proof (the ["S"] case), we have to do a little
    bookkeeping manually (the [intros]) that [induction] does
    automatically.

    Second, we do not introduce [n] into the context before applying
    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,
    and [apply] needs this conclusion to exactly match the shape of
    the goal state, including the quantifier.  The [induction] tactic
    works either with a variable in the context or a quantified
    variable in the goal.

    Third, the [apply] tactic automatically chooses variable names for
    us (in the second subgoal, here), whereas [induction] lets us
    specify (with the [as...]  clause) what names should be used.  The
    automatic choice is actually a little unfortunate, since it
    re-uses the name [n] for a variable that is different from the [n]
    in the original theorem.  This is why the [Case] annotation is
    just [S] -- if we tried to write it out in the more explicit form
    that we've been using for most proofs, we'd have to write [n = S
    n], which doesn't make a lot of sense!  All of these conveniences
    make [induction] nicer to use in practice than applying induction
    principles like [nat_ind] directly.  But it is important to
    realize that, modulo this little bit of bookkeeping, applying
    [nat_ind] is what we are really doing. *)

(** **** Exercise: 2 stars, optional (plus_one_r') *)
(** Complete this proof as we did [mult_0_r'] above, without using
    the [induction] tactic. *)

Theorem plus_one_r' : forall n:nat,
  n + 1 = S n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** Coq generates induction principles for every datatype defined with
    [Inductive], including those that aren't recursive. (Although
    we don't need induction to prove properties of non-recursive
    datatypes, the idea of an induction principle still makes sense
    for them: it gives a way to prove that a property holds for all
    values of the type.)

    These generated principles follow a similar pattern. If we define a
    type [t] with constructors [c1] ... [cn], Coq generates a theorem
    with this shape:
    t_ind :
       forall P : t -> Prop,
            ... case for c1 ... ->
            ... case for c2 ... ->
            ...
            ... case for cn ... ->
            forall n : t, P n
    The specific shape of each case depends on the arguments to the
    corresponding constructor.  Before trying to write down a general
    rule, let's look at some more examples. First, an example where
    the constructors take no arguments: *)

Inductive yesno : Type :=
  | yes : yesno
  | no : yesno.

Check yesno_ind.
(* ===> yesno_ind : forall P : yesno -> Prop,
                      P yes  ->
                      P no  ->
                      forall y : yesno, P y *)

(** **** Exercise: 1 star, optional (rgb) *)
(** Write out the induction principle that Coq will generate for the
    following datatype.  Write down your answer on paper or type it
    into a comment, and then compare it with what Coq prints. *)

Inductive rgb : Type :=
  | red : rgb
  | green : rgb
  | blue : rgb.
Check rgb_ind.
(** [] *)

(** Here's another example, this time with one of the constructors
    taking some arguments. *)

Inductive natlist : Type :=
  | nnil : natlist
  | ncons : nat -> natlist -> natlist.

Check natlist_ind.
(* ===> (modulo a little variable renaming for clarity)
   natlist_ind :
      forall P : natlist -> Prop,
         P nnil  ->
         (forall (n : nat) (l : natlist), P l -> P (ncons n l)) ->
         forall n : natlist, P n *)

(** **** Exercise: 1 star, optional (natlist1) *)
(** Suppose we had written the above definition a little
   differently: *)

Inductive natlist1 : Type :=
  | nnil1 : natlist1
  | nsnoc1 : natlist1 -> nat -> natlist1.

(** Now what will the induction principle look like? *)
(** [] *)

(** From these examples, we can extract this general rule:

    - The type declaration gives several constructors; each
      corresponds to one clause of the induction principle.
    - Each constructor [c] takes argument types [a1]...[an].
    - Each [ai] can be either [t] (the datatype we are defining) or
      some other type [s].
    - The corresponding case of the induction principle
      says (in English):
        - "for all values [x1]...[xn] of types [a1]...[an], if [P]
           holds for each of the inductive arguments (each [xi] of
           type [t]), then [P] holds for [c x1 ... xn]".

*)

(** **** Exercise: 1 star, optional (byntree_ind) *)
(** Write out the induction principle that Coq will generate for the
    following datatype.  Write down your answer on paper or type it
    into a comment, and then compare it with what Coq prints. *)

Inductive byntree : Type :=
 | bempty : byntree
 | bleaf  : yesno -> byntree
 | nbranch : yesno -> byntree -> byntree -> byntree.
(** [] *)

(** **** Exercise: 1 star, optional (ex_set) *)
(** Here is an induction principle for an inductively defined
    set.
      ExSet_ind :
         forall P : ExSet -> Prop,
             (forall b : bool, P (con1 b)) ->
             (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) ->
             forall e : ExSet, P e
    Give an [Inductive] definition of [ExSet]: *)

Inductive ExSet : Type :=
  (* FILL IN HERE *)
.
(** [] *)

(** What about polymorphic datatypes?

    The inductive definition of polymorphic lists
      Inductive list (X:Type) : Type :=
        | nil : list X
        | cons : X -> list X -> list X.
    is very similar to that of [natlist].  The main difference is
    that, here, the whole definition is _parameterized_ on a set [X]:
    that is, we are defining a _family_ of inductive types [list X],
    one for each [X].  (Note that, wherever [list] appears in the body
    of the declaration, it is always applied to the parameter [X].)
    The induction principle is likewise parameterized on [X]:
     list_ind :
       forall (X : Type) (P : list X -> Prop),
          P [] ->
          (forall (x : X) (l : list X), P l -> P (x :: l)) ->
          forall l : list X, P l
   Note the wording here (and, accordingly, the form of [list_ind]):
   The _whole_ induction principle is parameterized on [X].  That is,
   [list_ind] can be thought of as a polymorphic function that, when
   applied to a type [X], gives us back an induction principle
   specialized to the type [list X]. *)

(** **** Exercise: 1 star, optional (tree) *)
(** Write out the induction principle that Coq will generate for
   the following datatype.  Compare your answer with what Coq
   prints. *)

Inductive tree (X:Type) : Type :=
  | leaf : X -> tree X
  | node : tree X -> tree X -> tree X.
Check tree_ind.
(** [] *)

(** **** Exercise: 1 star, optional (mytype) *)
(** Find an inductive definition that gives rise to the
    following induction principle:
      mytype_ind :
        forall (X : Type) (P : mytype X -> Prop),
            (forall x : X, P (constr1 X x)) ->
            (forall n : nat, P (constr2 X n)) ->
            (forall m : mytype X, P m ->
               forall n : nat, P (constr3 X m n)) ->
            forall m : mytype X, P m
*)
(** [] *)

(** **** Exercise: 1 star, optional (foo) *)
(** Find an inductive definition that gives rise to the
    following induction principle:
      foo_ind :
        forall (X Y : Type) (P : foo X Y -> Prop),
             (forall x : X, P (bar X Y x)) ->
             (forall y : Y, P (baz X Y y)) ->
             (forall f1 : nat -> foo X Y,
               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->
             forall f2 : foo X Y, P f2
*)
(** [] *)

(** **** Exercise: 1 star, optional (foo') *)
(** Consider the following inductive definition: *)

Inductive foo' (X:Type) : Type :=
  | C1 : list X -> foo' X -> foo' X
  | C2 : foo' X.

(** What induction principle will Coq generate for [foo']?  Fill
   in the blanks, then check your answer with Coq.)
     foo'_ind :
        forall (X : Type) (P : foo' X -> Prop),
              (forall (l : list X) (f : foo' X),
                    _______________________ ->
                    _______________________   ) ->
             ___________________________________________ ->
             forall f : foo' X, ________________________
*)

(** [] *)

(* ##################################################### *)
(** ** Induction Hypotheses *)

(** Where does the phrase "induction hypothesis" fit into this story?

    The induction principle for numbers
       forall P : nat -> Prop,
            P 0  ->
            (forall n : nat, P n -> P (S n))  ->
            forall n : nat, P n
   is a generic statement that holds for all propositions
   [P] (strictly speaking, for all families of propositions [P]
   indexed by a number [n]).  Each time we use this principle, we
   are choosing [P] to be a particular expression of type
   [nat->Prop].

   We can make the proof more explicit by giving this expression a
   name.  For example, instead of stating the theorem [mult_0_r] as
   "[forall n, n * 0 = 0]," we can write it as "[forall n, P_m0r
   n]", where [P_m0r] is defined as... *)

Definition P_m0r (n:nat) : Prop :=
  n * 0 = 0.

(** ... or equivalently... *)

Definition P_m0r' : nat->Prop :=
  fun n => n * 0 = 0.

(** Now when we do the proof it is easier to see where [P_m0r]
    appears. *)

Theorem mult_0_r'' : forall n:nat,
  P_m0r n.
Proof.
  apply nat_ind.
  Case "n = O". reflexivity.
  Case "n = S n'".
    (* Note the proof state at this point! *)
    intros n IHn.
    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.

(** This extra naming step isn't something that we'll do in
    normal proofs, but it is useful to do it explicitly for an example
    or two, because it allows us to see exactly what the induction
    hypothesis is.  If we prove [forall n, P_m0r n] by induction on
    [n] (using either [induction] or [apply nat_ind]), we see that the
    first subgoal requires us to prove [P_m0r 0] ("[P] holds for
    zero"), while the second subgoal requires us to prove [forall n',
    P_m0r n' -> P_m0r n' (S n')] (that is "[P] holds of [S n'] if it
    holds of [n']" or, more elegantly, "[P] is preserved by [S]").
    The _induction hypothesis_ is the premise of this latter
    implication -- the assumption that [P] holds of [n'], which we are
    allowed to use in proving that [P] holds for [S n']. *)

(* ##################################################### *)
(** ** More on the [induction] Tactic *)

(** The [induction] tactic actually does even more low-level
    bookkeeping for us than we discussed above.

    Recall the informal statement of the induction principle for
    natural numbers:
      - If [P n] is some proposition involving a natural number n, and
        we want to show that P holds for _all_ numbers n, we can
        reason like this:
          - show that [P O] holds
          - show that, if [P n'] holds, then so does [P (S n')]
          - conclude that [P n] holds for all n.
    So, when we begin a proof with [intros n] and then [induction n],
    we are first telling Coq to consider a _particular_ [n] (by
    introducing it into the context) and then telling it to prove
    something about _all_ numbers (by using induction).

    What Coq actually does in this situation, internally, is to
    "re-generalize" the variable we perform induction on.  For
    example, in our original proof that [plus] is associative...
*)

Theorem plus_assoc' : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  (* ...we first introduce all 3 variables into the context,
     which amounts to saying "Consider an arbitrary [n], [m], and
     [p]..." *)
  intros n m p.
  (* ...We now use the [induction] tactic to prove [P n] (that
     is, [n + (m + p) = (n + m) + p]) for _all_ [n],
     and hence also for the particular [n] that is in the context
     at the moment. *)
  induction n as [| n'].
  Case "n = O". reflexivity.
  Case "n = S n'".
    (* In the second subgoal generated by [induction] -- the
       "inductive step" -- we must prove that [P n'] implies
       [P (S n')] for all [n'].  The [induction] tactic
       automatically introduces [n'] and [P n'] into the context
       for us, leaving just [P (S n')] as the goal. *)
    simpl. rewrite -> IHn'. reflexivity.  Qed.

(** It also works to apply [induction] to a variable that is
   quantified in the goal. *)

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

(** Note that [induction n] leaves [m] still bound in the goal --
    i.e., what we are proving inductively is a statement beginning
    with [forall m].

    If we do [induction] on a variable that is quantified in the goal
    _after_ some other quantifiers, the [induction] tactic will
    automatically introduce the variables bound by these quantifiers
    into the context. *)

Theorem plus_comm'' : forall n m : nat,
  n + m = m + n.
Proof.
  (* Let's do induction on [m] this time, instead of [n]... *)
  induction m as [| m'].
  Case "m = O". simpl. rewrite -> plus_0_r. reflexivity.
  Case "m = S m'". simpl. rewrite <- IHm'.
    rewrite <- plus_n_Sm. reflexivity.  Qed.

(** **** Exercise: 1 star, optional (plus_explicit_prop) *)
(** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in
    the same style as [mult_0_r''] above -- that is, for each theorem,
    give an explicit [Definition] of the proposition being proved by
    induction, and state the theorem and proof in terms of this
    defined proposition.  *)

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

(** ** Generalizing Inductions. *)

(** One potentially confusing feature of the [induction] tactic is
that it happily lets you try to set up an induction over a term
that isn't sufficiently general.  The net effect of this will be
to lose information (much as [destruct] can do), and leave
you unable to complete the proof. Here's an example: *)

Lemma one_not_beautiful_FAILED: ~ beautiful 1.
Proof.
  intro H.
  (* Just doing an [inversion] on [H] won't get us very far in the [b_sum]
    case. (Try it!). So we'll need induction. A naive first attempt: *)
  induction H.
  (* But now, although we get four cases, as we would expect from
     the definition of [beautiful], we lose all information about [H] ! *)
Abort.

(** The problem is that [induction] over a Prop only works properly over
   completely general instances of the Prop, i.e. one in which all
   the arguments are free (unconstrained) variables.
   In this respect it behaves more
   like [destruct] than like [inversion].

   When you're tempted to do use [induction] like this, it is generally
   an indication that you need to be proving something more general.
   But in some cases, it suffices to pull out any concrete arguments
   into separate equations, like this: *)

Lemma one_not_beautiful: forall n, n = 1 -> ~ beautiful n.
Proof.
 intros n E H.
  induction H  as [| | | p q Hp IHp Hq IHq].
    Case "b_0".
      inversion E.
    Case "b_3".
      inversion E.
    Case "b_5".
      inversion E.
    Case "b_sum".
      (* the rest is a tedious case analysis *)
      destruct p as [|p'].
      SCase "p = 0".
        destruct q as [|q'].
        SSCase "q = 0".
          inversion E.
        SSCase "q = S q'".
          apply IHq. apply E.
      SCase "p = S p'".
        destruct q as [|q'].
        SSCase "q = 0".
          apply IHp.  rewrite plus_0_r in E. apply E.
        SSCase "q = S q'".
          simpl in E. inversion E.  destruct p'.  inversion H0.  inversion H0.
Qed.

(** There's a handy [remember] tactic that can generate the second
proof state out of the original one. *)

Lemma one_not_beautiful': ~ beautiful 1.
Proof.
  intros H.
  remember 1 as n eqn:E.
  (* now carry on as above *)
  induction H.
Admitted.

(* ####################################################### *)
(** * Informal Proofs (Advanced) *)

(** Q: What is the relation between a formal proof of a proposition
       [P] and an informal proof of the same proposition [P]?

    A: The latter should _teach_ the reader how to produce the
       former.

    Q: How much detail is needed??

    Unfortunately, There is no single right answer; rather, there is a
    range of choices.

    At one end of the spectrum, we can essentially give the reader the
    whole formal proof (i.e., the informal proof amounts to just
    transcribing the formal one into words).  This gives the reader
    the _ability_ to reproduce the formal one for themselves, but it
    doesn't _teach_ them anything.

   At the other end of the spectrum, we can say "The theorem is true
   and you can figure out why for yourself if you think about it hard
   enough."  This is also not a good teaching strategy, because
   usually writing the proof requires some deep insights into the
   thing we're proving, and most readers will give up before they
   rediscover all the same insights as we did.

   In the middle is the golden mean -- a proof that includes all of
   the essential insights (saving the reader the hard part of work
   that we went through to find the proof in the first place) and
   clear high-level suggestions for the more routine parts to save the
   reader from spending too much time reconstructing these
   parts (e.g., what the IH says and what must be shown in each case
   of an inductive proof), but not so much detail that the main ideas
   are obscured.

   Another key point: if we're comparing a formal proof of a
   proposition [P] and an informal proof of [P], the proposition [P]
   doesn't change.  That is, formal and informal proofs are _talking
   about the same world_ and they _must play by the same rules_. *)
(** ** Informal Proofs by Induction *)

(** Since we've spent much of this chapter looking "under the hood" at
    formal proofs by induction, now is a good moment to talk a little
    about _informal_ proofs by induction.

    In the real world of mathematical communication, written proofs
    range from extremely longwinded and pedantic to extremely brief
    and telegraphic.  The ideal is somewhere in between, of course,
    but while you are getting used to the style it is better to start
    out at the pedantic end.  Also, during the learning phase, it is
    probably helpful to have a clear standard to compare against.
    With this in mind, we offer two templates below -- one for proofs
    by induction over _data_ (i.e., where the thing we're doing
    induction on lives in [Type]) and one for proofs by induction over
    _evidence_ (i.e., where the inductively defined thing lives in
    [Prop]).  In the rest of this course, please follow one of the two
    for _all_ of your inductive proofs. *)

(** *** Induction Over an Inductively Defined Set *)

(** _Template_:

       - _Theorem_: <Universally quantified proposition of the form
         "For all [n:S], [P(n)]," where [S] is some inductively defined
         set.>

         _Proof_: By induction on [n].

           <one case for each constructor [c] of [S]...>

           - Suppose [n = c a1 ... ak], where <...and here we state
             the IH for each of the [a]'s that has type [S], if any>.
             We must show <...and here we restate [P(c a1 ... ak)]>.

             <go on and prove [P(n)] to finish the case...>

           - <other cases similarly...>                        []

    _Example_:

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

        _Proof_: By induction on [l].

        - Suppose [l = []].  We must show, for all numbers [n],
          that, if length [[] = n], then [index (S n) [] =
          None].

          This follows immediately from the definition of index.

        - Suppose [l = x :: l'] for some [x] and [l'], where
          [length l' = n'] implies [index (S n') l' = None], for
          any number [n'].  We must show, for all [n], that, if
          [length (x::l') = n] then [index (S n) (x::l') =
          None].

          Let [n] be a number with [length l = n].  Since
            length l = length (x::l') = S (length l'),
          it suffices to show that
            index (S (length l')) l' = None.
]]
          But this follows directly from the induction hypothesis,
          picking [n'] to be length [l'].  [] *)

(** *** Induction Over an Inductively Defined Proposition *)

(** Since inductively defined proof objects are often called
    "derivation trees," this form of proof is also known as _induction
    on derivations_.

    _Template_:

       - _Theorem_: <Proposition of the form "[Q -> P]," where [Q] is
         some inductively defined proposition (more generally,
         "For all [x] [y] [z], [Q x y z -> P x y z]")>

         _Proof_: By induction on a derivation of [Q].  <Or, more
         generally, "Suppose we are given [x], [y], and [z].  We
         show that [Q x y z] implies [P x y z], by induction on a
         derivation of [Q x y z]"...>

           <one case for each constructor [c] of [Q]...>

           - Suppose the final rule used to show [Q] is [c].  Then
             <...and here we state the types of all of the [a]'s
             together with any equalities that follow from the
             definition of the constructor and the IH for each of
             the [a]'s that has type [Q], if there are any>.  We must
             show <...and here we restate [P]>.

             <go on and prove [P] to finish the case...>

           - <other cases similarly...>                        []

    _Example_

       - _Theorem_: The [<=] relation is transitive -- i.e., for all
         numbers [n], [m], and [o], if [n <= m] and [m <= o], then
         [n <= o].

         _Proof_: By induction on a derivation of [m <= o].

           - Suppose the final rule used to show [m <= o] is
             [le_n]. Then [m = o] and we must show that [n <= m],
             which is immediate by hypothesis.

           - Suppose the final rule used to show [m <= o] is
             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].
             We must show that [n <= S o'].
             By induction hypothesis, [n <= o'].

             But then, by [le_S], [n <= S o'].  [] *)

(* ##################################################### *)
(** * Optional Material *)

(** The remainder of this chapter offers some additional details on
    how induction works in Coq, the process of building proof
    trees, and the "trusted computing base" that underlies
    Coq proofs.  It can safely be skimmed on a first reading.  (We
    recommend skimming rather than skipping over it outright: it
    answers some questions that occur to many Coq users at some point,
    so it is useful to have a rough idea of what's here.) *)

(* ##################################################### *)
(** ** Induction Principles in [Prop] *)

(** Earlier, we looked in detail at the induction principles that Coq
    generates for inductively defined _sets_.  The induction
    principles for inductively defined _propositions_ like [gorgeous]
    are a tiny bit more complicated.  As with all induction
    principles, we want to use the induction principle on [gorgeous]
    to prove things by inductively considering the possible shapes
    that something in [gorgeous] can have -- either it is evidence
    that [0] is gorgeous, or it is evidence that, for some [n], [3+n]
    is gorgeous, or it is evidence that, for some [n], [5+n] is
    gorgeous and it includes evidence that [n] itself is.  Intuitively
    speaking, however, what we want to prove are not statements about
    _evidence_ but statements about _numbers_.  So we want an
    induction principle that lets us prove properties of numbers by
    induction on evidence.

    For example, from what we've said so far, you might expect the
    inductive definition of [gorgeous]...
    Inductive gorgeous : nat -> Prop :=
         g_0 : gorgeous 0
       | g_plus3 : forall n, gorgeous n -> gorgeous (3+m)
       | g_plus5 : forall n, gorgeous n -> gorgeous (5+m).
    ...to give rise to an induction principle that looks like this...
    gorgeous_ind_max :
       forall P : (forall n : nat, gorgeous n -> Prop),
            P O g_0 ->
            (forall (m : nat) (e : gorgeous m),
               P m e -> P (3+m) (g_plus3 m e) ->
            (forall (m : nat) (e : gorgeous m),
               P m e -> P (5+m) (g_plus5 m e) ->
            forall (n : nat) (e : gorgeous n), P n e
    ... because:

     - Since [gorgeous] is indexed by a number [n] (every [gorgeous]
       object [e] is a piece of evidence that some particular number
       [n] is gorgeous), the proposition [P] is parameterized by both
       [n] and [e] -- that is, the induction principle can be used to
       prove assertions involving both a gorgeous number and the
       evidence that it is gorgeous.

     - Since there are three ways of giving evidence of gorgeousness
       ([gorgeous] has three constructors), applying the induction
       principle generates three subgoals:

         - We must prove that [P] holds for [O] and [b_0].

         - We must prove that, whenever [n] is a gorgeous
           number and [e] is an evidence of its gorgeousness,
           if [P] holds of [n] and [e],
           then it also holds of [3+m] and [g_plus3 n e].

         - We must prove that, whenever [n] is a gorgeous
           number and [e] is an evidence of its gorgeousness,
           if [P] holds of [n] and [e],
           then it also holds of [5+m] and [g_plus5 n e].

     - If these subgoals can be proved, then the induction principle
       tells us that [P] is true for _all_ gorgeous numbers [n] and
       evidence [e] of their gorgeousness.

    But this is a little more flexibility than we actually need or
    want: it is giving us a way to prove logical assertions where the
    assertion involves properties of some piece of _evidence_ of
    gorgeousness, while all we really care about is proving
    properties of _numbers_ that are gorgeous -- we are interested in
    assertions about numbers, not about evidence.  It would therefore
    be more convenient to have an induction principle for proving
    propositions [P] that are parameterized just by [n] and whose
    conclusion establishes [P] for all gorgeous numbers [n]:
       forall P : nat -> Prop,
          ... ->
             forall n : nat, gorgeous n -> P n
    For this reason, Coq actually generates the following simplified
    induction principle for [gorgeous]: *)

Check gorgeous_ind.
(* ===>  gorgeous_ind
     : forall P : nat -> Prop,
       P 0 ->
       (forall n : nat, gorgeous n -> P n -> P (3 + n)) ->
       (forall n : nat, gorgeous n -> P n -> P (5 + n)) ->
       forall n : nat, gorgeous n -> P n *)

(** In particular, Coq has dropped the evidence term [e] as a
    parameter of the the proposition [P], and consequently has
    rewritten the assumption [forall (n : nat) (e: gorgeous n), ...]
    to be [forall (n : nat), gorgeous n -> ...]; i.e., we no longer
    require explicit evidence of the provability of [gorgeous n]. *)

(** In English, [gorgeous_ind] says:

    - Suppose, [P] is a property of natural numbers (that is, [P n] is
      a [Prop] for every [n]).  To show that [P n] holds whenever [n]
      is gorgeous, it suffices to show:

      - [P] holds for [0],

      - for any [n], if [n] is gorgeous and [P] holds for
        [n], then [P] holds for [3+n],

      - for any [n], if [n] is gorgeous and [P] holds for
        [n], then [P] holds for [5+n]. *)

(** As expected, we can apply [gorgeous_ind] directly instead of using [induction]. *)

Theorem gorgeous__beautiful' : forall n, gorgeous n -> beautiful n.
Proof.
   intros.
   apply gorgeous_ind.
   Case "g_0".
       apply b_0.
   Case "g_plus3".
       intros.
       apply b_sum. apply b_3.
       apply H1.
   Case "g_plus5".
       intros.
       apply b_sum. apply b_5.
       apply H1.
   apply H.
Qed.

(** The precise form of an Inductive definition can affect the
    induction principle Coq generates.

For example, in [Logic], we have defined [<=] as: *)

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

(** This definition can be streamlined a little by observing that the
    left-hand argument [n] is the same everywhere in the definition,
    so we can actually make it a "general parameter" to the whole
    definition, rather than an argument to each constructor. *)

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

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

(** The second one is better, even though it looks less symmetric.
    Why?  Because it gives us a simpler induction principle. *)

Check le_ind.
(* ===>  forall (n : nat) (P : nat -> Prop),
           P n ->
           (forall m : nat, n <= m -> P m -> P (S m)) ->
           forall n0 : nat, n <= n0 -> P n0 *)

(** By contrast, the induction principle that Coq calculates for the
    first definition has a lot of extra quantifiers, which makes it
    messier to work with when proving things by induction.  Here is
    the induction principle for the first [le]: *)

(* le_ind :
     forall P : nat -> nat -> Prop,
     (forall n : nat, P n n) ->
     (forall n m : nat, le n m -> P n m -> P n (S m)) ->
     forall n n0 : nat, le n n0 -> P n n0 *)

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

(** **** Exercise: 2 stars, optional (foo_ind_principle) *)
(** Suppose we make the following inductive definition:
   Inductive foo (X : Set) (Y : Set) : Set :=
     | foo1 : X -> foo X Y
     | foo2 : Y -> foo X Y
     | foo3 : foo X Y -> foo X Y.
   Fill in the blanks to complete the induction principle that will be
   generated by Coq.
   foo_ind
        : forall (X Y : Set) (P : foo X Y -> Prop),
          (forall x : X, __________________________________) ->
          (forall y : Y, __________________________________) ->
          (________________________________________________) ->
           ________________________________________________

*)
(** [] *)

(** **** Exercise: 2 stars, optional (bar_ind_principle) *)
(** Consider the following induction principle:
   bar_ind
        : forall P : bar -> Prop,
          (forall n : nat, P (bar1 n)) ->
          (forall b : bar, P b -> P (bar2 b)) ->
          (forall (b : bool) (b0 : bar), P b0 -> P (bar3 b b0)) ->
          forall b : bar, P b
   Write out the corresponding inductive set definition.
   Inductive bar : Set :=
     | bar1 : ________________________________________
     | bar2 : ________________________________________
     | bar3 : ________________________________________.

*)
(** [] *)

(** **** Exercise: 2 stars, optional (no_longer_than_ind) *)
(** Given the following inductively defined proposition:
  Inductive no_longer_than (X : Set) : (list X) -> nat -> Prop :=
    | nlt_nil  : forall n, no_longer_than X [] n
    | nlt_cons : forall x l n, no_longer_than X l n ->
                               no_longer_than X (x::l) (S n)
    | nlt_succ : forall l n, no_longer_than X l n ->
                             no_longer_than X l (S n).
  write the induction principle generated by Coq.
  no_longer_than_ind
       : forall (X : Set) (P : list X -> nat -> Prop),
         (forall n : nat, ____________________) ->
         (forall (x : X) (l : list X) (n : nat),
          no_longer_than X l n -> ____________________ ->
                                  _____________________________ ->
         (forall (l : list X) (n : nat),
          no_longer_than X l n -> ____________________ ->
                                  _____________________________ ->
         forall (l : list X) (n : nat), no_longer_than X l n ->
           ____________________

*)
(** [] *)

(* ##################################################### *)
(** ** Induction Principles for other Logical Propositions *)

(** Similarly, in [Logic] we have defined [eq] as: *)

(* Inductive eq (X:Type) : X -> X -> Prop :=
       refl_equal : forall x, eq X x x. *)

(** In the Coq standard library, the definition of equality is
    slightly different: *)

Inductive eq' (X:Type) (x:X) : X -> Prop :=
    refl_equal' : eq' X x x.

(** The advantage of this definition is that the induction
    principle that Coq derives for it is precisely the familiar
    principle of _Leibniz equality_: what we mean when we say "[x] and
    [y] are equal" is that every property on [P] that is true of [x]
    is also true of [y].  *)

Check eq'_ind.
(* ===>
     forall (X : Type) (x : X) (P : X -> Prop),
       P x -> forall y : X, x =' y -> P y

   ===>  (i.e., after a little reorganization)
     forall (X : Type) (x : X) forall y : X,
       x =' y ->
       forall P : X -> Prop, P x -> P y *)

(** The induction principles for conjunction and disjunction are a
    good illustration of Coq's way of generating simplified induction
    principles for [Inductive]ly defined propositions, which we
    discussed above.  You try first: *)

(** **** Exercise: 1 star, optional (and_ind_principle) *)
(** See if you can predict the induction principle for conjunction. *)

(* Check and_ind. *)
(** [] *)

(** **** Exercise: 1 star, optional (or_ind_principle) *)
(** See if you can predict the induction principle for disjunction. *)

(* Check or_ind. *)
(** [] *)

Check and_ind.

(** From the inductive definition of the proposition [and P Q]
     Inductive and (P Q : Prop) : Prop :=
       conj : P -> Q -> (and P Q).
    we might expect Coq to generate this induction principle
     and_ind_max :
       forall (P Q : Prop) (P0 : P /\ Q -> Prop),
            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->
            forall a : P /\ Q, P0 a
    but actually it generates this simpler and more useful one:
     and_ind :
       forall P Q P0 : Prop,
            (P -> Q -> P0) ->
            P /\ Q -> P0
    In the same way, when given the inductive definition of [or P Q]
     Inductive or (P Q : Prop) : Prop :=
       | or_introl : P -> or P Q
       | or_intror : Q -> or P Q.
    instead of the "maximal induction principle"
     or_ind_max :
       forall (P Q : Prop) (P0 : P \/ Q -> Prop),
            (forall a : P, P0 (or_introl P Q a)) ->
            (forall b : Q, P0 (or_intror P Q b)) ->
            forall o : P \/ Q, P0 o
    what Coq actually generates is this:
     or_ind :
       forall P Q P0 : Prop,
            (P -> P0) ->
            (Q -> P0) ->
            P \/ Q -> P0
]]
*)

(** **** Exercise: 1 star, optional (False_ind_principle) *)
(** Can you predict the induction principle for falsehood? *)

(* Check False_ind. *)
(** [] *)

(** Here's the induction principle that Coq generates for existentials: *)

Check ex_ind.
(* ===>  forall (X:Type) (P: X->Prop) (Q: Prop),
         (forall witness:X, P witness -> Q) ->
          ex X P ->
           Q *)

(** This induction principle can be understood as follows: If we have
         a function [f] that can construct evidence for [Q] given _any_
        witness of type [X] together with evidence that this witness has
        property [P], then from a proof of [ex X P] we can extract the
        witness and evidence that must have been supplied to the
        constructor, give these to [f], and thus obtain a proof of [Q]. *)

(* ######################################################### *)
(** ** Explicit Proof Objects for Induction *)

(** Although tactic-based proofs are normally much easier to
    work with, the ability to write a proof term directly is sometimes
    very handy, particularly when we want Coq to do something slightly
    non-standard.  *)

(** Recall the induction principle on naturals that Coq generates for
    us automatically from the Inductive declation for [nat]. *)

Check nat_ind.
(* ===>
   nat_ind : forall P : nat -> Prop,
      P 0 ->
      (forall n : nat, P n -> P (S n)) ->
      forall n : nat, P n  *)

(** There's nothing magic about this induction lemma: it's just
   another Coq lemma that requires a proof.  Coq generates the proof
   automatically too...  *)

Print nat_ind.
Print nat_rect.
(* ===> (after some manual inlining and tidying)
   nat_ind =
    fun (P : nat -> Prop)
        (f : P 0)
        (f0 : forall n : nat, P n -> P (S n)) =>
          fix F (n : nat) : P n :=
             match n with
            | 0 => f
            | S n0 => f0 n0 (F n0)
            end.
*)

(** We can read this as follows:
     Suppose we have evidence [f] that [P] holds on 0,  and
     evidence [f0] that [forall n:nat, P n -> P (S n)].
     Then we can prove that [P] holds of an arbitrary nat [n] via
     a recursive function [F] (here defined using the expression
     form [Fix] rather than by a top-level [Fixpoint]
     declaration).  [F] pattern matches on [n]:
      - If it finds 0, [F] uses [f] to show that [P n] holds.
      - If it finds [S n0], [F] applies itself recursively on [n0]
         to obtain evidence that [P n0] holds; then it applies [f0]
         on that evidence to show that [P (S n)] holds.
    [F] is just an ordinary recursive function that happens to
    operate on evidence in [Prop] rather than on terms in [Set].

*)

(**  We can adapt this approach to proving [nat_ind] to help prove
    _non-standard_ induction principles too.  Recall our desire to
    prove that

    [forall n : nat, even n -> ev n].

    Attempts to do this by standard induction on [n] fail, because the
    induction principle only lets us proceed when we can prove that
    [even n -> even (S n)] -- which is of course never provable.  What
    we did in [Logic] was a bit of a hack:

    [Theorem even__ev : forall n : nat,
     (even n -> ev n) /\ (even (S n) -> ev (S n))].

    We can make a much better proof by defining and proving a
    non-standard induction principle that goes "by twos":

 *)

 Definition nat_ind2 :
    forall (P : nat -> Prop),
    P 0 ->
    P 1 ->
    (forall n : nat, P n -> P (S(S n))) ->
    forall n : nat , P n :=
       fun P => fun P0 => fun P1 => fun PSS =>
          fix f (n:nat) := match n with
                             0 => P0
                           | 1 => P1
                           | S (S n') => PSS n' (f n')
                          end.

 (** Once you get the hang of it, it is entirely straightforward to
     give an explicit proof term for induction principles like this.
     Proving this as a lemma using tactics is much less intuitive (try
     it!).

     The [induction ... using] tactic variant gives a convenient way to
     specify a non-standard induction principle like this. *)

Lemma even__ev' : forall n, even n -> ev n.
Proof.
 intros.
 induction n as [ | |n'] using nat_ind2.
  Case "even 0".
    apply ev_0.
  Case "even 1".
    inversion H.
  Case "even (S(S n'))".
    apply ev_SS.
    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H.
Qed.

(* ######################################################### *)
(** ** The Coq Trusted Computing Base *)

(** One issue that arises with any automated proof assistant is "why
    trust it?": what if there is a bug in the implementation that
    renders all its reasoning suspect?

    While it is impossible to allay such concerns completely, the fact
    that Coq is based on the Curry-Howard correspondence gives it a
    strong foundation. Because propositions are just types and proofs
    are just terms, checking that an alleged proof of a proposition is
    valid just amounts to _type-checking_ the term.  Type checkers are
    relatively small and straightforward programs, so the "trusted
    computing base" for Coq -- the part of the code that we have to
    believe is operating correctly -- is small too.

    What must a typechecker do?  Its primary job is to make sure that
    in each function application the expected and actual argument
    types match, that the arms of a [match] expression are constructor
    patterns belonging to the inductive type being matched over and
    all arms of the [match] return the same type, and so on.

    There are a few additional wrinkles:

    - Since Coq types can themselves be expressions, the checker must
      normalize these (by using the computation rules) before
      comparing them.

    - The checker must make sure that [match] expressions are
      _exhaustive_.  That is, there must be an arm for every possible
      constructor.  To see why, consider the following alleged proof
      object:
      Definition or_bogus : forall P Q, P \/ Q -> P :=
        fun (P Q : Prop) (A : P \/ Q) =>
           match A with
           | or_introl H => H
           end.
      All the types here match correctly, but the [match] only
      considers one of the possible constructors for [or].  Coq's
      exhaustiveness check will reject this definition.

    - The checker must make sure that each [fix] expression
      terminates.  It does this using a syntactic check to make sure
      that each recursive call is on a subexpression of the original
      argument.  To see why this is essential, consider this alleged
      proof:
          Definition nat_false : forall (n:nat), False :=
             fix f (n:nat) : False := f n.
      Again, this is perfectly well-typed, but (fortunately) Coq will
      reject it. *)

(** Note that the soundness of Coq depends only on the correctness of
    this typechecking engine, not on the tactic machinery.  If there
    is a bug in a tactic implementation (and this certainly does
    happen!), that tactic might construct an invalid proof term.  But
    when you type [Qed], Coq checks the term for validity from
    scratch.  Only lemmas whose proofs pass the type-checker can be
    used in further proof developments.  *)

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


From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.

Set Implicit Arguments.

Module MyNamespace.

(** Euclidean division: returns quotient and reminder  *)

(** Type constructors, Product type *)

Section ProductType.

Inductive prod (A B : Type) : Type :=
  | pair of A & B.

About pair.

(** Explicit binding of type constructor's parameters for
    data constructors
  *)
Check pair 42 true : prod nat bool.

(** Implicit arguments;
    local deactivation of implicit arguments (@)
 *)

Fail Check pair nat bool 42 true : prod nat bool.  (* inconvenient *)
Check @pair nat bool 42 true.

(** Notations for better UX *)

Notation "A * B" := (prod A B) (at level 40, left associativity) : type_scope.

(** Notation scopes *)

Fail Check nat * bool.

Check (nat * nat)%type.

Check (nat * bool) : Type.

Open Scope type_scope.
Check (nat * nat).
Close Scope type_scope.
Fail Check (nat * nat).

(** Left / right associativity *)
Check ((nat * bool) * nat)%type.

Check (nat * (bool * nat))%type.

(** Weak notation *)
Notation "( p ; q )" := (pair p q).

(** Triples, quadruples, ... ? *)

(** Recursive notations *)

Notation "( p , q , .. , r )" := (pair .. (pair p q) .. r)
                                   : core_scope.

Check (1, false) : nat * bool.

Unset Printing Notations.
Check (1, false) : nat * bool.
Set Printing Notations.

Definition fst {A B : Type} : A * B -> A :=
  (* fun p => match p with | pair a b => a end. *)
  (* fun p => let (a, b) := p in a. *)
  fun '(a, _) => a.

Notation "p .1" := (fst p).

Definition snd {A B : Type} : A * B -> B :=
  fun '(a, b) => b.

Notation "p .2" := (snd p).

Definition swap {A B : Type} : A * B -> B * A :=
  fun '(a,b) => (b,a).

End ProductType.

(**
      A /\ B -> B /\ A
 *)

Check fst.
Check snd.
Check @pair _ _.

Section Intuitionistic_Propositional_Logic.

(** Implication *)

Definition A_implies_A (A : Prop) :
  A -> A
:=
  fun proof_A : A => proof_A.

Definition A_implies_B_implies_A (A B : Prop) :
  A -> B -> A
:=
  fun proof_A => fun proof_B => proof_A.
(* const *)

(** Conjunction *)

Inductive and (A B : Prop) : Prop :=
  | conj of A & B.

Notation "A /\ B" := (and A B) : type_scope.

Definition andC (A B : Prop) :
  A /\ B -> B /\ A
:=
  fun '(conj proof_A proof_B) => conj proof_B proof_A.

Definition andA (A B C : Prop) :
  (A /\ B) /\ C -> A /\ (B /\ C)
:=
  fun '(conj (conj a b) c) => conj a (conj b c).

(** Biimplication, a.k.a. if and only if *)

Definition iff (A B : Prop) : Prop :=
  (A -> B) /\ (B -> A).

Notation "A <-> B" := (iff A B) : type_scope.

Definition andA_iff (A B C : Prop) :
  (A /\ B) /\ C <-> A /\ (B /\ C)
:=
  conj
    (fun '(conj (conj a b) c) => conj a (conj b c))
    (fun '(conj a (conj b c)) => (conj (conj a b) c)).

(** Disjunction *)

Inductive or (A B : Prop) : Prop :=
| or_introl of A
| or_intror of B.

Arguments or_introl [A B] a, [A] B a.
Arguments or_intror [A B] b, A [B] b.

Notation "A \/ B" := (or A B) : type_scope.

Definition or1 (A B : Prop) : A -> A \/ B
  :=
fun proofA => or_introl proofA.

Definition orC A B :
  A \/ B -> B \/ A
:=
  fun a_or_b =>
    match a_or_b with
    | or_introl proofA => or_intror proofA
    | or_intror proofB => or_introl proofB
    end.

Definition or_and_distr A B C :
  (A \/ B) /\ C -> (A /\ C) \/ (B /\ C)
:=
  fun '(conj a_or_b c) =>
    match a_or_b with
    | or_introl a => or_introl (conj a c)
    | or_intror b => or_intror (conj b c)
    end.

Inductive False : Prop := .

Inductive True : Prop :=
  | I.

Definition t : True
  :=
I.

Definition t_and_t : True /\ True
  :=
conj I I.

Definition not (A : Prop) :=
  A -> False.

Notation "~ A" := (not A) : type_scope.

Definition A_implies_not_not_A (A : Prop) :
   A -> ~ ~ A
(* A -> (A -> False) -> False *)
:=
  fun a => fun not_a => not_a a.

(* Double negation elimination is
   not provable in Intuitionistic Logic *)
Fail Definition DNE (A : Prop) :
   ~ ~ A -> A
:=
  fun nna => __.  (* can't call [nna] *)

(* Since the Law of Excluded Middle
   is equivalent to DNE it's not provable
   either
 *)
Fail Definition LEM (A : Prop) :
   A \/ ~A
:=
  (* or_intror (fun a => ???). *)
  __. (* or_introl / or_intror ? *)

End Intuitionistic_Propositional_Logic.

Section Propositional_Equality.

Inductive eq (A : Type)
             (a : A) : A -> Prop :=
| eq_refl : eq a a.
Check eq_ind.

About eq.
Check eq_refl 1 : eq 1 1.
Fail Check eq_refl 1 : eq 1 21.

Check @eq_refl nat 2 : @eq nat 2 2.
Fail Check eq_refl 1 : @eq nat 1 2.
Fail Check eq_refl 2 : @eq nat 1 2.

Notation "a = b" := (eq a b) : type_scope.

Definition eq_reflexive A (x : A) :
  x = x
:=
  eq_refl x.

(* dependent pattern matching *)
Definition eq_sym A (x y : A) :
  x = y -> y = x
:=
  fun proof_x_eq_y =>
    match proof_x_eq_y with
    | eq_refl => eq_refl x
    end.

Definition eq_foo (x y z : nat) :
  x + y = y + z -> (x + y) + z = (y + z) + z
:=
  fun prf_eq =>
    match prf_eq with
    | eq_refl => eq_refl ((x + y) + z)
    end.

Definition eq_trans A (x y z : A) :
  x = y -> (y = z -> x = z)
:=
  fun x_eq_y : x = y =>
    match x_eq_y with
    | eq_refl => id
    end.

End Propositional_Equality.

End MyNamespace.

(** The SSReflect proof language *)

Lemma A_implies_A (A : Prop) :
  A -> A.
Proof. (* <-- optional *)
Show Proof.
move => a.   (* tactical *)
Show Proof.
(* move: a. exact. *)
exact: a.
Show Proof.
(* by []. *)
Qed.

Lemma or_and_distr A B C :
  (A \/ B) /\ C -> A /\ C \/ B /\ C.
Proof.
case.
case.
- move=> a. move=> c. left. split.
  - exact: a.
  by apply: c.
move=> b c. right. by split.
Qed.

About or_and_distr.

(* a terser version *)
Lemma or_and_distr' A B C :
  (A \/ B) /\ C -> A /\ C \/ B /\ C.
Proof.
by move=> [[a | b] c]; [left | right].
Qed.

(* An example taken from
"An Ssreflect Tutorial" by G.Gonthier, R.S. Le(2009)
 *)
Section HilbertSaxiom.

Variables A B C : Prop.

Lemma HilbertS :
  (A -> B -> C) -> (A -> B) -> A -> C.
Proof.
move=> hAiBiC hAiB hA.
move: hAiBiC.
apply.
- by [].
by apply: hAiB.
Qed.

End HilbertSaxiom.

Section Rewrite.

Variable A : Type.
Implicit Types x y z : A.

Lemma eq_reflexive x :
  x = x.
Proof. by []. Qed.

Lemma eq_sym x y :
  x = y -> y = x.
Proof.
move=> x_eq_y. rewrite -x_eq_y. by [].
Show Proof.
Qed.
Eval compute in eq_sym.

Lemma eq_sym_shorter x y :
  x = y -> y = x.
Proof.
by move=> ->.
Qed.

Lemma eq_trans x y z :
  x = y -> y = z -> x = z.
Proof.
move=> ->->.
apply: eq_reflexive.
Qed.


Require Import FOL Deduction Tarski DecidabilityFacts Synthetic NumberTheory.
Require Import List Lia.
Import Vector.VectorNotations.

Require Import Equations.Equations Equations.Prop.DepElim.

(* For Definitions, my reference was the treatment of Peter Smith in "Introduction to Gödel's Theorems"
 (page 37) *)

Existing Instance falsity_on.

(** * Peano Arithmetic *)

(** Non-logical symbols used in the language of PA *)

Inductive PA_funcs : Type :=
  Zero : PA_funcs
| Succ : PA_funcs
| Plus : PA_funcs
| Mult : PA_funcs.

Definition PA_funcs_ar (f : PA_funcs ) :=
match f with
 | Zero => 0
 | Succ => 1
 | Plus => 2
 | Mult => 2
 end.

Inductive PA_preds : Type := .

Definition PA_preds_ar (P : PA_preds) :=
match P with
 | _ => 0
end.

Instance PA_funcs_signature : funcs_signature :=
{| syms := PA_funcs ; ar_syms := PA_funcs_ar |}.

Instance PA_preds_signature : preds_signature :=
{| preds := PA_preds ; ar_preds := PA_preds_ar |}.

Arguments Vector.cons {_} _ {_} _, _ _ _ _.

Declare Scope PA_Notation.
Open Scope PA_Notation.

Notation "'zero'" := (func Zero ([])) (at level 1) : PA_Notation.
Notation "'σ' x" := (func Succ ([x])) (at level 37) : PA_Notation.
Notation "x '⊕' y" := (func Plus ([x ; y]) ) (at level 39) : PA_Notation.
Notation "x '⊗' y" := (func Mult ([x ; y]) ) (at level 38) : PA_Notation.
Notation "x '==' y" := (eq x y) (at level 40) : PA_Notation.
(* Definition syntac_less (x y : term) := (∃ y[↑] == σ (x[↑] ⊕ $0)) : PA_Notation. *)
Definition sless x y := (∃ y`[↑] == σ (x`[↑] ⊕ $0)).
Notation "x '⧀' y" := (sless x y)  (at level 40) : PA_Notation.

Fact unfold_sless x y :
  sless x y = ∃ y`[↑] == σ (x`[↑] ⊕ $0).
Proof.
reflexivity.
Qed.

Fact sless_subst x y s :
  (sless x y)[s] = sless (x`[s]) (y`[s]).
Proof.
cbn. now rewrite !up_term.
Qed.

(* Defines numerals i.e. a corresponding term for every natural number *)
Fixpoint num n :=
  match n with
    O => zero
  | S x => σ (num x)
  end.

Definition forall_times n (phi : form) := iter (fun psi => ∀ psi) n phi.

(** ** PA Axioms *)

(** Basic Axioms *)

Definition ax_zero_succ := ∀  (zero == σ var 0 --> ⊥).
Definition ax_succ_inj :=  ∀∀ (σ $1 == σ $0 --> $1 == $0).
Definition ax_add_zero :=  ∀  (zero ⊕ $0 == $0).
Definition ax_add_rec :=   ∀∀ ((σ $0) ⊕ $1 == σ ($0 ⊕ $1)).
Definition ax_mult_zero := ∀  (zero ⊗ $0 == zero).
Definition ax_mult_rec :=  ∀∀ (σ $1 ⊗ $0 == $0 ⊕ $1 ⊗ $0).

(** Induction Scheme *)

Definition ax_induction (phi : form) :=
  phi[zero..] --> (∀ phi --> phi[σ $0 .: S >> var]) --> ∀ phi.

Definition ax_zero_or_succ := ∀ $0 == zero ∨ ∃ $1 == σ $0.

(** Equality Axioms *)

Definition ax_refl :=  ∀   $0 == $0.
Definition ax_sym :=   ∀∀  $1 == $0 --> $0 == $1.
Definition ax_trans := ∀∀∀ $2 == $1 --> $1 == $0 --> $2 == $0.

Definition ax_succ_congr := ∀∀ $0 == $1 --> σ $0 == σ $1.
Definition ax_add_congr := ∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3.
Definition ax_mult_congr := ∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3.

Definition EQ :=
  (ax_refl :: ax_sym :: ax_trans :: ax_succ_congr :: ax_add_congr :: ax_mult_congr :: nil)%list.

(** ** Robinson Arithmetic *)
Definition Q := (EQ ++ ax_zero_succ :: ax_succ_inj :: ax_add_zero :: ax_add_rec :: ax_mult_zero :: ax_mult_rec :: ax_zero_or_succ :: nil)%list.

Fact unfold_Q :
  Q = (EQ ++ ax_zero_succ :: ax_succ_inj :: ax_add_zero :: ax_add_rec :: ax_mult_zero :: ax_mult_rec :: ax_zero_or_succ :: nil)%list.
Proof. reflexivity. Qed.

Global Opaque Q.

(** The Theory PA *)
Inductive PA : form -> Prop :=
| PA_Q : forall ax, List.In ax Q -> PA ax
| PA_induction : forall phi, bounded 1 phi -> PA (ax_induction phi).

Notation "x 'i=' y" := (i_P (Σ_funcs:=PA_preds_signature) (P:=Eq) [x ; y]) (at level 30) : PA_Notation.
Notation "'i0'" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Zero) []) (at level 2) : PA_Notation.
Notation "'iσ' d" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Succ) [d]) (at level 37) : PA_Notation.
Notation "x 'i⊕' y" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Plus) [x ; y]) (at level 39) : PA_Notation.
Notation "x 'i⊗' y" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Mult) [x ; y]) (at level 38) : PA_Notation.

(** ** PA Models *)

Section Models.

  Variable D : Type.
  Variable I : interp D.

  Notation "x 'i⧀' y" := (exists d : D, y = iσ (x i⊕ d) ) (at level 40).

  Definition theory := form -> Prop.
  Definition in_theory (T : theory) phi := T phi.

  Notation "phi ∈ T" := (in_theory T phi) (at level 70).
  Notation "A ⊏ T" := (forall phi, In phi A -> phi ∈ T) (at level 70).
  Definition PAsat phi := exists A, A ⊏ PA /\ forall rho, (forall α, In α A -> rho ⊨ α) -> rho ⊨ phi.

  Fixpoint inu n :=
    match n with
    | 0 => i0
    | S x => iσ (inu x)
    end.

  Fact eval_num sigma n :
    eval sigma (num n) = inu n.
  Proof.
    induction n.
    - reflexivity.
    - cbn. now rewrite IHn.
  Qed.

  Lemma num_subst :
    forall n rho, (num n)`[rho] = num n.
  Proof.
    induction n.
    - reflexivity.
    - intros rho. cbn. now rewrite IHn.
  Qed.

  Lemma switch_num alpha rho n :
    rho ⊨ alpha[(num n)..] <-> ((inu n).:rho) ⊨ alpha.
  Proof.
    split; intros H.
    - erewrite <-eval_num. apply sat_single, H.
    - apply sat_single. now rewrite eval_num.
  Qed.

  Lemma switch_up_num α rho x d :
    (d.:rho) ⊨ (α [up (num x)..]) <-> (d.:((inu x).:rho)) ⊨ α.
  Proof.
    rewrite sat_comp. apply sat_ext.
    intros [|[]]; try reflexivity.
    cbn. now rewrite num_subst, eval_num.
  Qed.

  Lemma eq_sym : forall rho a b, rho ⊨ (a == b) -> rho ⊨ (b == a).
  Proof.
    intros. now cbn in *.
  Qed.

  Lemma eq_trans : forall rho a b c, rho ⊨ (a == b) /\ rho ⊨ (b == c) -> rho ⊨ (a == c).
  Proof.
    intros ????. cbn in *. intros []. congruence.
  Qed.

  Notation "⊨ phi" := (forall rho, rho ⊨ phi) (at level 21).

  Section PA_Model.

    Context {axioms : forall ax, PA ax -> ⊨ ax}.

    (* provide all axioms in a more useful form *)

    Lemma zero_succ x : i0 = iσ x -> False.
    Proof.
      assert (⊨ ax_zero_succ) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) x).
      apply H.
    Qed.

    Lemma succ_inj x y : iσ y = iσ x -> y = x.
    Proof.
      assert (⊨ ax_succ_inj ) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) y x).
      apply H.
    Qed.

    Lemma succ_inj' x y : iσ y = iσ x <-> y = x.
    Proof.
      split.
      apply succ_inj. now intros ->.
    Qed.

    Lemma add_zero d : i0 i⊕ d = d.
    Proof.
      assert (⊨ ax_add_zero) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) d).
      apply H.
    Qed.

    Lemma add_rec n d : (iσ n) i⊕ d = iσ (n i⊕ d).
    Proof.
      assert (⊨ ax_add_rec) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) d n).
      apply H.
    Qed.

    Lemma mult_zero d : i0 i⊗ d = i0.
    Proof.
      assert (⊨ ax_mult_zero) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) d).
      apply H.
    Qed.

    Lemma mult_rec n d : (iσ d) i⊗ n = n i⊕ (d i⊗ n).
    Proof.
      assert (⊨ ax_mult_rec) as H.
      apply axioms; constructor.
      firstorder.
      specialize (H (fun _ => i0) d n).
      apply H.
    Qed.

    Section Induction.

      Notation "phi [[ d ]] " := (forall rho, (d.:rho) ⊨ phi) (at level 19).

      Variable phi : form.
      Variable pred : bounded 1 phi.

      Lemma induction1 : phi[[i0]] -> ⊨ phi[zero..].
      Proof.
        intros H0 rho.
        apply sat_single. apply H0.
      Qed.

      Lemma induction2 :
        (forall n, phi[[n]] -> phi[[iσ n]]) -> ⊨ (∀ phi --> phi[σ $ 0 .: S >> var]).
      Proof.
        intros IH rho d Hd.
        eapply sat_comp, sat_ext.
        instantiate (1 := ((iσ d).:rho)).
        intros []; now cbn.
        apply IH. intros ?.
        eapply bound_ext. apply pred. 2 : apply Hd.
        intros []; intros.
        reflexivity. lia.
      Qed.

      Theorem induction : phi[[i0]] -> (forall n, phi[[n]] -> phi[[iσ n]] ) -> forall n, phi[[n]].
      Proof.
        assert (⊨ ax_induction phi) as H.
        apply axioms. apply PA_induction; trivial.
        intros ??? rho.
        specialize (H rho).
        apply H.
        now apply induction1.
        now apply induction2.
      Qed.

    End Induction.

    Lemma inu_inj x y : inu x = inu y <-> x = y.
    Proof.
      split.
      induction x in y |-*; destruct y; auto; cbn.
      - now intros ?%zero_succ.
      - intros H. symmetry in H. now apply zero_succ in H.
      - now intros <-%succ_inj%IHx.
      - congruence.
    Qed.

    Lemma inu_add_hom x y : inu (x + y) = inu x i⊕ inu y.
    Proof.
      induction x; cbn.
      - now rewrite add_zero.
      - now rewrite add_rec, IHx.
    Qed.

    Lemma inu_mult_hom x y : inu (x * y) = inu x i⊗ inu y.
    Proof.
      induction x; cbn.
      - now rewrite mult_zero.
      - now rewrite inu_add_hom, IHx, mult_rec.
    Qed.

    Lemma add_zero_r n : n i⊕ i0 = n.
    Proof.
      pose (phi := $0 ⊕ zero == $0).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ?. cbn. now rewrite add_zero.
      - intros x IH rho.
        specialize (IH (fun _ => i0)); cbn in *.
        now rewrite add_rec, IH.
      - now specialize (H n (fun _ => i0)).
    Qed.

    Lemma mult_zero_r n : n i⊗ i0 = i0.
    Proof.
      pose (phi := $0 ⊗ zero == zero).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ?. cbn. now rewrite mult_zero.
      - intros x IH rho.
        specialize (IH (fun _ => i0)); cbn in *.
        now rewrite mult_rec, IH, add_zero.
      - now specialize (H n (fun _ => i0)).
    Qed.

    Lemma add_rec_r n d : n i⊕ (iσ d) = iσ (n i⊕ d).
    Proof.
      pose (phi := ∀ $1 ⊕ (σ $0) == σ ($1 ⊕ $0) ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ??. cbn. now rewrite !add_zero.
      - intros x IH rho y. cbn.
        specialize (IH (fun _ => i0) y); cbn in *.
        now rewrite !add_rec, IH.
      - now specialize (H n (fun _ => i0) d); cbn in *.
    Qed.

    Lemma add_comm n d : n i⊕ d = d i⊕ n.
    Proof.
      pose (phi := ∀ $0 ⊕ $1 == $1 ⊕ $0).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ??; cbn. now rewrite add_zero, add_zero_r.
      - intros x IH rho.
        specialize (IH (fun _ => i0)); cbn in *.
        intros y. now rewrite add_rec, add_rec_r, IH.
      - now specialize (H n (fun _ => i0) d); cbn in *.
    Qed.

    Lemma add_asso x y z : (x i⊕ y) i⊕ z = x i⊕ (y i⊕ z).
    Proof.
      pose (phi := ∀∀ ($2 ⊕ $1) ⊕ $0 == $2 ⊕ ($1 ⊕ $0) ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ???. cbn. now rewrite !add_zero.
      - intros X IH rho Y Z. cbn.
        specialize (IH (fun _ => i0) Y); cbn in *.
        now rewrite !add_rec, IH.
      - now specialize (H x (fun _ => i0) y z); cbn in *.
    Qed.

    Lemma mult_rec_r n d : n i⊗ (iσ d) = n i⊕ (n i⊗ d) .
    Proof.
      pose (phi := ∀ $1 ⊗ (σ $0) == $1 ⊕ ($1 ⊗ $0) ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ??. cbn. now rewrite !mult_zero, add_zero.
      - intros x IH rho y. cbn.
        specialize (IH (fun _ => i0) y); cbn in *.
        rewrite !mult_rec, IH, <- !add_asso.
        rewrite add_rec, <- add_rec_r. now rewrite (add_comm y).
      - now specialize (H n (fun _ => i0) d); cbn in *.
    Qed.

    Lemma mult_comm n d : n i⊗ d = d i⊗ n.
    Proof.
      pose (phi := ∀ $0 ⊗ $1 == $1 ⊗ $0).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ??; cbn. now rewrite mult_zero, mult_zero_r.
      - intros x IH rho.
        specialize (IH (fun _ => i0)); cbn in *.
        intros y. now rewrite mult_rec, mult_rec_r, IH.
      - now specialize (H n (fun _ => i0) d); cbn in *.
    Qed.

    Lemma distributive x y z : (x i⊕ y) i⊗ z = (x i⊗ z) i⊕ (y i⊗ z).
    Proof.
      pose (phi := ∀∀ ($1 ⊕ $0) ⊗ $2 == ($1 ⊗ $2) ⊕ ($0 ⊗ $2) ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ???. cbn. now rewrite !mult_zero_r, add_zero.
      - intros X IH rho Y Z. cbn.
        specialize (IH (fun _ => i0) Y); cbn in *.
        rewrite mult_rec_r, IH.
        rewrite <- add_asso, (add_comm Y Z), (add_asso Z Y).
        rewrite <- mult_rec_r.
        rewrite add_comm, <-add_asso, (add_comm _ Z).
        rewrite <- mult_rec_r.
        now rewrite add_comm.
      - now specialize (H z (fun _ => i0) x y); cbn in *.
    Qed.

    Lemma mult_asso x y z : (x i⊗ y) i⊗ z = x i⊗ (y i⊗ z).
    Proof.
      pose (phi := ∀∀ ($2 ⊗ $1) ⊗ $0 == $2 ⊗ ($1 ⊗ $0) ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ???. cbn. now rewrite !mult_zero.
      - intros X IH rho Y Z. cbn.
        specialize (IH (fun _ => i0) Y); cbn in *.
        now rewrite !mult_rec, <-IH, distributive.
      - now specialize (H x (fun _ => i0) y z); cbn in *.
    Qed.

    Lemma nolessthen_zero d : ~ d i⧀ i0.
    Proof. now intros [? []%zero_succ]. Qed.

    Lemma zero_or_succ : forall d, d = i0 \/ exists x, d = iσ x.
    Proof.
      pose (phi := $0 == zero ∨ ∃ $1 == σ $0).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros rho. cbn. now left.
      - intros n IH rho. cbn. right. exists n. reflexivity.
      - intros d. now specialize (H d (fun _ => i0)); cbn in *.
    Qed.

    Lemma eq_dec : forall x y : D, x = y \/ x <> y.
    Proof.
      pose (phi := ∀ $1 == $0 ∨ ($1 == $0 --> ⊥)).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros rho d. cbn.
        destruct (zero_or_succ d) as [|[x ->]].
        + now left.
        + right. apply zero_succ.
      - intros n IH rho. cbn.
        intros d. destruct (zero_or_succ d) as [-> | [x ->]].
        + right. intros ?. eapply zero_succ. eauto.
        + destruct (IH (fun _ => i0) x); cbn in H.
          left. now rewrite H.
          right. intros ?%succ_inj. auto.
      - intros x y.
        now specialize (H x (fun _ => i0) y); cbn in *.
    Qed.

    Lemma sum_is_zero x y : x i⊕ y = i0 -> x = i0 /\ y = i0.
    Proof.
      intros H.
      destruct (zero_or_succ x) as [-> |[? ->]], (zero_or_succ y) as [-> |[? ->]]; auto.
      - repeat split. now rewrite add_zero in H.
      - repeat split. rewrite add_rec in H. symmetry in H.
        now apply zero_succ in H.
      - split; rewrite add_rec in H; symmetry in H; now apply zero_succ in H.
    Qed.

    Lemma lt_SS x y : (iσ x) i⧀ (iσ y) <-> x i⧀ y.
    Proof.
      split; intros [k Hk]; exists k.
      - apply succ_inj in Hk. now rewrite <-add_rec.
      - now rewrite Hk, add_rec.
    Qed.

    Lemma trichotomy x y : x i⧀ y \/ x = y \/ y i⧀ x.
    Proof.
      pose (phi := ∀ ($1 ⧀ $0) ∨ ($1 == $0 ∨ $0 ⧀ $1)).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros rho d; cbn. destruct (zero_or_succ d) as [-> | [k ->] ].
        + now right; left.
        + left. exists k. now rewrite add_zero.
      - intros n IH rho d. cbn. destruct (zero_or_succ d) as [-> | [k ->] ].
        + right; right. exists n. now rewrite add_zero.
        + specialize (IH (fun _ => i0) k); cbn in IH.
          rewrite !lt_SS. intuition congruence.
      - now specialize (H x (fun _ => i0) y); cbn in H.
    Qed.

    Lemma add_eq x y t : x i⊕ t = y i⊕ t -> x = y.
    Proof.
      pose (phi := ∀∀ $0 ⊕ $2 == $1 ⊕ $2 --> $0 == $1  ).
      assert (forall n rho, (n.:rho) ⊨ phi).
      apply induction. repeat solve_bounds.
      - intros ???. cbn. now rewrite !add_zero_r.
      - intros T IH rho Y X; cbn in *.
        rewrite !add_rec_r, <-!add_rec.
        now intros ?%IH%succ_inj.
      - now specialize (H t (fun _ => i0) y x); cbn in *.
    Qed.

    Lemma lt_neq x y : x i⧀ y -> x = y -> False.
    Proof.
      intros [k Hk] ->. revert Hk.
      rewrite <-add_rec_r, <-(add_zero_r y) at 1.
      rewrite !(add_comm y).
      intros H%add_eq. revert H.
      apply zero_succ.
    Qed.

    Notation "x 'i≤' y" := (exists d : D, y = x i⊕ d)  (at level 40).

    Lemma lt_le_equiv1 x y : x i⧀ iσ y <-> x i≤ y.
    Proof.
      split; intros [k Hk].
      - exists k. now apply succ_inj in Hk.
      - exists k. congruence.
    Qed.

    Lemma lt_S d e : d i⧀ (iσ e) <-> d i⧀ e \/ d = e.
    Proof.
      pose (Φ := ∀ $0 ⧀ σ $1 <--> $0 ⧀ $1 ∨ $0 == $1).
      assert (H: forall d rho, (d .: rho)⊨ Φ).
      apply induction.
      repeat solve_bounds; cbn in H.
      1,2 : apply vec_cons_inv in H; destruct H as [-> |]; solve_bounds.
      - intros rho x. cbn; destruct (zero_or_succ x) as [-> | [x' ->]]; cbn; split.
        + intros _. now right.
        + intros _. exists i0. now rewrite add_zero.
        + rewrite lt_SS. now intros ?%nolessthen_zero.
        + intros [?%nolessthen_zero | E]. tauto.
          symmetry in E. now apply zero_succ in E.
      - intros y IH rho x; cbn; destruct (zero_or_succ x) as [-> | [x' ->]].
        + split.
        ++ intros _. left. exists y. now rewrite add_zero.
        ++ intros _. exists (iσ y). now rewrite add_zero.
        + rewrite !lt_SS, !succ_inj'.
          specialize (IH rho x'). apply IH.
      - specialize (H e (fun _ => d) d). apply H.
    Qed.

    Lemma lt_le_trans {x z} y : x i⧀ y -> y i≤ z -> x i⧀ z.
    Proof.
      intros [k1 H1] [k2 H2]. exists (k1 i⊕ k2). rewrite H2, H1.
      now rewrite add_rec, add_asso.
    Qed.

    Lemma le_le_trans {x z} y : x i≤ y -> y i≤ z -> x i≤ z.
    Proof.
      intros [k1 H1] [k2 H2]. exists (k1 i⊕ k2). rewrite H2, H1.
      now rewrite add_asso.
    Qed.

    Lemma add_lt_mono x y t : x i⧀ y -> x i⊕ t i⧀ y i⊕ t.
    Proof.
      intros [k Hk]. exists k. rewrite Hk.
      now rewrite add_rec, !add_asso, (add_comm k t).
    Qed.

    Lemma add_le_mono x y t : x i≤ y -> x i⊕ t i≤ y i⊕ t.
    Proof.
      intros [k Hk]. exists k. rewrite Hk.
      now rewrite !add_asso, (add_comm k t).
    Qed.

    Lemma mult_le_mono x y t : x i≤ y -> x i⊗ t i≤ y i⊗ t.
    Proof.
      intros [k Hk]. exists (k i⊗ t). rewrite Hk.
      now rewrite distributive.
    Qed.

    Section Euclid.

      (** *** Euclidean Lemma *)

      Lemma iEuclid :
        forall x q, exists d r, x = d i⊗ q i⊕ r /\ (i0 i⧀ q -> r i⧀ q).
      Proof.
        intros x q.
        destruct (zero_or_succ q) as [-> | [q_ ->]].
        - exists i0, x. split.
          + rewrite mult_zero, add_zero. reflexivity.
          + now intros ?%nolessthen_zero.
        - pose (phi := ∀∃∃ $3 == $1 ⊗ (σ $2) ⊕ $0 ∧ (zero ⧀ (σ $2) --> $0 ⧀ (σ $2) ) ).
          assert (forall n rho, (n.:rho) ⊨ phi).
          apply induction. unfold sless in *. cbn. cbn in *. repeat solve_bounds.
          + intros rho d. cbn. exists i0, i0. fold i0. split.
            * now rewrite mult_zero, add_zero.
            * tauto.
          + intros x' IH rho q'. cbn.
            destruct (IH rho q') as [d' [r' [H ]]]. cbn in *.
            destruct (eq_dec r' q') as [<- | F].
            * exists (iσ d'), i0. split.
              rewrite add_zero_r, H.
              now rewrite <-add_rec_r, mult_rec, add_comm.
              tauto.
            * exists d', (iσ r'). split.
              now rewrite H, <-add_rec_r.
              intros _. rewrite lt_SS.
              assert (r' i≤ q') as G.
              { rewrite <-lt_le_equiv1.
                apply H0. exists q'. now rewrite add_zero. }
              destruct (trichotomy r' q') as [h |[h|h] ]; intuition.
              exfalso. specialize (lt_le_trans _ h G).
              intros. now apply (lt_neq q' q').
          + destruct (H x (fun _ => i0) q_) as [d [r [H1 H2]]]. cbn in H1, H2.
            exists d, r. split; auto.
      Qed.

      Lemma iFac_unique1 d q1 r1 q2 r2 : r1 i⧀ d ->
            r1 i⊕ q1 i⊗ d = r2 i⊕ q2 i⊗ d -> q1 i⧀ q2 -> False.
      Proof.
        intros H1 E H. revert E. apply lt_neq.
        apply lt_le_trans with (d i⊕ q1 i⊗ d).
        - now apply add_lt_mono.
        - rewrite <- !mult_rec.
          apply le_le_trans with (q2 i⊗ d).
          + apply mult_le_mono.
            destruct H as [k ->].
            exists k. now rewrite add_rec.
          + pattern (q2 i⊗ d) at 2.
            rewrite <-(add_zero (q2 i⊗ d)).
            apply add_le_mono.
            exists r2. now rewrite add_zero.
      Qed.

      (** Uniqueness for the Euclidean Lemma *)

      Lemma iFac_unique q d1 r1 d2 r2 : r1 i⧀ q -> r2 i⧀ q ->
            r1 i⊕ d1 i⊗ q = r2 i⊕ d2 i⊗ q -> d1 = d2 /\ r1 = r2.
      Proof.
        intros H1 H2 E.
        assert (d1 = d2) as ->.
        - destruct (trichotomy d1 d2) as [ H | [ | H ]]; auto.
          + exfalso. eapply iFac_unique1. 2: apply E. all: tauto.
          + exfalso. eapply iFac_unique1. symmetry in E.
            3: apply H. apply H2. eauto.
        - repeat split. now apply add_eq in E.
      Qed.

    End Euclid.

    Lemma lessthen_num : forall n d, d i⧀ inu n -> exists k, k < n /\ d = inu k.
    Proof.
      induction n ; intros d H.
      - now apply nolessthen_zero in H.
      - destruct (zero_or_succ d) as [-> | [e ->]].
        exists 0; split; auto; lia.
        cbn in H; apply ->lt_SS in H.
        apply IHn in H.
        destruct H as [k []].
        exists (S k); split. lia. cbn; congruence.
    Qed.

    Lemma iEuclid' : forall x y, 0 < y -> exists a b, b < y /\ x = a i⊗ inu y i⊕ inu b.
      Proof.
        intros x y.
        destruct y as [|y]. lia.
        destruct (iEuclid x (inu (S y))) as (a & b & H).
        intros Hy.
        enough (Hlt : forall x y, x < y -> inu x i⧀ inu y).
        apply Hlt, H, lessthen_num in Hy.
        destruct Hy as [r [Hr ->]].
        exists a, r. split.
        apply Hr. apply H.
        intros n m [k <-]%lt_nat_equiv.
        exists (inu k); cbn. now rewrite inu_add_hom.
      Qed.

  End PA_Model.

End Models.

Arguments PAsat {_ _} _.
Notation "'PA⊨' phi" := (forall D (I : interp D) rho, (forall psi : form, PA psi -> rho ⊨ psi) -> rho ⊨ phi) (at level 30).

(** *** Standard Model of PA *)

Section StandartModel.

  Definition interp_nat : interp nat.
  Proof.
    split.
    - destruct f; intros v.
      + exact 0.
      + exact (S (Vector.hd v) ).
      + exact (Vector.hd v + Vector.hd (Vector.tl v) ).
      + exact (Vector.hd v * Vector.hd (Vector.tl v) ).
    - destruct P.
  Defined.

  (* We now show that there is a model in which all of PA's axioms hold. *)
  Lemma PA_std_axioms :
    forall rho ax, PA ax -> @sat _ _ nat interp_nat _ rho ax.
  Proof.
    intros rho ax [a H | H].
    repeat (destruct H as [<-| H]); cbn ; try congruence.
    intros []. auto.
    - right. exists n; auto.
    - destruct H.
    - intros H1 IH. intros d. induction d.
      + apply sat_single in H1. apply H1.
      + apply IH in IHd.
        eapply sat_comp, sat_ext in IHd.
        apply IHd. intros []; now cbn.
  Qed.

  Lemma Q_std_axioms :
    forall rho ax, In ax Q -> @sat _ _ nat interp_nat _ rho ax.
  Proof.
    intros rho ax H.
    repeat (destruct H as [<-| H]); cbn ; try congruence.
    - intros []; auto. right. exists n; auto.
    - destruct H.
  Qed.

  Fact inu_nat_id : forall n, @inu nat interp_nat n = n.
  Proof.
    induction n; cbn; congruence.
  Qed.

End StandartModel.

Arguments inu {_ _} _.

Section ND.

  Variable p : peirce.

  Fixpoint iter {X: Type} f n (x : X) :=
    match n with
      0 => x
    | S m => f (iter f m x)
    end.

  Fact iter_switch {X} f n x : f (@iter X f n x) = iter f n (f x).
  Proof. induction n; cbn; now try rewrite IHn. Qed.

  Lemma subst_up_var k x sigma :
    x < k -> (var x)`[iter up k sigma] = var x.
  Proof.
    induction k in x, sigma |-*.
    - now intros ?%PeanoNat.Nat.nlt_0_r.
    - intros H.
      destruct (Compare_dec.lt_eq_lt_dec x k) as [[| <-]|].
      + cbn [iter]. rewrite iter_switch. now apply IHk.
      + destruct x. reflexivity.
        change (iter _ _ _) with (up (iter up (S x) sigma)).
        change (var (S x)) with ((var x)`[↑]).
        rewrite up_term, IHk. reflexivity. constructor.
      + lia.
  Qed.

  Lemma subst_bounded_term t sigma k :
    bounded_t k t -> t`[iter up k sigma] = t.
  Proof.
    induction 1.
    - now apply subst_up_var.
    - cbn. f_equal.
      rewrite <-(Vector.map_id _ _ v) at 2.
      apply Vector.map_ext_in. auto.
  Qed.

  Lemma subst_closed_term t sigma :
    bounded_t 0 t -> t`[sigma] = t.
  Proof.
    intros H0.
    refine (_ (subst_bounded_term t sigma 0 H0)).
    now cbn.
  Qed.

  Lemma subst_bounded k phi sigma :
    bounded k phi -> phi[iter up k sigma] = phi.
  Proof.
    induction 1 in sigma |-*; cbn.
    - f_equal.
      rewrite <-(Vector.map_id _ _ v) at 2.
      apply Vector.map_ext_in.
      intros t Ht. apply subst_bounded_term. auto.
    - now rewrite IHbounded1, IHbounded2.
    - f_equal; now apply subst_bounded_term.
    - f_equal.
      change (up _) with (iter up (S n) sigma).
      apply IHbounded.
    - reflexivity.
  Qed.

  Definition exist_times n (phi : form) := iter (fun psi => ∃ psi) n phi.

  Lemma up_decompose sigma phi :
    phi[up (S >> sigma)][(sigma 0)..] = phi[sigma].
  Proof.
    rewrite subst_comp. apply subst_ext.
    intros [].
    - reflexivity.
    - apply subst_term_shift.
  Qed.

  Lemma subst_exist_prv {sigma N Gamma} phi :
    Gamma ⊢ phi[sigma] -> bounded N phi -> Gamma ⊢ exist_times N phi.
  Proof.
    induction N in phi, sigma |-*; intros; cbn.
    - erewrite <-(subst_bounded 0); eassumption.
    - rewrite iter_switch. eapply (IHN (S >> sigma)).
      cbn. eapply (ExI (sigma 0)).
      now rewrite up_decompose.
      now apply bounded_S_exists.
  Qed.

  Lemma subst_forall_prv phi {N Gamma} :
    Gamma ⊢ (forall_times N phi) -> bounded N phi -> forall sigma, Gamma ⊢ phi[sigma].
  Proof.
    induction N in phi |-*; intros ?? sigma; cbn in *.
    - change sigma with (iter up 0 sigma).
      now rewrite (subst_bounded 0).
    - specialize (IHN (∀ phi) ).
      rewrite <-up_decompose.
      apply AllE. apply IHN.
      unfold forall_times. now rewrite <-iter_switch.
      now apply bounded_S_forall.
  Qed.

End ND.

Fixpoint join {X n} (v : Vector.t X n) (rho : nat -> X) :=
    match v with
    | Vector.nil _ => rho
    | Vector.cons _ x n w  => join w (x.:rho)
    end.

Notation "v '∗' rho" := (join v rho) (at level 20).

Section Q_prv.

  Variable p : peirce.

  Variable Gamma : list form.
  Variable G : incl Q Gamma.

  Arguments Weak {_ _ _ _}, _.

  Lemma reflexivity t : Gamma ⊢ (t == t).
  Proof.
    apply (Weak Q).
    pose (sigma := [t] ∗ var ).
    change (Q ⊢ _) with (Q ⊢ ($0 == $0)[sigma]).
    eapply (@subst_forall_prv _ _ 1).
    apply Ctx.
    - now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma symmetry x y : Gamma ⊢ (x == y) -> Gamma ⊢ (y == x).
  Proof.
    apply IE. apply (Weak Q).
    pose (sigma := [x ; y] ∗ var ).
    change (Q ⊢ _) with (Q ⊢ ($1 == $0 --> $0 == $1)[sigma]).
    apply (@subst_forall_prv _ _ 2).
    apply Ctx.
    - do 1 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma transitivity x y z :
    Gamma ⊢ (x == y) -> Gamma ⊢ (y == z) -> Gamma ⊢ (x == z).
  Proof.
    intros H. apply IE. revert H; apply IE.
    apply Weak with Q.
    pose (sigma := [x ; y ; z] ∗ var).
    change (Q ⊢ _) with (Q ⊢ ($2 == $1 --> $1 == $0 --> $2 == $0)[sigma]).
    apply (@subst_forall_prv _ _ 3).
    apply Ctx.
    - do 2 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma eq_succ x y : Gamma ⊢ (x == y) -> Gamma ⊢ (σ x == σ y).
  Proof.
    apply IE. apply Weak with Q.
    pose (sigma := [y ; x] ∗ var ).
    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> σ $0 == σ $1)[sigma]).
    apply (@subst_forall_prv _ _ 2).
    apply Ctx.
    - do 3 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma eq_add {x1 y1 x2 y2} :
    Gamma ⊢ (x1 == x2) -> Gamma ⊢ (y1 == y2) -> Gamma ⊢ (x1 ⊕ y1 == x2 ⊕ y2).
  Proof.
    intros H; apply IE. revert H; apply IE.
    apply Weak with Q.
    pose (sigma := [y2 ; y1 ; x2 ; x1] ∗ var).
    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3)[sigma]).
    apply (@subst_forall_prv _ _ 4).
    apply Ctx.
    - do 4 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma eq_mult {x1 y1 x2 y2} :
    Gamma ⊢ (x1 == x2) -> Gamma ⊢ (y1 == y2) -> Gamma ⊢ (x1 ⊗ y1 == x2 ⊗ y2).
  Proof.
    intros H; apply IE. revert H; apply IE.
    apply Weak with Q.
    pose (sigma := [y2 ; y1 ; x2 ; x1] ∗ var).
    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3)[sigma]).
    apply (@subst_forall_prv _ _ 4).
    apply Ctx.
    - do 5 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma Zero_succ x :
    Gamma ⊢ ¬ zero == σ x.
  Proof.
    apply Weak with Q.
    pose (sigma := [x] ∗ var).
    change (Q ⊢ _) with (Q ⊢ (¬ zero == σ $0)[sigma]).
    apply (@subst_forall_prv _ _ 1).
    apply Ctx.
    - do 6 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma Succ_inj x y :
    Gamma ⊢ σ x == σ y -> Gamma ⊢ x == y.
  Proof.
    intros H; eapply IE. 2: apply H.
    apply Weak with Q.
    pose (sigma := [x ; y] ∗ var).
    change (Q ⊢ _) with (Q ⊢ (σ $1 == σ $0 --> $1 == $0)[sigma]).
    apply (@subst_forall_prv _ _ 2).
    apply Ctx.
    - do 7 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma Add_rec x y :
    Gamma ⊢ ( (σ x) ⊕ y == σ (x ⊕ y) ).
  Proof.
    apply Weak with Q.
    pose (sigma := [y ; x] ∗ var).
    change (Q ⊢ _) with (Q ⊢ (σ $0 ⊕ $1 == σ ($0 ⊕ $1))[sigma]).
    apply (@subst_forall_prv _ _ 2).
    apply Ctx.
    - do 9 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  (** Homomorphism Properties of Numerals *)

  Lemma num_add_homomorphism  x y :
    Gamma ⊢ ( num x ⊕ num y == num (x + y) ).
  Proof.
    induction x; cbn.
    - pose (phi := zero ⊕ $0 == $0).
      apply (@AllE _ _ _ _ _ _ phi ).
      apply Weak with Q.
      apply Ctx. do 8 right; now left.
      assumption.
    - eapply transitivity.
      apply Add_rec.
      now apply eq_succ.
  Qed.

  Lemma Mult_rec x y :
    Gamma ⊢ ( (σ x) ⊗ y == y ⊕ (x ⊗ y) ).
  Proof.
    apply Weak with Q.
    pose (sigma := [x ; y] ∗ var).
    change (Q ⊢ _) with (Q ⊢ ((σ $1) ⊗ $0 == $0 ⊕ ($1 ⊗ $0))[sigma]).
    eapply (@subst_forall_prv _ _ 2).
    apply Ctx.
    - do 11 right; now left.
    - repeat solve_bounds.
    - assumption.
  Qed.

  Lemma num_mult_homomorphism (x y : nat) :
    Gamma ⊢ ( num x ⊗ num y == num (x * y) ).
  Proof.
    induction x; cbn.
    - pose (phi := zero ⊗ $0 == zero).
      apply (@AllE _ _ _ _ _ _ phi).
      apply Weak with Q. apply Ctx; do 10 right; now left.
      assumption.
    - eapply transitivity.
      apply Mult_rec.
      eapply transitivity.
      2: apply num_add_homomorphism.
      apply eq_add. apply reflexivity. apply IHx.
  Qed.

End Q_prv.

Section Q_prv.

  Variable p : peirce.

  Variable Gamma : list form.
  Variable G : incl Q Gamma.

  Derive Signature for Vector.t.

  Lemma vec_nil_eq X (v : vec X 0) :
    v = Vector.nil X.
  Proof.
    depelim v. reflexivity.
  Qed.

  Lemma vec_inv1 X (v : vec X 1) :
    v = [ Vector.hd v ].
  Proof.
    repeat depelim v. cbn. reflexivity.
  Qed.

  Lemma vec_inv2 X (v : vec X 2) :
    v = [ Vector.hd v ; Vector.hd (Vector.tl v) ].
  Proof.
    repeat depelim v. cbn. reflexivity.
  Qed.

  Lemma map_hd X Y n (f : X -> Y) (v : vec X (S n)) :
    Vector.hd (Vector.map f v) = f (Vector.hd v).
  Proof.
    depelim v. reflexivity.
  Qed.

  Lemma map_tl X Y n (f : X -> Y) (v : vec X (S n)) :
    Vector.tl (Vector.map f v) = Vector.map f (Vector.tl v).
  Proof.
    depelim v. reflexivity.
  Qed.

  Lemma vec_in_hd X n (v : vec X (S n)) :
    vec_in (Vector.hd v) v.
  Proof.
    depelim v. constructor.
  Qed.

  Lemma vec_in_hd_tl X n (v : vec X (S (S n))) :
    vec_in (Vector.hd (Vector.tl v)) v.
  Proof.
    depelim v. constructor. depelim v. constructor.
  Qed.

  Lemma in_hd X n (v : vec X (S n)) :
    Vector.In (Vector.hd v) v.
  Proof.
    depelim v. constructor.
  Qed.

  Lemma in_hd_tl X n (v : vec X (S (S n))) :
    Vector.In (Vector.hd (Vector.tl v)) v.
  Proof.
    depelim v. constructor. depelim v. constructor.
  Qed.

  (** Closed terms are numerals. *)

  Lemma closed_term_is_num s :
    bounded_t 0 s -> { n & Gamma ⊢ s == num n }.
  Proof.
    pattern s; revert s. apply term_rect.
    - intros ? H. exists 0. inversion H; lia.
    - intros [] v N H; cbn in v.
      + exists 0. rewrite (vec_nil_eq _ v).
        now apply reflexivity.
      + rewrite (vec_inv1 _ v).
        destruct (N (Vector.hd v)) as [n Hn].
        apply vec_in_hd.
        inversion H. subst.
        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.
        apply H1. apply in_hd. decide equality.
        exists (S n); cbn. now apply eq_succ.
      + rewrite (vec_inv2 _ v).
        remember (Vector.hd v) as x eqn:Hx.
        remember (Vector.hd (Vector.tl v)) as y eqn:Hy.
        destruct (N x) as [n Hn].
        rewrite Hx. apply vec_in_hd.
        inversion H. subst.
        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.
        apply H1. apply in_hd. decide equality.
        destruct (N y) as [m Hm].
        rewrite Hy. apply vec_in_hd_tl.
        inversion H. subst.
        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.
        apply H1. apply in_hd_tl. decide equality.
        exists (n + m).
        eapply transitivity.
        3 : apply num_add_homomorphism.
        all: try assumption.
        now apply eq_add.
      + rewrite (vec_inv2 _ v).
        remember (Vector.hd v) as x eqn:Hx.
        remember (Vector.hd (Vector.tl v)) as y eqn:Hy.
        destruct (N x) as [n Hn].
        rewrite Hx. apply vec_in_hd.
        inversion H. subst.
        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.
        apply H1. apply in_hd. decide equality.
        destruct (N y) as [m Hm].
        rewrite Hy. apply vec_in_hd_tl.
        inversion H. subst.
        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.
        apply H1. apply in_hd_tl. decide equality.
        exists (n * m).
        eapply transitivity.
        3 : apply num_mult_homomorphism.
        all: try assumption.
        now apply eq_mult.
  Qed.

  Fact num_eq x y :
    x = y -> Gamma ⊢ num x == num y.
  Proof.
    intros ->. now apply reflexivity.
  Qed.

  Lemma num_neq x :
    forall y, x <> y -> Gamma ⊢ ¬ num x == num y.
  Proof.
    induction x as [| x IHx].
    - intros [] neq.
      + congruence.
      + now apply Zero_succ.
    - intros [|y] neq.
      + apply II. eapply IE with (phi := num 0 == num (S x)).
        eapply Weak with Gamma. now apply Zero_succ.
        firstorder.
        apply symmetry; [now right; apply G|].
        apply Ctx. now left.
      + apply II. eapply IE with (phi := num x == num y).
        { eapply Weak with Gamma. apply IHx.
          - lia.
          - now right. }
        apply Succ_inj.
        ++ now right; apply G.
        ++ apply Ctx. now left.
  Qed.

  Lemma num_eq_dec x y :
    { Gamma ⊢ num x == num y } + { Gamma ⊢ ¬ num x == num y }.
  Proof.
    destruct (dec_eq_nat x y); [left|right].
    - now apply num_eq.
    - now apply num_neq.
  Qed.

  (** Provability of equality for closed terms is decidable. *)

  Lemma term_eq_dec s t :
    bounded_t 0 s -> bounded_t 0 t -> { Gamma ⊢ s == t } + { Gamma ⊢ ¬ s == t }.
  Proof.
    intros Hs Ht.
    destruct (closed_term_is_num s Hs) as [n Hn], (closed_term_is_num t Ht) as [m Hm].
    destruct (num_eq_dec n m) as [H|H].
    - left. eapply transitivity; eauto 1.
      eapply transitivity; eauto 1.
      apply symmetry; assumption.
    - right.
      apply II. eapply IE.
      apply Weak with Gamma; try apply H; firstorder.
      eapply transitivity. shelve.
      2 : eapply Weak with Gamma; try apply Hm.
      eapply transitivity. shelve.
      eapply Weak with Gamma. apply symmetry in Hn. apply Hn.
      assumption. shelve.
      apply Ctx. Unshelve.
      + now left.
      + now right.
      + right. now apply G.
      + right. now apply G.
      + now right.
  Qed.

  Lemma num_lt x y :
    x < y -> Gamma ⊢ num x ⧀ num y.
  Proof.
    intros [k Hk]%lt_nat_equiv.
    apply ExI with (t := num k). cbn.
    rewrite !num_subst, <-Hk. cbn.
    apply eq_succ. easy.
    apply symmetry, num_add_homomorphism; easy.
  Qed.

  Lemma not_lt_zero_prv' :
  Q ⊢ ∀ ¬ $0 ⧀ num 0.
  Proof.
    apply AllI, II. eapply ExE.
    - apply Ctx. now left.
    - cbn. eapply IE.
      + pose (s := $1 ⊕ $0).
        apply Zero_succ with (x := s).
        right; now right.
      + apply Ctx. now left.
  Qed.

  Lemma not_lt_zero_prv t :
    Q ⊢ ¬ t ⧀ num 0.
  Proof.
    change (Q ⊢ (¬ $0 ⧀ num 0)[t..]).
    apply AllE, not_lt_zero_prv'.
  Qed.

  Lemma Faster3 :
    forall A, Q <<= A ++ map (subst_form ↑) Q.
  Proof.
    intros A; induction A; cbn.
    - firstorder.
    - right. now apply IHA.
  Qed.

  Lemma num_nlt x :
    forall y, ~ (x < y) -> Q ⊢ ¬ num x ⧀ num y.
  Proof.
    induction x as [| x IHx].
    - intros [] ineq.
      + apply not_lt_zero_prv.
      + lia.
    - intros [|y] ineq.
      + apply not_lt_zero_prv.
      + assert (~ x < y) as H % IHx by lia.
        apply II. eapply IE.
        { eapply Weak; [apply H | now right]. }
        eapply ExE.
        * apply Ctx. now left.
        * apply ExI with (t := $0).
          cbn. rewrite !num_subst.
          eapply transitivity. right; now right.
          2 : {apply Add_rec. right; now right. }
          apply Succ_inj. right; now right.
          apply Ctx. now left.
  Qed.

  Lemma num_lt_dec x y :
    { Gamma ⊢ num x ⧀ num y } + { Gamma ⊢ ¬ num x ⧀ num y }.
  Proof.
    destruct (lt_dec x y); [left|right].
    - now apply num_lt.
    - apply Weak with Q; [now apply num_nlt | assumption].
  Qed.

  Lemma term_lt_dec s t :
    map (subst_form ↑) Gamma = Gamma -> bounded_t 0 s -> bounded_t 0 t -> { Gamma ⊢ s ⧀ t } + { Gamma ⊢ ¬ s ⧀ t }.
  Proof.
    intros HG Hs Ht.
    destruct (closed_term_is_num s Hs) as [n Hn], (closed_term_is_num t Ht) as [m Hm].
    destruct (num_lt_dec n m) as [H|H].
    - left. eapply ExE. apply H.
      apply ExI with (t0:=$0).
      rewrite !num_subst, HG. cbn.
      repeat rewrite (subst_closed_term t), (subst_closed_term s); auto.
      eapply transitivity.
      2 : { eapply Weak. apply Hm. now right. }
      now right; apply G.
      apply symmetry. now right; apply G.
      pose (j := σ (num n ⊕ $0)).
      eapply transitivity with (y:= j); unfold j. now right; apply G.
      apply eq_succ. now right; apply G.
      apply eq_add. now right; apply G.
      eapply Weak. apply Hn. now right.
      apply reflexivity. now right; apply G.
      apply symmetry. now right; apply G.
      apply Ctx; now left.
    - right. apply II. eapply IE.
      eapply Weak. apply H. now right.
      eapply ExE. apply Ctx; now left.
      apply ExI with (t0:=$0).
      cbn. rewrite !num_subst.
      repeat rewrite (subst_closed_term t), (subst_closed_term s), HG; auto.
      apply symmetry in Hm; auto.
      apply symmetry in Hn; auto.
      eapply transitivity.
      2 : { eapply Weak. apply Hm. right; now right. }
      now right; right; apply G.
      apply symmetry. now right; right; apply G.
      pose (j := σ (s ⊕ $0)).
      eapply transitivity with (y:= j); unfold j.
      now right; right; apply G.
      apply eq_succ. now right; right; apply G.
      apply eq_add. now right; right; apply G.
      eapply Weak. apply Hn. now right; right.
      apply reflexivity. now right; right; apply G.
      apply symmetry. now right; right; apply G.
      apply Ctx; now left.
  Qed.

End Q_prv.

Definition std {D I} d := exists n, @inu D I n = d.
Definition stdModel D {I} := forall d, exists n, (@inu D I) n = d.
Definition nonStd D {I} := exists e, ~ @std D I e.
Definition notStd D {I} := ~ @stdModel D I.

Fact nonStd_notStd {D I} :
  @nonStd D I -> ~ stdModel D.
Proof.
  intros [e He] H; apply He, H.
Qed.

Notation "⊨ phi" := (forall rho, rho ⊨ phi) (at level 21).

Section stdModel.

  Variable D : Type.
  Variable I : interp D.
  Variable axioms : forall ax, PA ax -> ⊨ ax.

  Definition nat_hom (f : nat -> D) :=
    f 0 = @inu D I 0
    /\ forall n, f (S n) = iσ (f n).
  Definition stdModel' := exists f, nat_hom f /\ bij f.

  Lemma hom_agree_inu f :
    nat_hom f -> forall x, f x = inu x.
  Proof.
    intros [H0 H] x. induction x as [| x IH].
    - assumption.
    - cbn. now rewrite H, IH.
  Qed.

  Lemma stdModel_eqiv :
    stdModel' <-> @stdModel D I.
  Proof.
    split.
    - intros (f & Hf & [inj surj]) e.
      destruct (surj e) as [n <-].
      exists n. now rewrite (hom_agree_inu _ Hf).
    - intros H. exists inu. repeat split.
      + intros ???. now eapply inu_inj.
      + apply H.
  Qed.

End stdModel.