(*
 Copyright 2022 ZhengPu Shi
  This file is part of coq-matrix. It is distributed under the MIT
  "expat license". You should have recieved a LICENSE file with it.

  purpose   : Vector Theory based on Matrix of Function
  author    : ZhengPu Shi
  date      : 2021.12

  remark    :
  1. This is version 2, fixed the shape problem
*)

Require Export VectorThySig.

Require Import NatFun.MatrixThy.

Require Import ListListExt.
Require Import Lia.

Require Import Setoid.  (* => *)

(* ######################################################################### *)
(** * Vector theory *)
Module VectorThy (F : FieldSig) <: VectorThySig F.

  (* ==================================== *)
  (** ** Matrix theory *)
  Module Export MatrixThy := MatrixThy F.

  (* ==================================== *)
  (** ** Vector type *)

  Declare Scope vec_scope.
  Delimit Scope vec_scope with V.
  Open Scope vec_scope.

  Definition vec X n := mat X n 1.
  Notation V n := (vec X n).

  (** Get generate function of the vector *)
  Definition vdata {n} (v : V n) : nat -> X :=
    let g := mdata v in
      fun i => g i O.

  (* ==================================== *)
  (** ** Vector equility *)
(*   Definition veq {n} (v1 v2 : V n) := meq v1 v2.
  Notation "v1 == v2 " := (@veq _ v1 v2) (at level 70).

  Lemma veq_refl : forall {n} (v : V n), v = v.
  Proof. intros. apply meq_refl. Qed.

  Lemma veq_sym : forall {n} (v1 v2 : V n), v1 = v2 -> v2 = v1.
  Proof. intros. apply meq_sym. easy. Qed.

  Lemma veq_trans : forall {n} (v1 v2 v3 : V n),
    v1 = v2 -> v2 = v3 -> v1 = v3.
  Proof. intros. apply meq_trans with (m2:=v2); auto. Qed. *)

  Lemma veq_dec : forall {n} (v1 v2 : V n), {v1 = v2} + {v1 <> v2}.
  Proof. intros. apply meq_dec. Qed.

  (* ==================================== *)
  (** ** Convert between tuples and vector *)
  Definition t2v_2 (t : @T2 X) : V 2 :=
    let '(a,b) := t in l2m [[a];[b]].

  Definition t2v_3 (t : @T3 X) : V 3 :=
    let '(a,b,c) := t in l2m [[a];[b];[c]].

  Definition t2v_4 (t : @T4 X) : V 4 :=
    let '(a,b,c,d) := t in l2m [[a];[b];[c];[d]].

  Definition v2t_2 (v : V 2) : @T2 X :=
    let g := vdata v in (g 0, g 1)%nat.

  Definition v2t_3 (v : V 3) : @T3 X :=
    let g := vdata v in (g 0, g 1, g 2)%nat.

  Definition v2t_4 (v : V 4) : @T4 X :=
    let g := vdata v in (g 0, g 1, g 2, g 3)%nat.

  Lemma v2t_t2v_id_2 : forall (t : X * X), v2t_2 (t2v_2 t) = t.
  Proof.
    intros. destruct t. simpl. unfold v2t_2. simpl. f_equal.
  Qed.

  Lemma t2v_v2t_id_2 : forall (v : V 2), t2v_2 (v2t_2 v) = v.
  Proof.
    intros. apply meq_iff; intros i j Hi Hj. simpl.
    repeat (try destruct i; try destruct j; auto; try lia).
  Qed.

  (* ==================================== *)
  (** ** Convert between list and vector *)
  Definition v2l {n} (v : V n) : list X := MCol 0 v.
  Definition l2v {n} (l : list X) : V n := l2m (cvt_row2col l).

  Lemma v2l_length : forall {n} (v : V n), length (v2l v) = n.
  Admitted.

  Lemma v2l_l2v_id : forall {n} (l : list X),
    length l = n -> @v2l n (@l2v n l) = l.
  Admitted.

  Lemma l2v_v2l_id : forall {n} (v : V n),
    l2v (v2l v) = v.
  Admitted.

  (* ==================================== *)
  (** ** Zero vector *)
  Definition vec0 {n} : V n := mat0 n 1.

  (** Assert that a vector is an zero vector. *)
  Definition vzero {n} (v : V n) : Prop := v = vec0.

  (** Assert that a vector is an non-zero vector. *)
  Definition vnonzero {n} (v : V n) : Prop := ~(vzero v).

  (** vec0 is equal to mat0 with column 1 *)
  Lemma vec0_eq_mat0 : forall n, vec0 = mat0 n 1.
  Proof. intros. easy. Qed.

  (** It is decidable that if a vector is zero vector. *)
  Lemma vzero_dec : forall {n} (v : V n), {vzero v} + {vnonzero v}.
  Proof. intros. apply meq_dec. Qed.

  (* ==================================== *)
  (** ** algebra operations *)

  (** 一个向量的映射 *)
  Definition vmap {n} (v : V n) f : V n := mmap f v.

  (** 一个向量的fold操作 *)
(*   Definition vfold : forall {B : Type} {n} (v : V n) (f : X -> B) (b : B), B. *)

  (** 两个向量的映射 *)
  Definition vmap2 {n} (v1 v2 : V n) f : V n := mmap2 f v1 v2.

  (* 两个向量的点积。这里用矩阵乘法来定义点积，而我们之前是用点积来定义乘法 *)
  Definition vdot {n : nat} (X : V n) (B : V n) :=
    scalar_of_mat (@mmul 1 n 1 (mtrans X) B).

  (** 向量加法 *)
  Definition vadd {n} (v1 v2 : V n) : V n := madd v1 v2.
  Infix "+" := vadd.

  (** 向量加法交换律 *)
  Lemma vadd_comm : forall {n} (v1 v2 : V n), v1 + v2 = v2 + v1.
  Proof. intros. apply madd_comm. Qed.

  (** 向量加法结合律 *)
  Lemma vadd_assoc : forall {n} (v1 v2 v3 : V n),
    (v1 + v2) + v3 = v1 + (v2 + v3).
  Proof. intros. apply madd_assoc. Qed.

  (** 向量左加0 *)
  Lemma vadd_0_l : forall {n} (v : V n), vec0 + v = v.
  Proof. intros. apply (@madd_0_l n 1). Qed.

  (** 向量右加0 *)
  Lemma vadd_0_r : forall {n} (v : V n), v + vec0 =  v.
  Proof. intros. apply (@madd_0_r n 1). Qed.

  (** 负向量 *)
  Definition vopp {n} (v : V n) : V n := mopp v.
  Notation "- v" := (vopp v).

  (** 加上负向量等于0 *)
  Lemma vadd_opp : forall {n} (v : V n), v + (- v) = vec0.
  Proof. intros. apply madd_opp. Qed.

  (** 向量减法 *)
  Definition vsub {n} (v1 v2 : V n) : V n := v1 + (- v2).
  Infix "-" := vsub.

  (** 取元素 *)
  Definition vnth {n} (v : V n) i : X := @mnth n 1 v i 0.

(*   Notation "v # i" := (vnth v i) (at level 30). *)

  (** 取出1x1矩阵的第 0,0 个元素 *)
(*   Definition scalar_of_mat (m : mat 1 1) := mnth m 0 0. *)

  (** 向量数乘 *)
  Definition vcmul {n} a (v : V n) : V n := a c* v.
  Definition vmulc {n} (v : V n) a : V n := v *c a.

  (** 右数乘和左数乘等价 *)
  Lemma vmulc_eq_vcmul : forall {n} a (v : V n),
    v *c a = a c* v.
  Proof. intros. apply mmulc_eq_mcmul. Qed.

  (** 数乘结合律1 *)
  Lemma vcmul_assoc : forall {n} a b (v : V n),
    a c* (b c* v) = (a * b)%X c* v.
  Proof. intros. apply mcmul_assoc. Qed.

  (** 数乘结合律2 *)
  Lemma vcmul_perm : forall {n} a b (v : V n),
    a c* (b c* v) = b c* (a c* v).
  Proof. intros. apply mcmul_perm. Qed.

  (** 数乘左分配律 *)
  Lemma vcmul_add_distr_l : forall {n} a b (v : V n),
    (a + b)%X c* v = (a c* v) + (b c* v).
  Proof. intros. apply mcmul_add_distr_r. Qed.

  (** 数乘右分配律 *)
  Lemma vcmul_add_distr_r : forall {n} a (v1 v2 : V n),
    a c* (v1 + v2) = (a c* v1) + (a c* v2).
  Proof. intros. unfold vadd. apply mcmul_add_distr_l. Qed.

  (** 用1数乘 *)
  Lemma vcmul_1_l : forall {n} (v : V n), X1 c* v = v.
  Proof. intros. apply mcmul_1_l. Qed.

  (** 用0数乘 *)
  Lemma vcmul_0_l : forall {n} (v : V n), X0 c* v = vec0.
  Proof. intros. apply mcmul_0_l. Qed.

  (** 非零向量是k倍关系，则系数k不为0 *)
  Lemma vec_eq_vcmul_imply_coef_neq0 : forall {n} (v1 v2 : V n) k,
    vnonzero v1 -> vnonzero v2 -> v1 = k c* v2 -> k <> X0.
  Proof.
    intros. intro. subst. rewrite vcmul_0_l in H. destruct H. easy.
  Qed.

  (* ==================================== *)
  (** ** 2-dim vector operations *)

  (** 2维向量的“长度”，这里不是欧式距离，而是欧式距离的平方，为了方便计算 *)
  Definition vlen2 (v : V 2) : X :=
    let '(x,y) := v2t_2 v in
      (x * x + y * y)%X.

  (* ==================================== *)
  (** ** 3-dim vector operations *)

  (** 3维向量的“长度”，这里不是欧式距离，而是欧式距离的平方，为了方便计算 *)
  Definition vlen3 (v : V 3) : X :=
    let '(x,y,z) := v2t_3 v in
      (x * x + y * y + z * z)%X.

  (** V3的点积 *)
  Definition vdot3 (v0 v1 : V 3) : X :=
    let '(a0,b0,c0) := v2t_3 v0 in
    let '(a1,b1,c1) := v2t_3 v1 in
      (a0 * a1 + b0 * b1 + c0 * c1)%X.

End VectorThy.

(* ######################################################################### *)
(** * Vector on R *)
Module VectorR := VectorThy (FieldR.FieldDefR).

(* ######################################################################### *)
(** * Test of VectorR *)
Module VectorR_test.

  Import FieldR.
  Import VectorR.
  Open Scope R.
  Open Scope mat_scope.

  Definition v1 : V 3 := l2v [1;2;3].
  Definition v2 : V 3 := l2v [4;5;6].
  Example vdot_ex1 : vdot v1 v2 = (4+10+18)%R.
  Proof. compute. ring. Qed.

End VectorR_test.

(* ######################################################################### *)
(** * Vector on Qc *)
Module VectorQc := VectorThy (FieldQc.FieldDefQc).

(* ######################################################################### *)
(** * Test of VectorQc *)
Module VectorQc_test.

  Import FieldQc.
  Import VectorQc.
  Open Scope Qc.
  Open Scope mat_scope.
  Definition v1 : V 3 := l2v [Q2Qc 1; Q2Qc 2; Q2Qc 3].
  Definition v2 : V 3 := l2v [Q2Qc 4; Q2Qc 5; Q2Qc 6].
  Example vdot_ex1 : vdot v1 v2 = Q2Qc (4+10+18).
  Proof. compute. ring. Qed.

(*   Compute v2l v1. *)

End VectorQc_test.


(*
(C) Copyright 2010, COQTAIL team

Project Info: http://sourceforge.net/projects/coqtail/

This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*)

(** Some usual integrals *)

Require Import Reals.
Require Import MyRfunctions.
Require Import Rintegral.
Require Import Lia.

Open Scope R_scope.

Lemma Rint_inv : forall a b,
  0 < a <= b -> Rint (fun x => /x) a b (ln b - ln a).
intros a b Hab.
apply Rint_derive.
  intuition.
intros x Hx.
  apply derivable_pt_lim_ln.
  apply Rlt_le_trans with a; intuition.
  intros x Hx.
  apply continuity_pt_inv.
  apply derivable_continuous, derivable_id.
  assert( 0 < x).
  apply Rlt_le_trans with a; tauto.
  auto with *.
Qed.
Hint Resolve Rint_inv : Rint.

Lemma Rint_exp : forall a b, Rint exp a b (exp b - exp a).
Proof.
intros a b.
apply Rint_derive2.
intros; apply derivable_pt_lim_exp.
intros; apply derivable_continuous_pt, derivable_pt_exp.
Qed.
Hint Resolve Rint_exp : Rint.

Lemma Rint_pow_pos : forall n a b,
  Rint (fun y : R => INR n * y ^ (pred n)) a b ((b ^ n - a ^ n)).
Proof.
intros n a b.
destruct n.
  replace (b ^ 0 - a ^ 0) with (0 * (b - a)) by ring.
  apply Rint_eq_compat with (fct_cte 0).
  unfold fct_cte; auto with *.
  apply Rint_constant.
apply Rint_derive2 with (f := fun x => x ^ (S n)); intros.
apply derivable_pt_lim_pow_pos; lia.
apply continuity_pt_mult.
apply continuity_pt_const; intros u v ; reflexivity.

  induction n.
  apply continuity_pt_const; intros u v ; reflexivity.
  simpl.
  apply continuity_pt_mult.

auto with Rcont.
auto with Rcont.
Qed.
Hint Resolve Rint_pow_pos : Rint.

Lemma Rint_cos : forall a b,
  Rint cos a b (sin b - sin a).
Proof.
intros a b.
apply Rint_derive2.
intros; apply derivable_pt_lim_sin.
intros; apply continuity_cos.
Qed.
Hint Resolve Rint_cos : Rint.

Lemma Rint_sin : forall a b,
  Rint sin a b (cos a - cos b).
intros a b.
replace (cos a - cos b) with (- cos b - -cos a) by ring.
apply Rint_derive2 with (f := (-cos)%F).
intros; replace (sin x) with (--sin x) by ring;
  apply derivable_pt_lim_opp, derivable_pt_lim_cos.
intros; apply continuity_sin.
Qed.
Hint Resolve Rint_sin : Rint.

Lemma Rint_sqrt_inv : forall a b, 0 < a -> 0 < b ->
  Rint (fun x => /(sqrt x)) a b (2 *( sqrt b - sqrt a)).
Proof.
intros a b Ha Hb.
assert(Hneq : forall x, Rmin a b <= x <= Rmax a b -> 0 < sqrt x).
  intros;
    apply sqrt_lt_R0.
    apply Rlt_le_trans with (Rmin a b).
    apply Rmin_pos; assumption.
    intuition.
apply Rint_eq_compat with (fun x => 2 * /(2 * sqrt x)).
  intros; field.
  auto with *.
apply Rint_scalar_mult_compat_l.
apply Rint_derive2.
intros; apply derivable_pt_lim_sqrt.
  apply Rlt_le_trans with (Rmin a b).
  apply Rmin_pos; assumption.
  intuition.
intros.
apply continuity_pt_inv.
  apply continuity_pt_mult.
  apply continuity_pt_constant.
  apply continuity_pt_sqrt.
  apply Rle_trans with (Rmin a b).
  apply Rmin_ge; intuition.
  intuition.
assert( 0 < 2 * sqrt x).
apply Rmult_lt_0_compat.
  auto with *.
  auto.
auto with *.
Qed.
Hint Resolve Rint_sqrt_inv : Rint.

(* cosh sinh  *)


Require Export ZArith.
Require Export Znumtheory.
Require Export Zpow_facts.
(*Require Export Binomial.
Require Export Rdefinitions.*)

Definition nCr n r : Z := Z.of_nat ((fact n) / (fact r * fact (n-r))).

(*Search ((_:nat -> Z) (_:nat)).*)

Fixpoint sum_fZ (f:nat -> Z) (n:nat): Z :=
  match n with
  | O => f 0%nat
  | S i => sum_fZ f i + f (S i)
  end.

Lemma zbinomial : forall (x y n:Z),
    (x + y) ^ n = sum_fZ (fun i:nat => nCr (Z.to_nat n) i * x ^ (Z.of_nat i) * y ^ (Z.of_nat ((Z.to_nat n)-i))) (Z.to_nat n).
Proof.
Admitted.

(* Theorem 70 *)

Lemma freshmans_dream : forall p : Z, prime p -> forall x y : Z, (x + y)^p mod p = (x^p+y^p) mod p.
Proof.
Admitted.

Theorem theorem_70 : forall p : Z, prime p -> forall a : Z, a>=0 -> a^p mod p = a mod p.
Proof.
  intros.
  pattern a.
  apply natlike_ind.
  rewrite Z.pow_0_l.
  reflexivity.
  apply prime_ge_2 in H.
  omega.

  intros.
  replace (Z.succ x) with (x + 1); [|omega].
  rewrite freshmans_dream.
  replace (1^p) with 1.
  rewrite <- Zplus_mod_idemp_l.
  rewrite H2.
  rewrite -> Zplus_mod_idemp_l.
  reflexivity.

  symmetry.
  apply Z.pow_1_l.
  apply prime_ge_2 in H.
  omega.
  assumption.
  omega.
Qed.

Search (_ * _ = _ * _).

(* Theorem 71 *)
Lemma mod_mul_cancel_l : forall p q r n : Z, prime n /\ ~(n|r) -> (r * p) mod n = (r * q) mod n <-> p mod n = q mod n.
Proof.
  intros.
  split.

  intros eq.
  (* hmm, is this actually true, or only if n is prime... *)

  admit.

  intros eq.
  rewrite <- Zmult_mod_idemp_r.
  rewrite eq.
  rewrite -> Zmult_mod_idemp_r.
  reflexivity.
Admitted.

Theorem fermats_theorem : forall a p : Z, a>=0 -> prime p /\ ~(p|a) -> a^(p-1) mod p = 1.
Proof.
  intros a p age0 [H H0].

  (* so basically it comes down to the fact that a must have an inverse mod p *)

  (*
  replace (a ^ (p - 1) mod p = 1) with (p|(a ^ (p - 1) - 1)).
  unfold Z.divide.

  specialize (theorem_70 p).
  intros eq.
  apply eq with (a:=a) in H.
  clear eq.

  replace (a ^ p mod p = a mod p) with (p | (a ^ p - a)) in H.
  destruct H.
  exists x.
  rewrite <- (Z.mul_cancel_l _ _ a).
  *)

  replace 1 with (1 mod p) at 2.
  2 : {
    apply Zmod_small.
    apply prime_ge_2 in H.
    omega.
  }

  rewrite <- (mod_mul_cancel_l _ _ a).
  rewrite <- Z.pow_succ_r.
  replace (Z.succ (p - 1)) with p; [|omega].
  rewrite Z.mul_1_r.
  rewrite theorem_70.
  reflexivity.

  - apply H.
  - apply age0.
  - apply prime_ge_2 in H.
    omega.
  - split.
    + apply H.
    + apply H0.
Qed.

(* Theorem 72 : a^phi(m) mod m = 1 *)


Require Import List.

Require Import Logic.Func.Composition.

Definition injective (v w:Type) (f:v -> w) : Prop :=
    forall (x y:v), f x = f y -> x = y.

Arguments injective {v} {w} _.

Lemma injective_comp : forall (v w u:Type) (f:v -> w) (g:w -> u),
    injective f -> injective g -> injective (g ; f).
Proof.
    intros v w u f g If Ig x y H. apply If. apply Ig. assumption.
Qed.


Theorem Ex029 (A B C : Prop): (A -> B) -> (C -> ~B) -> (A -> ~C).
Proof.
  intros.
  intro.
  apply H0.
  + exact H2.
  + apply H.
    exact H1.
Qed.


(************************************************)
(************************************************)
(****                                        ****)
(****   The category of sets and functions   ****)
(****                                        ****)
(************************************************)
(************************************************)

Require Import Coq.Logic.FunctionalExtensionality.
Require Import Main.CategoryTheory.Arrow.
Require Import Main.CategoryTheory.Category.
Require Import Main.CategoryTheory.Product.
Require Import Main.Tactics.

#[local] Open Scope type. (* Parse `*` as `prod` rather than `mul`. *)

(* Sets and functions form a category. *)

#[local] Theorem setCAssoc w x y z (f : w -> x) (g : x -> y) (h : y -> z) :
  (fun e : w => h (g (f e))) = (fun e : w => h (g (f e))).
Proof.
  search.
Qed.

#[local] Theorem setCIdent x y (f : x -> y) : (fun e : x => f e) = f.
Proof.
  search.
Qed.

Definition setCategory : category := newCategory
  Type
  (fun x y => x -> y)
  (fun _ _ _ f g e => f (g e))
  (fun x e => e)
  setCAssoc setCIdent setCIdent.

(* Cartesian products are categorical products in this category. *)

Theorem cartesianProduct x y :
  @product setCategory x y (x * y) fst snd.
Proof.
  unfold product.
  clean.
  unfold universal.
  split.
  - exists (fun w => (qx w, qy w)). search.
  - unfold arrowUnique.
    intros.
    destruct H.
    destruct H0.
    apply functional_extensionality.
    intros.
    apply injective_projections.
    + replace (fst (f x0)) with (qx x0); [idtac | search].
      replace (fst (g x0)) with (qx x0); [search | rewrite H0; search].
    + replace (snd (f x0)) with (qy x0); [idtac | search].
      replace (snd (g x0)) with (qy x0); [search | rewrite H2; search].
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-style" and
      "backward-style" proofs;
    - how to reason about data constructors (in particular, how to use
      the fact that they are injective and disjoint);
    - how to strengthen an induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis. *)

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

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

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

  apply eq2.  Qed.

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

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

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

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

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

(** **** Exercise: 2 stars, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

(** Here we cannot use [apply] directly, 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 (apply_exercise1)  *)
(** (_Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [Search] is
    your friend.) *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optionalM (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied?
(* FILL IN HERE *)
*)
(** [] *)

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

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

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

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

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

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

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

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

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

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

(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition (and in our
    informal understanding of how datatype declarations work in other
    programming languages) are two more facts:
    - The constructor [S] is _injective_.  That is, if [S n = S m], it
      must be the case that [n = m].
    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n].
    Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since neither
    [true] nor [false] take any arguments, their injectivity is not
    interesting.)  And so on. *)

(** Coq provides a tactic called [inversion] that allows us to
    exploit these principles in proofs. To see how to use it, let's
    show explicitly that the [S] constructor is injective: *)

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

(** By writing [inversion H] at this point, we are asking Coq to
    generate all equations that it can infer from [H] as additional
    hypotheses, replacing variables in the goal as it goes. In the
    present example, this amounts to adding a new hypothesis [H1 : n =
    m] and replacing [n] by [m] in the goal. *)

  inversion H.
  reflexivity.
Qed.

(** Here's a more interesting example that shows how multiple
    equations can be derived at once. *)

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

(** We can name the equations that [inversion] generates with an
    [as ...] clause: *)

Theorem inversion_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.

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

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately.  Consider the following proof: *)

Theorem beq_nat_0_l : forall n,
   beq_nat 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'].
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming
    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
    clearly contradictory!  The way forward lies in the assumption.
    After simplifying the goal state, we see that [beq_nat 0 (S n') =
    true] has become [false = true]: *)

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

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

    intros H. inversion 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 inversion_ex4 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. inversion contra. Qed.

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

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

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

(** To summarize this discussion, suppose [H] is a hypothesis in the
    context or a previously proven lemma of the form
        c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] has the following effect:
    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know that [a1 = b1], [a2 =
      b2], etc.  The [inversion H] adds these facts to the context and
      tries to use them to rewrite the goal.
    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory, and the current goal doesn't have to be
      considered at all.  In this case, [inversion H] marks the
      current goal as completed and pops it off the goal stack. *)

(** 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 useful in a few
    places below: *)

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

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

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.
    For example, the tactic [simpl in H] performs simplification in
    the hypothesis named [H] in the context. *)

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

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]
    against [L1] and, if successful, replaces it with [L2].
    In other words, [apply L in H] gives us a form of "forward
    reasoning": from [L1 -> L2] and a hypothesis matching [L1], it
    produces a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning": it says that if we know [L1->L2] and we are
    trying to prove [L2], it suffices to prove [L1].
    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

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

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise.  (Hint: use
    [plus_n_Sm].) *)

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

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

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that the [double] function is injective -- i.e.,
    that it maps different arguments to different results:
    Theorem double_injective: forall n m,
      double n = double m -> n = m.
    The way we _start_ this proof is a bit delicate: if we begin with
      intros n. induction n.
    all is well.  But if we begin it with
      intros n m. induction n.
    we get stuck in the middle of the inductive case... *)

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

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

      Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _these particular_ [n] and [m], then [n = m].
    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition
      - [P n] = "if [double n = double m], then [n = m]"
    holds, by showing
      - [P O]
         (i.e., "if [double O = double m] then [O = m]") and
      - [P n -> P (S n)]
        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").
    If we look closely at the second statement, it is saying something
    rather strange: it says that, for a _particular_ [m], if we know
      - "if [double n = double m] then [n = m]"
    then we can prove
       - "if [double (S n) = double m] then [S n = m]".
    To see why this is strange, let's think of a particular [m] --
    say, [5].  The statement is then saying that, if we know
      - [Q] = "if [double n = 10] then [n = 5]"
    then we can prove
      - [R] = "if [double (S n) = 10] then [S n = 5]".
    But knowing [Q] doesn't give us any help at all with proving
    [R]!  (If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing about
    whether [double n] is [10], so [Q] is useless.) *)

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

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

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

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

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

    intros m eq.

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

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

