Require Import Psatz.
Require Import Reals.

Require Export Prelim.
Require Export Complex.
Require Export Matrix.

(* Using our (complex, unbounded) matrices, their complex numbers *)

Open Scope R_scope.
Open Scope C_scope.
Open Scope matrix_scope.

(*******************************************)
(* Quantum basis states *)
(*******************************************)

(* Maybe change to IF statements? *)
Definition qubit0 : Vector 2 :=
  fun x y => match x, y with
          | 0, 0 => C1
          | 1, 0 => C0
          | _, _ => C0
          end.
Definition qubit1 : Vector 2 :=
  fun x y => match x, y with
          | 0, 0 => C0
          | 1, 0 => C1
          | _, _ => C0
          end.

(* Ket notation: \mid 0 \rangle *)
Notation "∣0⟩" := qubit0.
Notation "∣1⟩" := qubit1.
Notation "⟨0∣" := qubit0†.
Notation "⟨1∣" := qubit1†.
Notation "∣0⟩⟨0∣" := (∣0⟩×⟨0∣).
Notation "∣1⟩⟨1∣" := (∣1⟩×⟨1∣).
Notation "∣1⟩⟨0∣" := (∣1⟩×⟨0∣).
Notation "∣0⟩⟨1∣" := (∣0⟩×⟨1∣).

Definition bra (x : nat) : Matrix 2 1 := if x =? 0 then ⟨0∣ else ⟨1∣.
Definition ket (x : nat) : Matrix 2 1 := if x =? 0 then ∣0⟩ else ∣1⟩.

(* Note the 'mid' symbol for these *)
Notation "'∣' x '⟩'" := (ket x).
Notation "'⟨' x '∣'" := (bra x). (* This gives the Coq parser headaches *)

Notation "∣ x , y , .. , z ⟩" := (kron .. (kron ∣x⟩ ∣y⟩) .. ∣z⟩) (at level 0).

Transparent bra.
Transparent ket.
Transparent qubit0.
Transparent qubit1.

Definition bool_to_ket (b : bool) : Matrix 2 1 := if b then ∣1⟩ else ∣0⟩.

Definition bool_to_matrix (b : bool) : Matrix 2 2 := if b then ∣1⟩⟨1∣ else ∣0⟩⟨0∣.

Definition bool_to_matrix' (b : bool) : Matrix 2 2 := fun x y =>
  match x, y with
  | 0, 0 => if b then 0 else 1
  | 1, 1 => if b then 1 else 0
  | _, _ => 0
  end.

Lemma bool_to_matrix_eq : forall b, bool_to_matrix b = bool_to_matrix' b.
Proof. intros. destruct b; simpl; solve_matrix. Qed.

Lemma bool_to_ket_matrix_eq : forall b,
    outer_product (bool_to_ket b) (bool_to_ket b) = bool_to_matrix b.
Proof. unfold outer_product. destruct b; simpl; reflexivity. Qed.

Definition bools_to_matrix (l : list bool) : Square (2^(length l)) :=
  big_kron (map bool_to_matrix l).

(*************)
(* Unitaries *)
(*************)

Definition hadamard : Matrix 2 2 :=
  (fun x y => match x, y with
          | 0, 0 => (1 / √2)
          | 0, 1 => (1 / √2)
          | 1, 0 => (1 / √2)
          | 1, 1 => -(1 / √2)
          | _, _ => 0
          end).

Fixpoint hadamard_k (k : nat) : Matrix (2^k) (2^k):=
  match k with
  | 0 => I 1
  | S k' => hadamard ⊗ hadamard_k k'
  end.

Lemma hadamard_1 : hadamard_k 1 = hadamard.
Proof. apply kron_1_r. Qed.

(* Alternative definitions:
Definition pauli_x : Matrix 2 2 := fun x y => if x + y =? 1 then 1 else 0.
Definition pauli_y : Matrix 2 2 := fun x y => if x + y =? 1 then (-1) ^ x * Ci else 0.
Definition pauli_z : Matrix 2 2 := fun x y => if (x =? y) && (x <? 2)
                                           then (-1) ^ x * Ci else 0.
*)

Definition σx : Matrix 2 2 :=
  fun x y => match x, y with
          | 0, 1 => C1
          | 1, 0 => C1
          | _, _ => C0
          end.

Definition σy : Matrix 2 2 :=
  fun x y => match x, y with
          | 0, 1 => -Ci
          | 1, 0 => Ci
          | _, _ => C0
          end.

Definition σz : Matrix 2 2 :=
  fun x y => match x, y with
          | 0, 0 => C1
          | 1, 1 => -C1
          | _, _ => C0
          end.

Definition phase_shift (ϕ : R) : Matrix 2 2 :=
  fun x y => match x, y with
          | 0, 0 => C1
          | 1, 1 => Cexp ϕ
          | _, _ => C0
          end.

Definition control {n : nat} (A : Matrix n n) : Matrix (2*n) (2*n) :=
  fun x y => if (x <? n) && (y =? x) then 1 else
          if (n <=? x) && (n <=? y) then A (x-n)%nat (y-n)%nat else 0.

(* Definition cnot := control pauli_x. *)
(* Direct definition makes our lives easier *)
Definition cnot : Matrix 4 4 :=
  fun x y => match x, y with
          | 0, 0 => C1
          | 1, 1 => C1
          | 2, 3 => C1
          | 3, 2 => C1
          | _, _ => C0
          end.

Lemma cnot_eq : cnot = control σx.
Proof.
  unfold cnot, control, σx.
  solve_matrix.
Qed.

(* Swap Matrices *)

Definition swap : Matrix 4 4 :=
  fun x y => match x, y with
          | 0, 0 => C1
          | 1, 2 => C1
          | 2, 1 => C1
          | 3, 3 => C1
          | _, _ => C0
          end.

(* Does this overwrite the other Hint DB M? *)
Hint Unfold qubit0 qubit1 hadamard σx σy σz control cnot swap bra ket : M_db.

(* Lemmas *)
Lemma MmultX1 : σx × ∣1⟩ = ∣0⟩. Proof. solve_matrix. Qed.
Lemma Mmult1X : ⟨1∣ × σx = ⟨0∣. Proof. solve_matrix. Qed.
Lemma MmultX0 : σx × ∣0⟩ = ∣1⟩. Proof. solve_matrix. Qed.
Lemma Mmult0X : ⟨0∣ × σx = ⟨1∣. Proof. solve_matrix. Qed.
Hint Rewrite Mmult0X Mmult1X MmultX0 MmultX1 : M_db.

Lemma swap_swap : swap × swap = I 4. Proof. solve_matrix. Qed.

Lemma swap_swap_r : forall n A, WF_Matrix n 4 A ->
      A × swap × swap = A.
Proof.
  intros.
  rewrite Mmult_assoc.
  rewrite swap_swap.
  apply Mmult_1_r.
  auto.
Qed.

Hint Rewrite swap_swap swap_swap_r using (auto 100 with wf_db): M_db.

(* The input k is really k+1, to appease to Coq termination gods *)
(* NOTE: Check that the offsets are right *)
(* Requires: i + 1 < n *)
Fixpoint swap_to_0_aux (n i : nat) {struct i} : Matrix (2^n) (2^n) :=
  match i with
  | O => swap ⊗ I (2^(n-2))
  | S i' =>  (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) × (* swap i-1 with i *)
            swap_to_0_aux n i' ×
            (I (2^i) ⊗ swap ⊗ I (2^(n-i-2))) (* swap i-1 with 0 *)
  end.

(* Requires: i < n *)
Definition swap_to_0 (n i : nat) : Matrix (2^n) (2^n) :=
  match i with
  | O => I (2^n)
  | S i' => swap_to_0_aux n i'
  end.

(* Swapping qubits i and j in an n-qubit system, where i < j *)
(* Requires i < j, j < n *)
Fixpoint swap_two_aux (n i j : nat) : Matrix (2^n) (2^n) :=
  match i with
  | O => swap_to_0 n j
  | S i' => I 2 ⊗ swap_two_aux (n-1) (i') (j-1)
  end.

(* Swapping qubits i and j in an n-qubit system *)
(* Requires i < n, j < n *)
Definition swap_two (n i j : nat) : Matrix (2^n) (2^n) :=
  if i =? j then I (2^n)
  else if i <? j then swap_two_aux n i j
  else swap_two_aux n j i.

(* Simpler version of swap_to_0 that shifts other elements *)
(* Requires: i+1 < n *)
Fixpoint move_to_0_aux (n i : nat) {struct i}: Matrix (2^n) (2^n) :=
  match i with
  | O => swap ⊗ I (2^(n-2))
  | S i' => (move_to_0_aux n i') × (I (2^i) ⊗ swap ⊗ I (2^(n-i-2)))

  end.

(* Requires: i < n *)
Definition move_to_0 (n i : nat) : Matrix (2^n) (2^n) :=
  match i with
  | O => I (2^n)
  | S i' => move_to_0_aux n i'
  end.

(* Always moves up in the matrix from i to k *)
(* Requires: k < i < n *)
Fixpoint move_to (n i k : nat) : Matrix (2^n) (2^n) :=
  match k with
  | O => move_to_0 n i
  | S k' => I 2 ⊗ move_to (n-1) (i-1) (k')
  end.

(*
Eval compute in ((swap_two 1 0 1) 0 0)%nat.
Eval compute in (print_matrix (swap_two 1 0 2)).
*)

(** Well Formedness of Quantum States and Unitaries **)

Lemma WF_bra0 : WF_Matrix 1 2 ⟨0∣. Proof. show_wf. Qed.
Lemma WF_bra1 : WF_Matrix 1 2 ⟨1∣. Proof. show_wf. Qed.
Lemma WF_qubit0 : WF_Matrix 2 1 ∣0⟩. Proof. show_wf. Qed.
Lemma WF_qubit1 : WF_Matrix 2 1 ∣1⟩. Proof. show_wf. Qed.
Lemma WF_braqubit0 : WF_Matrix 2 2 ∣0⟩⟨0∣. Proof. show_wf. Qed.
Lemma WF_braqubit1 : WF_Matrix 2 2 ∣1⟩⟨1∣. Proof. show_wf. Qed.
Lemma WF_bool_to_ket : forall b, WF_Matrix 2 1 (bool_to_ket b).
Proof. destruct b; show_wf. Qed.
Lemma WF_bool_to_matrix : forall b, WF_Matrix 2 2 (bool_to_matrix b).
Proof. destruct b; show_wf. Qed.
Lemma WF_bool_to_matrix' : forall b, WF_Matrix 2 2 (bool_to_matrix' b).
Proof. destruct b; show_wf. Qed.

