(**
ProofCafe 名古屋 補足資料

萩原学 アフェルト・レナルド 「Coq/SSReflect/MathCompによる定理証明」 森北出版

[http://www.morikita.co.jp/books/book/3287]

3.6.3 rewrite /= または simpl (simplifies タクティク) の説明をします。

本書 p.135 注記2 にも関連する記述があり、それについても言及します。

@suharahiromichi

2019_08_17

参考資料

[1] CRM simpl tactic
https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.simpl

[2] "Simple Simpl"
https://hal.archives-ouvertes.fr/hal-00816918/document

[3] CRM, The SSReflect proof language, locking unlocking
https://coq.inria.fr/refman/proof-engine/ssreflect-proof-language.html#locking-unlocking
*)

From mathcomp Require Import all_ssreflect.

(** * simpl タクティク

Mathcomp で、rewrite /= または move=> /= を実行したとき、
バニラCoq の simpl タクティクが実行される。
Mathcomp で simpl をコマンドしてもよい。

simpl は、（ゴールに対して）項の簡約をするタクティクで、
simplification または simplify の略である。
多少駄洒落はあるかもしれないが[2]、「簡単な」計算を行うコマンドという説明は適切ではない。
ただし、簡約のことを計算と呼ぶのは支障ないだろう。

計算はできる限り繰り返し行われる。なので、simpl を2回以上繰り返す意味はない。
一方で、Coqなので必ず停止することは保証されている。
 *)
Goal true && (true || false).
Proof.
  rewrite /=.
  (* Goal : true *)
  done.
Qed.

(** 計算の対象をゴールの一部に限定することができる。案外便利である。
    指定の方法は 3.6.6 rewrite [条件] 要素名 を参照のこと。
 *)
Goal true && (true || false).
Proof.
  rewrite [true || false]/=.
  (* Goal : true && true *)
  rewrite /=.
  (* Goal : true *)
  done.
Qed.

(** * simpl タクティクはなにをするのか

まずは、βベータ簡約をする、と覚えて間違いない。
 *)

Definition first {T1 T2} (s : T1 * T2) :=
  match s with
  | (x, y) => x
  end.

Definition pair1 (s : (bool * bool) * (nat * nat)) :=
  match s with
  | (bs, ns) => (first bs, first ns)
  end.
(* 説明の都合から、回りくどい書き方をしています。 *)

Goal pair1 ((false, true), (1, 2)) = (false, 1).
Proof.
  simpl.
  done.
Qed.
(** 左辺は、
    pair1 ((false, true), (1, 2)) ==> (false, 1)
    とβ簡約されている。 *)

(** 実際にはもうすこし複雑である。 *)
Goal forall bs, pair1 (bs, (1, 2)) = (first bs, 1).
Proof.
  move=> bs.
  simpl.
  (* pair1 (bs, (1, 2)) ==>  (first bs, 1) *)

  (* 参考 *)
  Eval cbv delta                in pair1 (bs, (1, 2)).
  Eval cbv delta beta           in pair1 (bs, (1, 2)).
  Eval cbv delta beta zeta      in pair1 (bs, (1, 2)).
  Eval cbv delta beta zeta iota in pair1 (bs, (1, 2)).

  Restart.
  move=> bs.
  rewrite /pair1.
  rewrite [first (1, 2)]/=.
  done.
Qed.

(** 4段階を踏んでいる [2] ：

(1) pair1 の引数である (bs, (1, 2)) は、pair コンストラクタを逆につかって分解できる。
bs と (1,2) の pair。

(2) pair1 を unfold (ηイータ簡約）する。変数を置き換える（δデルタ簡約）とも。

(3) 実引数による仮引数の書換（βベータ簡約）をする。

(4) match の場合分け（ιイオタ簡約）をする。 (bs.1, (1,2).1) を得る。
ι簡約は、inductiveに定義された型の値を使う、という意味から。
（特別な場合として、letへの代入をζゼータ簡約という。）

(1) first の引数である (1, 2) に対して、以下同様にする。

これが、「ポアンカレ原理」を支える「計算」の実際といえるのだろう。
*)

(** fixpoint で定義された関数についても、同様に処理され、再帰的に行われる。
    Coqなので必ず停止する。  *)
Fixpoint bsize (s : seq bool) : nat := if s is _ :: s' then (bsize s').+1 else 0.

Goal bsize [:: true; false; true] = 3.
Proof.
  simpl.
  (* Goal : 3 = 3
     左辺が
     bsize [:: true; false; true] => 3
     とβ簡約された。 *)
  done.
Qed.

Goal forall b s, bsize (b :: s) = bsize s + 1.
Proof.
  move=> b s.
  simpl.
  (* Goal : (bsize s).+1 = bsize s + 1
     ... 左辺が
     bsize (b :: s) => (bsize s).+1
     とβ簡約された。 *)
    by rewrite -addn1.

  Restart.
  move=> b s.
  rewrite [bsize (b :: s)]/bsize.
    by rewrite -addn1.
Qed.

Goal forall b1 b2 s, bsize (b1 :: b2 :: s) = bsize s + 2.
  move=> b1 b2 s.
  simpl.
    by rewrite -addn2.
Qed.

(** * simpl の lock について

Mathcomp の自然数の加・減・乗・累乗・階乗 はlockされている。
そのため、simpl では、自然数の計算は行われない。
*)

Fixpoint fact n :=
  match n with
  | 0 => 1
  | n'.+1 => n * fact n'
  end.

Goal fact 3 = 6.
Proof.
  simpl.
  (* Goal : 3 * (2 * (1 * 1)) = 6 *)
  (* fact は簡約されるが、掛け算はそのまま。 *)

  apply: refl_equal.                        (* reflexivity *)
Qed.

(**
バニラCoqと異なり、Mathcomp では、simpl では自然数の計算は行えない。
これは、ゴールが大きくなることを避けるため、とされている。[3]

Mathcomp で、simpl では自然数の計算は行えないことは、
Mathcomp で omega が使えない理由のひとつ。もうひとつは le の定義の違い。
 *)

(*
参考： ssrnat.v

Definition addn := nosimpl addn_rec.
Definition subn := nosimpl subn_rec.
Definition muln := nosimpl muln_rec.
Definition expn := nosimpl expn_rec.
Definition factorial := nosimpl fact_rec.
Definition double := nosimpl double_rec.

なお、.+1 や .*2 は計算される。
 *)

(**
lock を解除するには、以下のどれかを使う。[3]

unlockをunfold する。 rewrite /unlock
lockをfold する。     rewrite -/lock
unlock タクティクを使う。

（あるいは、simpl の代わりに cbn を使うこともできる [1]）

実際には、ssromegaタクティクの定義の中以外では、unlock する必要はないであろう。
 *)

Goal fact 3 = 6.
Proof.
  simpl.
  (* Goal : 3 * (2 * (1 * 1)) = 6 *)

  rewrite /muln /unlock /=.
  (* Goal : 6 = 6 *)

  done.
Qed.

(* END *)


Module FOL.

Parameter T : Set.

Parameter T_dec : forall x y : T, { x = y } + { x <> y }.

Parameter IsVariable : T -> Prop.

Definition Var : Set := { x : T & (IsVariable x) }.

Definition Substitution := Var -> T.

Hypothesis subst_dec : forall s s' : Substitution, { s = s' } + { s <> s' }.

Parameter Apply : Substitution -> T -> T.

Parameter Update : Substitution -> Var -> T -> Substitution.

Inductive Formula : Set :=
  | Equals : T -> T -> Formula
  | And  : Formula -> Formula -> Formula
  | Not : Formula -> Formula
  | Forall : Var  -> Formula -> Formula.

Definition Valuation := Substitution.

Definition coerce (v : Var) := projS1 v.

Parameter Satisfies : Valuation -> Formula -> Prop.

Axiom SatEquals : forall rho : Valuation, forall t t' : T,
  Apply rho t = Apply rho t'
  <->
  Satisfies rho (Equals t t').

Axiom SatForall : forall rho : Valuation, forall x : Var, forall phi : Formula,
  (forall t : T, Satisfies (Update rho x t) phi)
  <->
  Satisfies rho (Forall x phi).

Axiom SatAnd : forall rho : Valuation, forall phi phi' : Formula,
  (Satisfies rho phi /\ Satisfies rho phi')
  <->
  Satisfies rho (And phi phi').

Axiom SatNot : forall rho : Valuation, forall phi : Formula,
  (~Satisfies rho phi)
  <->
  Satisfies rho (Not phi).

Fixpoint SatisfiesF (rho : Valuation) (phi : Formula) : Prop :=
  match phi with
    | Equals t1 t2 => (Apply rho t1 = Apply rho t2)
    | Forall v phi' => forall (s : T), SatisfiesF (Update rho v s) phi'
    | And phi1 phi2 => SatisfiesF rho phi1 /\ SatisfiesF rho phi2
    | Not phi' => ~SatisfiesF rho phi'
  end.

Require Import Setoid.

Theorem sameThing : forall (phi : Formula) (rho : Valuation),
  SatisfiesF rho phi <-> Satisfies rho phi.
  induction phi.
  intros. apply SatEquals.
  intros. simpl. rewrite IHphi1. rewrite IHphi2. apply SatAnd.
  intros. simpl. rewrite IHphi. apply SatNot.
  intros. simpl. setoid_rewrite IHphi. apply SatForall.
Qed.

Inductive SatI : Valuation -> Formula -> Prop :=
  | SatIEquals : forall rho : Valuation, forall t t' : T,
                  (Apply rho t = Apply rho t') ->
                    SatI rho (Equals t t')
  | SatIForall : forall rho : Valuation, forall x : Var, forall phi : Formula,
                  (forall t : T, SatI (Update rho x t) phi) ->
                        SatI rho (Forall x phi)
  | SatIAnd : forall rho : Valuation, forall phi phi' : Formula,
               SatI rho phi ->
                 SatI rho phi' ->
                   SatI rho (And phi phi')
  | SatINot : forall rho : Valuation, forall phi : Formula,
               (SatNI rho phi) ->
                 SatI rho (Not phi)
with SatNI : Valuation -> Formula -> Prop :=
  | SatNIEquals : forall rho : Valuation, forall t t' : T,
                  (Apply rho t <> Apply rho t') ->
                    SatNI rho (Equals t t')
  | SatNIForall : forall rho : Valuation, forall x : Var, forall phi : Formula,
    (exists t : T, SatNI (Update rho x t) phi) -> SatNI rho (Forall x phi)
  | SatNIAnd : forall rho : Valuation, forall phi phi' : Formula,
               (SatNI rho phi \/ SatNI rho phi') ->
                   SatNI rho (And phi phi')
  | SatNINot : forall rho : Valuation, forall phi : Formula,
               (SatI rho phi) ->
                 SatNI rho (Not phi).

Require Import Classical.

Theorem EM : forall (p : Prop), p \/ ~ p.
  intros.
  tauto.
Qed.

Theorem forall_exists : forall D, forall P : D -> Prop, ~ (forall d : D, P d) <->
  exists d : D, ~ P d.
split;[|firstorder]. (* only the forward direction needs EM *)
intros.
apply NNPP; contradict H.
intro d.
apply NNPP; contradict H.
firstorder.
Qed.

(*Require Import Classical.

Theorem deMorgan : forall p q,
  ~ (p /\ q) <-> ~ p \/ ~ q.
  intros.
  apply NNPP. tauto.
Qed.

Theorem sameThing' : forall (rho : Valuation) (phi : Formula),
  (SatisfiesF rho phi <-> SatI rho phi) /\ ((~SatisfiesF rho phi) <-> SatNI rho phi).
  intros. generalize dependent rho.
  induction phi.
  intros.
     (* equals *)
    split.
      simpl. split. apply SatIEquals. intros. inversion H. assumption.
      simpl. split. intros. apply SatNIEquals. assumption. intros. inversion H. assumption.
      (* and *)
    split.
      simpl. split. intros. inversion H. constructor. apply IHphi1. assumption. apply IHphi2. assumption.
      simpl. split. inversion H. apply IHphi1. assumption. apply IHphi2. inversion H. assumption.
      simpl. setoid_replace (SatNI rho (And phi1 phi2)) with (~ SatisfiesF rho phi1 \/ ~ SatisfiesF rho phi2).
      apply deMorgan. setoid_replace (~ SatisfiesF rho phi1) with (SatNI rho phi1).
      setoid_replace (~ SatisfiesF rho phi2) with (SatNI rho phi2). split.
      inversion 1. assumption. intros. constructor. assumption.
      decompose [and] (IHphi1 rho). decompose [and] (IHphi2 rho).
      assumption. decompose [and] (IHphi1 rho). decompose [and] (IHphi2 rho).
      assumption.
      (* not *)
      intros. decompose [and] (IHphi rho).
      split. simpl. rewrite H0. split. intros. constructor. assumption.
      inversion 1. assumption.
      split. simpl. intros. constructor. apply H. apply NNPP. assumption.
      intros. inversion H1. simpl. tauto.
      (* forall *)
      intros.
      split. split.
      simpl. intros. constructor. intro. apply IHphi. apply H.
      simpl. intros. apply IHphi. inversion H. apply H2.
      split. unfold SatisfiesF. fold SatisfiesF. unfold not. intros.
      admit. admit.
Qed.
*)

Theorem or_from_sumbool : forall T, forall p : ( forall s s' : T, { s = s'} + { s <> s' } ),
  forall s s' : T, s = s' \/ s <> s'.
firstorder.
Qed.

Theorem subst_dec' : forall s s' : Substitution,
  s = s' \/ s <> s'.
apply or_from_sumbool.
apply subst_dec.
Qed.

Theorem T_dec' : forall t t' : T,
  t = t' \/ t <> t'.
apply or_from_sumbool.
apply T_dec.
Qed.

Theorem sameThing'' : forall (phi : Formula) (rho : Valuation) ,
  (Satisfies rho phi <-> SatI rho phi) /\ (~ Satisfies rho phi <-> SatNI rho phi).

  induction phi.
  (* equals *)
  intros. rewrite <- SatEquals.
  split; (split; [constructor | inversion 1]; assumption).
  (* and *)
  intros. rewrite <- SatAnd.
  specialize (IHphi1 rho).
  specialize (IHphi2 rho).
  split; (split; [constructor | inversion 1]; tauto).
  (* not *)
  intros. rewrite <- SatNot.
  specialize (IHphi rho).
  split; (split; [constructor | inversion 1];tauto).
  (* forall *)
  intro. rewrite <- SatForall.
  split; (split;[constructor | inversion 1]);try firstorder.

  rewrite forall_exists in H.
    destruct H. exists x. firstorder.
Qed.

End FOL.


From mathcomp
Require Import ssreflect.

Section ModusPonens.
Variables X Y : Prop.

Hypothesis XtoY_is_true : X -> Y.
Hypothesis X_is_true : X.

Theorem MP : Y.
Proof.
move: X_is_true.
by [].
Qed.

End ModusPonens.


Require Crypto.Algebra.Field.

Module W.
  Section WeierstrassCurves.
    (* Short Weierstrass curves with addition laws. References:
     * <https://hyperelliptic.org/EFD/g1p/auto-shortw.html>
     * <https://cr.yp.to/talks/2007.06.07/slides.pdf>
     * See also:
     * <http://cs.ucsb.edu/~koc/ccs130h/2013/EllipticHyperelliptic-CohenFrey.pdf> (page 79)
     *)

    Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}.
    Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope.
    Local Notation "x =? y" := (Decidable.dec (Feq x y)) (at level 70, no associativity) : type_scope.
    Local Notation "x =? y" := (Sumbool.bool_of_sumbool (Decidable.dec (Feq x y))) : bool_scope.
    Local Infix "+" := Fadd. Local Infix "*" := Fmul.
    Local Infix "-" := Fsub. Local Infix "/" := Fdiv.
    Local Notation "- x" := (Fopp x).
    Local Notation "x ^ 2" := (x*x) (at level 30). Local Notation "x ^ 3" := (x*x^2) (at level 30).
    Local Notation "'∞'" := unit : type_scope.
    Local Notation "'∞'" := (inr tt) : core_scope.

    Local Notation "( x , y )" := (inl (pair x y)).
    Local Open Scope core_scope.

    Context {a b: F}.

    Definition point := { P | match P with
                              | (x, y) => y^2 = x^3 + a*x + b
                              | ∞ => True
                              end }.
    Definition coordinates (P:point) : F*F + ∞ := let (xyi,_) := P in xyi.

    Definition eq (P1 P2:point) :=
      match coordinates P1, coordinates P2 with
      | (x1, y1), (x2, y2) => x1 = x2 /\ y1 = y2
      | ∞, ∞ => True
      | _, _ => False
      end.

    Program Definition zero : point := ∞.

    Local Notation "0" := Fzero.  Local Notation "1" := Fone.
    Local Notation "2" := (1+1). Local Notation "3" := (1+2).

    Program Definition add (P1 P2:point) : point :=
      match coordinates P1, coordinates P2 return F*F+∞ with
      | (x1, y1), (x2, y2) =>
        if x1 =? x2
        then
          if y2 =? -y1
          then ∞
          else let k := (3*x1^2+a)/(2*y1) in
               let x3 := k^2-x1-x2 in
               let y3 := k*(x1-x3)-y1 in
               (x3, y3)
        else let k := (y2-y1)/(x2-x1) in
             let x3 := k^2-x1-x2 in
             let y3 := k*(x1-x3)-y1 in
             (x3, y3)
      | ∞, ∞ => ∞
      | ∞, _ => coordinates P2
      | _, ∞ => coordinates P1
      end.
    Next Obligation.
      cbv [coordinates]; BreakMatch.break_match; trivial; Field.fsatz.
    Qed.

    Fixpoint mul (n:nat) (P : point) : point :=
      match n with
      | O => zero
      | S n' => add P (mul n' P)
      end.
  End WeierstrassCurves.
End W.

Delimit Scope W_scope with W.
Infix "+" := W.add : W_scope.
Infix "*" := W.mul : W_scope.


C02W82DBHV2R:~ i847419$ coqtop
Welcome to Coq 8.8.0 (April 2018)

Coq < Require Import Classical.

Coq <
Coq < Theorem exp002: (forall I R : Prop, ((I /\ ~R) /\ ~I) -> R).
1 subgoal

  ============================
  forall I R : Prop, (I /\ ~ R) /\ ~ I -> R

exp002 < intros.
1 subgoal

  I, R : Prop
  H : (I /\ ~ R) /\ ~ I
  ============================
  R

exp002 < destruct H.
1 subgoal

  I, R : Prop
  H : I /\ ~ R
  H0 : ~ I
  ============================
  R

exp002 < destruct H.
1 subgoal

  I, R : Prop
  H : I
  H1 : ~ R
  H0 : ~ I
  ============================
  R

exp002 < tauto.
No more subgoals.

exp002 < Qed.
exp002 is defined

Coq <


Require Export ZArith.

Lemma IZN : forall n:Z,
  (0 <= n)%Z ->
  exists m : nat,
  n = Z.of_nat m.
Proof.
  intros z hz.
  exists (Z.to_nat z).
  rewrite Z2Nat.id.
  { reflexivity. }
  { exact hz. }
Qed.


Require Coq.Init.Datatypes.
Import Coq.Init.Notations.
Notation "A -> B" := (forall (_ : A), B) : type_scope.
Set Printing Universes.
Require Import propositionsSets.
Require Import equivalencesDefinitions.

Section univalence.

Inductive IsEquiv (X Y:Type):=
|isEquiv (f:X->Y) (H:IsContractibleMap f).

Definition idToEquiv (X Y:Type):
  Id X Y -> IsEquiv X Y.
Proof.
(* your proof here *)
Defined.

Axiom univalence:
  forall X Y:Type, IsContractibleMap(idToEquiv X Y).

End univalence.


Variable Ack : nat -> nat -> nat.

Axiom Ack0 : forall m : nat, Ack 0 m = S m.
Axiom Ack1 : forall n : nat, Ack (S n) 0 = Ack n 1.
Axiom Ack2 : forall n m : nat, Ack (S n) (S m) = Ack n (Ack (S n) m).

Hint Rewrite Ack0 Ack1 Ack2 : base0.

Lemma ResAck0 : (Ack 2 2 = 7 -> False) -> False.
Proof.
  intros.
  autorewrite with base0 in H using try (apply H; reflexivity).
Qed.

Lemma ResAck1 : forall H:(Ack 2 2 = 7 -> False), True -> False.
Proof.
  intros.
  autorewrite with base0 in *.
    apply H;reflexivity.
Qed.


Require Import ArithRing.
Require Import Compare_dec.
Require Import Wf_nat.
Require Import Arith.
Require Import Lia.

Theorem minus_minus : forall a b c : nat, a - b - c = a - (b + c).
intros a; elim a; auto.
intros n' Hrec b; case b; auto.
Qed.

Remark expand_mult2 : forall x : nat, 2 * x = x + x.
intros x; ring.
Qed.

Theorem lt_neq : forall x y : nat, x < y -> x <> y.
unfold not in |- *; intros x y H H1; elim (Nat.lt_irrefl x);
 pattern x at 2 in |- *; rewrite H1; auto.
Qed.

#[local] Hint Resolve lt_neq : core.

Theorem monotonic_inverse :
 forall f : nat -> nat,
 (forall x y : nat, x < y -> f x < f y) ->
 forall x y : nat, f x < f y -> x < y.
intros f Hmon x y Hlt; case (le_gt_dec y x); auto.
intros Hle; apply Nat.lt_eq_cases in Hle.
destruct Hle as [Hlt'|Heq].
elim (Nat.lt_asymm _ _ Hlt); apply Hmon; auto.
elim (lt_neq _ _ Hlt); rewrite Heq; auto.
Qed.

Theorem mult_lt : forall a b c : nat, c <> 0 -> a < b -> a * c < b * c.
intros a b c; elim c.
intros H; elim H; auto.
intros c'; case c'.
intros; lia.
intros c'' Hrec Hneq Hlt;
 repeat rewrite <- (fun x : nat => mult_n_Sm x (S c'')).
lia.
Qed.

Remark add_sub_square_identity :
 forall a b : nat,
 (b + a - b) * (b + a - b) = (b + a) * (b + a) + b * b - 2 * ((b + a) * b).
intros a b; rewrite (Nat.add_comm b a) at 1 2; rewrite Nat.add_sub.
repeat rewrite Nat.mul_add_distr_r || rewrite <- (Nat.mul_comm (b + a)).
replace (b * b + a * b + (b * a + a * a) + b * b) with
 (b * b + a * b + (b * b + a * b + a * a)); try (ring; fail).
rewrite expand_mult2; repeat rewrite Nat.add_sub; auto with *.
Qed.

Theorem sub_square_identity :
 forall a b : nat, b <= a -> (a - b) * (a - b) = a * a + b * b - 2 * (a * b).
intros a b H.
apply Nat.sub_add in H; rewrite Nat.add_comm in H.
rewrite <- H.
apply add_sub_square_identity.
Qed.

Theorem square_monotonic : forall x y : nat, x < y -> x * x < y * y.
intros x; case x.
intros y; case y; simpl in |- *; auto with *.
intros x' y Hlt; apply Nat.lt_trans with (S x' * y).
rewrite (Nat.mul_comm (S x') y); apply mult_lt; auto.
apply mult_lt; lia.
Qed.

Theorem root_monotonic : forall x y : nat, x * x < y * y -> x < y.
exact (monotonic_inverse (fun x : nat => x * x) square_monotonic).
Qed.

Remark square_recompose : forall x y : nat, x * y * (x * y) = x * x * (y * y).
intros; ring.
Qed.

Remark mult2_recompose : forall x y : nat, x * (2 * y) = x * 2 * y.
intros; ring.
Qed.

Section sqrt2_decrease.

Variables (p q : nat) (pos_q : 0 < q) (hyp_sqrt : p * p = 2 * (q * q)).

Theorem sqrt_q_non_zero : 0 <> q * q.
generalize pos_q; case q.
intros H; elim (Nat.nlt_0_r 0); auto.
intros n H.
simpl in |- *; discriminate.
Qed.

#[local] Hint Resolve sqrt_q_non_zero : core.

Ltac solve_comparison :=
  apply root_monotonic; repeat rewrite square_recompose; rewrite hyp_sqrt;
   rewrite mult2_recompose; apply mult_lt; auto with arith.

Theorem comparison1 : q < p.
replace q with (1 * q); try ring.
replace p with (1 * p); try ring.
solve_comparison.
Qed.

Theorem comparison2 : 2 * p < 3 * q.
solve_comparison.
Qed.

Theorem comparison3 : 4 * q < 3 * p.
solve_comparison.
Qed.

#[local] Hint Resolve comparison1 comparison2 comparison3: arith.

Theorem comparison4 : 3 * q - 2 * p < q.
apply Nat.add_lt_mono_l with (2 * p).
rewrite Nat.add_comm; rewrite Nat.sub_add;
 try (simple apply Nat.lt_le_incl; auto with arith).
replace (3 * q) with (2 * q + q); try ring.
apply Nat.add_lt_le_mono; auto.
repeat rewrite (Nat.mul_comm 2); apply mult_lt; auto with arith.
Qed.

Remark mult_minus_distr_l : forall a b c : nat, a * (b - c) = a * b - a * c.
intros a b c; repeat rewrite (Nat.mul_comm a); apply Nat.mul_sub_distr_r.
Qed.

Remark minus_eq_decompose :
 forall a b c d : nat, a = b -> c = d -> a - c = b - d.
intros a b c d H H0; rewrite H; rewrite H0; auto.
Qed.

Theorem new_equality :
 (3 * p - 4 * q) * (3 * p - 4 * q) = 2 * ((3 * q - 2 * p) * (3 * q - 2 * p)).
repeat rewrite sub_square_identity; auto with arith.
repeat rewrite square_recompose; rewrite mult_minus_distr_l.
apply minus_eq_decompose; try rewrite hyp_sqrt; ring.
Qed.

End sqrt2_decrease.

#[local] Hint Resolve Nat.lt_le_incl comparison2: sqrt.

Theorem sqrt2_not_rational :
 forall p q : nat, q <> 0 -> p * p = 2 * (q * q) -> False.
intros p q; generalize p; clear p; elim q using (well_founded_ind lt_wf).
clear q; intros q Hrec p Hneq;
 pose proof Hneq as Hlt_O_q; apply Nat.neq_0_lt_0 in Hlt_O_q;
 intros Heq.
apply (Hrec (3 * q - 2 * p) (comparison4 _ _ Hlt_O_q Heq) (3 * p - 4 * q)).
apply sym_not_equal; apply lt_neq; apply Nat.add_lt_mono_l with (2 * p);
 rewrite <- plus_n_O; rewrite Nat.add_comm; rewrite Nat.sub_add; auto with *.
apply new_equality; auto.
Qed.


(** * BasicTactics: Additional Basic Coq Tactics *)

Require Export Poly.

(* SOONER: (SCW) This and earlier chapters could use a few WORKINCLASS
   tags... *)

(** FULL: This chapter introduces several more proof strategies and
    tactics that, together, allow us to prove theorems about the
    functional programs we have been writing. In particular, we'll
    reason about functions that work with natural numbers and
    lists. We will see:

    - how to use auxiliary lemmas, in both forwards and backwards reasoning;
    - how to reason about data constructors, which are injective and disjoint;
    - how to create a strong induction hypothesis (and when
      strengthening is required); and
    - how to reason by case analysis.
 *)

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

(** FULL: 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. *)
(** TERSE: We can use [apply] when some hypothesis or an earlier
    lemma matches the goal: *)

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.
  (* At this point, we could finish with
     "[rewrite -> eq2. reflexivity.]" as we have
     done several times above. But we can achieve the
     same effect in a single step by using the
     [apply] tactic instead: *)
  apply eq2.  Qed.

(* SOONER: This is the first time we've seen a theorem with
multiple hypotheses.  Say a few words about how -> is right-associative
and perhaps tie in to currying. *)

(** FULL: 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. *)
(** TERSE: [apply] also works with _conditional_ hypotheses: *)

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.

(** FULL: 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]. *)
(* HIDEFROMADVANCED *)
(* HIDE *)
(* SOONER: The following quiz is ambiguous, since you can solve it without apply,
   by using "rewrite with (r:=m)". *)
(* QUIZ *)
(** Could we have completed this proof without [apply]?

    (1 for yes, 2 for no) *)
(* /QUIZ *)
(* /HIDE *)

(** FULL: Typically, when we use [apply H], the statement [H] will
    begin with a [forall] binding 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]. *)
(** TERSE: Observe how Coq picks appropriate values for the universal
    variables of the hypothesis here: *)

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.

(* FULL *)
(* EX2? (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.
  (* ADMITTED *)
  intros H1 H2.
  apply H1. apply H2.  Qed.
(* /ADMITTED *)
(** [] *)
(* /FULL *)

(** FULL: 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. *)
(** TERSE: The goal must match the hypothesis _exactly_ for [apply] to
    work: *)

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

(** In this case we can use the [symmetry] tactic, which switches the
    left and right sides of an equality in the goal. *)

Theorem silly3 : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  symmetry.
  simpl. (* Actually, this [simpl] is unnecessary, since
            [apply] will perform simplification first. *)
  apply H.  Qed.

(* FULL *)
(* EX3 (apply_exercise1) *)
(** Hint: you can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [SearchAbout] is
    your friend. *)
(* QUIETSOLUTION *)

(** For the slick solution to this exercise, we can use the fact that
    [rev] is involutive. *)

(* /QUIETSOLUTION *)
Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* ADMITTED *)
  intros l l' eq. rewrite -> eq.
  symmetry.
  apply rev_involutive.   Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: rev_exercise1 *)
(** [] *)

(* EX1? (apply_rewrite) *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  Are there situations where both can usefully be
    applied?
  (* SOLUTION *)
    The [rewrite] tactic is used to apply a known equality (a hypothesis
    from the context or a previously proved lemma) to modify the goal,
    replacing all occurrences of one side by the other.  The [apply]
    tactic uses a known implication (a hypothesis from the context, a
    previously proved lemma, or a constructor) to replace a goal that
    matches the conclusion of the implication with subgoals, one for
    each premise of the implication.  If the known fact is itself an
    equality (with no premises), then either tactic can be used.  (We
    will see below that each tactic can also be used to modify a
    hypothesis rather than the goal.)
(* /SOLUTION *)
*)
(** [] *)
(* /FULL *)
(* /HIDEFROMADVANCED *)

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

(* HIDE: Does this belong with [apply] earlier? APT:
   Yes, after moving a couple of not-very-relevant exercises
   to the end section.
   *)
(** FULL: The following silly example uses two rewrites in a row to
    get from [[a,b]] to [[e,f]]. *)
(** TERSE: Examples like this one use two rewrites to exploit the
    transitivity of equality.  We can abstract this into its own
    lemma. *)

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.

(** FULL: Since this is a common pattern, we might
    abstract 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.

(** FULL: 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. *)
(** TERSE: But applying this lemma requires a slight
    variation on [apply]: *)

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.
(* FULL *)
  (* 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]. *)
(* /FULL *)
(* TERSE *)
  (* Doing [apply trans_eq] doesn't work!  But... *)
(* /TERSE *)
  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.

(** FULL:  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]]. *)
(** TERSE: In practice, often Coq can figure out the correct variable
    and we can omit the "[m :=]" part. *)

(* FULL *)
(* EX3? (apply_with_exercise) *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* ADMITTED *)
  intros n m o p eq1 eq2.
  apply trans_eq with m. apply eq2. apply eq1.   Qed.
(* /ADMITTED *)
(** [] *)

(* /FULL *)

(* ###################################################### *)
(** * The [inversion] tactic *)
(* SOONER: We're going to wind up admitting that inversion and
   destruct are similar, although here they look completely different.
   Be careful not to say anything that will turn out to be false
   later!  In fact, it would surely be possible to phrase the
   discussion here in terms that will extend naturally, in particular
   by talking explicitly about unification. *)

(** FULL: Recall the definition of natural numbers:
[[
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
]]
    It is clear 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 other facts:

    - The constructor [S] is _injective_.  That is, the only way we can
      have [S n = S m] is if [n = m].

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

(** FULL: 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 unequal.  (Since neither [true]
    nor [false] take any arguments, their injectivity is not an issue.) *)
(** TERSE: In Coq, the constructors of inductive types are _injective_
    and _disjoint_.

    E.g., for [nat]...

    - the only way we can have [S n = S m] is if [n = m] (that is, [S]
      is _injective_)

    - [O] is not equal to [S n] for any [n] (that is, [O] and [S] are
      _disjoint_)
*)

(** Coq provides a tactic called [inversion] that allows us to exploit
    these principles in proofs.

    The [inversion] tactic is used like this.  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] instructs Coq to "invert" this
    equality to extract the information it contains about these terms:

    - If [c] and [d] are the same constructor, then we know, by the
      injectivity of this constructor, that [a1 = b1], [a2 = b2],
      etc.; [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.  That is, a false assumption has crept
      into the context, and this means that any goal whatsoever is
      provable!  In this case, [inversion H] marks the current goal as
      completed and pops it off the goal stack. *)

(** FULL: The [inversion] tactic is probably easier to understand by
    seeing it in action than from general descriptions like the above.
    Below you will find example theorems that demonstrate the use of
    [inversion] and exercises to test your understanding. *)

Theorem eq_add_S : forall (n m : nat),
     S n = S m ->
     n = m.
Proof.
  intros n m eq. inversion eq. reflexivity.  Qed.

(* HIDEFROMADVANCED *)
Theorem silly4 : forall (n m : nat),
     [n] = [m] ->
     n = m.
Proof.
  intros n o eq. inversion eq. reflexivity.  Qed.

(** FULL: As a convenience, the [inversion] tactic can also
    destruct equalities between complex values, binding
    multiple variables as it goes. *)

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

(* FULL *)
(* EX1 (sillyex1) *)
Example sillyex1 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = z :: j ->
     y :: l = x :: j ->
     x = y.
Proof.
  (* ADMITTED *)
  intros X x y z l j eq1 eq2.
  inversion eq1. inversion eq2. symmetry. apply H0. Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 1: sillyex1 *)
(** [] *)
(* /FULL *)

(* /HIDEFROMADVANCED *)
(* SOONER: Text needed for FULL version *)
Theorem silly6 : forall (n : nat),
     S n = O ->
     2 + 2 = 5.
Proof.
  intros n contra. inversion contra. Qed.
(* HIDEFROMADVANCED *)

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

(* /HIDEFROMADVANCED *)
(* FULL *)
(* EX1 (sillyex2) *)
Example sillyex2 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = [] ->
     y :: l = z :: j ->
     x = z.
Proof.
  (* ADMITTED *)
  intros X x y z l j eq1 eq2. inversion eq1. Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 1: sillyex2 *)
(** [] *)
(* /FULL *)

(** FULL: While the injectivity of constructors allows us to reason
    [forall (n m : nat), S n = S m -> n = m], the reverse direction of
    the implication is an instance of a more general fact about
    constructors and functions, which we will often find useful: *)

(** TERSE: A useful theorem in the reverse direction: *)

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.

(* SOONER: Also: "There should be more discussion and practice with
   how to deal with subexpressions that do not allow application of
   hypotheses, for example how to deal with the [S m] in [m + (S m)].
   Again, I sort of understand what to do with [destruct] and
   induction, but it would help to have more exercises that break down
   the process of making this connection." *)

(* EX2? (practice) *)
(** A couple more nontrivial but not-too-complicated proofs to work
    together in class, or for you to work as exercises. *)
(* HIDE: They may
    involve applying lemmas from earlier lectures or homeworks.
   APT: Not true of what's left. *)

(* HIDE *)
(* HIDE: Not sure whether this is worth showing.  The chapter is
   getting long.  In any case, it doesn't belong here!*)
(** A slightly different way of making the same assertion
    as above. *)

(* SOONER: Danger! This is actually somewhat tricky.  In particular,
   it's important not to introduce [n] before the induction, which is
   something we may not have discussed at this point.  (BCP: We have,
   I guess, but perhaps this should be moved later anyway?) *)
Theorem length_snoc'' : forall (X : Type) (v : X)
                             (l : list X) (n : nat),
     S (length l) = n ->
     length (snoc l v) = n.
Proof.
  intros X v l. induction l as [| v' l'].
    - (* l = [] *) intros n eq. rewrite <- eq. reflexivity.
    - (* l = v' :: l' *)
      intros n eq. simpl.
      (* Note the care we take here: first we introduce n
         and the equality, then we simplify.  This leaves
         the equation about length UN-simplified, which
         means our context will make a little bit more
         sense.  (The proof will work either way.) *)
      destruct n as [| n'].
      (* Now we destruct n; if it's 0, we have a
         contradiction immediately. *)
      + (* n = 0 *) inversion eq.
      + (* n = S n' *)
      (* We use the IH and the inversion of eq to prove the
         equation we want about length. *)
        apply f_equal. apply IHl'. inversion eq.
        reflexivity. Qed.
(* /HIDE *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  (* ADMITTED *)
  intros n. intros Heq.
  destruct n as [| n'].
  - (* n = 0 *)
    reflexivity.
  - (* n = S n' *)
    inversion Heq. Qed.
(* /ADMITTED *)

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  (* ADMITTED *)
  intros n. intros Heq.
  destruct n as [| n'].
  - (* n = 0 *)
    reflexivity.
  - (* n = S n' *)
    inversion Heq. Qed.
(* /ADMITTED *)
(** [] *)

(* QUIZ *)
(** Suppose Coq's proof state looks like
[[
    1 subgoals, subgoal 1

      H : false = true
      ============================
       negb true = negb false
]]
    and we apply the tactic [inversion H].  What will happen?

    (1) No new information available in the context

    (2) Substitute [true] with [false] in the conclusion, leaving
        [negb false = negb false]

    (3) "No more subgoals"

*)
(* HIDE *)
Theorem quiz1 : false = true -> negb true = negb false.
Proof. intros H. inversion H. Qed.
(* /HIDE *)
(* /QUIZ *)
(* QUIZ *)
(** Suppose Coq's proof state looks like
[[
    1 subgoals, subgoal 1

  x : bool
  y : bool
  H : x = y
  ============================
   y = x
]]
    and we apply the tactic [inversion H].  What will happen?

    (1) No new information available in the context

    (2) Substitute [x] with [y] in the conclusion, leaving
        [y = y]

    (3) "No more subgoals"

*)
(* HIDE *)
Theorem quiz3 : forall x y : bool, x = y -> y = x.
Proof. intros x y H. inversion H. Abort.
(* /HIDE *)
(* /QUIZ *)
(* QUIZ *)
(** Suppose Coq's proof state looks like
[[
    1 subgoals, subgoal 1

      H : negb false = negb true
      ============================
       true = false
]]
    and we apply the tactic [inversion H].  What will happen?

    (1) No new information available in the context

    (2) Substitute [true] with [false] in the conclusion, leaving
        [false = false]

    (3) "No more subgoals"

*)
(* HIDE *)
Theorem quiz2 : negb true = negb false -> false = true.
Proof. intros H. inversion H. Qed.
(* /HIDE *)
(* /QUIZ *)

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

(** FULL: 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. *)
(** TERSE: Tactics often come with "[...in...]" variants that can be
    used on hypotheses instead of goals. *)

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.

(** FULL: Similarly, the tactic [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
    gives us 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. *)
(** TERSE: The tactic [apply] is a form of "backward reasoning": it
    says "We're trying to prove [X] and we know [Y->X], so if we can
    prove [Y] we'll be done."  By contrast, the variant
    [apply... in...] is "forward reasoning": it says "We know [Y] and
    we know [Y->X], so we can deduce [X]." *)
(* HIDEFROMADVANCED *)

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.

(* /HIDEFROMADVANCED *)
(** FULL: 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, Coq tends to favor backward reasoning, but in some
    situations the forward style can be easier to use or to think
    about.  *)

(* EX3! (plus_n_n_injective) *)
(** Practice using "in" variants in this exercise. *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* Hint: use the plus_n_Sm lemma *)
    (* ADMITTED *)
    - (* n = 0 *) intros m. simpl. intros eq. destruct m as [| m'].
      + (* m = 0 *) reflexivity.
      + (* m = S m' *) inversion eq.
    - (* n = S n' *) intros m eq. destruct m as [| m'].
      + (* m = 0 *) inversion eq.
      + (* m = S m' *)
        apply f_equal. apply IHn'.
        (* just [simpl in eq] doesn't work here *)
        rewrite <- plus_n_Sm in eq. rewrite <- plus_n_Sm in eq.
        inversion eq. reflexivity.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: plus_n_n_injective *)
(** [] *)

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

(* TERSE *)
(** Here's a function for doubling a natural number (from the [Induction]
    chapter): *)
(* HIDE: Repeated because double only appears in the FULL version of
   Induction.v *)

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

(** FULL: 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 always 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 little 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... *)
(** TERSE: Suppose we want to show that [double] is injective -- i.e.,
    that it always maps different arguments to different results.  The
    way we _start_ this proof is a little bit delicate: *)

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.
      (* Here we are stuck.  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.
(* HIDEFROMADVANCED *)

(** What went wrong? *)

(** FULL: 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 that
    the proposition

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

    holds for all [n] by showing

      - [P O]

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

      - [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 with proving [R]!  (If we
    tried to prove [R] from [Q], we would say 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 at this point.) *)

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

(** The good 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' *)
(* FULL *)
    (* Notice that both the goal and the induction
       hypothesis have changed: 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.  *)
(* /FULL *)
    intros m eq.
(* FULL *)
    (* Now we choose a particular [m] and introduce the
       assumption that [double n = double m].  Since we
       are doing a case analysis on [n], we need a case
       analysis on [m] to keep the two "in sync." *)
(* /FULL *)
    destruct m as [| m'].
    + (* m = O *)
(* FULL *)
      (* The 0 case is trivial *)
(* /FULL *)
      inversion eq.
    + (* m = S m' *)
      apply f_equal.
(* FULL *)
      (* At this point, since we are in the second
         branch of the [destruct m], the [m'] mentioned
         in the context at this point is actually the
         predecessor of the one 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
         [m'] that we are talking about right now (this
         instantiation is performed automatically by
         [apply]), then [IHn'] gives us exactly what we
         need to finish the proof. *)
(* /FULL *)
      apply IHn'. inversion eq. reflexivity. Qed.

(* HIDEFROMADVANCED *)
(** What this teaches us is that we need to be careful about using
    induction to try to prove something too specific: If we're proving
    a property of [n] and [m] by induction on [n], we may need to
    leave [m] generic. *)

(* /HIDEFROMADVANCED *)
(** The proof of this theorem (left as an exercise) has to be treated similarly: *)

(* FULL *)
(* EX2 (beq_nat_true) *)
(* /FULL *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  (* ADMITTED *)
  intros n. induction n as [| n'].
  - (* n = 0 *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) simpl. intros contra. inversion contra.
  - (* n = S n' *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) simpl. intros contra. inversion contra.
    + (* m = S m' *) simpl. intros H.
      apply f_equal. apply IHn'. apply H. Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 2: beq_nat_true *)
(* FULL *)
(** [] *)

(* EX2A (beq_nat_true_informal) *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)
(* GRADE_MANUAL 2: informal proof *)

(* SOLUTION *)
(** _Theorem_: For all natural numbers n and m, if [beq_nat n m = true],
      then [n = m].

    _Proof_ (more pedantic, arguably less clear): We show, by
    induction on [n], that, for all [m], if [beq_nat n m = true], then
    [n = m].

      - Suppose [n = 0].  We must show, for all [m], that if
        [beq_nat 0 m = true], then [0 = m].  We proceed by cases on [m].

          - If [m = 0], we must show [0 = 0], which holds by
            reflexivity.

          - If [m = S m'], our hypothesis states that [beq_nat 0
            (S m') = true].  But [beq_nat 0 (S m')] reduces to [false], so
            this is absurd.

      - Otherwise, [n = S n'], and the induction hypothesis states
        that for all natural numbers m', if [beq_nat n' m' = true],
        then [n' = m'].  We must show that if [beq_nat (S n') m = true],
        then [S n' = m].  We again proceed by cases on m.

          - If [m = 0], the IH states that [beq_nat (S n') 0 = true],
            which is absurd.

          - Otherwise [m = S m'], and the IH states that
            [beq_nat (S n') (S m') = true], which simplifies to
            [beq_nat n' m' = true].  We may therefore apply the
            induction hypothesis (instantiated at [m']) to conclude
            that [n' = m'], which immediately implies that
            [S n' = S m']. []

    _Proof_ (more natural style): By induction on [n].

      - Suppose [n = 0].  We must show that if [beq_nat 0 m = true],
        then [0 = m].  Now, it must be that [m = 0] and must therefore
        show [0 = 0], which is true by reflexivity.  (Otherwise, we
        would have [m = S m'] and [beq_nat 0 (S m') = true].  But
        [beq_nat 0 (S m')] reduces to [false], so we would have
        [true = false], a contradiction.)

      - Otherwise, [n = S n'], and the induction hypothesis states
        that for all natural numbers m', if [beq_nat n' m' = true],
        then [n' = m'].  We must show that if [beq_nat (S n')
        m = true], then [S n' = m].  This time, it cannot be that [m = 0],
        since then the hypothesis would state that
        [beq_nat (S n') 0 = true], which is absurd.  So suppose
        [m = S m'] for some [m'].  The IH now states that
        [beq_nat (S n') (S m') = true], which simplifies to
        [beq_nat n' m' = true].  We may therefore
        apply the induction hypothesis (instantiated at [m']) to
        conclude that [n' = m'], which immediately implies that
        [S n' = S m'].  [] *)
(* /SOLUTION *)
(** [] *)

(* /FULL *)

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

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

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

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

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

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

(* SOONER: Somewhere (in this file? in Poly?), we need to do a more
   careful discussion of the way generalized IHs are handled in
   informal proofs.  Basically, the practice seems to be to assume
   we're working with a "general enough" IH, but seldom to bother
   saying exactly what it is! *)

(** FULL: 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 this is what we wanted to show.  Otherwise, if [n = S
    n'] for some [n'], we derive a contradiction: by the definition of
    [double] we would have [double n = S (S (double n'))], but this
    contradicts the assumption that [double n = 0].

  - Otherwise, 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 inversion 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. [] *)

(** Here's another illustration of [inversion] and using an
    appropriately general induction hypothesis.  This is a slightly
    roundabout way of stating a fact that we have already proved
    above.  The extra equalities force us to do a little more
    equational reasoning and exercise some of the tactics we've seen
    recently. *)

Theorem length_snoc' : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l. induction l as [| v' l'].

  - (* l = [] *)
    intros n eq. rewrite <- eq. reflexivity.

  - (* l = v' :: l' *)
    intros n eq. simpl. destruct n as [| n'].
    + (* n = 0 *) inversion eq.
    + (* n = S n' *)
      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.

(** FULL: It might be tempting to start proving the above theorem
    by introducing [n] and [eq] at the outset.  However, this leads
    to an induction hypothesis that is not strong enough.  Compare
    the above to the following (aborted) attempt: *)
(** TERSE: Note that introducing [n] too early doesn't yield a
    general enough induction hypothesis: *)

Theorem length_snoc_bad : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l n eq. induction l as [| v' l'].

  - (* l = [] *)
    rewrite <- eq. reflexivity.

  - (* l = v' :: l' *)
    simpl. destruct n as [| n'].
    + (* n = 0 *) inversion eq.
    + (* n = S n' *)
      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)

(** FULL: As in the double examples, the problem is that by
    introducing [n] before doing induction on [l], the induction
    hypothesis is specialized to one particular natural number, namely
    [n].  In the induction case, however, we need to be able to use
    the induction hypothesis on some other natural number [n'].
    Retaining the more general form of the induction hypothesis thus
    gives us more flexibility.

    In general, a good rule of thumb is to make the induction hypothesis
    as general as possible. *)

(* FULL *)
(* EX3! (gen_dep_practice) *)
(** Prove this by induction on [l]. *)

Theorem index_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     index n l = None.
Proof.
  (* ADMITTED *)
  intros n X l. generalize dependent n. induction l as [| x l'].
  - (* l = nil *) reflexivity.
  - (* l = x :: l' *) intros n eq. simpl. simpl in eq.
    rewrite <- eq.  apply IHl'.  reflexivity.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: index_after_last *)
(** [] *)

(* EX3?A (index_after_last_informal) *)
(** Write an informal proof corresponding to your Coq proof
    of [index_after_last]:

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

     _Proof_:
     (* SOLUTION *)
      By induction on [l].

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

        This follows immediately from the definition of index.

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

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

(* EX3? (gen_dep_practice_more) *)
(** Prove this by induction on [l]. *)

Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : list X),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  (* ADMITTED *)
  intros n X v l.
  generalize dependent n.
  induction l as [| x l'].
  - (* l = nil *) intros n eq. rewrite <- eq. reflexivity.
  - (* l = x :: l' *) simpl. intros n eq.
    assert (length (snoc l' v) = n).
    { rewrite <- eq. apply IHl'. reflexivity. }
    rewrite -> H. reflexivity.  Qed.
(* /ADMITTED *)
(** [] *)

(* EX3? (app_length_cons) *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  (* ADMITTED *)
  intros X l1 l2 x. induction l1 as [| y l1'].
  - (* l1 = nil *)
    intros n eq. apply eq.
  - (* l1 = y :: l1' *)
    simpl. intros n eq. rewrite <- eq.
      assert (S (length (l1' ++ l2)) = length (l1' ++ x :: l2)).
        apply IHl1'. reflexivity.
      rewrite -> H. reflexivity.  Qed.
(* /ADMITTED *)
(** [] *)

(* EX4? (app_length_twice) *)
(** Prove this by induction on [l], without using [app_length] from [Lists]. *)
(* SOONER: This might be a little bit hard??
   There are a couple of tricky little points!
   APT: Yes: the nested induction is a first, I think. And it would
     be good to have seen rewrite with an applied term; otherwise
     a kludgy forward [assert] or [pose proof] seems needed. *)
(* SOONER: no need for a _nested_ induction per se -- side lemmas will
   do the trick, too, and students have been exposed to that
   already.  *)
(* SOONER: APT: Yes, but the lemma above is terribly ad-hoc, as well
   as ill-suited for its use here!
   I realize that the pedagogical point here has nothing to do with
   developing sensible lemmas for lists, but these seem pretty distorted. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  (* ADMITTED *)
  intros X n l.
  generalize dependent n.
  induction l as [| x l'].
  - (* l = nil *)
    simpl. intros n eq. rewrite <- eq. reflexivity.
  - (* l = x :: l' *)
    simpl. intros n eq. rewrite <- eq.
    rewrite <- plus_n_Sm. simpl. rewrite <- IHl' by reflexivity.
    assert (S (length (l' ++ l')) = length (l' ++ x :: l')).
    { apply app_length_cons with x. reflexivity. }
    rewrite <- H. reflexivity.  Qed.
(* /ADMITTED *)
(** [] *)

(* EX3? (double_induction) *)
(* SOONER: Comment from reader: I would call this "diagonal induction"
   rather than "double induction". The latter word, for me, means a
   nested pair of inductions. *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  (* ADMITTED *)
  intros P H00 HS0 H0S HSS.
  induction m.
  - (* m = 0 *)
    intro n. induction n.
    + (* n = 0 *)
      apply H00.
    + (* n = S n *)
      apply H0S. apply IHn.
  - (* m = S m *)
    intro n. destruct n.
    + (* n = 0 *)
      apply HS0. apply IHm.
    + (* n = S n *)
      apply HSS. apply IHm.
Qed.
(* /ADMITTED *)
(** [] *)

(* /FULL *)

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

(** FULL: We have seen many examples where the [destruct] tactic 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: *)
(** TERSE: The [destruct] tactic can be used on expressions as well as
    variables: *)

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.

(** FULL: After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,
    either [n] is equal to [3] or it isn't, so we use [destruct
    (beq_nat 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].

*)

(* FULL *)
(* EX1 (override_shadow) *)
Theorem override_shadow : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  (override (override f k1 x2) k1 x1) k2 = (override f k1 x1) k2.
Proof.
  (* ADMITTED *)
  intros X x1 x2 k1 k2 f.
  unfold override.
  destruct (beq_nat k1 k2).
  - (* beq_nat k1 k2 = true *)
    reflexivity.
  - (* beq_nat k1 k2 = false *)
    reflexivity.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 1: override_shadow *)
(** [] *)

(* EX3? (combine_split) *)
(** Complete the proof below *)

(* LATER: AAA: Should we rework this exercise so that it doesn't
   depend on their own definition of [split] given in Poly.v? *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* ADMITTED *)
  intros X Y l. induction l as [| [x y] l'].
  - (* l = [] *)
    intros l1 l2 H.
    inversion H.
    reflexivity.
  - (* l = (x, y) :: l' *)
    intros l1 l2 H.
    simpl in H.
    destruct (split l') as [lx ly].
    inversion H.
    simpl.
    rewrite -> IHl'.
      reflexivity.
      reflexivity.  Qed.
(* /ADMITTED *)
(** [] *)
(* /FULL *)

(** Sometimes, doing a [destruct] on a compound expression (a
    non-variable) will erase information we need to complete a proof. *)
(** FULL: 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.

(** FULL: And suppose that we want to convince Coq of the rather
    obvious observation 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.

(** FULL: We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution peformed 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, in this branch of the case
    analysis, [beq_nat n 3 = true], 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 (with whatever
    name we choose). *)
(** TERSE:
    We can use the [eqn:] qualifier to save that information. *)

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.
(* FULL *)
  (* 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. *)
(* /FULL *)
    - (* e3 = true *) apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
(* FULL *)
     (* 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. *)
(* /FULL *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

(* FULL *)
(* EX2 (destruct_eqn_practice) *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  (* ADMITTED *)
  intros f b.
  destruct b.
  - (* b = true *)
    destruct (f true) eqn:Heqftrue.
    + (* f true = true *)
      rewrite Heqftrue.
      apply Heqftrue.
    + (* f true = false *)
      destruct (f false) eqn:Heqffalse.
      * (* f false = true *)
        apply Heqftrue.
      * (* f false = false *)
        apply Heqffalse.
  - (* b = false *)
    destruct (f false) eqn:Heqffalse.
    + (* f false = true *)
      destruct (f true) eqn: Heqftrue.
      * (* f true = true *)
        apply Heqftrue.
      * (* f true = false *)
        apply Heqffalse.
    + (* f false = false *)
      rewrite Heqffalse.
      apply Heqffalse.
Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 2: bool_fn_applied_thrice *)
(** [] *)

(* EX2 (override_same) *)
Theorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),
  f k1 = x1 ->
  (override f k1 x1) k2 = f k2.
Proof.
  (* ADMITTED *)
  intros X x1 k1 k2 f. intros Hx1.
  unfold override.
  destruct (beq_nat k1 k2) eqn:Heq.
  - (* beq_nat k1 k2 = true *)
    apply beq_nat_true in Heq.
    rewrite <- Heq.
    symmetry. apply Hx1.
  - (* beq_nat k1 k2 = false *)
    reflexivity.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 2: override_same *)
(** [] *)
(* /FULL *)

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

(** We've now seen a bunch of Coq's fundamental tactics.  We'll
    introduce a few more as we go along through the coming lectures,
    and later in the course we'll introduce some more powerful
    _automation_ tactics that make Coq do more of the low-level work
    in many cases.  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 (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
*)

(* TERSE *)
(* ###################################################### *)
(** * Micro Sermon *)

(** Mindless proof-hacking is a terrible temptation...

    Try to resist! *)

(* /TERSE *)
(* FULL *)
(* ###################################################### *)
(** * Additional Exercises *)

(* FULL *)
(* EX3 (beq_nat_sym) *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* ADMITTED *)
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) reflexivity.
  - (* n = S n' *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) apply IHn'.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: beq_nat_sym *)
(** [] *)

(* EX3A? (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:
   (* SOLUTION *)
   Let an arbitrary nat [n] be given.  We go by induction
   on [n].

   - For the base case, we have [n = 0].  Let [m] be given.
     We must show that
[[
       beq_nat 0 m = beq_nat m 0
]]
     Either [m = 0] or not.

     - If [m = 0], we must show [beq_nat 0 0 = beq_nat 0 0]
       which is true by reflexivity.

     - Otherwise, [m = S m'] for some [m'], and we must show
       [beq_nat 0 (S m') = beq_nat (S m') 0]. By the definition
       of [beq_nat], both sides are [false].

   - In the inductive case, we have [n = S n'] for some
     [n'] such that, for any [m],
[[
       beq_nat n' m = beq_nat m n'
]]
     Let [m] be given.  Again, [m] is either zero or nonzero.

     - Suppose first [m = 0].  It's
       enough to show [beq_nat (S n') 0 = beq_nat 0 (S n')].
       By the definition of [beq_nat], both sides are [false].

     - Otherwise, [m = S m'] for some [m'].  By the
       assumption, it's enough to show:
[[
         beq_nat (S n') (S m') = beq_nat (S m') (S n')
]]
       And, by the definition of [beq_nat], this reduces to
       showing:
[[
         beq_nat m' n' = beq_nat n' m'.
]]
       which is exactly the induction hypothesis.
   (* /SOLUTION *)
[]
 *)
(* /FULL *)

(* FULL *)
(* EX3? (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.
  (* ADMITTED *)
  intros n m p. intros Hnm Hmp.
  apply beq_nat_true in Hnm.
  rewrite -> Hnm.
  rewrite -> Hmp.
  reflexivity.  Qed.
(* /ADMITTED *)
(** [] *)
(* /FULL *)

(* FULL *)
(* EX3A (split_combine) *)
(** We have just proven 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 :=
(* ADMIT *)
  forall (X Y:Type) (l1 : list X) (l2 : list Y),
    length l1 = length l2 -> split (combine l1 l2) = (l1, l2).
(* /ADMIT *)

Theorem split_combine : split_combine_statement.
Proof.
(* ADMITTED *)
  intros X Y. induction l1 as [| x l1'].
  - (* l1 = [] *)
    intros l2 Heq. destruct l2 as [|y l2'].
    + (* l2 = [] *) reflexivity.
    + (* l2 = y :: l2' *) inversion Heq.
  - (* l1 = x :: l1' *)
    intros l2 Heq. destruct l2 as [|y l2'].
    + (* l2 = [] *) inversion Heq.
    + (* l2 = y :: l2' *)
      simpl. rewrite IHl1'. reflexivity.
      inversion Heq. reflexivity.  Qed.
(* /ADMITTED *)

(* GRADE_THEOREM 3: split_combine *)

(* QUIETSOLUTION *)
(** Here is another approach *)

Theorem split_combine' : forall (X Y:Type) l (l1 : list X) (l2 : list Y),
  (l1, l2) = split l -> split (combine l1 l2) = (l1, l2).
Proof.
  induction l as [| [x y] l'].
  - (* l = [] *) intros l1 l2 Heq.
    simpl in Heq. inversion Heq. reflexivity.
  - (* l = (x,y) :: l' *) intros l1 l2 Heq.
    simpl in Heq. destruct (split l') as [l1' l2'].
    inversion Heq. simpl. rewrite IHl'.
    reflexivity. reflexivity.  Qed.
(* /QUIETSOLUTION *)
(** [] *)
(* /FULL *)

(* FULL *)
(* EX3! (override_permute) *)
Theorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  (* ADMITTED *)
  (* This simple proof is by Aaditya Shirodkar *)
  intros X x1 x2 k1 k2 k3 f H. unfold override.
  destruct (beq_nat k1 k3) eqn: Heq13.
  - (* beq_nat k1 k3 = true *)
    apply beq_nat_true in Heq13.
    rewrite -> Heq13 in H.
    rewrite H. reflexivity.
  - (* beq_nat k1 k3 = false *) reflexivity.
Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: override_permute *)
(** [] *)

(* FULL *)
(* EX3A (filter_exercise) *)
(** This one is a bit challenging.  Pay attention to the form of your IH. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* ADMITTED *)
  intros X test x l. induction l as [| v' l'].
    - (* l = [] *) intros lf eq. inversion eq.
    - (* l = v' :: l' *) intros lf eq.
      simpl in eq.
      destruct (test v') eqn: Heq.
        + (* test v' = true *)
          inversion eq. rewrite <- H0.
          rewrite <- Heq. reflexivity.
        + (* test v' = false *)
          apply IHl' with lf. apply eq.  Qed.
(* /ADMITTED *)
(* GRADE_THEOREM 3: filter_exercise *)
(** [] *)

(* EX4!A (forall_exists_challenge) *)
(* HIDE: Why not turn these tests in comments into real tests? *)
(** 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 (beq_nat 5) [] = true
]]
    The second checks whether there exists an element in the list that
    satisfies a given predicate:
[[
      existsb (beq_nat 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].

    Prove theorem [existsb_existsb'] that [existsb'] and [existsb] have
    the same behavior.
*)

(* SOLUTION *)
Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
    | [] => true
    | x :: l' => andb (test x) (forallb test l')
  end.

Example test_forallb_1 : forallb oddb [1;3;5;7;9] = true.
Proof. reflexivity.  Qed.

Example test_forallb_2 : forallb negb [false;false] = true.
Proof. reflexivity.  Qed.

Example test_forallb_3 : forallb evenb [0;2;4;5] = false.
Proof. reflexivity.  Qed.

Example test_forallb_4 : forallb (beq_nat 5) [] = true.
Proof. reflexivity.  Qed.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
    | [] => false
    | x :: l' => orb (test x) (existsb test l')
  end.

Example test_existsb_1 : existsb (beq_nat 5) [0;2;3;6] = false.
Proof. reflexivity.  Qed.

Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. reflexivity.  Qed.

Example test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.
Proof. reflexivity.  Qed.

Example test_existsb_4 : existsb evenb [] = false.
Proof. reflexivity.  Qed.

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=
  negb (forallb (fun x => negb (test x)) l).

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof.
  intros. induction l as [| x l'].
  - (* l = [] *)
    unfold existsb'. simpl. reflexivity.
  - (* l = x :: l' *)
    unfold existsb'. simpl.
    destruct (test x).
    + (* test x = true *)
      simpl. reflexivity.
    + (* test x = false *)
      simpl.
      rewrite -> IHl'.
      unfold existsb'. reflexivity.  Qed.

(* GRADE_MANUAL 3: need to rework to make autograding possible *)

(* /SOLUTION *)
(** [] *)

(* SOONER: Another nice exercise would be to show how to
   define forallb in terms of fold, as in...
      Complete the following definition of [every] as a recursive function:
         Definition forallb' (X:Type) (p:X->bool) (l:list X) : bool :=
           fold _ _
             (fun x acc => both_yes _________  __________) ________  _________.
*)

(* HIDE *)
(* SOONER: ... *)
(* APT: If and when override and its many close relatives are
   rationalized across chapters, it might be good to stress that all
   the necessary properties of finite maps can be recovered just from
   the override_eq and override_neq lemmas... Here's an example: *)

(* That last theorem is a bit more challenging if you do it without
   unfolding the definition of [override], and instead use
   previously-proved lemmas about it.  *)
Theorem override_permute' : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  intros X x1 x2 k1 k2 k3 f. intros Hneq.
  destruct (beq_nat k1 k3) eqn: Heq13.
    - (* beq_nat k1 k3 = true *)
      apply beq_nat_true in Heq13.  rewrite <- Heq13.
      rewrite override_eq.
      symmetry. apply override_neq. apply override_eq.
      rewrite <- Hneq. reflexivity.
    - (* beq_nat k1 k3 = false *)
      destruct (beq_nat k2 k3) eqn: Heq23.
      + (* beq_nat k2 k3 = true *)
           apply beq_nat_true in Heq23. rewrite <- Heq23.
           rewrite override_eq.  apply override_neq.
           apply override_eq. rewrite -> beq_nat_sym.
           rewrite <- Hneq. reflexivity.
      + (* beq_nat k2 k3 = false *)
           apply override_neq.
              symmetry.  apply override_neq.
                apply override_neq.
                   symmetry. apply override_neq.
                     reflexivity.
                     rewrite Heq23. reflexivity.
                   rewrite Heq13. reflexivity.
                rewrite Heq23. reflexivity.
              rewrite Heq13. reflexivity.  Qed.
(* /HIDE *)

(** $Date$ *)

(* /FULL *)


From LF Require Export poly.

(* apply *)
Theorem sill1 : 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. apply eq2.
Qed.

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.

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.

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

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

Theorem rev_exercise1 : forall l l' : list nat,
  l = rev l' -> l' = rev l.
Proof.
  intros.
  rewrite H. symmetry.
  apply rev_involutive.
Qed.

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.

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

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.
  apply trans_eq with (m:=[c;d]).
  apply eq1. apply eq2.
Qed.

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.

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.

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

Theorem S_injective' : forall n m : nat,
  S n = S m ->
  n = m.
Proof.
  intros n m H.
  injection H as Hnm. apply Hnm.
Qed.

Theorem injective_ex1 : forall n m o : nat,
  [n;m] = [o;o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H as H1 H2.
  rewrite H1. rewrite H2.
  reflexivity.
Qed.

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 H0 H1.
  injection H0 as H2 H3.
  rewrite H1 in H3. injection H3 as H4.
  rewrite H4. apply H2.
Qed.

Theorem eqb_0_l : forall n : nat,
  0 =? n = true -> n = 0.
Proof.
  destruct n.
  - reflexivity.
  - intros H. discriminate.
Qed.

Theorem discriminate_ex1 : forall n : nat,
  S n = 0 ->
  2 + 2 = 5.
Proof.
  intros. discriminate.
Qed.

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

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

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

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

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.

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

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

Theorem double_injective : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n. induction n as [| n' IHn'].
  - simpl. intros m eq. destruct m.
      + reflexivity.
      + discriminate.
  - simpl. intros m eq.
    destruct m.
      + discriminate.
      + apply f_equal. apply IHn'. simpl in eq.
        injection eq as goal. apply goal.
Qed.

Theorem eqb_true : forall n m,
  n =? m = true -> n = m.
Proof.
  induction n.
  - intros. destruct m.
    + reflexivity.
    + discriminate.
  - intros. destruct m.
    + discriminate.
    + apply f_equal. apply IHn. simpl in H.
      apply H.
Qed.

Theorem plus_n_n_injective : forall n m,
  n + n = m + m ->
  n = m.
Proof.
  induction n.
  + intros. destruct m.
    - reflexivity.
    - discriminate.
  + simpl. intros. destruct m.
    - discriminate.
    - simpl in H.
      rewrite <- plus_n_Sm in H.
      rewrite <- plus_n_Sm in H.
      injection H as H1. f_equal.
      apply IHn. apply H1.
Qed.

Theorem double_injective_take2 : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n m.
  generalize dependent n.
  induction m.
  - simpl. intros n eq. destruct n.
    + reflexivity.
    + discriminate.
  - intros n eq. destruct n.
    + discriminate.
    + f_equal. apply IHm.
      injection eq as H. apply H.
Qed.

Theorem nth_error_after_last : forall (n : nat) (X : Type) (l : list X),
  length l = n ->
  nth_error l n = None.
Proof.
  induction n.
  + intros X l. destruct l.
    - reflexivity.
    - discriminate.
  + intros X l eq. destruct l.
    - discriminate.
    - simpl. apply IHn.
      injection eq as H. apply H.
Qed.

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

Lemma square_mult : forall n m,
  square (n * m) = square n * square m.
Proof.
  intros n m. unfold square.
  rewrite mult_assoc. rewrite mult_assoc.
  assert (H: n * m * n = n * n * m).
    { rewrite mult_comm. apply mult_assoc. }
  rewrite H. reflexivity.
Qed.

Definition foo (x : nat) := 5.

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

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

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

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.
  - reflexivity.
  - destruct (n =? 5) eqn:E2.
    + reflexivity.
    + reflexivity.
Qed.

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.

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.
  - intros. simpl in H. injection H as eq1 eq2.
    rewrite <- eq1. rewrite <- eq2. reflexivity.
  - destruct x. simpl. destruct (split l). intros.
    injection H as H1 H2. rewrite <- H1. rewrite <- H2.
    simpl. assert (H3: combine x0 y0 = l).
           { apply IHl. reflexivity. }
    rewrite H3. reflexivity.
Qed.

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

Theorem sillyfun1_odd : forall n : nat,
  sillyfun1 n = true ->
  oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3) eqn:Heq3. apply eqb_true in Heq3.
  - rewrite Heq3. reflexivity.
  - destruct (n =? 5) eqn:Heq4.
    + apply eqb_true in Heq4.
      rewrite Heq4. reflexivity.
    + discriminate.
Qed.

Theorem bool_fn_applied_thrice :
  forall (b : bool) (f : bool -> bool),
  f (f (f b)) = f b.
Proof.
  intros b f. destruct b.
  - destruct (f true) eqn:Heq1.
    + rewrite Heq1. apply Heq1.
    + destruct (f false) eqn:Heq2.
      * apply Heq1.
      * apply Heq2.
  - destruct (f false) eqn:Heq1.
    + destruct (f true) eqn:Heq2.
      * apply Heq2.
      * apply Heq1.
    + rewrite Heq1. apply Heq1.
Qed.

Theorem eqb_sym : forall n m : nat,
  (n =? m) = (m =? n).
Proof.
  induction n.
  - destruct m.
    + reflexivity.
    + reflexivity.
  - destruct m.
    + reflexivity.
    + simpl. apply IHn.
Qed.

Lemma obvious : forall n,
  (n =? n) = true.
Proof.
  intros. induction n.
  - reflexivity.
  - simpl. apply IHn.
Qed.

Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  intros n m p eq1 eq2.
  apply eqb_true in eq1.
  apply eqb_true in eq2.
  rewrite eq1. rewrite eq2.
  apply obvious.
Qed.

Definition split_combine_statement : Prop :=
  forall (X Y : Type) (l1 : list X) (l2 : list Y),
  length l1 = length l2 -> split (combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
  intros X Y l1. induction l1.
  - intros. simpl. destruct l2.
    + reflexivity.
    + discriminate.
  - intros. destruct l2.
    * simpl. inversion H.
    * simpl. rewrite IHl1.
      + reflexivity.
      + injection H as H1.
        apply H1.
Qed.

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                                 (x : X) (l lf : list X),
  filter test l = x :: lf ->
  test x = true.
Proof.
  intros. induction l.
  - discriminate.
  - simpl in H. destruct test eqn:Heq1.
    + injection H as H1 H2. rewrite <- H1. apply Heq1.
    + apply IHl in H. apply H.
Qed.

Fixpoint forallb {X} (test: X -> bool) (l: list X): bool :=
  match l with
  | [] => true
  | h :: t => test h && forallb test t
  end.

Fixpoint existsb {X} (test: X -> bool) (l: list X): bool :=
  match l with
  | [] => false
  | h :: t => test h || existsb test t
  end.

Definition existsb' {X} (test: X -> bool) (l: list X): bool :=
  negb (forallb (fun h => negb (test h)) l).

Theorem existsb_existsb' : forall (X: Type) (f: X -> bool) (l: list X),
  existsb f l = existsb' f l.
Proof.
  intros. unfold existsb'.
  induction l.
  - reflexivity.
  - simpl. destruct f.
    + reflexivity.
    + simpl. rewrite IHl. reflexivity.
Qed.


Require Export Arith.
Require Export ArithRing.
Require Export Omega.
Require Export Compare_dec.
Require Export Wf_nat.

Definition div4_spec:
 forall (n : nat),  ({q : nat & {r : nat | n = 4 * q + r /\ r < 4}}).
refine (fix
        div4_spec (n : nat) : {q : nat & {r : nat | n = 4 * q + r /\ r < 4}} :=
           match n return {q : nat & {r : nat | n = 4 * q + r /\ r < 4}} with
              S (S (S (S x'))) =>
                match div4_spec x' with existS _ q' (exist _ r' H) => _ end
             | _ => _
           end); clear div4_spec.
- exists 0, 0; omega.
- exists 0, 1; omega.
- exists 0, 2; omega.
- exists 0,  3; omega.
- exists (S q'), r'; omega.
Qed.

Definition sqrt_nat_F:
 forall n,
 (forall y,
  y < n ->  ({s : nat & {r : nat | y = s * s + r /\ y < (s + 1) * (s + 1)}})) ->
  ({s : nat & {r : nat | n = s * s + r /\ n < (s + 1) * (s + 1)}}).
refine (fun n sqrt_nat =>
           match div4_spec n with
             existS _ 0 (exist _ 0 (conj Heq _)) => _
            | existS _ 0 (exist _ (S r') (conj Heq Hle)) => _
            | existS _ (S q') (exist _ r' (conj Heq Hle)) => _
           end).
- clear sqrt_nat;exists 0, 0; omega.
- exists 1, r';rewrite Heq; split.
  + ring.
  + omega.
 - assert (Hlt: S q' < n) by omega.
   destruct (sqrt_nat (S q') Hlt) as [s' [r'' [Heq' Hlt']]].
   case (le_lt_dec (4 * s' + 1) (4 * r'' + r')).
   + intros Hle'';
     exists (2 * s' + 1), ((4 * r'' + r') - (4 * s' + 1)).
    rewrite Heq,  Heq'; split.
    * replace ((2 * s' + 1) * (2 * s' + 1) + ((4 * r'' + r') - (4 * s' + 1)))
     with (4 * (s' * s') + ((4 * s' + 1) + ((4 * r'' + r') - (4 * s' + 1)))).
     rewrite le_plus_minus_r; [ring | assumption].
     ring.
    * replace (4 * (s' * s' + r'') + r') with ((4 * s') * s' + (4 * r'' + r')).
      replace (((2 * s' + 1) + 1) * ((2 * s' + 1) + 1))
      with ((4 * s') * s' + (8 * s' + 4)).
      apply plus_lt_compat_l.
      assert (H: r'' < 2 * s' + 1).
      { apply plus_lt_reg_l with (s' * s').
        rewrite <- Heq'.
        replace (s' * s' + (2 * s' + 1)) with ((s' + 1) * (s' + 1)).
        assumption.
        ring.
      }
      omega.
      ring.
      ring.
   + intros Hlt''; exists (2 * s'),  (4 * r'' + r');
     rewrite Heq,  Heq'.
     split.
     * ring.
     * replace (4 * (s' * s' + r'') + r') with ((4 * s') * s' + (4 * r'' + r')).
       replace ((2 * s' + 1) * (2 * s' + 1)) with ((4 * s') * s' + (4 * s' + 1)).
       omega.
       ring.
       ring.
Qed.

Definition sqrt_nat' :
  forall n,  ({s : nat & {r : nat | n = s * s + r /\ n < (s + 1) * (s + 1)}}) :=
   well_founded_induction
    lt_wf
    (fun n => {s : nat & {r : nat | n = s * s + r /\ n < (s + 1) * (s + 1)}})
    sqrt_nat_F.


Require Import SfLib.
Require Import Logic.
Require Import Basics.

Inductive ty : Type :=
  | ty_Bool : ty
  | ty_arrow : ty -> ty -> ty.

Inductive tm : Type :=
  | tm_var : id -> tm
  | tm_app : tm -> tm -> tm
  | tm_abs : id -> ty -> tm -> tm
  | tm_true : tm
  | tm_false : tm
  | tm_if : tm -> tm -> tm -> tm.

Tactic Notation "tm_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "tm_var" | Case_aux c "tm_app"
  | Case_aux c "tm_abs" | Case_aux c "tm_true"
  | Case_aux c "tm_false" | Case_aux c "tm_if" ].

Definition context := partial_map ty.

Inductive option (A:Type) : Type :=
  | Some : A -> option A
  | None : option A.

(*
Definition option_map (A B:Type) (f:A->B) o (a:A):=
  match o with
    | Some a => Some (f a)
    | None => None
  end.
*)

Inductive has_type : context -> tm -> ty -> Prop :=
  | T_Var : forall (Γ:context) (x: id) (T : ty),
      extend Γ x T = Some T ->
      has_type Γ (tm_var x) T
  | T_Abs : forall Γ x T11 T12 t12,
      has_type (extend Γ x T11) t12 T12 ->
      has_type Γ (tm_abs x T11 t12) (ty_arrow T11 T12)
  | T_App : forall T11 T12 Γ t1 t2,
      has_type Γ t1 (ty_arrow T11 T12) ->
      has_type Γ t2 T11 ->
      has_type Γ (tm_app t1 t2) T12
  | T_True : forall Γ,
       has_type Γ tm_true ty_Bool
  | T_False : forall Γ,
       has_type Γ tm_false ty_Bool
  | T_If : forall t1 t2 t3 T Γ,
       has_type Γ t1 ty_Bool ->
       has_type Γ t2 T ->
       has_type Γ t3 T ->
       has_type Γ (tm_if t1 t2 t3) T.

Tactic Notation "has_type_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "T_Var" | Case_aux c "T_Abs"
  | Case_aux c "T_App" | Case_aux c "T_True"
  | Case_aux c "T_False" | Case_aux c "T_If" ].

Hint Constructors has_type.


(*

(* H : 投票者 *)
(* X : 選択肢 *)
Definition C_set := {set Choice}.
Parameter Choicer : finType.
Parameter X : {set Choice}.
Parameter H : {set Choicer}.
Parameter n : nat.
Axiom n_gt_1 : n > 1.
Axiom H_card : #|H| = n.
Axiom X_card : 2 < #|X|.

Definition pow_X := powerset X ~ [set φ].
Definition pow_Rel := powerset (setX X X).
Definition all_order := [set R in pow_Rel| orderB R].
Definition restrict (R : Rel) S := [set u in R | u ∈ (setX S S)].
Notation "R | ( S )" := (restrict R S)(at level 10).

(* 各個人の選好を導く関数 *)
Definition indiv_choice_func := Choicer -> Rel.
(* プロファイル付き集合値選択関数：プロファイルから社会全体の選好を導く関数 *)
Definition setvalue_choice_func := {set set_of_finType (prod_finType Choice Choice)} -> Rel.
(* 集合値選択関数：選択肢の集合を絞る関数 *)
Definition set_choice_func := C_set -> C_set.
(* 各個人の選好の集合 *)
Definition profile (f : indiv_choice_func) := f @: H.

(* 集合値選択関数の整合性の条件 *)
Definition α :=
  forall S1 S2 : C_set, S1 ⊂ S2 ->
  (forall x (C : set_choice_func),
   x ∈ S1 -> x ∈ (C S2) -> x ∈ (C S1)).

Definition β' :=
  forall S1 S2 : C_set, S1 ⊂ S2 ->
  (forall x y (C : set_choice_func),
    x ∈ S1 -> y ∈ S1 -> x ∈ (C S1) -> y ∈ (C S2) -> x ∈ (C S2)).

Definition β :=
  forall S1 S2 : C_set, S1 ⊂ S2 ->
  (forall x y (C : set_choice_func),
   x ∈ S1 -> y ∈ S2 -> x ∈ (C S1) -> y ∈ (C S1 ∩ C S2) -> x ∈ (C S2)).

Definition δ :=
  forall S1 S2 : C_set, S1 ⊂ S2 ->
  (forall (x y : Choice) (C : set_choice_func),
  x ∈ S1 -> y ∈ S2 -> x <> y -> x ∈ (C S1) -> y ∈ (C S1) -> [set x] <> C S2).

Definition γ :=
   forall (C : set_choice_func) (S : C_set) x,
  (forall Si : C_set, Si ⊂ S /\ Si <> S /\ Si <> φ -> x ∈ (C Si)) -> x ∈ (C S).

Definition path_independence :=
  forall (C : set_choice_func) (S1 S2 : C_set),
  (C (S1 ∪ S2)) = C ((C S1) ∪ (C S2)).

  (*  最良関数 *)

Definition greatest (x : Choice) (S : C_set) (R : Rel) :=
    forall y, y ∈ S -> (x,y) ∈ R.

Parameter greatestB : Choice -> C_set -> Rel -> bool.

Axiom greatestP : forall x S R, reflect (greatest x S R) (greatestB x S R).

Definition greatesst_func (S : C_set) (R : Rel) :=
  [set x in S | greatestB x S R].

Lemma greatest_not_empty S R:
  greatesst_func S R != φ <-> acyclic_orderB R.
Proof.
Admitted.

(* 正規性 *)

Definition normality C :=
    exists R, forall S, C S = greatesst_func S R.

   *)


Require Export GeoCoq.Elements.OriginalProofs.lemma_squareparallelogram.
Require Export GeoCoq.Elements.OriginalProofs.lemma_PGrectangle.

Section Euclid.

Context `{Ax1:euclidean_euclidean}.

Lemma lemma_squarerectangle :
   forall A B C D,
   SQ A B C D ->
   RE A B C D.
Proof.
intros.
assert (PG A B C D) by (conclude lemma_squareparallelogram).
assert (Per D A B) by (conclude_def SQ ).
assert (RE A B C D) by (conclude lemma_PGrectangle).
close.
Qed.

End Euclid.