(** The 0 case is trivial: *)

      inversion 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'. inversion eq. reflexivity. Qed.

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

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

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

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

Theorem ble_nat_true : forall n m,
    ble_nat n m = true -> n <= m.
Proof.
  (* FILL IN HERE *) Admitted.

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

Definition square (n: nat) := n*n.

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

(** At this point, a deeper discussion of unfolding and simplification
    is in order.
    You may already have observed that tactics like [simpl],
    [reflexivity], and [apply] will often unfold the definitions of
    functions automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

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

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

(** However, this automatic unfolding is rather 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, itself, cannot 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.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress.
    A more straightforward way to make progress is to explicitly tell
    Coq to unfold [bar]. *)

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

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

  destruct m.
  - reflexivity.
  - reflexivity.
Qed.

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

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

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

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

Fixpoint combine (X: Type)(l1 l2: list X): list X :=
match l1 with
| [] => l2
| h :: t => h :: (combine X t l2)
end.
(** **** Exercise: 3 stars, optional (combine_split)  *)

(** However, [destruct]ing compound expressions requires a bit of
    care, as such [destruct]s can sometimes erase information we need
    to complete a proof. *)
(** For example, suppose we define a function [sillyfun1] like
    this: *)

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

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact that [sillyfun1 n] yields [true] only when [n] is
    odd.  By analogy with the proofs we did with [sillyfun] above, it
    is natural to start the proof like this: *)

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

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution performed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat n 3], but we need to keep some
    memory of this expression and how it was destructed, because we
    need to be able to reason that, since [beq_nat 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 would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation, giving it a
    name that we choose. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply beq_nat_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, allow us to finish the
        proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

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

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

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  But basically we've got what we need to
    get work done.
    Here are the ones we've seen:
      - [intros]: move hypotheses/variables from goal to context
      - [reflexivity]: finish the proof (when the goal looks like [e =
        e])
      - [apply]: prove goal using a hypothesis, lemma, or constructor
      - [apply... in H]: apply a hypothesis, lemma, or constructor to
        a hypothesis in the context (forward reasoning)
      - [apply... with...]: explicitly specify values for variables
        that cannot be determined by pattern matching
      - [simpl]: simplify computations in the goal
      - [simpl in H]: ... or a hypothesis
      - [rewrite]: use an equality hypothesis (or lemma) to rewrite
        the goal
      - [rewrite ... in H]: ... or a hypothesis
      - [symmetry]: changes a goal of the form [t=u] into [u=t]
      - [symmetry in H]: changes a hypothesis of the form [t=u] into
        [u=t]
      - [unfold]: replace a defined constant by its right-hand side in
        the goal
      - [unfold... in H]: ... or a hypothesis
      - [destruct... as...]: case analysis on values of inductively
        defined types
      - [destruct... eqn:...]: specify the name of an equation to be
        added to the context, recording the result of the case
        analysis
      - [induction... as...]: induction on values of inductively
        defined types
      - [inversion]: reason by injectivity and distinctness of
        constructors
      - [assert (H: e)] (or [assert (e) as H]): introduce a "local
        lemma" [e] and call it [H]
      - [generalize dependent x]: move the variable [x] (and anything
        else that depends on it) from the context back to an explicit
        hypothesis in the goal formula *)

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

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advancedM? (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:
   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].
   Proof:
   (* FILL IN HERE *)