Lemma WF_bools_to_matrix : forall l,
  WF_Matrix (2^(length l)) (2^(length l))  (bools_to_matrix l).
Proof.
  induction l; auto with wf_db.
  unfold bools_to_matrix in *; simpl.
  apply WF_kron; try rewrite map_length; try omega.
  apply WF_bool_to_matrix.
  apply IHl.
Qed.

Hint Resolve WF_bra0 WF_bra1 WF_qubit0 WF_qubit1 WF_braqubit0 WF_braqubit1 : wf_db.
Hint Resolve WF_bool_to_ket WF_bool_to_matrix WF_bool_to_matrix' : wf_db.
Hint Resolve WF_bools_to_matrix : wf_db.

Lemma WF_hadamard : WF_Matrix 2 2 hadamard. Proof. show_wf. Qed.
Lemma WF_σx : WF_Matrix 2 2 σx. Proof. show_wf. Qed.
Lemma WF_σy : WF_Matrix 2 2 σy. Proof. show_wf. Qed.
Lemma WF_σz : WF_Matrix 2 2 σz. Proof. show_wf. Qed.
Lemma WF_cnot : WF_Matrix 4 4 cnot. Proof. show_wf. Qed.
Lemma WF_swap : WF_Matrix 4 4 swap. Proof. show_wf. Qed.
Lemma WF_phase : forall ϕ, WF_Matrix 2 2 (phase_shift ϕ). Proof. intros. show_wf. Qed.

Lemma WF_control : forall (n m : nat) (U : Matrix n n),
      (m = 2 * n)%nat ->
      WF_Matrix n n U -> WF_Matrix m m (control U).
Proof.
  intros n m U E WFU. subst.
  unfold control, WF_Matrix in *.
  intros x y [Hx | Hy];
  bdestruct (x <? n); bdestruct (y =? x); bdestruct (n <=? x); bdestruct (n <=? y);
    simpl; try reflexivity; try omega.
  all: rewrite WFU; [reflexivity|omega].
Qed.

Hint Resolve WF_hadamard WF_σx WF_σy WF_σz WF_cnot WF_swap WF_phase WF_control : wf_db.

Hint Extern 2 (WF_Matrix 2 2 (phase_shift _)) => apply WF_phase : wf_db.
Hint Extern 2 (WF_Matrix 2 2 (control _)) => apply WF_control : wf_db.

(***************************)
(** Unitaries are unitary **)
(***************************)

Definition WF_Unitary {n: nat} (U : Matrix n n): Prop :=
  WF_Matrix n n U /\ U † × U = I n.

Hint Unfold WF_Unitary : M_db.