[]
*)

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

(** **** Exercise: 3 stars, advancedM (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.

(** [] *)

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


(**
Perfect Crypto - Simple definitions for message encryption and signing using
symmetric and assymetric keys

Perry Alexander
The University of Kansas

Provides definitions for:

- [keyType] - [symmetric], [public] and [private] key constructors.
- [inverse] - defines the inverse of any key.
- [is_inverse] - proof that [inverse] is decidable and provides a decision procesure for [inverse].
- [is_not_decryptable] - predicate indicating that a message is or is not decryptable using a specified key.
- [decrypt] - attempts to decrypt a message with a given key.  Returns the decrypted message if decryption occurs.  Returns a proof that the message cannot be decrypted with the key if decryption does not occur.
- [is_signed] - proof that signature checking is decidable and provides a decision procedure for signature check.
- [check] - checks a signature on a message with a given key.  Returns a proof that the check succeeds or does not succeed.
- [check_dec] - proof that signature checking is decidable and provides a decision procedure for signature checking.  Alternative function for [check].
*)

Require Import Omega.

(** Key values will be [nat] *)

Definition key_val : Type := nat.

(** Key types are [symmetric], [public] and [private]. *)
Inductive keyType: Type :=
| symmetric : key_val -> keyType
| private : key_val -> keyType
| public : key_val -> keyType.

(** A [symmetric] key is its own inverse.  A [public] key is the inverse of
  the [private] key with the same [key_val].  A [private] key is the inverse of
  the [public] key with the same [key_val]. *)

Fixpoint inverse(k:keyType):keyType :=
match k with
| symmetric k => symmetric k
| public k => private k
| private k => public k
end.

(** Proof that inverse is decidable for any two keys. The resulting proof
 gives us the function [is_inverse] that is a decision procedure for key
 inverse checking.  It will be used in [decrypt] and [check] later in the
 specification. *)
Theorem is_inverse:forall k k', {k = (inverse k')}+{k <> (inverse k')}.
Proof.
  intros.
  destruct k; destruct k'.
  destruct (eq_nat_dec k k0) as [Hinv | Hninv].
    left. simpl. auto.
    right. simpl. unfold not. intros. inversion H. contradiction.
  right; simpl; unfold not; intros; inversion H.
  right. simpl. unfold not. intros. inversion H.
  right. simpl. unfold not. intros. inversion H.
  right. simpl. unfold not. intros. inversion H.
  destruct (eq_nat_dec k k0) as [Hinv | Hninv].
    left. simpl. auto.
    right. simpl. unfold not. intros. inversion H. contradiction.
  right. simpl. unfold not. intros. inversion H.
  destruct (eq_nat_dec k k0) as [Hinv | Hninv].
    left. simpl. auto.
    right. simpl. unfold not. intros. inversion H. contradiction.
  right. simpl. unfold not. intros. inversion H.
Defined.

Eval compute in (is_inverse (public 1) (private 1)).

Eval compute in (is_inverse (public 1) (private 2)).

Eval compute in (is_inverse (public 2) (private 1)).

Eval compute in (is_inverse (private 1) (public 1)).

Eval compute in (is_inverse (symmetric 1) (symmetric 1)).

Eval compute in (is_inverse (symmetric 1) (symmetric 2)).

(** Various proofs for keys and properties of the inverse operation.  All keys
  must have an inverse.  All keys have a unique inverse.  Equal inverses come
  from equal keys *)

Theorem inverse_injective : forall k1 k2, inverse k1 = inverse k2 -> k1 = k2.
Proof.
  intros.
  destruct k1; destruct k2; simpl in H; try (inversion H); try (reflexivity).
Qed.

Hint Resolve inverse_injective.

Theorem inverse_inverse : forall k, inverse (inverse k) = k.
Proof.
  intros. destruct k; try reflexivity.
Qed.

Hint Resolve inverse_inverse.

Theorem inverse_surjective : forall k, exists k', (inverse k) = k'.
Proof.
  intros. exists (inverse k). auto.
Qed.

Hint Resolve inverse_surjective.

Theorem inverse_bijective : forall k k',
    inverse k = inverse k' ->
    k = k' /\ forall k, exists k'', inverse k = k''.
Proof.
  auto.
Qed.

(** Basic messages held abstract.  Compound messages are keys, encrypted and
  signed messages, hashes and pairs. *)

Inductive message(basicType:Type) : Type :=
| basic : basicType -> message basicType
| key : keyType -> message basicType
| encrypt : message basicType -> keyType -> message basicType
| sign : message basicType -> keyType -> message basicType
| hash : message basicType -> message basicType
| pair : message basicType -> message basicType -> message basicType.

(** Predicate that determines if a message cannot be decrypted.  Could be
  that it is not encrypted to begin with or the wrong key is used. *)

Definition is_not_decryptable{T:Type}(m:message T)(k:keyType):Prop :=
  match m with
  | basic _ => True
  | key _ => True
  | encrypt m' k' => k <> inverse k'
  | sign _ _ => True
  | hash _ => True
  | pair _ _ => True
  end.

(** [decrypt] returns either a decrypted message or a proof of why the message
  cannot be decrypted. *)

Fixpoint decrypt{T:Type}(m:message T)(k:keyType):(message T)+{(is_not_decryptable m k)}.
refine
  match m with
  | basic c => inright _ _
  | key _ => inright _ _
  | encrypt m' j => (if (is_inverse k j) then (inleft _ m') else (inright _ _ ))
  | sign m' k => inright _ _
  | hash _ => inright _ _
  | pair _ _ => inright _ _
  end.
Proof.
  reflexivity.
  reflexivity.
  simpl. assumption.
  reflexivity.
  reflexivity.
  reflexivity.
Defined.

Eval compute in decrypt(encrypt nat (basic nat 1) (symmetric 1)) (symmetric 1).

Eval compute in decrypt(encrypt nat (basic nat 1) (symmetric 1)) (symmetric 2).

(** Predicate that determines if a message is properly signed. *)

Definition is_signed{T:Type}(m:message T)(k:keyType):Prop :=
  match m with
  | basic _ => False
  | key _ => False
  | encrypt _ _ => False
  | sign m' k' => k = inverse k'
  | hash _ => False
  | pair _ _ => False
  end.

(** Signature check returns either a proof that the signature is correct
  or a proof that the signature is not correct. *)

Fixpoint check{T:Type}(m:message T)(k:keyType):{(is_signed m k)}+{not (is_signed m k)}.
refine
  match m with
  | basic c => right _ _
  | key _ => right _ _
  | sign m' j => (if (is_inverse k j) then (left _ _) else (right _ _ ))
  | encrypt m' k => right _ _
  | hash _ => right _ _
  | pair _ _ => right _ _
  end.
Proof.
  unfold not. intros. simpl in H. assumption.
  unfold not. intros. simpl in H. assumption.
  unfold not. intros. simpl in H. assumption.
  destruct (is_inverse j k).
  simpl. rewrite _H. reflexivity.
  simpl. rewrite <- _H. reflexivity.
  simpl. assumption.
  unfold not. intros. simpl in H. assumption.
  unfold not. intros. simpl in H. assumption.