(* More precise *)
(* Definition unitary_matrix' {n: nat} (A : Matrix n n): Prop := Minv A A†. *)

Lemma H_unitary : WF_Unitary hadamard.
Proof.
  split.
  show_wf.
  unfold Mmult, I.
  prep_matrix_equality.
  autounfold with M_db.
  destruct x as [| [|x]]; destruct y as [|[|y]]; simpl; autorewrite with C_db;
    try reflexivity.
  replace ((S (S x) <? 2)) with false by reflexivity.
  rewrite andb_false_r.
  reflexivity.
Qed.

Lemma σx_unitary : WF_Unitary σx.
Proof.
  split.
  show_wf.
  unfold Mmult, I.
  prep_matrix_equality.
  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.
  simpl.
  replace ((S (S x) <? 2)) with false by reflexivity.
  rewrite andb_false_r.
  clra.
Qed.

Lemma σy_unitary : WF_Unitary σy.
Proof.
  split.
  show_wf.
  unfold Mmult, I.
  prep_matrix_equality.
  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.
  simpl.
  replace ((S (S x) <? 2)) with false by reflexivity.
  rewrite andb_false_r.
  clra.
Qed.

Lemma σz_unitary : WF_Unitary σz.
Proof.
  split.
  show_wf.
  unfold Mmult, I.
  prep_matrix_equality.
  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.
  simpl.
  replace ((S (S x) <? 2)) with false by reflexivity.
  rewrite andb_false_r.
  clra.
Qed.

Lemma phase_unitary : forall ϕ, @WF_Unitary 2 (phase_shift ϕ).
Proof.
  intros ϕ.
  split; [show_wf|].
  unfold Mmult, I, phase_shift, adjoint, Cexp.
  prep_matrix_equality.
  destruct x as [| [|x]]; destruct y as [|[|y]]; try clra.
  - simpl.
    Csimpl.
    unfold Cconj, Cmult.
    simpl.
    unfold Rminus.
    rewrite Ropp_mult_distr_l.
    rewrite Ropp_involutive.
    replace (cos ϕ * cos ϕ)%R with ((cos ϕ)²) by easy.
    replace (sin ϕ * sin ϕ)%R with ((sin ϕ)²) by easy.
    rewrite Rplus_comm.
    rewrite sin2_cos2.
    clra.
  - simpl. Csimpl.
    replace ((S (S x) <? 2)) with false by reflexivity.
    rewrite andb_false_r.
    clra.
Qed.

Lemma control_unitary : forall n (A : Matrix n n),
                          WF_Unitary A -> WF_Unitary (control A).
Proof.
  intros n A H.
  destruct H as [WF U].
  split; auto with wf_db.
  unfold control, adjoint, Mmult, I.
  prep_matrix_equality.
  simpl.
  bdestructΩ (x =? y).
  - subst; simpl.
    rewrite Csum_sum.
    bdestructΩ (y <? n + (n + 0)).
    + bdestructΩ (n <=? y).
      * rewrite Csum_0_bounded. Csimpl.
        rewrite (Csum_eq _ (fun x => A x (y - n)%nat ^* * A x (y - n)%nat)).
        ++ unfold control, adjoint, Mmult, I in U.
           rewrite Nat.add_0_r.
           eapply (equal_f) in U.
           eapply (equal_f) in U.
           rewrite U.
           rewrite Nat.eqb_refl. simpl.
           bdestructΩ (y - n <? n).
           easy.
        ++ apply functional_extensionality. intros x.
           bdestructΩ (n + x <? n).
           bdestructΩ (n <=? n + x).
           rewrite minus_plus.
           easy.
        ++ intros x L.
           bdestructΩ (y =? x).
           rewrite andb_false_r.
           bdestructΩ (n <=? x).
           simpl. clra.
      * rewrite (Csum_unique 1).
        rewrite Csum_0_bounded.
        ++ clra.
        ++ intros.
           rewrite andb_false_r.
           bdestructΩ (n + x <? n).
           simpl.
           clra.
        ++ exists y.
           repeat rewrite andb_false_r.
           split. easy.
           split.
           rewrite Nat.eqb_refl.
           bdestructΩ (y <? n).
           simpl. clra.
           intros x Ne.
           bdestructΩ (y =? x ).
           repeat rewrite andb_false_r.
           clra.
    + rewrite 2 Csum_0_bounded; [clra| |].
      * intros x L.
        rewrite WF by (right; omega).
        bdestructΩ (n + x <? n).
        bdestructΩ (n <=? n + x).
        bdestructΩ (n <=? y).
        clra.
      * intros x L.
        bdestructΩ (y =? x).
        rewrite andb_false_r.
        bdestructΩ (n <=? x).
        simpl. clra.
  - simpl.
    rewrite Csum_sum.
    bdestructΩ (y <? n + (n + 0)).
    + bdestructΩ (n <=? y).
      * rewrite Csum_0_bounded. Csimpl.
        bdestructΩ (n <=? x).
        rewrite (Csum_eq _ (fun z => A z (x - n)%nat ^* * A z (y - n)%nat)).
        ++ unfold control, adjoint, Mmult, I in U.
           rewrite Nat.add_0_r.
           eapply (equal_f) in U.
           eapply (equal_f) in U.
           rewrite U.
           bdestructΩ (x - n =? y - n).
           simpl.
           easy.
        ++ apply functional_extensionality. intros z.
           bdestructΩ (n + z <? n).
           bdestructΩ (n <=? n + z).
           rewrite minus_plus.
           easy.
        ++ rewrite Csum_0. easy.
           intros z.
           bdestructΩ (n + z <? n).
           rewrite andb_false_r.
           Csimpl. easy.
        ++ intros z L.
           bdestructΩ (z <? n).
           bdestructΩ (n <=? z).
           bdestructΩ (x =? z); bdestructΩ (y =? z); try clra.
      * bdestructΩ (n <=? x).
        ++ rewrite Csum_0_bounded.
           rewrite Csum_0_bounded. clra.
           ** intros z L.
              bdestructΩ (n + z <? n).
              rewrite andb_false_r.
              clra.
           ** intros z L.
              bdestructΩ (z <? n).
              rewrite andb_false_r.
              bdestructΩ (x =? z); bdestructΩ (y =? z); try clra.
              bdestructΩ (n <=? z).
              clra.
        ++ rewrite 2 Csum_0_bounded; [clra| |].
           ** intros z L.
              rewrite andb_false_r.
              bdestructΩ (x =? n + z); bdestructΩ (y =? n + z); rewrite andb_false_r; clra.
           ** intros z L.
              rewrite andb_false_r.
              bdestructΩ (x =? z); bdestructΩ (y =? z); rewrite andb_false_r; clra.
    + rewrite 2 Csum_0_bounded; [clra| |].
      * intros z L.
        bdestructΩ (n + z <? n).
        bdestructΩ (n <=? n + z).
        bdestructΩ (n <=? y).
        rewrite (WF _ (y-n)%nat) by (right; omega).
        clra.
      * intros z L.
        bdestructΩ (y =? z).
        rewrite andb_false_r.
        rewrite (WF _ (y-n)%nat) by (right; omega).
        destruct ((n <=? z) && (n <=? y)); clra.
Qed.

Lemma transpose_unitary : forall n (A : Matrix n n), WF_Unitary A -> WF_Unitary (A†).
Proof.
  intros.
  simpl.
  split.
  + destruct H; auto with wf_db.
  + unfold WF_Unitary in *.
    rewrite adjoint_involutive.
    destruct H as [_ H].
    apply Minv_left in H as [_ S]. (* NB: admitted lemma *)
    assumption.
Qed.

Lemma cnot_unitary : WF_Unitary cnot.
Proof.
  split.
  apply WF_cnot.
  unfold Mmult, I.
  prep_matrix_equality.
  do 4 (try destruct x; try destruct y; try clra).
  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.
  rewrite andb_false_r.
  clra.
Qed.

Lemma id_unitary : forall n, WF_Unitary (I n).
Proof.
  split.
  apply WF_I.
  unfold WF_Unitary.
  rewrite id_adjoint_eq.
  apply Mmult_1_l.
  apply WF_I.
Qed.

Lemma swap_unitary : WF_Unitary swap.
Proof.
  split.
  apply WF_swap.
  unfold WF_Unitary, Mmult, I.
  prep_matrix_equality.
  do 4 (try destruct x; try destruct y; try clra).
  replace ((S (S (S (S x))) <? 4)) with (false) by reflexivity.
  rewrite andb_false_r.
  clra.
Qed.

Lemma kron_unitary : forall {m n} (A : Matrix m m) (B : Matrix n n),
  WF_Unitary A -> WF_Unitary B -> WF_Unitary (A ⊗ B).
Proof.
  intros m n A B [WFA UA] [WFB UB].
  unfold WF_Unitary in *.
  split.
  auto with wf_db.
  rewrite kron_adjoint.
  rewrite kron_mixed_product.
  rewrite UA, UB.
  rewrite id_kron.
  easy.
Qed.

Lemma Mmult_unitary : forall (n : nat) (A : Square n) (B : Square n),
  WF_Unitary A ->
  WF_Unitary B ->
  WF_Unitary (A × B).
Proof.
  intros n A B [WFA UA] [WFB UB].
  split.
  auto with wf_db.
  autorewrite with M_db.
  rewrite Mmult_assoc.
  rewrite <- (Mmult_assoc _ _ _ _ (A†)).
  rewrite UA.
  autorewrite with M_db.
  apply UB.
Qed.

(********************)
(* Self-adjointness *)
(********************)

Definition id_sa := id_adjoint_eq.

Lemma hadamard_sa : hadamard† = hadamard.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma σx_sa : σx† = σx.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma σy_sa : σy† = σy.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma σz_sa : σz† = σz.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma cnot_sa : cnot† = cnot.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma swap_sa : swap† = swap.
Proof.
  prep_matrix_equality.
  repeat (try destruct x; try destruct y; try clra; trivial).
Qed.

Lemma control_adjoint : forall n (U : Square n), (control U)† = control (U†).
Proof.
  intros n U.
  unfold control, adjoint.
  prep_matrix_equality.
  rewrite Nat.eqb_sym.
  bdestruct (y =? x).
  - subst.
    bdestruct (x <? n); bdestruct (n <=? x); try omega; simpl; clra.
  - rewrite 2 andb_false_r.
    rewrite andb_comm.
    rewrite (if_dist _ _ _ Cconj).
    rewrite Cconj_0.
    reflexivity.
Qed.

Lemma control_sa : forall (n : nat) (A : Square n),
    A† = A -> (control A)† = (control A).
Proof.
  intros n A H.
  rewrite control_adjoint.
  rewrite H.
  easy.
Qed.

Lemma phase_adjoint : forall ϕ, (phase_shift ϕ)† = phase_shift (-ϕ).
Proof.
  intros ϕ.
  unfold phase_shift, adjoint.
  prep_matrix_equality.
  destruct_m_eq; try clra.
  unfold Cexp, Cconj.
  rewrite cos_neg, sin_neg.
  easy.
Qed.

Lemma braqubit0_sa : ∣0⟩⟨0∣† = ∣0⟩⟨0∣. Proof. mlra. Qed.
Lemma braqubit1_sa : ∣1⟩⟨1∣† = ∣1⟩⟨1∣. Proof. mlra. Qed.

Hint Rewrite hadamard_sa σx_sa σy_sa σz_sa cnot_sa swap_sa
             braqubit1_sa braqubit0_sa control_adjoint phase_adjoint : M_db.

(* Rather use control_adjoint :
Hint Rewrite control_sa using (autorewrite with M_db; reflexivity) : M_db. *)

(************************************)
(* Unitary Properties on Basis Kets *)
(************************************)

(*
Definition plus_state := 1/√2 .* ∣0⟩ .+ 1/√2 .* ∣1⟩.
Definition minus_state := 1/√2 .* ∣0⟩ .+ (-1/√2) .* ∣1⟩.

Transparent plus_state.
Transparent minus_state.

Notation "∣+⟩" := plus_state.
Notation "∣-⟩" := minus_state.
*)

Notation "∣+⟩" := (/√2 .* ∣0⟩ .+ /√2 .* ∣1⟩).
Notation "∣-⟩" := (/√2 .* ∣0⟩ .+ (-/√2) .* ∣1⟩).

(* Hadamard properties *)
Lemma H0_spec : hadamard × ∣0⟩ = ∣+⟩.
Proof. solve_matrix. Qed.

Lemma H1_spec : hadamard × ∣1⟩ = ∣-⟩.
Proof. solve_matrix. Qed.

Lemma Hplus_spec : hadamard × ∣+⟩ = ∣0⟩.
Proof. solve_matrix. Qed.

Lemma Hminus_spec : hadamard × ∣-⟩ = ∣1⟩.
Proof. solve_matrix.  Qed.

(* X properties *)
Lemma X0_spec : σx × ∣0⟩ = ∣1⟩.
Proof. solve_matrix. Qed.

Lemma X1_spec : σx × ∣1⟩ = ∣0⟩.
Proof. solve_matrix. Qed.

(* Y properties *)
Lemma Y0_spec : σy × ∣0⟩ = Ci .* ∣1⟩.
Proof. solve_matrix. Qed.

Lemma Y1_spec : σy × ∣1⟩ = -Ci .* ∣0⟩.
Proof. solve_matrix. Qed.

(* Z properties *)
Lemma Z0_spec : σz × ∣0⟩ = ∣0⟩.
Proof. solve_matrix. Qed.

Lemma Z1_spec : σz × ∣1⟩ = -C1 .* ∣1⟩.
Proof. solve_matrix. Qed.

(* CNOT properties *)

Lemma CNOT_spec : forall (x y : nat), (x < 2)%nat -> (y < 2)%nat -> cnot × ∣x,y⟩ = ∣x, (x + y) mod 2⟩.
Proof.
  intros.
  destruct x as [| [|x]], y as [| [|y]]; try omega; solve_matrix.
Qed.

Lemma CNOT00_spec : cnot × ∣0,0⟩ = ∣0,0⟩.
Proof. solve_matrix. Qed.

Lemma CNOT01_spec : cnot × ∣0,1⟩ = ∣0,1⟩.
Proof. crunch_matrix. Qed.

Lemma CNOT10_spec : cnot × ∣1,0⟩ = ∣1,1⟩.
Proof. solve_matrix. Qed.

Lemma CNOT11_spec : cnot × ∣1,1⟩ = ∣1,0⟩.
Proof. solve_matrix. Qed.

(* SWAP properties *)

Lemma SWAP_spec : forall x y, swap × ∣x,y⟩ = ∣y,x⟩.
Proof. intros. destruct x,y; solve_matrix. Qed.

(* Automation *)

Hint Rewrite Mmult_plus_distr_l Mscale_plus_distr Mscale_mult_dist_r Mscale_mult_dist_l : ket_db.
Hint Rewrite Mscale_assoc Mmult_assoc: ket_db.
Hint Rewrite Mscale_0_l Mscale_1_l : ket_db.
Hint Rewrite H0_spec H1_spec Hplus_spec Hminus_spec X0_spec X1_spec Y0_spec Y1_spec
     Z0_spec Z1_spec : ket_db.

Ltac ket_eq_solver :=
  intros; autorewrite with ket_db C_db;
  try match goal with
  | [|- ?a .* ∣0⟩ .+ ?b .* ∣1⟩ = ?a' .* ∣0⟩ .+ ?b' .* ∣1⟩ ] =>
    replace a with a'; try clra; replace b with b'; try clra; trivial
  end.

Lemma XYZ0 : -Ci .* σx × σy × σz × ∣0⟩ = ∣0⟩.
Proof. autorewrite with ket_db C_db; easy. Qed.

Lemma XYZ1 : -Ci .* σx × σy × σz × ∣1⟩ = ∣1⟩.
Proof. autorewrite with ket_db C_db; easy. Qed.

Lemma XYZ : forall α β, -Ci .* σx × σy × σz × (α .* ∣0⟩ .+ β .* ∣1⟩) = α .* ∣0⟩ .+ β .* ∣1⟩.
Proof.
  ket_eq_solver.
Qed.

Proposition HZH : forall α β,
  hadamard × σz × hadamard × (α .* ∣0⟩ .+ β .* ∣1⟩) = σx × (α .* ∣0⟩ .+ β .* ∣1⟩).
Proof.
  ket_eq_solver.
Abort.

(* Next up:
   Multiqubit systems.
   Have ket_eq_solver group ∣0⟩s and ∣1⟩s.
*)

(**************)
(* Automation *)
(**************)

(* For when autorewrite needs some extra help *)

Ltac Msimpl :=
  repeat match goal with
  | [ |- context[(?A ⊗ ?B)†]]    => let H := fresh "H" in
                                  specialize (kron_adjoint _ _ _ _ A B) as H;
                                  simpl in H; rewrite H; clear H
  | [ |- context[(control ?U)†]] => let H := fresh "H" in
                                  specialize (control_sa _ U) as H;
                                  simpl in H; rewrite H;
                                  [clear H | Msimpl; reflexivity]
  | [|- context[(?A ⊗ ?B) × (?C ⊗ ?D)]] =>
                                  let H := fresh "H" in
                                  specialize (kron_mixed_product _ _ _ _ _ _ A B C D);
                                  intros H; simpl in H; rewrite H; clear H
  | _                           => autorewrite with M_db
  end.

(*****************************)
(* Positive Semidefiniteness *)
(*****************************)

Definition positive_semidefinite {n} (A : Square n) : Prop :=
  forall (z : Matrix n 1), WF_Matrix 2 1 z -> fst ((z† × A × z) O O) >= 0.

Lemma braqubit0_psd : positive_semidefinite ∣0⟩⟨0∣.
Proof.
  intros z WFz.
  do 3 reduce_matrices.
  simpl.
  rewrite <- Ropp_mult_distr_l.
  unfold Rminus.
  rewrite Ropp_involutive.
  replace (fst (z 0%nat 0%nat) * fst (z 0%nat 0%nat))%R with ((fst (z 0%nat 0%nat))²) by easy.
  replace (snd (z 0%nat 0%nat) * snd (z 0%nat 0%nat))%R with ((snd (z 0%nat 0%nat))²) by easy.
  apply Rle_ge.
  apply Rplus_le_le_0_compat; apply Rle_0_sqr.
Qed.

Lemma braqubit1_psd : positive_semidefinite ∣1⟩⟨1∣.
Proof.
  intros z WFz.
  do 3 reduce_matrices.
  simpl.
  rewrite <- Ropp_mult_distr_l.
  unfold Rminus.
  rewrite Ropp_involutive.
  replace (fst (z 1%nat 0%nat) * fst (z 1%nat 0%nat))%R with ((fst (z 1%nat 0%nat))²) by easy.
  replace (snd (z 1%nat 0%nat) * snd (z 1%nat 0%nat))%R with ((snd (z 1%nat 0%nat))²) by easy.
  apply Rle_ge.
  apply Rplus_le_le_0_compat; apply Rle_0_sqr.
Qed.

Lemma H0_psd : positive_semidefinite (hadamard × ∣0⟩⟨0∣ × hadamard).
Proof.
  intros z WFz.
  do 5 reduce_matrices.
  simpl.
  autorewrite with R_db.
  replace (√ 2 * / 2 * (√ 2 * / 2))%R with ((√ 2 / 2)²) by reflexivity.
  rewrite Rsqr_div by lra.
  rewrite Rsqr_sqrt by lra.
  Search (_ * ?x + _ * ?x).
  rewrite <- Rmult_plus_distr_r.
  Search (- _ + - _).
  rewrite <- Ropp_plus_distr.
  repeat rewrite <- Ropp_mult_distr_l.
  repeat rewrite Ropp_involutive.
  rewrite <- Rmult_plus_distr_r.
  rewrite (Rmult_comm _ (2/2²)).
  rewrite (Rmult_comm _ (2/2²)).
  repeat rewrite Rmult_assoc.
  repeat rewrite <- Rmult_plus_distr_l.
  apply Rle_ge.
  apply Rmult_le_pos.
  left.
  apply Rmult_lt_0_compat.
  lra.
  apply Rinv_0_lt_compat.
  apply Rmult_lt_0_compat; lra.
  Search ((_ + _) * _)%R.
  repeat rewrite Rmult_plus_distr_r.
  remember (fst (z 0 0)%nat) as a.
  remember (snd (z 0 0)%nat) as b.
  remember (fst (z 1 0)%nat) as c.
  remember (snd (z 1 0)%nat) as d.
  (* This is (a + b)² + (b + c)². *)
  clear.
  rewrite <- Rplus_assoc.
  remember (a * a + c * a)%R as ac1.
  remember (b * b + d * b)%R as bd1.
  remember (a * c + c * c)%R as ac2.
  remember (b * d + d * d)%R as bd2.
  rewrite (Rplus_assoc ac1).
  rewrite (Rplus_comm bd1).
  repeat rewrite <- Rplus_assoc.
  rewrite (Rplus_assoc _ bd1).
  apply Rplus_le_le_0_compat.
  replace (ac1 + ac2)%R with ((a + c)²).
  apply Rle_0_sqr.
  unfold Rsqr. lra.
  replace (bd1 + bd2)%R with ((b + d)²).
  apply Rle_0_sqr.
  unfold Rsqr. lra.
Qed.

(*************************)
(* Pure and Mixed States *)
(*************************)

Notation Density n := (Matrix n n) (only parsing).

Definition Classical {n} (ρ : Density n) := forall i j, i <> j -> ρ i j = 0.

Definition Pure_State_Vector {n} (φ : Matrix n 1): Prop :=
  WF_Matrix n 1 φ /\ φ† × φ = I  1.

Definition Pure_State {n} (ρ : Density n) : Prop :=
  exists φ, Pure_State_Vector φ /\ ρ = φ × φ†.

Inductive Mixed_State {n} : Matrix n n -> Prop :=
| Pure_S : forall ρ, Pure_State ρ -> Mixed_State ρ
| Mix_S : forall (p : R) ρ1 ρ2, 0 < p < 1 -> Mixed_State ρ1 -> Mixed_State ρ2 ->
                                       Mixed_State (p .* ρ1 .+ (1-p)%R .* ρ2).

Lemma WF_Pure : forall {n} (ρ : Density n), Pure_State ρ -> WF_Matrix n n ρ.
Proof. intros. destruct H as [φ [[WFφ IP1] Eρ]]. rewrite Eρ. auto with wf_db. Qed.
Hint Resolve WF_Pure : wf_db.

Lemma WF_Mixed : forall {n} (ρ : Density n), Mixed_State ρ -> WF_Matrix n n ρ.
Proof. induction 1; auto with wf_db. Qed.
Hint Resolve WF_Mixed : wf_db.

Lemma pure0 : Pure_State ∣0⟩⟨0∣.
Proof. exists ∣0⟩. intuition. split. auto with wf_db. solve_matrix. Qed.

Lemma pure1 : Pure_State ∣1⟩⟨1∣.
Proof. exists ∣1⟩. intuition. split. auto with wf_db. solve_matrix. Qed.

Lemma pure_id1 : Pure_State (I  1).
Proof. exists (I  1). split. split. auto with wf_db. solve_matrix. solve_matrix. Qed.

Lemma pure_dim1 : forall (ρ : Square 1), Pure_State ρ -> ρ = I  1.
Proof.
  intros ρ [φ [[WFφ IP1] Eρ]].
  apply Minv_flip in IP1.
  rewrite Eρ; easy.
Qed.

Lemma pure_state_kron : forall m n (ρ : Square m) (φ : Square n),
  Pure_State ρ -> Pure_State φ -> Pure_State (ρ ⊗ φ).
Proof.
  intros m n ρ φ [u [[WFu Pu] Eρ]] [v [[WFv Pv] Eφ]].
  exists (u ⊗ v).
  split; [split |].
  - auto with wf_db.
  - Msimpl. rewrite Pv, Pu. Msimpl. easy.
  - Msimpl. subst. easy.
Qed.

Lemma mixed_state_kron : forall m n (ρ : Square m) (φ : Square n),
  Mixed_State ρ -> Mixed_State φ -> Mixed_State (ρ ⊗ φ).
Proof.
  intros m n ρ φ Mρ Mφ.
  induction Mρ.
  induction Mφ.
  - apply Pure_S. apply pure_state_kron; easy.
  - rewrite kron_plus_distr_l.
    rewrite 2 Mscale_kron_dist_r.
    apply Mix_S; easy.
  - rewrite kron_plus_distr_r.
    rewrite 2 Mscale_kron_dist_l.
    apply Mix_S; easy.
Qed.

Lemma pure_state_trace_1 : forall {n} (ρ : Density n), Pure_State ρ -> trace ρ = 1.
Proof.
  intros n ρ [u [[WFu Uu] E]].
  subst.
  clear -Uu.
  unfold trace.
  unfold Mmult, adjoint in *.
  simpl in *.
  match goal with
    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)
  end.
  unfold I in H; simpl in H.
  rewrite <- H.
  apply Csum_eq.
  apply functional_extensionality.
  intros x.
  rewrite Cplus_0_l, Cmult_comm.
  easy.