Defined.

Eval compute in check(sign nat (basic nat 1) (private 1)) (public 1).

Eval compute in check(sign nat (basic nat 1) (private 1)) (public 2).

Theorem check_dec: forall T, forall m:(message T), forall k, {(is_signed m k)}+{not (is_signed m k)}.
Proof.
  intros.
  destruct m.
  right. unfold is_signed. tauto.
  right. unfold is_signed. tauto.
  right. unfold is_signed. tauto.
  destruct (is_inverse k0 k).
  left. simpl. rewrite e. auto.
  right. unfold not. simpl. unfold not in n. intros. subst. auto.
  right. unfold is_signed. tauto.
  right. unfold is_signed. tauto.
Defined.

Eval compute in check_dec nat (sign nat (basic nat 1) (private 1)) (public 1).

Eval compute in check_dec nat (sign nat (basic nat 1) (private 1)) (public 2).

Require Import List.
Definition Name := nat.

Definition KeyServer  := list (Name * {k : keyType | exists x, k = public x}) % type.

SearchAbout exist .
Lemma noteqpOne : forall x : nat, S x <> x.
Proof.  intros. induction x. congruence. unfold not.  intros. inversion H. contradiction.  Qed.

Fixpoint nameinServer (n : Name) (ks : KeyServer): bool :=
  match ks with
   | nil => false
   | x :: xs => match x with
                 (na,kk) => if beq_nat na n then true else nameinServer n xs
                end
  end.
Inductive keyServerError (ks : KeyServer): Prop :=
 | notAPublicKey : {k  | forall x, k <> public x} -> keyServerError ks
 | alreadyEntryForName : { n : Name | (nameinServer n ks) = true} -> keyServerError ks.

SearchAbout In.

Definition addKey (ks : KeyServer) (name : Name) (k : keyType) : KeyServer + {keyServerError ks}.
Proof. destruct k. case (symmetric k). intros. right. constructor. exists (symmetric k) . intros. unfold not. intros. inversion H.
right. constructor. exists (private k). intros. unfold not. intros. inversion H.
left. assert ((public k) = (public k)). reflexivity.  refine ((name, _) ::ks).
eauto. Defined.

Definition ks0 : KeyServer := nil.
Eval compute in addKey ks0 1 (public 1).
Eval compute in addKey ks0 1 (private 1).
Eval compute in addKey ks0 1 (symmetric 1).

Fixpoint realRemove (ks : KeyServer) (name :Name) : KeyServer :=
  match ks with
    | nil => nil
    | x :: xs => if beq_nat (fst x) name then realRemove xs name else x :: (realRemove xs name)
  end.

Fixpoint  removeKey (ks : KeyServer) (name : Name) : KeyServer + {nameinServer name ks = false}.
  case_eq (nameinServer name ks). intros. left. exact (realRemove ks name).
  intros. right. reflexivity. Defined.

Definition PubProof :={k : keyType | exists x, k = public x}.

Definition pub2 : {k : keyType | exists x, k = public x}. exists (public 2). exists 2. reflexivity. Defined.
Definition pub3 : PubProof. exists (public 3). exists 3. reflexivity. Defined.

Definition ks3 := (2,pub2) :: ((3,pub3) :: ks0).
Eval compute in removeKey ks3 1.
Eval compute in removeKey ks3 2.
Eval compute in removeKey ks3 3.
Eval compute in removeKey ks3 4.

Definition publicServerKey := public 0.
Definition privateServerKey := private 0.

Inductive Maybe {T : Type} :=
 | Just : T -> Maybe
 | Nothing : Maybe.
(*
Theorem inImpliesIn : forall T : Type,
                      forall t : T,
                      forall t2 : T,
                      forall ls : list T,
                      In t ls
*)
SearchAbout In.
Fixpoint findOr (name : Name) (ks : KeyServer) : { x :PubProof | In (name,x) ks} + {forall kp : PubProof, ~In (name,kp) ks}.
Proof. induction ks. right.  intros.  simpl. unfold not.  intros.  apply H.
destruct a.  case_eq (beq_nat name n).  intros. left.  exists s.  SearchAbout beq_nat. symmetry in H. apply beq_nat_eq in H. rewrite H. SearchAbout In. apply in_eq.
intros. SearchAbout In. destruct IHks. left. destruct s0.  exists x. simpl. right. apply i. (* destruct s0. apply s0.  simpl.   exists s. exact p. right. *)
intros. assert (forall pp, ~ (n,s) = (name, pp)). intros.  unfold not. intros. inversion H0. SearchAbout beq_nat. apply beq_nat_false in H.   symmetry in H2. contradiction.
SearchAbout In. unfold not. right. intros. simpl in H1.  destruct H1.  apply H0 in H1.  apply H1. apply n0 in H1.  apply H1. Defined.

(*
Fixpoint findMaybe (name : Name) (ks : KeyServer) : Maybe (T := PubProof).
Proof.  intros. remember k as p.   trivial. remember k. ( k : PubProof).

 :=
  match ks with
   | nil => Nothing
   | x :: xs => if beq_nat (fst x) name then Just (snd x) else findMaybe name xs
  end.

Theorem findMaybeNotEmpty : forall name : Name, forall ks : KeyServer,
 forall s,  findMaybe name ks = Just s -> ks <> nil.
Proof. intros. induction ks. intros.  simpl in H. inversion H. unfold not. intros.  inversion H0. Qed.
Theorem nameinServerNotEmpty : forall name : Name, forall ks : KeyServer,
  nameinServer name ks = true -> ks <> nil.
Proof. intros. unfold not. intros. unfold nameinServer in H. rewrite H0 in H. inversion H. Defined.

Theorem notInImpliesNothings : forall (name : Name), forall ks : KeyServer, forall kp, ~(In (name,kp) ks) -> findMaybe name ks = Nothing.
Proof. intros.  unfold not in H. simpl.

Theorem  findImpliesIn : forall (name : Name), forall (ks : KeyServer), forall (s : PubProof),
(findMaybe name ks = Just s) ->   In (name, s) ks.
Proof.  intros. exists s.  case_eq (findMaybe name ks). intros.  induction findMaybe.
*)

Fixpoint requestKey {T : Type} (name :Name) (ks : KeyServer) : { m : message T |
                                                                 exists kp, m = sign T (key T (proj1_sig kp)) privateServerKey /\
                                                                 In (name,kp) ks } + {forall kp, ~ (In (name,kp) ks)}.
Proof. case_eq (findOr name ks). intros. destruct s.  left.  exists (sign T (key T (proj1_sig x)) privateServerKey). exists x. split. reflexivity. apply i. intros.    right. apply n. Defined.

Fixpoint findMaybe (name : Name) (ks : KeyServer) : Maybe :=
  match ks with
   | nil => Nothing
   | x :: xs => if beq_nat (fst x) name then Just (snd x) else findMaybe name xs
  end.

Theorem nameinServerNotEmpty : forall name : Name, forall ks : KeyServer,
  nameinServer name ks = true -> ks <> nil.
Proof. intros. unfold not. intros. unfold nameinServer in H. rewrite H0 in H. inversion H. Defined.

Fixpoint requestKey2 (name :Name) (ks : KeyServer) : keyType + { findMaybe name ks = Nothing}.
Proof. case_eq (findMaybe name ks). intros. left.  exact (proj1_sig s). right. reflexivity. Defined.

(*

 name ks = false}.
Proof. case_eq (nameinServer name ks). intros.   induction (requestKey name ks).  (findMaybe name ks). intros. left.  exact (proj1_sig t). right. simpl.

Fixpoint requestKey (name :Name) (ks : KeyServer) : Maybe := findMaybe name ks.

*)

Inductive RealMessage (T : Type) :=
  realmessage : Name -> Name -> message T -> RealMessage T.

Definition send {T : Type} (pk : keyType) (encryp : keyType) (m : message T) (fromGuy : Name) (toGuy : Name) : {mp : RealMessage T | mp = realmessage T fromGuy toGuy (sign T (encrypt T m encryp) pk)}.
Proof.  exists ( realmessage T fromGuy toGuy (sign T (encrypt T m encryp) pk)). reflexivity. Defined.
Definition getFrom {T : Type} (mp : RealMessage T): Name :=
  match mp with
   | realmessage f t m => f
  end.
Definition getTo {T : Type} (mp : RealMessage T): Name :=
  match mp with
   | realmessage f t m => t
  end.

Definition getMessage {T : Type} (mp : RealMessage T): message T :=
  match mp with
   | realmessage f t m => m
  end.
Inductive MyError : Prop :=
  myerror : MyError.