Qed.

Lemma mixed_state_trace_1 : forall {n} (ρ : Density n), Mixed_State ρ -> trace ρ = 1.
Proof.
  intros n ρ H.
  induction H.
  - apply pure_state_trace_1. easy.
  - rewrite trace_plus_dist.
    rewrite 2 trace_mult_dist.
    rewrite IHMixed_State1, IHMixed_State2.
    clra.
Qed.

(* The following two lemmas say that for any mixed states, the elements along the
   diagonal are real numbers in the [0,1] interval. *)

Lemma mixed_state_diag_in01 : forall {n} (ρ : Density n) i , Mixed_State ρ ->
                                                        0 <= fst (ρ i i) <= 1.
Proof.
  intros.
  induction H.
  - destruct H as [φ [[WFφ IP1] Eρ]].
    destruct (lt_dec i n).
    2: {
      rewrite Eρ. unfold Mmult, adjoint. simpl. rewrite WFφ. simpl. lra.
      omega. }
    rewrite Eρ.
    unfold Mmult, adjoint in *.
    simpl in *.
    rewrite Rplus_0_l.
    match goal with
    [H : ?f = ?g |- _] => assert (f O O = g O O) by (rewrite <- H; easy)
    end.
    unfold I in H. simpl in H. clear IP1.
    match goal with
    [ H : ?x = ?y |- _] => assert (H': fst x = fst y) by (rewrite H; easy); clear H
    end.
    simpl in H'.
    rewrite <- H'.
    split.
    + unfold Rminus. rewrite <- Ropp_mult_distr_r. rewrite Ropp_involutive.
      rewrite <- Rplus_0_r at 1.
      apply Rplus_le_compat; apply Rle_0_sqr.
    + match goal with
      [ |- ?x <= fst (Csum ?f ?m)] => specialize (Csum_member_le f n) as res
      end.
      simpl in *.
      unfold Rminus in *.
      Search (_ * - _)%R.
      rewrite <- Ropp_mult_distr_r.
      rewrite Ropp_mult_distr_l.
      apply res with (x := i); trivial.
      intros x.
      unfold Rminus. rewrite <- Ropp_mult_distr_l. rewrite Ropp_involutive.
      rewrite <- Rplus_0_r at 1.
      apply Rplus_le_compat; apply Rle_0_sqr.
  - simpl.
    repeat rewrite Rmult_0_l.
    repeat rewrite Rminus_0_r.
    split.
    assert (0 <= p * fst (ρ1 i i)).
      apply Rmult_le_pos; lra.
    assert (0 <= (1 - p) * fst (ρ2 i i)).
      apply Rmult_le_pos; lra.
    lra.
    assert (p * fst (ρ1 i i) <= p)%R.
      rewrite <- Rmult_1_r.
      apply Rmult_le_compat_l; lra.
    assert ((1 - p) * fst (ρ2 i i) <= (1-p))%R.
      rewrite <- Rmult_1_r.
      apply Rmult_le_compat_l; lra.
    lra.
Qed.

Lemma mixed_state_diag_real : forall {n} (ρ : Density n) i , Mixed_State ρ ->
                                                        snd (ρ i i) = 0.
Proof.
  intros.
  induction H.
  + unfold Pure_State in H.
  - destruct H as [φ [[WFφ IP1] Eρ]].
    rewrite Eρ.
    simpl.
    lra.
  + simpl.
    rewrite IHMixed_State1, IHMixed_State2.
    repeat rewrite Rmult_0_r, Rmult_0_l.
    lra.
Qed.

Lemma mixed_dim1 : forall (ρ : Square 1), Mixed_State ρ -> ρ = I  1.
Proof.
  intros.
  induction H.
  + apply pure_dim1; trivial.
  + rewrite IHMixed_State1, IHMixed_State2.
    prep_matrix_equality.
    clra.
Qed.

(** Density matrices and superoperators **)

Definition Superoperator m n := Density m -> Density n.

Definition WF_Superoperator {m n} (f : Superoperator m n) :=
  (forall ρ, Mixed_State ρ -> Mixed_State (f ρ)).

Definition super {m n} (M : Matrix m n) : Superoperator n m := fun ρ =>
  M × ρ × M†.

Lemma super_I : forall n ρ,
      WF_Matrix n n ρ ->
      super (I n) ρ = ρ.
Proof.
  intros.
  unfold super.
  autorewrite with M_db.
  reflexivity.
Qed.

Lemma WF_super : forall  m n (U : Matrix m n) (ρ : Square n),
  WF_Matrix m n U -> WF_Matrix n n ρ -> WF_Matrix m m (super U ρ).
Proof.
  unfold super.
  auto with wf_db.
Qed.

Hint Resolve WF_super : wf_db.

Lemma super_outer_product : forall m (φ : Matrix m 1) (U : Matrix m m),
    super U (outer_product φ φ) = outer_product (U × φ) (U × φ).
Proof.
  intros. unfold super, outer_product.
  autorewrite with M_db.
  repeat rewrite Mmult_assoc. reflexivity.
Qed.

Definition compose_super {m n p} (g : Superoperator n p) (f : Superoperator m n)
                      : Superoperator m p := fun ρ => g (f ρ).

Lemma WF_compose_super : forall m n p (g : Superoperator n p) (f : Superoperator m n)
  (ρ : Square m),
  WF_Matrix m m ρ ->
  (forall A, WF_Matrix m m A -> WF_Matrix n n (f A)) ->
  (forall A, WF_Matrix n n A -> WF_Matrix p p (g A)) ->
  WF_Matrix p p (compose_super g f ρ).
Proof.
  unfold compose_super.
  auto.
Qed.

Hint Resolve WF_compose_super : wf_db.

Lemma compose_super_correct : forall {m n p}
                              (g : Superoperator n p) (f : Superoperator m n),
      WF_Superoperator g ->
      WF_Superoperator f ->
      WF_Superoperator (compose_super g f).
Proof.
  intros m n p g f pf_g pf_f.
  unfold WF_Superoperator.
  intros ρ mixed.
  unfold compose_super.
  apply pf_g. apply pf_f. auto.
Qed.

Definition sum_super {m n} (f g : Superoperator m n) : Superoperator m n :=
  fun ρ => (1/2)%R .* f ρ .+ (1 - 1/2)%R .* g ρ.

Lemma sum_super_correct : forall m n (f g : Superoperator m n),
      WF_Superoperator f -> WF_Superoperator g -> WF_Superoperator (sum_super f g).
Proof.
  intros m n f g wf_f wf_g ρ pf_ρ.
  unfold sum_super.
  set (wf_f' := wf_f _ pf_ρ).
  set (wf_g' := wf_g _ pf_ρ).
  apply (Mix_S (1/2) (f ρ) (g ρ)); auto.
  lra.
Qed.

(* Maybe we shouldn't call these superoperators? Neither is trace-preserving *)
Definition SZero {m n} : Superoperator m n := fun ρ => Zero.
Definition Splus {m n} (S T : Superoperator m n) : Superoperator m n :=
  fun ρ => S ρ .+ T ρ.

(* These are *)
Definition new0_op : Superoperator 1 2 := super ∣0⟩.
Definition new1_op : Superoperator 1 2 := super ∣1⟩.
Definition meas_op : Superoperator 2 2 := Splus (super ∣0⟩⟨0∣) (super ∣1⟩⟨1∣).
Definition discard_op : Superoperator 2 1 := Splus (super ⟨0∣) (super ⟨1∣).

Lemma pure_unitary : forall {n} (U ρ : Matrix n n),
  WF_Unitary U -> Pure_State ρ -> Pure_State (super U ρ).
Proof.
  intros n U ρ [WFU H] [φ [[WFφ IP1] Eρ]].
  rewrite Eρ.
  exists (U × φ).
  split.
  - split; auto with wf_db.
    rewrite (Mmult_adjoint _ _ _ U φ).
    rewrite Mmult_assoc.
    rewrite <- (Mmult_assoc _ _ _ _ (U†)).
    rewrite H, Mmult_1_l, IP1; easy.
  - unfold super.
    rewrite (Mmult_adjoint _ _ _ U φ).
    repeat rewrite Mmult_assoc.
    reflexivity.
Qed.

Lemma mixed_unitary : forall {n} (U ρ : Matrix n n),
  WF_Unitary U -> Mixed_State ρ -> Mixed_State (super U ρ).
Proof.
  intros n U ρ H M.
  induction M.
  + apply Pure_S.
    apply pure_unitary; trivial.
  + unfold WF_Unitary, super in *.
    rewrite Mmult_plus_distr_l.
    rewrite Mmult_plus_distr_r.
    rewrite 2 Mscale_mult_dist_r.
    rewrite 2 Mscale_mult_dist_l.
    apply Mix_S; trivial.
Qed.

Lemma super_unitary_correct : forall {n} (U : Matrix n n),
  WF_Unitary U -> WF_Superoperator (super U).
Proof.
  intros n U H ρ Mρ.
  apply mixed_unitary; easy.
Qed.

Lemma compose_super_assoc : forall {m n p q}
      (f : Superoperator m n) (g : Superoperator n p) (h : Superoperator p q),
      compose_super (compose_super f g) h
    = compose_super f (compose_super g h).
Proof. easy. Qed.

(* This is compose_super_correct
Lemma WF_Superoperator_compose : forall m n p (s : Superoperator n p) (s' : Superoperator m n),
    WF_Superoperator s ->
    WF_Superoperator s' ->
    WF_Superoperator (compose_super s s').
Proof.
  unfold WF_Superoperator.
  intros m n p s s' H H0 ρ H1.
  unfold compose_super.
  apply H.
  apply H0.
  easy.
Qed.
*)

(****************************************)
(* Tests and Lemmas about swap matrices *)
(****************************************)

Lemma swap_spec : forall (q q' : Matrix 2 1), WF_Matrix 2 1 q ->
                                         WF_Matrix 2 1 q' ->
                                         swap × (q ⊗ q') = q' ⊗ q.
Proof.
  intros q q' WF WF'.
  solve_matrix.
  - destruct y. clra.
    rewrite WF by omega.
    rewrite (WF' O (S y)) by omega.
    clra.
  - destruct y. clra.
    rewrite WF by omega.
    rewrite (WF' O (S y)) by omega.
    clra.
  - destruct y. clra.
    rewrite WF by omega.
    rewrite (WF' 1%nat (S y)) by omega.
    clra.
  - destruct y. clra.
    rewrite WF by omega.
    rewrite (WF' 1%nat (S y)) by omega.
    clra.
Qed.

Example swap_to_0_test_24 : forall (q0 q1 q2 q3 : Matrix 2 1),
  WF_Matrix 2 1 q0 -> WF_Matrix 2 1 q1 -> WF_Matrix 2 1 q2 -> WF_Matrix 2 1 q3 ->
  swap_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q1 ⊗ q0 ⊗ q3).
Proof.
  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.
  unfold swap_to_0, swap_to_0_aux.
  repeat rewrite Mmult_assoc.
  rewrite (kron_assoc _ _ _ _ _ _ q0 q1).
  rewrite kron_mixed_product.
  rewrite (kron_mixed_product _ _ _ _ _ _ (I  (2^1)) swap).
  rewrite swap_spec by assumption.
  Msimpl.
  rewrite (kron_assoc _ _ _ _ _ _ q0).
  rewrite (kron_assoc _ _ _ _ _ _ q2 q1).
  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q2 (q1 ⊗ q3)).
  simpl.
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 4) (q0 ⊗ q2) (q1 ⊗ q3)).
  rewrite swap_spec by assumption.
  Msimpl.
  rewrite (kron_assoc _ _ _ _ _ _ q2 q0).
  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q1 q3).
  setoid_rewrite (kron_assoc _ _ _ _ _ _ (I 2)).
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ (I 2) (swap ⊗ I 2) q2 _).
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 2) _ _).
  Msimpl.
  rewrite swap_spec by assumption.
  repeat setoid_rewrite kron_assoc.
  reflexivity.
Qed.

Lemma swap_two_base : swap_two 2 1 0 = swap.
Proof. unfold swap_two. simpl. apply kron_1_r. Qed.

Lemma swap_second_two : swap_two 3 1 2 = I 2 ⊗ swap.
Proof. unfold swap_two.
       simpl.
       rewrite kron_1_r.
       reflexivity.
Qed.

Lemma swap_0_2 : swap_two 3 0 2 = (I 2 ⊗ swap) × (swap ⊗ I 2) × (I 2 ⊗ swap).
Proof.
  unfold swap_two.
  simpl.
  Msimpl.
  reflexivity.
Qed.

(*
Proposition swap_to_0_spec : forall (q q0 : Matrix 2 1) (n k : nat) (l1 l2 : list (Matrix 2 1)),
   length l1 = (k - 1)%nat ->
   length l2 = (n - k - 2)%nat ->
   @Mmult (2^n) (2^n) 1 (swap_to_0 n k) (⨂ ([q0] ++ l1 ++ [q] ++ l2)) =
     ⨂ ([q] ++ l1 ++ [q0] ++ l2).

Proposition swap_two_spec : forall (q q0 : Matrix 2 1) (n0 n1 n2 n k : nat) (l0 l1 l2 : list (Matrix 2 1)),
   length l0 = n0 ->
   length l1 = n1 ->
   length l2 = n2 ->
   n = (n0 + n1 + n2 + 2)%nat ->
   @Mmult (2^n) (2^n) 1
     (swap_two n n0 (n0+n1+1)) (⨂ (l0 ++ [q0] ++ l1 ++ [q] ++ l2)) =
     ⨂ (l0 ++ [q] ++ l1 ++ [q0] ++ l2).
*)

Example move_to_0_test_24 : forall (q0 q1 q2 q3 : Matrix 2 1),
  WF_Matrix 2 1 q0 -> WF_Matrix 2 1 q1 -> WF_Matrix 2 1 q2 -> WF_Matrix 2 1 q3 ->
  move_to_0 4 2 × (q0 ⊗ q1 ⊗ q2 ⊗ q3) = (q2 ⊗ q0 ⊗ q1 ⊗ q3).
Proof.
  intros q0 q1 q2 q3 WF0 WF1 WF2 WF3.
  unfold move_to_0, move_to_0_aux.
  repeat rewrite Mmult_assoc.
  rewrite (kron_assoc _ _ _ _ _ _ q0 q1).
  simpl.
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ ((I 2) ⊗ swap) (I 2)
                                     (q0 ⊗ (q1 ⊗ q2)) q3).
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ (I 2) swap q0 (q1 ⊗ q2)).
  Msimpl.
  rewrite swap_spec by assumption.
  setoid_rewrite <- (kron_assoc _ _ _ _ _ _ q0 q2 q1).
  setoid_rewrite (kron_assoc _ _ _ _ _ _ (q0 ⊗ q2) q1 q3).
  setoid_rewrite (kron_mixed_product _ _ _ _ _ _ swap (I 4) (q0 ⊗ q2) (q1 ⊗ q3)).
  rewrite swap_spec by assumption.
  Msimpl.
  repeat setoid_rewrite kron_assoc.
  reflexivity.
Qed.

(* *)


Set Primitive Projections.

From HB Require Import structures.

HB.mixin Record proset_op T := { Pleq : T -> T -> Prop }.
HB.structure Definition proset_raw := { T of proset_op T }.
Notation "x <= y" := (@Pleq _ x y) (at level 70).

HB.mixin Record monoid_op T of proset_raw T := { Mzero : T ; Madd : T -> T -> T }.
HB.structure Definition monoid_raw := { T of proset_raw T & monoid_op T }.
Notation "0" := (@Mzero _).
Notation "x + y" := (@Madd _ x y).

HB.mixin Record semiring_op T of monoid_raw T := { SRone : T ; SRmul : T -> T -> T }.
HB.structure Definition semiring_raw := { T of monoid_raw T & semiring_op T}.
Notation "1" := (@SRone _).
Notation "x * y" := (@SRmul _ x y).

HB.mixin Record proset_ax T of proset_raw T :=
  { Pleq_refl : forall x : T, x <= x ;
    Pleq_trans : forall {x y z : T}, x <= y -> y <= z -> x <= z }.
HB.structure Definition proset := {T of proset_raw T & proset_ax T }.

HB.mixin Record monoid_ax T of proset T & monoid_raw T :=
  { Madd_mono : forall a b c d : T, a <= b -> c <= d -> a + c <= b + d ;
    Madd_0_l : forall a : T, 0 + a <= a ;
    Madd_0_r : forall a : T, a <= a + 0 ;
    Madd_assoc : forall a b c : T, (a + b) + c <= a + (b + c) }.
HB.structure Definition monoid := { T of proset T & monoid_raw T & monoid_ax T }.

HB.mixin Record semiring_ax T of monoid T & semiring_raw T := {
  SRadd_comm : forall a b : T, a + b <= b + a ;
  SRmul_0_l : forall a : T, 0 * a <= 0 ;
  SRmul_0_r : forall a : T, 0 <= 0 * a ;
  SRaddmul_l : forall a b c : T, (a + b) * c <= a * c + b * c ;
  SRaddmul_r : forall a b c : T, a * b + a * c <= a * (b + c) ;
}.
HB.structure Definition semiring := { T of monoid T & semiring_raw T & semiring_ax T }.

(* /!\ upstream bug in hierarchical structures

HB.mixin Record semimodule_op (S : semiring.type) (T : Type) :=
  { SMact : S -> T -> T }.
HB.structure Definition semimodule_raw (S : semiring.type) :=
  { T of monoid_raw T & semimodule_op S T }.

Print semimodule_raw.axioms.
Notation "x # y" := (@SMact _ _ x y) (at level 50).

HB.mixin Record semimodule_ax (S : semiring.type) (T : Type) of semimodule_raw S T := {
  SMadd_comm : forall a : T, a <= a ;
}.
  SMmul_mono : forall (a b : SR) (c d : SM), a <= b -> c <= d -> a # c <= b # d ;
  SMmul_1_l : forall a : SM, 1 # a <= a ;
  SMmulact : forall (a b : SR) (c : SM), (a * b) # c <= a # (b # c) ;
  SMact_0_l : forall a : SM, 0 # a <= 0 ;
  SMact_0_r : forall a : SR, 0 <= a # (0 : SM) ;
  SMaddact_l : forall (a b : SR) (c : SM), (a + b) # c <= (a # c) + (b # c) ;
  SMaddact_r : forall (a : SR) (b c : SM), (a # b) + (a # c) <= a # (b + c) ;
}
*)


Require Import GeoCoq.Axioms.parallel_postulates.
Require Import GeoCoq.Tarski_dev.Annexes.saccheri.

Section thales_existence_rah.

Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.

Lemma thales_existence__rah : existential_thales_postulate -> postulate_of_right_saccheri_quadrilaterals.
Proof.
  intro thales.
  destruct thales as [A [B [C [M]]]].
  spliter.
  apply (t22_17__rah A B C M); assumption.
Qed.

End thales_existence_rah.


Require Import Bool Arith List.
Set Implicit Arguments.
Set Asymmetric Patterns.

Definition table_T (tuple_T: Type) := list tuple_T.
Definition non_empty {tuple_T: Type} (l: table_T tuple_T) :=
  match l with
   | nil => False
   | h :: t => True
  end.

Fixpoint row_transform {tuple_T1 tuple_T2: Type}
(op : tuple_T1 -> tuple_T2) (l : table_T tuple_T1) : table_T tuple_T2:=
  match l with
  | nil => nil
  | h :: t => (op h) :: (row_transform op t)
  end.

Fixpoint filter {tuple_T: Type}
(f : tuple_T -> bool) (l : table_T tuple_T) : table_T tuple_T:=
  match l with
  | nil => nil
  | h :: t => if f h then h :: (filter f t) else (filter f t)
  end.

Definition row_transform_sz {tuple_T1 tuple_T2: Type}
(op : tuple_T1 -> tuple_T2) (f : tuple_T2 -> bool) (g : tuple_T1 -> bool)
(len : nat) :=
forall (t : table_T tuple_T1),
(length t <= len) -> (filter f (row_transform op t) = row_transform op (filter g t)).

Lemma filter_split {tuple_T: Type} :
forall (t : table_T tuple_T) (tup : tuple_T) (f: tuple_T -> bool),
filter f (tup::t) = ((filter f (tup::nil)) ++ filter f t).
Proof.
intros.
simpl. destruct (f tup). simpl. reflexivity.
simpl. reflexivity.
Qed.

Lemma filter_split2 {tuple_T: Type} :
forall (t1 t2: table_T tuple_T) (f: tuple_T -> bool),
filter f (t1++t2) = (filter f t1) ++ (filter f t2).
Proof.
intros.
induction t1.
+ simpl. reflexivity.
+ rewrite filter_split. simpl.
  destruct (f a). simpl. rewrite IHt1. reflexivity.
  rewrite IHt1. simpl. reflexivity.
Qed.

Lemma transform_split {tuple_T1 tuple_T2: Type} :
forall (t : table_T tuple_T1) (tup : tuple_T1) (op: tuple_T1 -> tuple_T2),
row_transform op (tup::t) = (row_transform op (tup::nil)) ++ (row_transform op t).
Proof.
intros.
simpl. reflexivity.
Qed.

Lemma transform_split2 {tuple_T1 tuple_T2: Type} :
forall (t1 t2 : table_T tuple_T1) (op: tuple_T1 -> tuple_T2),
row_transform op (t1++t2) = (row_transform op t1) ++ (row_transform op t2).
Proof.
intros. induction t1.
 + simpl.  reflexivity.
 + rewrite transform_split. simpl. rewrite IHt1. reflexivity.
Qed.

(* SMP proof *)
Theorem row_transform_smp :
forall (tuple_T1 tuple_T2 : Type)
(op : tuple_T1 -> tuple_T2) (f : tuple_T2 -> bool) (g : tuple_T1 -> bool)
(len : nat),
(row_transform_sz op f g 1) -> (row_transform_sz op f g len).
Proof.
intros.
induction len.
(* empty table *)
{ unfold row_transform_sz. intros. induction t. simpl. reflexivity.
  simpl in H0. apply Nat.nle_succ_0 in H0. contradiction. }
induction len.
apply H.
{ unfold row_transform_sz. intros.
  induction t. simpl. reflexivity.
  rewrite transform_split. rewrite filter_split.
  rewrite transform_split2. rewrite filter_split2.
  simpl in H0. apply le_S_n in H0.
  assert (Hlen: length t <= S (S len)).
    { rewrite Nat.le_succ_diag_r. apply le_n_S. apply H0. }
  assert (part1: filter f (row_transform op t) = row_transform op (filter g t)).
    { apply IHt. apply Hlen. }
  assert (part2: filter f (row_transform op (a :: nil)) = row_transform op (filter g (a :: nil))).
    { unfold row_transform_sz in H. apply H. simpl. reflexivity. }
  rewrite part1. rewrite part2. reflexivity.
}
Qed.


(** * Tactics: More Basic Tactics *)

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

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

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

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

(** We often encounter situations where the goal to be proved is
    _exactly_ the same as some hypothesis in the context or some
    previously proved lemma. *)
Definition mon_type := forall x : nat , nat.
Print mon_type.

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

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

  apply eq2.  Qed.

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

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

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

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

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

    Complete the following proof using only [intros] and [apply]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 2 = true ->
     oddb 3 = true.
Proof.
  intros H Eq.
  apply H.
  apply Eq.
Qed.

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

Theorem silly3_firsttry : forall (n : nat),
     true = (n =? 5)  ->
     (S (S n)) =? 7 = true.
Proof.
  intros n H.

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

  symmetry.
  simpl. (** (This [simpl] is optional, since [apply] will perform
             simplification first, if needed.) *)
  apply H.  Qed.

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

    _Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  You may find earlier lemmas like
    [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],
    etc. helpful.  Also, remember that [Search] is your friend
    (though it may not find earlier lemmas if they were posed as
    optional problems and you chose not to finish the proofs). *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  intros l l' Eq.
  rewrite Eq.
  Search (rev(rev _ )).
  symmetry.
  apply rev_involutive.
Qed.
(** [] *)

(** **** Exercise: 1 star, standard, optional (apply_rewrite)

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

(* apply est une tactique qui permet d'utiliser la conclusion d'une hypothèse ou
d'un théorème pour démontrer le but. Pour que la tactique fonctionne, il faut
que le but soit une instance de cette hypothèse ou de ce théorème. Il reste
alors à démontrer les hypothèses qui permette d'utiliser la propriété utilisée
par apply.

rewrite permet de remplacer dans le but les occurrences d'un terme apparaissant
dans une égalité (présente en hypothèse ou issue d'un théorème) par l'autre
terme impliqué dans cette égalité.

    [] *)

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

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

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

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

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

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

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

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

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

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

(** Coq also has a tactic [transitivity] that accomplishes the
    same purpose as applying [trans_eq]. The tactic requires us to
    state the instantiation we want, just like [apply with] does. *)

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

(** **** Exercise: 3 stars, standard, optional (trans_eq_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros n m o p eq1 eq2.
  transitivity m.
  - apply eq2.
  - apply eq1.
Qed.
(** [] *)

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

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O
       | S (n : nat).

    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition are two more
    facts:

    - The constructor [S] is _injective_, or _one-to-one_.  That is,
      if [S n = S m], it must be that [n = m].

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

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

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

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  assert (H2: n = pred (S n)). { reflexivity. }
  rewrite H2. rewrite H1. reflexivity.
Qed.

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

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

(** By writing [injection H as Hmn] at this point, we are asking Coq
    to generate all equations that it can infer from [H] using the
    injectivity of constructors (in the present example, the equation
    [n = m]). Each such equation is added as a hypothesis (with the
    name [Hmn] in this case) into the context. *)

  injection H as Hnm. apply Hnm.
Qed.

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

Theorem injection_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  (* WORKED IN CLASS *)
  injection H as H1 H2.
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** Alternatively, if you just say [injection H] with no [as] clause,
    then all the equations will be turned into hypotheses at the
    beginning of the goal. *)

Theorem injection_ex2 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H.
  (* WORKED IN CLASS *)
  intros H1 H2. rewrite H1. rewrite H2. reflexivity.
Qed.

(** **** Exercise: 3 stars, standard (injection_ex3)  *)
Example injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  intros X x y z  l j eq1 eq2.
  injection eq1 as eq_x_z eq_yl_j.
  rewrite eq2 in eq_yl_j.
  injection eq_yl_j as eq_y_z.
  transitivity z.
  - apply eq_x_z.
  - rewrite eq_y_z. reflexivity.
Qed.
  (** [] *)
Theorem eq_aux_lemma : forall (X : Type) (x y : X) (l : list X),
  x :: l = y :: l -> x = y.
  Proof.
  intros.
  injection H. intros. apply H0. Qed.
Example injection_ex4 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  intros. injection H. rewrite H0.
  intros Eq1 Eq2.
  apply eq_aux_lemma in  Eq1.
  transitivity z.
  - apply Eq2.
  - symmetry. apply Eq1.
Qed.

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

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

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

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

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

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

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

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

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

    intros H. discriminate H.
Qed.

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

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

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

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, _if_ the
    nonsensical situation described by the premise did somehow arise,
    _then_ the nonsensical conclusion would also follow, because we'd
    be living in an inconsistent universe where every statement is
    true.  We'll explore the principle of explosion in more detail in
    the next chapter. *)

(** **** Exercise: 1 star, standard (discriminate_ex3)  *)
Example discriminate_ex3 :
  forall (X : Type) (x y z : X) (l j : list X),
    x :: y :: l = [] ->
    x = z.
Proof.
  intros X x y z l j eq.
  discriminate eq.
Qed.

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

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

Theorem eq_implies_succ_equal : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. apply f_equal. apply H. Qed.

(** There is also a tactic named `f_equal` that can prove such
    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],
    the tactic [f_equal] will produce subgoals of the form [f = g],
    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals
    that are simple enough (e.g., immediately provable by
    [reflexivity]) will be automatically discharged by [f_equal]. *)

Theorem eq_implies_succ_equal' : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. f_equal. apply H. Qed.

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

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

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

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

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

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

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

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

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

    The informal proofs that you've seen in math or computer science
    classes probably tended to use forward reasoning.  In general,
    idiomatic use of Coq favors backward reasoning, but in some
    situations the forward style can be easier to think about. *)

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

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

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

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

       intros n. induction n.

    all is well.  But if we begin it with

       intros n m. induction n.

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

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

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

Abort.

(** What went wrong? *)

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

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

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

    holds, by showing

      - [P O]

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

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

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

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

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

    then we can prove

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

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

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

    then we can prove

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

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

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

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

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

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

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

    intros m eq.

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

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

(** The 0 case is trivial: *)

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

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

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

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

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

(** **** Exercise: 2 stars, standard (eqb_true)  *)
Theorem eqb_true : forall n m,
    n =? m = true -> n = m.
Proof.
  intros n.
  (*
    On démontre par récurrence sur n que pour tout m
    n =? m = true -> n  = m
  *)
  induction n as  [| n' IHn'].
  - (*  Si n = 0, on prend un entier m et on suppose que 0 =? m = true. *)
    intros m Eq.
    (* On poursuit par une analyse de cas sur m : *)
    destruct m as [| m'].
    + (*  si m = 0, alors la conclusion est vérifiée *)
      reflexivity.
    + (*  si m = S m', alors  0 =? S m' s'évalue à false, *)
      simpl in Eq.
      (* contredisant l'hypothèse que 0 =? m = true.*)
      discriminate Eq.
  - (* Si n = S n', prend un entier m et on suppose que S n' =? m = true. *)
    intros m Eq.
    (* On fait une analyse de cas sur m : *)
    destruct m as [|m'].
    + (*  si m = 0 , alors S n' =? m s'évalue à false. *)
      simpl in Eq.
      (* Ce qui contredit les hypothèses. *)
      discriminate Eq.
    + (* si m = S m', alors S n' =? S m' s'évalue à n' =? m' *)
      (*  Par hypothèse, cela implique que n'=? m' = true. *)
      simpl in Eq.
      (* Par récurence il s'ensuit que  n' = m'. *)
      apply IHn' in Eq.
      (*  Ainsi S n' = S m' et n = m. *)
      rewrite Eq.
      reflexivity.
Qed.
  (** [] *)

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

    On démontre par récurrence sur n que pour tout m
    n =? m = true -> n  = m

   Si n = 0, on prend un entier m et on suppose que 0 =? m = true.
   On poursuit par une analyse de cas sur m :
   - si m = 0, alors la conclusion est vérifiée
   - si m = S m', alors  0 =? S m' s'évalue à false, contredisant l'hypothèse que
     0 =? m = true.

  Si n = S n', prend un entier m et on suppose que S n' =? m = true.
  On fait une analyse de cas sur m :
  - si m = 0 , alors S n' =? m s'évalue à false. Ce qui contredit les hypothèses.
  - si m = S m', alors S n' =? S m' s'évalue à n' =? m'. Par hypothèse, cela implique que
    n'=? m' = true. Par récurence il s'ensuit que  n' = m'. Ainsi S n' = S m' et n = m.

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

(* FILL IN HERE *)

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

(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective)

    In addition to being careful about how you use [intros], practice
    using "in" variants in this proof.  (Hint: use [plus_n_Sm].) *)
Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n.
  induction n as [| n' IHn'].
  - simpl. intros m eq. destruct m as [| m'].
    + reflexivity.
    + simpl in eq. discriminate eq.
  -  simpl.
     intros m eq.
     destruct m as [|m'].
     + simpl in eq.
       discriminate eq.
     + simpl in eq.
       Search (_ + S _).
       rewrite <- plus_n_Sm in eq.
       rewrite <- plus_n_Sm in eq.
       injection eq as eq.
       rewrite IHn' with (m:=m').
       * reflexivity.
       * apply eq.
Qed.

(** [] *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(** **** Exercise: 3 stars, standard, especially useful (gen_dep_practice)

    Prove this by induction on [l]. *)

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

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

(** It sometimes happens that we need to manually unfold a name that
    has been introduced by a [Definition] so that we can manipulate
    the expression it denotes.  For example, if we define... *)

Definition square n := n * n.

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

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

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

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

  unfold square.

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

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

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

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

Definition foo (x: nat) := 5.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Here are some examples: *)

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

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

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

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

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

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

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

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

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y l.
  induction l as [ | x l' IHl'].
  - intros l1 l2 H. simpl in H.
    injection H as H1 H2.
    rewrite <- H1.
    rewrite <- H2.
    reflexivity.
  - intros l1' l2' H'.
    simpl in H'.  destruct x as [x1 x2].
destruct (split l') as [l1'' l2''].
     injection  H' as H1 H2.
     rewrite <- H1. rewrite <- H2.
     simpl. rewrite -> IHl'.
    reflexivity. reflexivity.
Qed.

(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional: So far,
    we've chosen to include it most of the time, just for the sake of
    documentation.

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

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

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

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

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

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

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

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

(** **** Exercise: 2 stars, standard (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros. destruct b.
  - destruct (f true) eqn:fTrue.
    + rewrite -> fTrue.
      apply fTrue.
    + destruct (f false) eqn:fFalse.
      * apply fTrue. * apply fFalse.
 - destruct (f false) eqn: fFalse.
   + destruct (f true) eqn:fTrue.
     * apply fTrue. * apply fFalse.
   + rewrite -> fFalse.
     apply fFalse.
Qed.
(** [] *)

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

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

    Here are the ones we've seen:

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

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

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

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

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

      - [simpl]: simplify computations in the goal

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

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

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

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

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

      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,
        [x=y] and [y=z]

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

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

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

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

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

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

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

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

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

      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)

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

(** **** Exercise: 3 stars, standard (eqb_sym)  *)
Theorem eqb_sym : forall (n m : nat),
  (n =? m) = (m =? n).
Proof.
  intros n. induction n as [| n' IH].
  - intros m.
    destruct m as [| m'].
    + reflexivity.
    + reflexivity.
  - intros m. destruct m as [| m'].
    + reflexivity.
    + simpl. apply IH.
Qed.
(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)

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

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

   Proof: *)
   (* THéorème : Pour tous n et m de type nat , (n =? m) = (m =? n)

  preuve  : Par induction sur [n].

  - premièrement, on suppose que [l = []]. Et on doit montre que
       (0 =? m) = (m =? 0)
       Par induction sur m ,
       si m = 0,
         On aura (0 =? 0) = (0 =? 0),
         Ce qui est vrai est verifé par la definition eqb_true
       si m = S m',
         On

  - Secondement, on suppose que [l = n::l'], avec )

    [] *)

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

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

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

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

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

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

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

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

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

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

(** **** Exercise: 4 stars, advanced, especially useful (forall_exists_challenge)

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

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

      forallb negb [false;false] = true

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

      forallb (eqb 5) [] = true

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

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

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

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

      existsb evenb [] = false

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(** [] *)

(* 2020-09-09 20:51 *)


Require Export P03.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  exact FILL_IN_HERE.
Qed.


(***
  Lowenheim's Formula Implementation

  Authors:
    Joseph St. Pierre
    Spyridon Antonatos
***)

(*** Required Libraries ***)

Require Export terms.

Require Import List.
Import ListNotations.

(** * Introduction *)

(** In this section we formulate Lowenheim's algorithm using the data
    structures and functions defined in the [terms] library. The final occuring
    main function, [Lowenheim_Main], takes as input a term and produces a
    substitution that unifies the given term. The resulting substitution is said
    to be a most general unifier and not a mere substitution, but that statement
    is proven in the [lowenheim_proof] file. In this section we focus on the
    formulation of the algorithm itself, without any proofs about the properties
    of the formula or the algorithm. *)

(** * Lowenheim's Builder *)

(** In this subsection we are implementing the main component of Lowenheim's
    algorithm, which is the "builder" of Lowenheim's substitution for a given
    term. This implementation strictly follows as close as possible the formal,
    mathematical format of Lowenheim's algorithm. *)

(** Here is a skeleton function for building a substition on the format
    $\sigma(x) := (s + 1) \ast \sigma_{1}(x) + s \ast \sigma_{2}(x)$, each
    variable of a given list of variables, a given term [s] and subtitutions
    $\sigma_{1}$ and $\sigma_{2}$. This skeleton function is a more general
    format of Lowenheim's builder. *)

Fixpoint build_on_list_of_vars (list_var : var_set) (s : term) (sig1 : subst)
                               (sig2 : subst) : subst :=
  match list_var with
  | [] => []
  | v' :: v => (v', (s + T1) * apply_subst (VAR v') sig1 +
                    s * apply_subst (VAR v') sig2)
               :: build_on_list_of_vars v s sig1 sig2
  end.

(** This is the function to build a Lowenheim subsitution for a term _t_,
    given the term _t_ and a unifier of _t_, using the previously defined
    skeleton function. The list of variables is the variables within _t_ and the
    substitions are the identical subtitution and the unifer of the term. This
    fuction will often be referred in the rest of the document as our
    "Lowenheim builder" or the "Lowenheim substitution builder", etc. *)

Definition build_lowenheim_subst (t : term) (tau : subst) : subst :=
  build_on_list_of_vars (term_unique_vars t) t
                        (build_id_subst (term_unique_vars t)) tau.

(** * Lowenheim's Algorithm *)

(** In this subsection we enhance Lowenheim's builder to the level of a
    complete algorithm that is able to find ground substitutions before feeding
    them to the main formula to generate a most general unifier *)

(** ** Auxillary Functions and Definitions *)

(** This is a function to update a term, after it applies to it a given
    substitution and simplifies it. *)

Definition update_term (t : term) (s' : subst) : term :=
  simplify (apply_subst t s').

(** Here is a function to determine if a term is the ground term [T0]. *)

Definition term_is_T0 (t : term) : bool :=
  identical t T0.

(** In this development we have the need to be able to represent both the
    presence and the absence of a substitution. In case for example our
    [find_unifier] function cannot find a unifier for an input term, we need to
    be able to return a [subst nil] type, like a substitution option that states
    no substition was found. We are using the built-in [Some] and [None]
    inductive options (that are used as [Some] $\sigma$ and [None]) to represent
    some substitution and no substition repsectively. The type of the two above
    is the inductive [option {A:type}] that can be attached to any type; in our
    case it is [option subst]. *)

(** Our Lowenheim builder works when we provide an already existing unifier of
    the input term _t_. For our implementation to be complete we need to be able
    to generate that initial unifier ourselves. That is why we first need to
    define a function to find all possible "01" substitutions (substitutions
    where each variable gets mapped to [T0] or [T1]. *)

Fixpoint all_01_substs (vars : var_set) : list subst :=
  match vars with
  | [] => [[]]
  | v :: v' => (map (fun s => (v, T0) :: s) (all_01_substs v')) ++
               (map (fun s => (v, T1) :: s) (all_01_substs v'))
  end.

(** Next is a function to find an initial "ground unifier" for our Lowenheim
    builder function. It finds a substitution with ground terms that makes the
    given input term equivalent to [T0]. *)

Fixpoint find_unifier (t : term) : option subst :=
  find (fun s => match update_term t s with
                 | T0 => true
                 | _ => false
                 end) (all_01_substs (term_unique_vars t)).

(** ** Lowenheim's Main Function *)

(** Here is the main Lowenheim's formula; given a term, produce an MGU (a most
    general substitution that when applied on the input term, it makes it
    equivalent to [T0]), if there is one. Otherwise, return [None]. This
    function is often referred in the rest of the document as "Lowenheim Main"
    function or "Main Lowenheim" function, etc. *)

Definition Lowenheim_Main (t : term) : option subst :=
  match find_unifier t with
  | Some s => Some (build_lowenheim_subst t s)
  | None => None
  end.

(** * Lowenheim's Functions Testing *)

(** In this subsection we explore ways to test the correctness of our Lowenheim's
    functions on specific inputs. *)

(** Here is a function to test the correctness of the output of the
    [find_unifier] helper function defined above. True means expected output was
    produced, false otherwise. *)

Definition Test_find_unifier (t : term) : bool :=
  match find_unifier t with
  | Some s => term_is_T0 (update_term t s)
  | None => true
  end.


(* Since Coq allows us to manipulate proofs as first class objects,
   it is very common to design types which not only encapsulate data,
   but also proofs that the data satisfies some required property.
   These proofs are usually deemed irrelevant, and two objects whose
   data coincide are often deemed equal, regardless of the specifics
   of the proofs attributes they contain. However, even with proof
   irrelevance, the actual mechanics of coq tactics and rewrites may
   not be so obvious to handle, and some subtle tricks need to be
   applied. Let us consider an example: *)

(* Some predicate on nat *)
Parameter P : nat -> Prop.

(* Some type which encapsulate a natural number, together with a proof *)
Inductive Obj : Type :=
| make : forall n, P n -> Obj
.

(* We assume proof irrelevance *)
Axiom proof_irrelevance : forall (P:Prop) (p q:P), p = q.

(* Now let us consider the following result *)
Example obvious : forall (n m:nat) (p:P n) (q: P m),
    n = m -> make n p = make m q.
Proof.
    intros n m p q Enm.
    Fail rewrite Enm.
    (*
    Error: Abstracting over the term "n" leads to a term
    fun n0 : nat => make n0 p = make m q
    which is ill-typed.
        Reason is: Illegal application:
        The term "make" of type "forall n : nat, P n -> Obj"
        cannot be applied to the terms
         "n0" : "nat"
          "p" : "P n"
          The 2nd term has type "P n" which should be coercible to
          "P n0".
   *)

   (* We simply rewrite the equality 'n = m' in the goal because the type
      of p is dependent on n. We need to abstract over p. *)
   revert p. (* same as generalize p. clear p. *)
   (* We can now successfully rewrite Enm, then re-introduce p *)
   rewrite Enm. intros p.
   (* Now both p and q are of type P m, and we simply need to use irrelevance *)
   rewrite (proof_irrelevance _ p q).
   reflexivity.
Qed.