(*
Definition checkServerMessage {T :Type} {ks : KeyServer} {name : Name} (mp : { m : message T |   exists kp, m = sign T (key T (proj1_sig kp)) privateServerKey /\
                                                   In (name,kp) ks }) : keyType. case_eq mp. intros.  destruct x. inversion e.    exists kp. e. destruct e.
Proof. intros.
Definition requestKey2{T : Type} (name: Name) (ks : KeyServer) : keyType  + {forall kp, ~ (In (name,kp) ks)}.

Proof. case_eq (requestKey ( T:=T) name ks ). intros. left.  destruct s. exact kp. elim e. destruct e. left.    simpl e. destruct e.  simpl in s.  remember (proj2_sig s).   left. destruct s. exact k.  case_eq s.  intros.  destruct s.
*)
Inductive badbadnotgood {T : Type} ( mp : RealMessage T) (ks : KeyServer) (key : keyType) : Prop :=
  | notsignedman : (exists k, requestKey2 (getFrom mp) ks = inleft k /\ ~ (is_signed (getMessage mp) (k))) -> badbadnotgood mp ks key
  | cantdecryptman : { m : message T | exists innerM : message T, forall k, forall mm, innerM <> encrypt T mm k /\ exists someK,
                       m = sign T innerM someK} -> badbadnotgood mp ks key
  | myKeyFails : badbadnotgood mp ks key
  | keyLookupFail : badbadnotgood mp ks key.

Theorem inverses : forall k1 k2, inverse k1 = k2 -> inverse k2 = k1.
Proof. intros. destruct k1.
  simpl in H. rewrite <- H.  simpl. reflexivity.
  simpl in H. rewrite <- H.  simpl. reflexivity.
  simpl in H.  rewrite <- H. simpl. reflexivity. Qed.

Definition receiveMessage {T : Type} (ks : KeyServer) (mp : RealMessage T) (mypriv : keyType) :
   {res : message T |  exists kpub, (requestKey2 (getFrom mp) ks) = inleft kpub /\  (exists k2, (getMessage mp) = sign T (encrypt T res k2) (inverse kpub) /\
                       decrypt (encrypt T res k2) mypriv= (inleft res) )
                        }

  + { badbadnotgood mp ks mypriv }.
Proof. case_eq (requestKey2 (getFrom mp) ks).  (*at this point, successful look up of pub key *)
  intros.
    case_eq (getMessage mp).
       intros. right.  constructor. exists k. split.  apply H.  rewrite H0. simpl. unfold not. intros.  apply H1.
       intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.
       intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.
       intros. rename m into hopefullyEncrypted.
       case_eq (is_inverse k0 k).
        intros.
         (* this is the signed case *)
         case_eq (hopefullyEncrypted). (* for all except encrypt form, return the error. *)
           intros.  right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.
           intros.   right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.
           (*encrypt case *) intros. case_eq (decrypt hopefullyEncrypted mypriv).
                                        intros.  left. exists m. exists k. split. reflexivity. exists k1. split.    rewrite e.  reflexivity.
                                            assert (m0 = m).  rewrite H2 in H3.  simpl in H3. destruct (is_inverse mypriv k1).  inversion H3.  reflexivity.  inversion H3.  rewrite <- H2. rewrite H4 in H3. apply H3.

                                        intros. right. apply myKeyFails. (* this needs more descriptive args, but I'm really tired of this. *)
           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.
           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.
           intros.    right.  apply cantdecryptman. exists  (getMessage mp). exists hopefullyEncrypted. intros. unfold not. rewrite H2. split.  intros.  inversion H3. exists k0. rewrite H0. rewrite H2. reflexivity.
           intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. unfold not in n.  symmetry in H2. apply inverses in H2. symmetry in H2.   apply n in H2. apply H2.
intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.
intros. right. constructor. exists k. split. apply H.  rewrite H0. simpl. unfold not. intros. apply H1.
   intros. right.  apply keyLookupFail. (* needs more args again.*) Defined.

Definition engage {T: Type} (a : Name) (aPriv : keyType) (b: Name) ( bPriv : keyType) (ks : KeyServer) (m : message T) :=
   match requestKey2 b ks with
     | inright _ => false
     | inleft bPub => match receiveMessage ks (proj1_sig  (send bPriv aPriv m a b) ) bPriv with
                          | inright _ => false
                          | inleft _ => true
                      end
   end.

(*
Theorem Any message leaving a sending node is encrypted and signedsendTheorem     -- this is proven in the return type of send.
)*)


Parameter Atom : Type.

Inductive Proposition: Type :=
  | Atomic(P: Atom)
  | Negation(P: Proposition)
  | Conjunction(P Q: Proposition)
  | Disjunction(P Q: Proposition)
  | Implication(P Q: Proposition).

Notation "# P" := (Atomic P) (at level 1).
Notation "¬ P" := (Negation P) (at level 2).
Notation "P ∧ Q" := (Conjunction P Q) (at level 3).
Notation "P ∨ Q" := (Disjunction P Q) (at level 3).
Notation "P → Q" := (Implication P Q) (at level 4).

Fixpoint valuation v P: bool :=
  match P with
  | # P' => v P'
  | ¬ P' => negb (valuation v P')
  | P' ∧ Q' => andb (valuation v P') (valuation v Q')
  | P' ∨ Q' => orb (valuation v P') (valuation v Q')
  | P' → Q' => orb (negb (valuation v P')) (valuation v Q')
  end.

(* TODO: Logical Equivalence and Substitution *)

(* Satisfiability, Validity etc. *)

Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
  | nil => False
  | cons x' l' => x' = x \/ In x l'
  end.

Definition satisfiable P: Prop :=
  exists v, valuation v P = true.

Definition valid P: Prop :=
  forall v, valuation v P = true.

Definition unsatisfiable P: Prop :=
  forall v, valuation v P = false.

Definition falsifiable P: Prop :=
  exists v, valuation v P = false.

Definition Satisfies v Γ: Prop :=
  forall A, In A Γ -> valuation v A = true.

Fixpoint satisfies v Γ: bool :=
  match Γ with
  | nil => true
  | (p' :: Γ')%list => andb (valuation v p') (satisfies v Γ')
  end.

Theorem Satisfies_to_split: forall v Γ a,
  Satisfies v (a :: Γ)%list -> (valuation v a) = true /\ Satisfies v Γ.
Proof.
  unfold Satisfies.
  intros.
  split.
  - apply H.
    simpl.
    left.
    reflexivity.
  - intros.
    apply H.
    simpl.
    right.
    apply H0.
Qed.

Theorem split_to_Satisfies: forall v Γ a,
  (valuation v a) = true /\ Satisfies v Γ -> Satisfies v (a::Γ)%list.
Proof.
  intros v Γ A [H1 H2].
  unfold Satisfies.
  intros.
  simpl in H.
  destruct H as [H | H].
  - rewrite <- H. apply H1.
  - unfold Satisfies in H2. apply H2.
    apply H.
Qed.

Theorem satisfy_chain: forall v Γ A,
  (valuation v A) = true -> Satisfies v Γ -> Satisfies v (A :: Γ)%list.
Proof.
  intros.
  apply split_to_Satisfies.
  split.
  apply H.
  apply H0.
Qed.

Definition models Γ A: Prop :=
  forall v, Satisfies v Γ -> valuation v A = true.

Notation "Γ |= A" := (models Γ A) (at level 10).

Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y []) ..).

Lemma and_both_true: forall p q,
  (p && q)%bool = true -> p = true /\ q = true.
Proof.
  destruct p, q;
  simpl;
  intros.
  - split; reflexivity.
  - discriminate.
  - discriminate.
  - discriminate.
Qed.

Lemma or_either_true: forall p q,
  (p || q)% bool = true -> p = true \/ q = true.
Proof.
  destruct p, q.
  simpl;
  intros.
  - left. reflexivity.
  - left. reflexivity.
  - right. reflexivity.
  - discriminate.
Qed.

Theorem Satisfies_iff_satisfies: forall Γ v,
  Satisfies v Γ <-> satisfies v Γ = true.
Proof.
  intros.
  split.
  - induction Γ.
    + intros. simpl. reflexivity.
    + intros.
      simpl satisfies.
      apply Satisfies_to_split in H.
      destruct H as [H1 H2].
      rewrite H1.
      simpl.
      apply IHΓ.
      apply H2.
  - induction Γ.
    simpl.
    + intros.
      unfold Satisfies.
      simpl.
      intros.
      inversion H0.
    + intros. apply split_to_Satisfies.
      split.
      * simpl in H.
        destruct (valuation v a).
        --  reflexivity.
        --  simpl in H.
            discriminate H.
      * apply IHΓ.
        simpl in H.
        apply and_both_true in H.
        destruct H as [_ H].
        apply H.
Qed.


Require Import Bool Arith List Cpdt.CpdtTactics.
Set Implicit Arguments.

(* Source Language *)

Inductive type : Set := Nat | Bool.

Inductive binop : type -> type -> type -> Set :=
| Plus : binop Nat Nat Nat
| Times : binop Nat Nat Nat
| Eq : forall t , binop t t Bool
| Lt : binop Nat Nat Bool
.

Inductive exp : type -> Set :=
| NConst : nat -> exp Nat
| BConst : bool -> exp Bool
| Binop : forall t1 t2 t , binop t1 t2 t -> exp t1 -> exp t2 -> exp t
.

Definition typeDenote (t: type) : Set :=
  match t with
  | Nat => nat
  | Bool => bool
  end
.

Definition binopDenote arg1 arg2 res (b: binop arg1 arg2 res)
  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
  match b with
  | Plus => plus
  | Times => mult
  | Eq Nat => beq_nat
  | Eq Bool => eqb
  | Lt => leb
  end
.

Fixpoint expDenote t (e : exp t) : typeDenote t :=
  match e with
  | NConst n => n
  | BConst b => b
  | Binop _ _ _ b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
  end
.

(* Target langauge *)

Definition tstack := list type.

(* Define an indexed type family, which captures the relation between well
   defined stacks *)
Inductive instr : tstack -> tstack -> Set :=
| INConst : forall s , nat -> instr s (Nat :: s)
| IBConst : forall s , bool -> instr s (Bool :: s)
| IBinop : forall arg1 arg2 res s ,
    binop arg1 arg2 res -> instr (arg1 :: arg2 :: s) (res :: s)
.

Inductive prog : tstack -> tstack -> Set :=
| Nil : forall s , prog s s
| Cons : forall s1 s2 s3 ,
    instr s1 s2 -> prog s2 s3 -> prog s1 s3
.

Fixpoint vstack (ts : tstack) : Set :=
  match ts with
  | nil => unit
  | t :: ts' => typeDenote t * vstack ts'
  end % type (* %type means parse as a type *)
.

Definition instrDenote ts ts' (i : instr ts ts') : vstack ts -> vstack ts' :=
  match i with
  | INConst _ n => fun s => (n, s)
  | IBConst _ b => fun s => (b, s)
  | IBinop _ _ _ _ b => fun s =>
                          let '(arg1, (arg2, s')) := s in
                          ((binopDenote b) arg1 arg2, s')
  end
.

Fixpoint progDenote ts ts' (p : prog ts ts') : vstack ts -> vstack ts' :=
  match p with
  | Nil _ => fun s => s
  | Cons _ _ _ i p' => fun s => progDenote p' (instrDenote i s)
  end
.

Fixpoint concat ts ts' ts'' (p : prog ts ts') : prog ts' ts'' -> prog ts ts'' :=
  match p with
  | Nil _ => fun p' => p'
  | Cons _ _ _ i p1 => fun p' => Cons i (concat p1 p')
  end
.

Fixpoint compile t (e : exp t) (ts : tstack) : prog ts (t :: ts) :=
  match e with
  | NConst n => Cons (INConst _ n) (Nil _)
  | BConst b => Cons (IBConst _ b) (Nil _)
  | Binop _ _ _ b e1 e2 =>
    concat (compile e2 _)
           (concat (compile e1 _) (Cons (IBinop _ b) (Nil _)))
  end
.

Lemma compile_correct' : forall t (e : exp t) ts (s : vstack ts) ,
    progDenote (compile e ts) s = (expDenote e, s)
.

induction e; crush.

Abort.

Lemma concat_correct : forall ts ts' ts'' (p : prog ts ts') (p' : prog ts' ts'') (s : vstack ts) ,
    progDenote (concat p p') s = progDenote p' (progDenote p s)
.
    induction p; crush.
Qed.

Hint Rewrite concat_correct.

Lemma compile_correct' : forall t (e : exp t) ts (s : vstack ts),
    progDenote (compile e ts) s = (expDenote e, s).
    induction e; crush.
Qed.

Hint Rewrite compile_correct'.

Theorem compile_correct : forall t (e : exp t),
    progDenote (compile e nil) tt = (expDenote e, tt).
    crush.
Qed.

Extraction compile.


Require Import ProofCheckingEuclid.euclidean_axioms.
Require Import ProofCheckingEuclid.euclidean_defs.
Require Import ProofCheckingEuclid.lemma_extension.
Require Import ProofCheckingEuclid.lemma_inequalitysymmetric.
Require Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ABD.
Require Import ProofCheckingEuclid.lemma_s_onray.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma lemma_onray_assert :
	forall A B E,
	(BetS A E B \/ eq E B \/ BetS A B E) -> neq A B ->
	OnRay A B E.
Proof.
	intros A B E.
	intros BetS_A_E_B_or_eq_E_B_or_BetS_A_B_E.
	intros neq_A_B.

	pose proof (lemma_inequalitysymmetric _ _ neq_A_B) as neq_B_A.
	pose proof (lemma_extension _ _ _ _ neq_B_A neq_A_B) as (J & BetS_B_A_J & Cong_AJ_AB).
	pose proof (axiom_betweennesssymmetry _ _ _ BetS_B_A_J) as BetS_J_A_B.

	destruct BetS_A_E_B_or_eq_E_B_or_BetS_A_B_E as [BetS_A_E_B | [eq_E_B | BetS_A_B_E]].
	{
		(* case BetS_A_E_B *)
		pose proof (axiom_orderofpoints_ABD_BCD_ABC _ _ _ _ BetS_J_A_B BetS_A_E_B) as BetS_J_A_E.
		pose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.
		exact OnRay_AB_E.
	}
	{
		(* case eq_E_B *)
		assert (BetS J A E) as BetS_J_A_E by (rewrite eq_E_B; exact BetS_J_A_B).
		pose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.
		exact OnRay_AB_E.
	}
	{
		(* case BetS_A_B_E *)
		pose proof (lemma_orderofpoints_ABC_BCD_ABD _ _ _ _ BetS_J_A_B BetS_A_B_E) as BetS_J_A_E.
		pose proof (lemma_s_onray _ _ _ _ BetS_J_A_B BetS_J_A_E) as OnRay_AB_E.
		exact OnRay_AB_E.
	}
Qed.

End Euclid.