(**
末尾再帰判定するコマンド

2023_2_23

@suharahiromichi

see. prolog/elpi/minifp.elpi
*)

From elpi Require Import elpi.

Fixpoint fib (n : nat) : nat :=
	match n with
	| O => O
	| S m => match m with
			 | O => 1
			 | S m' => fib m + fib m'
			 end
	end.
Compute fib 10.							(* 55 *)

Fixpoint trec_fib (n a b : nat) : nat :=
	match n with
	| 0 => a
	| S m => trec_fib m b (a + b)
	end.
Compute trec_fib 10 0 1.				(* 55 *)

Fixpoint fact (n : nat) : nat :=
	match n with
	| O => 1
	| S m => n * fact m
	end.
Compute fact 5.							(* 120 *)

Fixpoint trec_fact (n a : nat) :nat :=
	match n with
	| 0 => a
	| S m => trec_fact m (n * a)
	end.
Compute trec_fact 5 1.					(* 120 *)

(**
fix (f\ M) の f が、match(ネストしてもよい)の節の最外側に限って出現することをチェックする。
*)
Elpi Command tailrec.
Elpi Accumulate lp:{{
/**
app の先頭に出現するならば、successとする。
*/
pred trec i:term i:term.
%trec F M :- coq.say "trec=" F "," M, fail.		% Check
trec F (fun _ _ M) :- pi n\ trec F (M n).
trec F (match _ _ L) :-	std.exists L (trec F).
trec F (app [F | _]).
trec F (app [N | _]) :- trec F N.

/**
app の先頭以外に出現するならば、successとする。
*/
pred occr i:term i:term.
%occr F M :- coq.say "occr=" F "," M, fail.		% Check
occr F (fun _ _ M) :- pi n\ occr F (M n).
occr F (match _ _ L) :-	std.exists L (occr F).
% appの先頭にFが出現した場合は、それ以外の箇所だけでを見る。
occr F (app [F | L]) :- !, std.exists L (occr F).
occr F (app [N | L]) :- occr F N, !, std.exists L (occr F).
% appの先頭にFが出現ししない場合は、全体を見る。
occr F (app L) :- std.exists L (occr F).
occr F F.

/**
どこにでも出現するならば、successとする。(不使用)
*/
pred in i:term i:term.
%in F M :- coq.say "in=" F "," M, fail.			% Check
in F (fun _ _ M) :- pi n\ in F (M n).
in F (match _ _ L) :- std.exists L (in F).
in F (app L) :- std.exists L (in F).
in F F.

main [str Name] :-
	coq.locate Name (const Const),
  	coq.env.const Const (some Bo) Ty,
  	coq.say "tailrec=" Bo,						% Check
	Bo = fix _ _ _ M,
	pi f\ trec f (M f),
	not (pi f\ occr f (M f)).					% おかしくなったらここを外す！
main [str Name] :-
	coq.say Name "IS NOT A RECURCEIVE FUNCTION.",
	!, fail.
}}.
Elpi Typecheck.

Fail Elpi tailrec fib.
Elpi tailrec trec_fib.
Fail Elpi tailrec fact.
Elpi tailrec trec_fact.

(* END *)


Theorem tautology: forall P : Prop, P -> P.
Proof.
 intros P H.
 assumption.
Qed.

Theorem wrong: forall P : Prop, P.
Proof.
 intros P.
Admitted.

Theorem Modus_ponens : forall P Q : Prop,
P->(P->Q)->Q.
Proof.
intros P Q.
intros H1.
intros H2.
apply H2.
assumption.
Qed.

Theorem Modus_tollens : forall P Q : Prop, ~Q /\ (P->Q) -> ~P.
Proof.
intros P Q.
unfold not.
intros.
apply H.
apply H.
assumption.
Qed.

(* 課題3 *)
Theorem Disjunctive_syllogism : forall P Q : Prop, (P \/ Q) -> ~P -> Q.
Proof.
intros.
unfold not in H0.
destruct H.
apply H0 in H.
inversion H.
assumption.
Qed.

(* 課題4 *)
Theorem DeMorgan1 : forall P Q : Prop,  ~P \/ ~Q -> ~(P /\ Q).
Proof.
unfold not.
intros.
inversion H.
apply H1.
apply H0.
apply H1.

apply H0.

Qed.

Theorem DeMorgan2 : forall P Q : Prop, ~P /\ ~Q -> ~(P \/ Q).
Proof.
unfold not.
intros.
inversion H.
apply H1. destruct H0. assumption.
apply H2 in H0. inversion H0.
Qed.

Theorem DeMorgan3 : forall P Q : Prop, ~(P \/ Q) -> ~P /\ ~Q.
Proof.
  unfold not.
  intros.
  apply conj.
  intros.
  destruct H. left.
  assumption.
  intros.  apply H. right. assumption.
Qed.

Theorem NotNot_LEM : forall P : Prop, ~ ~(P \/ ~P).
Proof.
  unfold not.
  intros. apply H.
  right. intros.
  apply H. left. assumption.
Qed.

Require Import Arith.

SearchAbout lt _ _.


From mathcomp
Require Import all_ssreflect.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit.

(*
* In Coq the way a lambda is defined is as follows:
* (fun n => n + 1) 2
*
* We can associate names with operations, using a definition:
* Definition f := fun n => n + 1.
*)

Definition f := fun n => n + 1.

Print f.

(*
* Within coq, well typed expressions can be computed
* this means that they are reduced to a simpler form.
*)

Definition h (n: nat) : nat -> nat := fun m => n + m * 2.

Definition repeat_twice (g : nat -> nat) : nat -> nat := fun x => g (g x).

(* Coq also supports local definitions *)
Definition fun_with_local (g : nat) : nat := let x := g + 2 in x * x.

(* booleans are a definition that are loaded
* into coq upon launch.
*
* to use a boolean we can use an if then statement
*)

Definition twoVthree (b : bool) := if b then 2 else 3.

(* We can also do pattern matching with inductive data types *)
Definition prednn n := if n is p.+1 then p else n.

(* for matching with multiple cases, we can use a match *)

Definition three_patterns n :=
    match n with
    | u.+1.+1.+1.+1 => u
    | v.+1 => v
    | 0 => n
    end.

(* also note that n.+1 is equivalent to (S n) *)

(* we can define recursive functions in coq using fixpoint*)
Fixpoint addnn n m := if n is p.+1 then (addn p m).+1 else m.

Fixpoint eqnnn n m :=
    match n, m with
    | 0, 0 => true
    | p.+1, q.+1 => eqn p q
    | _, _ => false
    end.

(*
* In coq terminology, we call a container a group of datatypes which have been grouped together so that they can be manipulated as a single object.  lists of nats *)
Inductive listn := niln | consn (hd : nat) (t1 : listn).

Inductive cust_list (A : Type) := cust_nil | cust_cons (hd : A) (t1 : cust_list A).

(* Type is the type of all types, seq is Type -> Type - a type constructor*)
(* mathcomp provides a series of definitions of lists
* Check 1 :: 2 :: 3 :: nil.
*)

(* mathcomp also provides a utility tool for the repeated application of right associative
* operations *)
Definition tandb (a b c : bool) := [&& a, b & c].
(* the last element is always seperated by & rather than a comma *)
Eval compute in [seq i.+1 | i <- [:: 2; 3]].

(* coq provides the record syntax for a shorthand equivalent to defining an inductive type
* with a single data constructor.*)

Record making_a_point (A : Type) : Type := myPoint { x : A; y : nat; z : nat }.

Section iterators.
    Variables (T : Type) (A: Type).
    Variables (f : T -> A -> A).

    Fixpoint foldr a s :=
        if s is x ::xs then f x (foldr a xs) else a.

    Variable init : A.
    Variables x1 x2 : T.

    Eval compute in foldr init [:: x1; x2].
End iterators.

Section addition.

    Fixpoint adds n m := if n is p.+1 then adds p m.+1 else m.
    Fixpoint addn n m := if n is p.+1 then (adds p m).+1 else m.

    Variable n : nat.

    Eval simpl in (adds n.+1 7).-1.
    Eval simpl in (addn n.+1 7).-1.

End addition.

Section exercises.

    Inductive triple (A : Type) : Type := mk_triple (x : A) (y: A) (z: A).

    Notation "( a , b , c )" := (mk_triple a b c).

    Definition fst (A : Type) (p : triple A) : A := match p with
    | mk_triple x _ _ => x
    end.

    Definition snd (A : Type) (p : triple A) : A := match p with mk_triple _ y _ => y end.

    Definition thrd (A : Type) (p : triple A) : A := match p with mk_triple _ _ z => z end.

    Notation "p .1" := (fst p).
    Notation "p .2" := (snd p).
    Notation "p .3" := (thrd p) (at level 2).

        Eval compute in (4, 5, 8).1.
        Eval compute in (4, 5, 8).2.
        Eval compute in (4, 5, 8).3.
End  exercises.

(*
* In this section the book describes how to state elementary candidate theorems starting with identities
*
* Coq provides the binary predicate eq with the infix notation =
* this statement is used to state that two objects are equal
*
* we can start with a few of coq's ground equality statements
*
* ground means that the statements do not contain any parameter variables.
*
* The check command can not only be used to verify the type of some expression, but to also check whether a formal statement is well formed or not.
*)

Check 3 = 3.
Check false && true = false.

(*
* much like the type system in coq ensures that function applications are correct, the type system also ensures that theorems are well formed.
*
* Formal statements in coq are themselves terms and have a type.
*
* The equlity statement is obtained by applying eq to two arguments of the same type, and results in a well formed term of type prop for proposition.
*
* While check ensures the formed ness of a formal theorem, it does not check the provability:
*)
Check 3 = 4.

(*
* In order to establish that an equality holds, the user should announce that they are going to prove a lemma.
* This can be done using a special command such as Lemma, Theorem, Remark, Corollary.
*
*
* To begin a Proof of a theroem simply use the Proof command to indicate the start of the proof text.
*
*)

Lemma my_first_lemma : 3 = 3.
Proof.
    (* in the coq system, the user builds a formal proof by providing instructions to the
    * coq system that  describe the construction
    *  of the proof
    * the list of instruction is called a proof script, and the commands are tactics
    *
    * Once a proof is completed the Qed command can be called which verifies that the proof is actually correct.
*)
    (* The statement in question holds by definition as the two sides of the equality are
    *  syntactically the same
    * The by tactical applies a tactic,
    * and then attempts to solve it by computation
    * in this case as the values are the same by computation, no extra work is necassary.
    *)
    by [].
Qed.
About my_first_lemma.

(* ground identities are a special case of statements called identities.
*
* an identity is an equality relation A = B that holds regardless of the values that are substituted for variables in A and B.
* for example we can state the identity expressing associativity of addition on natural numbers
*
*)
Lemma addnA (m n k : nat) : m + (n + k) = m + n + k.
Admitted.

Lemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.
Admitted.

Lemma my_second_lemma : 2 + 1 = 3.
Proof.
    (* shallow embedded, so we can just compute the result to be the same.*)
    by [].
Qed.

Lemma addSn m n : m.+1 + n = (m + n).+1.
Proof.
    by [].
Qed.

Lemma negbK (b : bool) : ~~ (~~ b) = b.
Proof.
    (* can not prove by computation,as b can not be expanded *)
    by case: b.
Qed.

Lemma leqn0 n : (n <= 0) = (n == 0).
Proof.
    by case: n => [| k].
Qed.

Fixpoint muln (m n : nat) : nat :=
    if m is p.+1 then n + muln p n else 0.

Lemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0).
Proof.
    case:  m => [| m] //.
    case: n => [| k] //.
    by rewrite muln0.
Qed.
(* page 56 *)


Require Import Arith.

Definition divides (n m:nat) := exists p:nat, p*n = m.

Lemma divides_O : forall n:nat, divides n 0.
Proof.
  intro n; exists 0; simpl; trivial.
Qed.

Lemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).
Proof.
 intros n m H; elim H; intros q Hq.
 exists (S q) ; simpl; auto.
Qed.

Lemma not_divides_plus : forall n m:nat, ~ divides n m -> ~ divides n (n+m).
Proof.
 intros n m H; red; intro H'; elim H'; intro y.
 case y; simpl.
 intro H2; apply H.
 cut (m=0).
 intro H3; rewrite H3; apply divides_O.
 Require Omega.
 omega.
 intros n0 Hn0.
 apply H.
 exists n0.
 omega.
Qed.

Lemma not_divides_lt : forall n m:nat, 0<m ->  m<n -> ~ divides n m.
Proof.
 intros n m H H0 H1.
 elim H1; intros q Hq.
 rewrite <- Hq in H.
 rewrite <- Hq in H0.
 generalize H H0; case q.
 simpl.
 intros; absurd (0 < 0); auto with arith.
 clear H H0; intros y Hy Hy'.
 simpl in Hy'.
 absurd (n <= n + y * n); auto with arith.
Qed.

Lemma not_lt_2_divides : forall n m:nat, n <> 1 -> n < 2 -> 0 < m ->
                        ~ divides n m.
Proof.
 intros n m H H0; cut (n=0).
 intro e;rewrite e.
 case m.
 intro; absurd (0 < 0); auto with arith.
 intros n0 Hn0 H1.
 elim H1; intros q Hq.
 rewrite mult_0_r in Hq; discriminate Hq.
Require Import Omega.
 omega.
Qed.

Lemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).
Proof.
 intros; omega.
Qed.

Lemma lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \/  n=m.
Proof.
 intros; omega.
Qed.


(**
 * PSet 1: Functional Programming in Coq

  This assignment is designed as a file that you should download and complete in a Coq IDE.
  Before doing that, you need to install Coq.  The installation instructions
  are on the course website.
*)

(*
 Exercise: mult2 [10 points].
 Define a function that multiplies its input by 2.
*)

Let mult2 (x:nat) :nat := 2*x.

(* What is the function's type? *)

(* The type of the function is : "nat -> nat" *)

Print mult2.
(*
  Output:
    mult2 = fun x : nat => 2 * x : nat -> nat
*)

(*  What is the result of computing the function on 0?  On 3110? *)
Eval compute in mult2 0.
(* Output: "0:nat" *)
Eval compute in mult2 3110.
(*Output: "6220:nat" *)

(*
  Exercise: xor [10 points].
   Define a function that computes the xor of two [bool] inputs.
   Do this by pattern matching on the inputs.
*)

Let xor (a:bool) (b:bool) :bool :=
match a,b with
| false,false => false
| false,true => true
| true,false => true
| true,true => false
end.

(* What is the function's type?  *)
(* The type of the function is "bool->bool->bool"  *)
Print xor.
(*
  Output:
    xor =
    fun a b : bool => if a then if b then false else true else if b then true else false
     : bool -> bool -> bool
*)

(* Compute all four possible combinations of inputs to test your function.  *)
Eval compute in xor false false.
(* Output: "false:bool" *)
Eval compute in xor false true.
(* Output: "true:bool" *)
Eval compute in xor true false.
(* Output: "true:bool" *)
Eval compute in xor true true.
(* Output: "false:bool" *)

(*
  Exercise: is_none [20 points].
   Define a function that returns [true] if its input is [None], and [false] otherwise.
   Your function's type should be [forall A : Type, option A -> bool].
   That means the function will actually need to take two inputs:
     the first has type [Type], and the second is an option.
   Hint:  model your solution on [is_empty] in the notes for this lecture.
*)

Let is_none (A:Type) (b:option A) :bool :=
match b with
| None => true
| Some _=> false
end.

Print is_none.
(* The type: "forall A : Type, option A -> bool" *)

(* Verification of definition *)
(* Eval compute in is_none nat None. *)
(* Output: = true : bool *)
(* Eval compute in is_none nat (Some 2). *)
(* Output: = false : bool *)

Require Import List.
Import ListNotations.

(*
   Exercise: double_all [20 points].
   There is a function [map] that was imported by the [Require Import List] command above.
   First, check its type with [Check map].  Explain that type in your own words.
   Second, print it with [Print map].  Note at the end of that which arguments are _implicit_.
   For a discussion of what implicit means, see the notes for this lecture.
   Third, use map to write your own function, which should double (i.e., multiply by 2)
   every value of a list.
   For example, [double_all [0;2;10]] should be [[0;4;20]].
*)

Check map.
(*
  Output:
    map
     : forall A B : Type, (A -> B) -> list A -> list B
*)

(*
    Map function takes in a function f:A->B and list l1 of type A and returns another list l2 of type B
  and this is achieved for all types A and B.
    Thus, for all types A and B, map takes in a function f:A->B and a list of type A  as inputs and outputs a list of type B.
*)

Print map.

(*
  Output:
    map =
      fun (A B : Type) (f : A -> B) =>
        fix map (l : list A) : list B := match l with
                                 | [] => []
                                 | a :: t => f a :: map t
                                 end
     : forall A B : Type, (A -> B) -> list A -> list B
*)

(*
Arguments A and B are implicit(they are enclosed within square braces). They can be inferred from the types of the arguments to the function.
The first argument f is of type A->B and the second arugment l is of type A.
*)

Definition double_all (a:list nat) :=  ((map mult2) a).

(*Verification of the Definition*)

(* Eval compute in double_all [0;2;10]. *)

(*
  Output:
     = [0; 4; 20]
      : list nat
*)

(* Exercise: sum [20 points]
   Write a function that sums all the natural numbers in a list.
   Implement this two different ways:
   - as a recursive function, using the [Fixpoint] syntax.
   - as a nonrecursive function, using [Definition] and an application of [fold_left].
*)

(* This is the recursive function using [Fixpoint] syntax *)

Fixpoint sum (lst: list nat) :nat :=
match lst with
| [] => 0
| h::t => h+(sum t)
end.

(* This is the non-recursive definition using [fold_left]*)

(* Kindly comment the previous definition of sum and uncomment the following definition if the following definition is to be used *)
(* Definition sum (lst: list nat): nat := fold_left (fun x y => x+y) lst 0. *)

(* Verification of the definition *)
(*
  Eval compute in sum [1;5;7].
  Eval compute in sum [20;40;12;89].
  Eval compute in sum [].
  Eval compute in sum [0].
*)
(*
  Outputs:
     = 13
     : nat
     = 0
     : nat
     = 0
     : nat
*)

Inductive day : Type :=
  | sun : day
  | mon : day
  | tue : day
  | wed : day
  | thu : day
  | fri : day
  | sat : day.

Definition next_day d :=
  match d with
  | sun => mon
  | mon => tue
  | tue => wed
  | wed => thu
  | thu => fri
  | fri => sat
  | sat => sun
  end.

(* Exercise: thu after wed [20 points].
   State a theorem that says [thu] is the [next_day] after [wed].
   Write down in natural language how you would informally explain
   to a human why this theorem is true.
   ---> Don't skip this "natural language" part of the exercise;
        it's crucial to develop intuition before proceeding.
   Prove the theorem in Coq.
*)
Theorem thu_after_wed: next_day wed = thu.
Proof.
  simpl. trivial.
Qed.
(*
  Natural language Explanation:
  We have next_day function which provides the case-wise value for each of the 7 days defined in [Inductive day].
  For proving that [next_day] of [wed] is [thu]:
    1.We will find [next_day] of [wed] by applying the function [next_day] to [wed]. // Simpl tactic helps us do this
    2.We will check/verify that this is [thu] and thus [next_day] of [wed] is thu.  // trivial tactic helps us do this.
*)

(* Exercise: wed before thu [30 points].
   Below is a theorem that says if the day after [d] is [thu], then
   [d] must be [wed].
   Write down in natural language how you would informally explain
   to a human why this theorem is true.
   ---> Don't skip this "natural language" part of the exercise;
        it's crucial to develop intuition before proceeding.
   Prove the theorem in Coq.  To do that, delete the [Abort]
   command, which tells Coq to discard the theorem,
   then fill in your own proof.
*)

Theorem wed_proceeds_thu : forall d : day, next_day d = thu -> d = wed.

(*
  Natural Language Explanation:
  To prove that if [next_day] [d] is [thu], then [d] must be wed:
    1. We will compute the [next_day] [d] for all the days defined in [Inductive day]
        // introd d.destruct d helps us in verifying the theorem for each of the days by creating a subgoal for each day
    2. We will verify that either
        [next_day] [d] is either not thu //tactic discriminate helps us with this.
      or [next_day] [d] is thu and [d] is wed. //tactic trivial helps us with this.
 // Note that the simplification of function application([next_day] [d]) is done by discriminate or trivial tactic.

*)
Proof.
intros d. destruct d
; discriminate || trivial.
Qed.

(*.
  simpl. discriminate.
  simpl. discriminate.
  simpl. discriminate.
  simpl. trivial.
  simpl. discriminate.
  simpl. discriminate.
  simpl. discriminate.
*)

(* Exercise: tl_opt [20 points].
   Define a function [tl_opt] such that [tl_opt lst] return [Some t] if [t] is the tail of [lst],
   or [None] if [lst] is empty.
   We have gotten you started by providing an obviously incorrect definition, below; you should
   replace the body of the function with a correct definition.
*)

Definition tl_opt {A : Type} (lst : list A) : option (list A) :=
 match lst with
| []   => None
| h::t => Some t
end.

(* Verification of Definition: *)
(* Eval compute in tl_opt [1;2;3]. *)
(* Output:  = Some [2; 3] : option (list nat) *)
(* Eval compute in tl_opt []. *)
(* Output: = None : option (list ?A) *)

(* Here is a new tactic: [rewrite x].  If [H: x = e] is an assumption in the
   proof state, then [rewrite H] replaces [x] with [e] in the subgoal being proved.  For example,
   here is a proof that incrementing 1 produces 2: *)

Theorem inc1_is_2 : forall n, n=1 -> (fun x => x+1) n = 2.
Proof.
  intros n n_is_1. rewrite n_is_1. trivial.
Qed.

(* Exercise: tl_opt correct [20 points].
   Using [rewrite], prove the following theorems. For both, first explain in natural language
   why the theorem should hold, before moving on to prove it with Coq. *)

Theorem nil_implies_tlopt_none :
  forall A : Type, forall lst : list A,
  lst = nil -> tl_opt lst = None.

Proof.
intros A lst lst_is_null.
rewrite lst_is_null. simpl. trivial.
Qed.
(*
   Natural Language Explanation:
    Proving "forall A : Type, forall lst : list A,  lst = nil -> tl_opt lst = None" is a straightforward problem:
    We will assume lst=nil(where lst is a list of type A where A is a type)  // the intros helps us in achieving this.
    and will prove tl_opt lst = None
    To prove tl_opt lst = None, we will apply the function tl_opt to the list lst. From the definition of function,
    lst will match with empty list and returns None. // simpl tactics helps in this
    We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this
*)
Theorem cons_implies_tlopt_some :
  forall {A : Type} (h:A) (t : list A) (lst : list A),
  lst = h::t -> tl_opt lst = Some t.
Proof.
intros A h t lst lst_is_ht.
rewrite lst_is_ht. simpl. trivial.
Qed.

(*
  Natural Language Explanation:
  Proving "forall {A : Type} (h:A) (t : list A) (lst : list A), lst = h::t -> tl_opt lst = Some t." is a straightforward problem:
    We will assume lst=h:t(given that h is of type A and t is a list of type A and A is a type)  // Intros helps us with this.
    and will prove tl_opt lst = Some t.
    We will apply the function tl_opt to the list lst.
    From the definition of function,
    lst will not match with empty list and will match with h::t and returns Some t . // simpl tactics helps in this
    We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this
*)

(*
  Ignore the below statements:

  Let a := simpl mult2 0.
  Print a.
  Let b:= mult2 3110.
  Print b.

  Theorem a: mult2 0 = 0.
  Proof.
  auto.
  Qed.

  Print a.

  Theorem b: mult2 3110 = 6220.
  Proof.
  auto.
  Qed.

  Print b.
*)


(** * Logic: Logic in Coq *)

Require Export MoreCoq.

(** Coq's built-in logic is very small: the only primitives are
    [Inductive] definitions, universal quantification ([forall]), and
    implication ([->]), while all the other familiar logical
    connectives -- conjunction, disjunction, negation, existential
    quantification, even equality -- can be encoded using just these.

    This chapter explains the encodings and shows how the tactics
    we've seen can be used to carry out standard forms of logical
    reasoning involving these connectives. *)

(* ########################################################### *)
(** * Propositions *)

(** In previous chapters, we have seen many examples of factual
    claims (_propositions_) and ways of presenting evidence of their
    truth (_proofs_).  In particular, we have worked extensively with
    _equality propositions_ of the form [e1 = e2], with
    implications ([P -> Q]), and with quantified propositions
    ([forall x, P]).
 *)

(** In Coq, the type of things that can (potentially)
    be proven is [Prop]. *)

(** Here is an example of a provable proposition: *)

Check (3 = 3).
(* ===> Prop *)

(** Here is an example of an unprovable proposition: *)

Check (forall (n:nat), n = 2).
(* ===> Prop *)

(** Recall that [Check] asks Coq to tell us the type of the indicated
  expression. *)

(* ########################################################### *)
(** * Proofs and Evidence *)

(** In Coq, propositions have the same status as other types, such as
    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit
    the type [nat], a Coq proposition [P] is inhabited by its
    _proofs_.  We will refer to such inhabitants as _proof term_ or
    _proof object_ or _evidence_ for the truth of [P].

    In Coq, when we state and then prove a lemma such as:

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

    the tactics we use within the [Proof]...[Qed] keywords tell Coq
    how to construct a proof term that inhabits the proposition.  In
    this case, the proposition [0 * 3 = 0] is justified by a
    combination of the _definition_ of [mult], which says that [0 * 3]
    _simplifies_ to just [0], and the _reflexive_ principle of
    equality, which says that [0 = 0].

 *)

(** *** *)

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

(** We can see which proof term Coq constructs for a given Lemma by
using the [Print] directive: *)

Print silly.
(* ===> silly = eq_refl : 0 * 3 = 0 *)

(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)

(** ** Implications _are_ functions *)

(** Just as we can implement natural number multiplication as a
function:

[
mult : nat -> nat -> nat
]

The _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.
 *)

Lemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.
Proof. intros H. reflexivity. Qed.

(** We can see that the proof term for the above lemma is indeed a
function: *)

Print silly_implication.
(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl
     : 1 + 1 = 2 -> 0 * 3 = 0 *)

(** ** Defining Propositions *)

(** Just as we can create user-defined inductive types (like the
    lists, binary representations of natural numbers, etc., that we
    seen before), we can also create _user-defined_ propositions.

    Question: How do you define the meaning of a proposition?
 *)

(** *** *)

(** The meaning of a proposition is given by _rules_ and _definitions_
    that say how to construct _evidence_ for the truth of the
    proposition from other evidence.

    - Typically, rules are defined _inductively_, just like any other datatype.

    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.

    In this, and subsequence chapters, we'll see more about how these
    proof terms work in more detail.
 *)

(* ########################################################### *)
(** * Conjunction (Logical "and") *)

(** The logical conjunction of propositions [P] and [Q] can be
    represented using an [Inductive] definition with one
    constructor. *)

Inductive and (P Q : Prop) : Prop :=
  conj : P -> Q -> (and P Q).

(** The intuition behind this definition is simple: to
    construct evidence for [and P Q], we must provide evidence
    for [P] and evidence for [Q].  More precisely:

    - [conj p q] can be taken as evidence for [and P Q] if [p]
      is evidence for [P] and [q] is evidence for [Q]; and

    - this is the _only_ way to give evidence for [and P Q] --
      that is, if someone gives us evidence for [and P Q], we
      know it must have the form [conj p q], where [p] is
      evidence for [P] and [q] is evidence for [Q].

   Since we'll be using conjunction a lot, let's introduce a more
   familiar-looking infix notation for it. *)

Notation "P /\ Q" := (and P Q) : type_scope.

(** (The [type_scope] annotation tells Coq that this notation
    will be appearing in propositions, not values.) *)

(** Consider the "type" of the constructor [conj]: *)

Check conj.
(* ===>  forall P Q : Prop, P -> Q -> P /\ Q *)

(** Notice that it takes 4 inputs -- namely the propositions [P]
    and [Q] and evidence for [P] and [Q] -- and returns as output the
    evidence of [P /\ Q]. *)

(** ** "Introducing" Conjuctions *)
(** Besides the elegance of building everything up from a tiny
    foundation, what's nice about defining conjunction this way is
    that we can prove statements involving conjunction using the
    tactics that we already know.  For example, if the goal statement
    is a conjuction, we can prove it by applying the single
    constructor [conj], which (as can be seen from the type of [conj])
    solves the current goal and leaves the two parts of the
    conjunction as subgoals to be proved separately. *)

Theorem and_example :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  apply conj.
  Case "left". reflexivity.
  Case "right". reflexivity.  Qed.

(** Just for convenience, we can use the tactic [split] as a shorthand for
    [apply conj]. *)

Theorem and_example' :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  split.
  Case "left". reflexivity.
  Case "right". reflexivity.  Qed.

(** ** "Eliminating" conjunctions *)
(** Conversely, the [inversion] tactic can be used to take a
    conjunction hypothesis in the context, calculate what evidence
    must have been used to build it, and add variables representing
    this evidence to the proof context. *)

Theorem proj1 : forall P Q : Prop,
                  P /\ Q -> P.
Proof.
  intros P Q H.
  inversion H as [HP HQ].
  apply HP.  Qed.

(** **** Exercise: 1 star, optional (proj2) *)
Theorem proj2 : forall P Q : Prop,
                  P /\ Q -> Q.
Proof.
  intros.
  inversion H.
  apply H1.
Qed.

(** [] *)

Theorem and_commut : forall P Q : Prop,
                       P /\ Q -> Q /\ P.
Proof.
  (* WORKED IN CLASS *)
  intros P Q H.
  inversion H as [HP HQ].
  split.
  Case "left". apply HQ.
  Case "right". apply HP.  Qed.

(** **** Exercise: 2 stars (and_assoc) *)
(** In the following proof, notice how the _nested pattern_ in the
    [inversion] breaks the hypothesis [H : P /\ (Q /\ R)] down into
    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)

Theorem and_assoc : forall P Q R : Prop,
                      P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R H.
  inversion H as [HP [HQ HR]].
  split. split.
  apply HP. apply HQ. apply HR.
Qed.

(** [] *)

(* ###################################################### *)
(** * Iff *)

(** The handy "if and only if" connective is just the conjunction of
    two implications. *)

Definition iff (P Q : Prop) := (P -> Q) /\ (Q -> P).

Notation "P <-> Q" := (iff P Q)
                        (at level 95, no associativity)
                      : type_scope.

Theorem iff_implies : forall P Q : Prop,
                        (P <-> Q) -> P -> Q.
Proof.
  intros P Q H.
  inversion H as [HAB HBA]. apply HAB.  Qed.

Theorem iff_sym : forall P Q : Prop,
                    (P <-> Q) -> (Q <-> P).
Proof.
  (* WORKED IN CLASS *)
  intros P Q H.
  inversion H as [HAB HBA].
  split.
  Case "->". apply HBA.
  Case "<-". apply HAB.  Qed.

(** **** Exercise: 1 star, optional (iff_properties) *)
(** Using the above proof that [<->] is symmetric ([iff_sym]) as
    a guide, prove that it is also reflexive and transitive. *)

Theorem iff_refl : forall P : Prop,
                     P <-> P.
Proof.
  intros. split.
  intros. apply H.
  intros. apply H.
Qed.

Theorem iff_trans : forall P Q R : Prop,
                      (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros P Q R H I.
  inversion H.
  inversion I.
  split.
    intros. apply H2. apply H0. apply H4.
    intros. apply H1. apply H3. apply H4.
Qed.

(** Hint: If you have an iff hypothesis in the context, you can use
    [inversion] to break it into two separate implications.  (Think
    about why this works.) *)
(** [] *)

(** Some of Coq's tactics treat [iff] statements specially, thus
    avoiding the need for some low-level manipulation when reasoning
    with them.  In particular, [rewrite] can be used with [iff]
    statements, not just equalities. *)

(* ############################################################ *)
(** * Disjunction (Logical "or") *)

(** ** Implementing Disjunction *)

(** Disjunction ("logical or") can also be defined as an
    inductive proposition. *)

Inductive or (P Q : Prop) : Prop :=
| or_introl : P -> or P Q
| or_intror : Q -> or P Q.

Notation "P \/ Q" := (or P Q) : type_scope.

(** Consider the "type" of the constructor [or_introl]: *)

Check or_introl.
(* ===>  forall P Q : Prop, P -> P \/ Q *)

(** It takes 3 inputs, namely the propositions [P], [Q] and
    evidence of [P], and returns, as output, the evidence of [P \/ Q].
    Next, look at the type of [or_intror]: *)

Check or_intror.
(* ===>  forall P Q : Prop, Q -> P \/ Q *)

(** It is like [or_introl] but it requires evidence of [Q]
    instead of evidence of [P]. *)

(** Intuitively, there are two ways of giving evidence for [P \/ Q]:

    - give evidence for [P] (and say that it is [P] you are giving
      evidence for -- this is the function of the [or_introl]
      constructor), or

    - give evidence for [Q], tagged with the [or_intror]
      constructor. *)

(** *** *)
(** Since [P \/ Q] has two constructors, doing [inversion] on a
    hypothesis of type [P \/ Q] yields two subgoals. *)

Theorem or_commut : forall P Q : Prop,
                      P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  inversion H as [HP | HQ].
  Case "left". apply or_intror. apply HP.
  Case "right". apply or_introl. apply HQ.  Qed.

(** From here on, we'll use the shorthand tactics [left] and [right]
    in place of [apply or_introl] and [apply or_intror]. *)

Theorem or_commut' : forall P Q : Prop,
                       P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  inversion H as [HP | HQ].
  Case "left". right. apply HP.
  Case "right". left. apply HQ.  Qed.

Theorem or_distributes_over_and_1 : forall P Q R : Prop,
                                      P \/ (Q /\ R) -> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R. intros H. inversion H as [HP | [HQ HR]].
  Case "left". split.
  SCase "left". left. apply HP.
  SCase "right". left. apply HP.
  Case "right". split.
  SCase "left". right. apply HQ.
  SCase "right". right. apply HR.  Qed.

(** **** Exercise: 2 stars (or_distributes_over_and_2) *)
Theorem or_distributes_over_and_2 : forall P Q R : Prop,
                                      (P \/ Q) /\ (P \/ R) -> P \/ (Q /\ R).
Proof.
  intros. inversion H as [[HP | HQ] [HP' | HR]].
  Case "l".
    SCase "l". left. apply HP.
    SCase "r". left. apply HP.
  Case "r".
    SCase "l". left. apply HP'.
    SCase "r".
      right. split.
        apply HQ.
        apply HR.
Qed.

(** [] *)

(** **** Exercise: 1 star, optional (or_distributes_over_and) *)
Theorem or_distributes_over_and : forall P Q R : Prop,
                                    P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros. split. intros.
  Case "l". apply or_distributes_over_and_1. apply H.
  Case "r". apply or_distributes_over_and_2.
Qed.

(** [] *)

(* ################################################### *)
(** ** Relating [/\] and [\/] with [andb] and [orb] (advanced) *)

(** We've already seen several places where analogous structures
    can be found in Coq's computational ([Type]) and logical ([Prop])
    worlds.  Here is one more: the boolean operators [andb] and [orb]
    are clearly analogs of the logical connectives [/\] and [\/].
    This analogy can be made more precise by the following theorems,
    which show how to translate knowledge about [andb] and [orb]'s
    behaviors on certain inputs into propositional facts about those
    inputs. *)

Theorem andb_prop : forall b c,
                      andb b c = true -> b = true /\ c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  destruct b.
  Case "b = true". destruct c.
  SCase "c = true". apply conj. reflexivity. reflexivity.
  SCase "c = false". inversion H.
  Case "b = false". inversion H.  Qed.

Theorem andb_true_intro : forall b c,
                            b = true /\ c = true -> andb b c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  inversion H.
  rewrite H0. rewrite H1. reflexivity. Qed.

(** **** Exercise: 2 stars, optional (bool_prop) *)
Theorem andb_false : forall b c,
                       andb b c = false -> b = false \/ c = false.
Proof.
  intros.
  destruct b.
  Case "true". destruct c.
    SCase "true". inversion H.
    SCase "false". right. reflexivity.

  Case "false". left. reflexivity.
Qed.

Theorem orb_prop : forall b c,
                     orb b c = true -> b = true \/ c = true.
Proof.
  intros.
  destruct b.
  Case "true". left. reflexivity.
  Case "false". destruct c.
    right. reflexivity.
    inversion H.
Qed.

Theorem orb_false_elim : forall b c,
                           orb b c = false -> b = false /\ c = false.
Proof.
  intros.
  destruct b.
  Case "true". inversion H.
  Case "false". split.
    SCase "l". reflexivity.
    SCase "r". destruct c.
      inversion H.
      reflexivity.
Qed.

(** [] *)

(* ################################################### *)
(** * Falsehood *)

(** Logical falsehood can be represented in Coq as an inductively
    defined proposition with no constructors. *)

Inductive False : Prop := .

(** Intuition: [False] is a proposition for which there is no way
    to give evidence. *)

(** Since [False] has no constructors, inverting an assumption
    of type [False] always yields zero subgoals, allowing us to
    immediately prove any goal. *)

Theorem False_implies_nonsense :
  False -> 2 + 2 = 5.
Proof.
  intros contra.
  inversion contra.  Qed.

(** How does this work? The [inversion] tactic breaks [contra] into
    each of its possible cases, and yields a subgoal for each case.
    As [contra] is evidence for [False], it has _no_ possible cases,
    hence, there are no possible subgoals and the proof is done. *)

(** *** *)
(** Conversely, the only way to prove [False] is if there is already
    something nonsensical or contradictory in the context: *)

Theorem nonsense_implies_False :
  2 + 2 = 5 -> False.
Proof.
  intros contra.
  inversion contra.  Qed.

(** Actually, since the proof of [False_implies_nonsense]
    doesn't actually have anything to do with the specific nonsensical
    thing being proved; it can easily be generalized to work for an
    arbitrary [P]: *)

Theorem ex_falso_quodlibet : forall (P:Prop),
                               False -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P contra.
  inversion contra.  Qed.

(** The Latin _ex falso quodlibet_ means, literally, "from
    falsehood follows whatever you please."  This theorem is also
    known as the _principle of explosion_. *)

(* #################################################### *)
(** ** Truth *)

(** Since we have defined falsehood in Coq, one might wonder whether
    it is possible to define truth in the same way.  We can. *)

(** **** Exercise: 2 stars, advanced (True) *)
(** Define [True] as another inductively defined proposition.  (The
    intution is that [True] should be a proposition for which it is
    trivial to give evidence.) *)

Inductive True : Prop := X.

(** [] *)

(** However, unlike [False], which we'll use extensively, [True] is
    used fairly rarely. By itself, it is trivial (and therefore
    uninteresting) to prove as a goal, and it carries no useful
    information as a hypothesis. But it can be useful when defining
    complex [Prop]s using conditionals, or as a parameter to
    higher-order [Prop]s. *)

(* #################################################### *)
(** * Negation *)

(** The logical complement of a proposition [P] is written [not
    P] or, for shorthand, [~P]: *)

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

(** The intuition is that, if [P] is not true, then anything at
    all (even [False]) follows from assuming [P]. *)

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

Check not.
(* ===> Prop -> Prop *)

(** It takes a little practice to get used to working with
    negation in Coq.  Even though you can see perfectly well why
    something is true, it can be a little hard at first to get things
    into the right configuration so that Coq can see it!  Here are
    proofs of a few familiar facts about negation to get you warmed
    up. *)

Theorem not_False :
  ~ False.
Proof.
  unfold not. intros H. inversion H.  Qed.

(** *** *)
Theorem contradiction_implies_anything : forall P Q : Prop,
                                           (P /\ ~P) -> Q.
Proof.
  (* WORKED IN CLASS *)
  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.
  apply HNA in HP. inversion HP.  Qed.

Theorem double_neg : forall P : Prop,
                       P -> ~~P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not. intros G. apply G. apply H.  Qed.

(** **** Exercise: 2 stars, advanced (double_neg_inf) *)
(** Write an informal proof of [double_neg]:

   _Theorem_: [P] implies [~~P], for any proposition [P].

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

(** **** Exercise: 2 stars (contrapositive) *)
Theorem contrapositive : forall P Q : Prop,
                           (P -> Q) -> (~Q -> ~P).
Proof.
  intros. unfold not. intros.
  unfold not in H0.
  apply H0. apply H. apply H1.
Qed.

(** [] *)

(** **** Exercise: 1 star (not_both_true_and_false) *)
Theorem not_both_true_and_false : forall P : Prop,
                                    ~ (P /\ ~P).
Proof.
  intros. unfold not. intros.
  apply H. apply H.
Qed.

(** [] *)

(** **** Exercise: 1 star, advanced (informal_not_PNP) *)
(** Write an informal proof (in English) of the proposition [forall P
    : Prop, ~(P /\ ~P)]. *)

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

(** *** Constructive logic *)
(** Note that some theorems that are true in classical logic are _not_
    provable in Coq's (constructive) logic.  E.g., let's look at how
    this proof gets stuck... *)

Theorem classic_double_neg : forall P : Prop,
                               ~~P -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not in H.
(* But now what? There is no way to "invent" evidence for [~P]
     from evidence for [P]. *)
Abort.

(** **** Exercise: 5 stars, advanced, optional (classical_axioms) *)
(** For those who like a challenge, here is an exercise
    taken from the Coq'Art book (p. 123).  The following five
    statements are often considered as characterizations of
    classical logic (as opposed to constructive logic, which is
    what is "built in" to Coq).  We can't prove them in Coq, but
    we can consistently add any one of them as an unproven axiom
    if we wish to work in classical logic.  Prove that these five
    propositions are equivalent. *)

Definition peirce := forall P Q: Prop,
                       ((P -> Q) -> P) -> P.
Definition classic := forall P:Prop,
                        ~~P -> P.
Definition excluded_middle := forall P:Prop,
                                P \/ ~P.
Definition de_morgan_not_and_not := forall P Q:Prop,
                                      ~(~P /\ ~Q) -> P\/Q.
Definition implies_to_or := forall P Q:Prop,
                              (P -> Q) -> (~P\/Q).

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

(** **** Exercise: 3 stars (excluded_middle_irrefutable) *)
(** This theorem implies that it is always safe to add a decidability
axiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].
Why? Because we cannot prove the negation of such an axiom; if we could,
we would have both [~ (P \/ ~P)] and [~ ~ (P \/ ~P)], a contradiction. *)

Theorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \/ ~ P).
Proof.
  intros. unfold not. intros. apply H.
  right. intros. apply H.
  left. apply H0.
Qed.

(* ########################################################## *)
(** ** Inequality *)

(** Saying [x <> y] is just the same as saying [~(x = y)]. *)

Notation "x <> y" := (~ (x = y)) : type_scope.

(** Since inequality involves a negation, it again requires
    a little practice to be able to work with it fluently.  Here
    is one very useful trick.  If you are trying to prove a goal
    that is nonsensical (e.g., the goal state is [false = true]),
    apply the lemma [ex_falso_quodlibet] to change the goal to
    [False].  This makes it easier to use assumptions of the form
    [~P] that are available in the context -- in particular,
    assumptions of the form [x<>y]. *)

Theorem not_false_then_true : forall b : bool,
                                b <> false -> b = true.
Proof.
  intros b H. destruct b.
  Case "b = true". reflexivity.
  Case "b = false".
  unfold not in H.
  apply ex_falso_quodlibet.
  apply H. reflexivity.   Qed.

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** **** Exercise: 2 stars (false_beq_nat) *)
Theorem false_beq_nat : forall n m : nat,
                          n <> m ->
                          beq_nat n m = false.
Proof.
  intros n. induction n.
  Case "0".
    intros. unfold not in H. destruct m.
    SCase "0". apply ex_falso_quodlibet. apply H. reflexivity.
    SCase "S m". reflexivity.
  Case "S n".
    unfold not in IHn.
    intros.
    unfold not in H.
    destruct m.
    SCase "0". reflexivity.
    SCase "S m".
      simpl.
      apply IHn. intros.
      apply H. apply eq_S. apply H0.
Qed.

(** [] *)

(** **** Exercise: 2 stars, optional (beq_nat_false) *)
Theorem beq_nat_false : forall n m,
                          beq_nat n m = false -> n <> m.
Proof.
  intros n. unfold not. induction n.
  Case "0".
    intros. destruct m.
    SCase "0". inversion H.
    SCase "S m". intros. inversion H0.
  Case "S n".
    intros. destruct m.
    SCase "0". intros. inversion H0.
    SCase "S m".
      intros. inversion H.
      apply IHn in H2.
      apply H2.
      inversion H0. reflexivity.
Qed.

(** [] *)

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


Theorem or_commut : forall P Q : Prop,  P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  destruct H as [H1 | H2].
  + right. apply H1.
  + left. apply H2.
Qed.

Theorem not_both_true_and_false : forall P : Prop,
  ~ (P /\ ~P).
Proof.
  unfold not.
  intros P [H1 H2].
  apply H2.
  apply H1.
Qed.

 Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) -> (P \/ Q) /\ (P \/ R).
Proof.
  intros.
  split.
  + destruct H as [H1 | H2].
     - left. apply H1.
     - destruct H2 as [H21 H22].
       right. apply H21.
  + destruct H as [H1 | H2].
     - left. apply H1.
     - destruct H2 as [H21  H22].
       right. apply H22.
Qed.

Theorem or_distributes_over_and' : forall P Q R : Prop,
  (P \/ Q) /\ (P \/ R) -> P \/ (Q /\ R).
Proof.
  intros.
  destruct H as [H1 H2].
  destruct H1 as [H11 | H12].
  + destruct H2 as [H21 | H22].
     - left. apply H11.
     - left. apply H11.
  + destruct H2 as [H21 | H22].
     - left. apply H21.
     - right. split.
       * apply H12.
       * apply H22.
Qed.


Require Import Arith.
Require Import ArithRing Ring.
Require Import Lia.
Import Nat.

(*
  这一次我们着重介绍如何用Coq证明涉及到多项式的定理;
  首先我们可以定义一个简单的递归函数用于计算∑n.
 *)

Fixpoint sum (n : nat) :=
  match n with
  | 0 => 0
  | S n' => n + sum n'
  end.

(*想要证明2 * sum n = n * (n + 1)*)

Theorem sum_1 : forall n : nat,
    2 * sum n = n * (n + 1).
Proof.
  induction n.
  - (*n = 0*)
    simpl. reflexivity.
  - simpl. ring_simplify.
    rewrite IHn.
    ring_simplify. reflexivity.
Qed.

(*
  我们可以通过不断使用交换律结合律和分配律来改写待证明的项，
  但这么做是非常繁杂且无趣的。
  那么有什么手段能够帮助我们自动地对待证项使用上述定理改写呢？
  巧合的是，抽象代数中的环结构非常完美地契合我们的要求。
  Coq提供的ring策略能够对所有在环或半环上的多项式命题进行化简,
  那么，什么是环？
  下面的代码给出了一个环或半环结构需要满足的性质。
 *)

Record ring_theory : Prop := mk_rt {
  Radd_0_l    : forall x, 0 + x == x;
  Radd_sym    : forall x y, x + y == y + x;
  Radd_assoc  : forall x y z, x + (y + z) == (x + y) + z;
  Rmul_1_l    : forall x, 1 * x == x;
  Rmul_sym    : forall x y, x * y == y * x;
  Rmul_assoc  : forall x y z, x * (y * z) == (x * y) * z;
  Rdistr_l    : forall x y z, (x + y) * z == (x * z) + (y * z);
  Rsub_def    : forall x y, x - y == x + -y;
  Ropp_def    : forall x, x + (- x) == 0
}.

Record semi_ring_theory : Prop := mk_srt {
  SRadd_0_l   : forall n, 0 + n == n;
  SRadd_sym   : forall n m, n + m == m + n ;
  SRadd_assoc : forall n m p, n + (m + p) == (n + m) + p;
  SRmul_1_l   : forall n, 1*n == n;
  SRmul_0_l   : forall n, 0*n == 0;
  SRmul_sym   : forall n m, n*m == m*n;
  SRmul_assoc : forall n m p, n*(m*p) == (n*m)*p;
  SRdistr_l   : forall n m p, (n + m)*p == n*p + m*p
}.

(*
  ring策略会利用上述的性质对待证项进行化简，
  这个过程是自动化的，而且化简的效果非常好。
 *)

Fixpoint summation (n : nat) :=
  match n with
  | 0 => 0
  | S n' => n ^ 2 + summation n'
  end.
(*∑ n^2*)

Theorem sum_2 : forall n : nat,
    6 * summation n = n * (2 * n + 1) *  (n + 1).
Proof.
  induction n.
  -simpl. reflexivity.
  -simpl. ring_simplify.
   rewrite IHn. ring.
Qed.

(*
  我们可以再举几个ring应用的例子.
 *)

Fixpoint sum_3 (n : nat) :=
  match n with
  | 0 => 0
  | S n' => n ^ 3 + sum_3 n'
  end.

Theorem sum_three : forall n : nat,
    4 * sum_3 n = n * n * (n + 1) * (n + 1).
Proof.
  induction n.
  -simpl. reflexivity.
  - simpl. ring_simplify.
    rewrite IHn. ring.
Qed.

(*
  然而ring并非是万能的，它只能处理"+"和"*"运算，
  一旦证明式中出现"-"，ring也无可奈何.
 *)

Fixpoint summa (n : nat) : nat :=
  match n with
  | O => O
  | S n' => n * (2 * n - 1) + summa n'
  end.

(*∑n*(2*n-1)*)

Theorem summa_formula : forall n,
  6 * summa n = n * (n + 1) * (4 * n - 1).
Proof.
  induction n.
  -auto.
  -simpl. ring_simplify.
   rewrite IHn.
   destruct n.
   +lia.
   +lia.
Qed.


Require Import ZArith.
Require Import Coq.Lists.List.
Require Import LiterateCoq.Tactics.
Require Coq.Program.Wf.

Import ListNotations.
Open Scope list_scope.

Inductive Expr : Set :=
| Num : Z -> Expr
| Plus : Expr -> Expr -> Expr
| Minus : Expr -> Expr -> Expr.

Fixpoint eval_Expr (e : Expr) : Z :=
  match e with
  | Num n => n
  | Plus e1 e2 => eval_Expr e1 + eval_Expr e2
  | Minus e1 e2 => eval_Expr e1 - eval_Expr e2
  end.

Inductive Op : Set :=
| Push : Z -> Op
| Add : Op
| Sub : Op
| OpCount : Op.

Fixpoint compile_Expr (e : Expr) : list Op :=
  match e with
  | Num n => [Push n]
  | Plus e1 e2 => compile_Expr e1 ++ compile_Expr e2 ++ [Add]
  | Minus e1 e2 => compile_Expr e1 ++ compile_Expr e2 ++ [Sub]
  end.

Fixpoint eval_Op (s : list Z) (ops : list Op) : option Z :=
  match (ops, s) with
  | ([], [n]) => Some n
  | (Push z :: rest, _) => eval_Op (z :: s) rest
  | (Add :: rest, n2 :: n1 :: ns) => eval_Op (n1 + n2 :: ns)%Z rest
  | (Sub :: rest, n2 :: n1 :: ns) => eval_Op (n1 - n2 :: ns)%Z rest
  | (OpCount :: rest, _) => eval_Op (Z.of_nat (length rest) :: s) rest
  | _ => None
  end.

Lemma eval_step : forall a : Expr, forall s : list Z, forall xs : list Op,
      eval_Op s (compile_Expr a ++ xs) = eval_Op (eval_Expr a :: s) xs.
Proof.
  hint_rewrite List.app_assoc_reverse.
  induction a; intros; iauto; simpl;
  hint_rewrite IHa2, IHa1;
  iauto'.
Qed.

Lemma eval_step' : forall a : Expr, forall s : list Z,
      eval_Op s (compile_Expr a) = eval_Op (eval_Expr a :: s) [].
Proof.
  intros.
  assert (H: compile_Expr a = compile_Expr a ++ []) by (rewrite app_nil_r; reflexivity); rewrite H; clear H.
  hint eval_step.
  iauto.
Qed.

Theorem compiler_correctness : forall a : Expr,
    eval_Op [] (compile_Expr a) = Some (eval_Expr a).
Proof.
  hint_rewrite eval_step.
  hint_simpl.
  induction a; iauto'.
Qed.

Definition equiv_Expr (e1 e2 : Expr) : Prop := eval_Expr e1 = eval_Expr e2.
Definition equiv_Op (p1 p2 : list Op) : Prop := eval_Op [] p1 = eval_Op [] p2.

Inductive ExprCtxt : Set :=
| Hole : ExprCtxt
| Plus1 : ExprCtxt -> Expr -> ExprCtxt
| Plus2 : Expr -> ExprCtxt -> ExprCtxt
| Minus1 : ExprCtxt -> Expr -> ExprCtxt
| Minus2 : Expr -> ExprCtxt -> ExprCtxt .

Fixpoint link_Expr (c : ExprCtxt) (e : Expr) : Expr :=
  match c with
  | Hole => e
  | Plus1 c' e' => Plus (link_Expr c' e) e'
  | Plus2 e' c' => Plus e' (link_Expr c' e)
  | Minus1 c' e' => Minus (link_Expr c' e) e'
  | Minus2 e' c' => Minus e' (link_Expr c' e)
  end.

Definition ctxtequiv_Expr (e1 e2 : Expr) : Prop :=
  forall c : ExprCtxt, eval_Expr (link_Expr c e1) = eval_Expr (link_Expr c e2).

Inductive OpCtxt : Set :=
| PushAdd : Z -> OpCtxt
| PushSub : Z -> OpCtxt
| Empty : OpCtxt.

Definition link_Op  (c : OpCtxt) (p : list Op) : list Op :=
  match c with
  | PushAdd n => Push n :: p ++ [Add]
  | PushSub n => Push n :: p ++ [Sub]
  | Empty => p
  end.

Definition ctxtequiv_Op (p1 p2 : list Op) : Prop :=
  forall c : OpCtxt, eval_Op [] (link_Op c p1) = eval_Op [] (link_Op c p2).

Lemma equivalence_reflection :
  forall e1 e2 : Expr,
  forall p1 p2 : list Op,
  forall comp1 : compile_Expr e1 = p1,
  forall comp2 : compile_Expr e2 = p2,
  forall eqtarget : ctxtequiv_Op p1 p2,
    ctxtequiv_Expr e1 e2.
Proof.
  unfold ctxtequiv_Expr, ctxtequiv_Op in *.
  intros.
  induction c; simpl; try solve [hint_rewrite IHc; iauto];
    (* NOTE(dbp 2018-04-16): Only the base case, for Hole, remains *)
    [idtac].
  (* NOTE(dbp 2018-04-16): In the hole case, we specialize the target ctxt equiv hypothesis to empty *)
  specialize (eqtarget Empty);
    simpl in eqtarget; repeat rewrite app_nil_r in eqtarget.
  unfold link_Op in eqtarget.

  (* NOTE(dbp 2018-04-16): At this point, we know e1 -> p1, e2 -> p2, & p1 ≈ p2,
  and want e1 ≈ e2, which follows from compiler correctness *)
  rewrite <- comp1 in eqtarget. rewrite <- comp2 in eqtarget.
  repeat rewrite compiler_correctness in eqtarget.

  inversion eqtarget.
  reflexivity.
Qed.

Lemma equivalence_preservation :
  forall e1 e2 : Expr,
  forall p1 p2 : list Op,
  forall comp1 : compile_Expr e1 = p1,
  forall comp2 : compile_Expr e2 = p2,
  forall eqsource : ctxtequiv_Expr e1 e2,
    ctxtequiv_Op p1 p2.
Proof.
Abort.

Example src_equiv : ctxtequiv_Expr (Plus (Num 1) (Num 1)) (Num 2).
Proof.
  unfold ctxtequiv_Expr.
  induction c; simpl; try rewrite IHc; iauto.
Qed.

Example target_not_equiv :
  eval_Op [] (OpCount :: compile_Expr (Plus (Num 1) (Num 1)) ++ [Add]) <>
  eval_Op [] (OpCount :: compile_Expr (Num 2) ++ [Add]).
Proof.
  simpl.
  congruence.
Qed.

Definition backtranslate (c : OpCtxt) : ExprCtxt :=
  match c with
  | PushAdd n => Plus2 (Num n) Hole
  | PushSub n => Minus2 (Num n) Hole
  | Empty => Hole
  end.

Lemma back_translation_equiv :
  forall c : OpCtxt,
  forall p : list Op,
  forall e : Expr,
  forall c' : ExprCtxt,
    compile_Expr e = p ->
    backtranslate c = c' ->
    eval_Op [] (link_Op c p) = Some (eval_Expr (link_Expr c' e)).
Proof.
  hint_rewrite eval_step, eval_step'.
  intros.
  match goal with
  | [ c : OpCtxt |- _] => destruct c
  end;
    match goal with
    | [ H : backtranslate _ = _ |- _] => invert H
    end; simpl; iauto.
Qed.

Lemma equivalence_preservation :
  forall e1 e2 : Expr,
  forall p1 p2 : list Op,
  forall comp1 : compile_Expr e1 = p1,
  forall comp2 : compile_Expr e2 = p2,
  forall eqsource : ctxtequiv_Expr e1 e2,
    ctxtequiv_Op p1 p2.
Proof.
  unfold ctxtequiv_Expr, ctxtequiv_Op in *.
  intros.

  remember (backtranslate c) as c'.
  destruct c; iauto;

  erewrite back_translation_equiv with (e := e1) (c' := c'); iauto;
  erewrite back_translation_equiv with (e := e2) (c' := c'); iauto;
  specialize (eqsource c'); simpl in *; congruence.
Qed.


(** * Prop: Propositions and Evidence *)

Require Export Logic.

(* ####################################################### *)
(** * Inductively Defined Propositions *)

(** In chapter [Basics] we defined a _function_ [evenb] that tests a
    number for evenness, yielding [true] if so.  We can use this
    function to define the _proposition_ that some number [n] is
    even: *)

Definition even (n:nat) : Prop :=
  evenb n = true.

(** That is, we can define "[n] is even" to mean "the function [evenb]
    returns [true] when applied to [n]."

    Note that here we have given a name
    to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. This isn't a fundamentally
    new kind of proposition;  it is still just an equality. *)

(** Another alternative is to define the concept of evenness
    directly.  Instead of going via the [evenb] function ("a number is
    even if a certain computation yields [true]"), we can say what the
    concept of evenness means by giving two different ways of
    presenting _evidence_ that a number is even. *)

Inductive ev : nat -> Prop :=
  | ev_0 : ev O
  | ev_SS : forall n:nat, ev n -> ev (S (S n)).

(** The first line declares that [ev] is a proposition -- or,
    more formally, a family of propositions "indexed by" natural
    numbers.  (That is, for each number [n], the claim that "[n] is
    even" is a proposition.)  Such a family of propositions is
    often called a _property_ of numbers.

    The last two lines declare the two ways to give evidence that a
    number [m] is even.  First, [0] is even, and [ev_0] is evidence
    for this.  Second, if [m = S (S n)] for some [n] and we can give
    evidence [e] that [n] is even, then [m] is also even, and [ev_SS n
    e] is the evidence.
*)

(** **** Exercise: 1 star (double_even)  *)

Theorem double_even : forall n,
  ev (double n).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

(** For [ev], we had already defined [even] as a function (returning a
   boolean), and then defined an inductive relation that agreed with
   it. However, we don't necessarily need to think about propositions
   first as boolean functions, we can start off with the inductive
   definition.
*)

(** As another example of an inductively defined proposition, let's
    define a simple property of natural numbers -- we'll call it
    "[beautiful]." *)

(** Informally, a number is [beautiful] if it is [0], [3], [5], or the
    sum of two [beautiful] numbers.

    More pedantically, we can define [beautiful] numbers by giving four
    rules:

       - Rule [b_0]: The number [0] is [beautiful].
       - Rule [b_3]: The number [3] is [beautiful].
       - Rule [b_5]: The number [5] is [beautiful].
       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is
         their sum. *)

(** We will see many definitions like this one during the rest
    of the course, and for purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**
                              -----------                               (b_0)
                              beautiful 0

                              ------------                              (b_3)
                              beautiful 3

                              ------------                              (b_5)
                              beautiful 5

                       beautiful n     beautiful m
                       ---------------------------                      (b_sum)
                              beautiful (n+m)
*)

(** *** *)
(** Each of the textual rules above is reformatted here as an
    inference rule; the intended reading is that, if the _premises_
    above the line all hold, then the _conclusion_ below the line
    follows.  For example, the rule [b_sum] says that, if [n] and [m]
    are both [beautiful] numbers, then it follows that [n+m] is
    [beautiful] too.  If a rule has no premises above the line, then
    its conclusion holds unconditionally.

    These rules _define_ the property [beautiful].  That is, if we
    want to convince someone that some particular number is [beautiful],
    our argument must be based on these rules.  For a simple example,
    suppose we claim that the number [5] is [beautiful].  To support
    this claim, we just need to point out that rule [b_5] says so.
    Or, if we want to claim that [8] is [beautiful], we can support our
    claim by first observing that [3] and [5] are both [beautiful] (by
    rules [b_3] and [b_5]) and then pointing out that their sum, [8],
    is therefore [beautiful] by rule [b_sum].  This argument can be
    expressed graphically with the following _proof tree_: *)
(**
         ----------- (b_3)   ----------- (b_5)
         beautiful 3         beautiful 5
         ------------------------------- (b_sum)
                   beautiful 8
*)
(** *** *)
(**
    Of course, there are other ways of using these rules to argue that
    [8] is [beautiful], for instance:
         ----------- (b_5)   ----------- (b_3)
         beautiful 5         beautiful 3
         ------------------------------- (b_sum)
                   beautiful 8
*)

(** **** Exercise: 1 star (varieties_of_beauty)  *)
(** How many different ways are there to show that [8] is [beautiful]? *)

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

(* ####################################################### *)
(** ** Constructing Evidence *)

(** In Coq, we can express the definition of [beautiful] as
    follows: *)

Inductive beautiful : nat -> Prop :=
  b_0   : beautiful 0
| b_3   : beautiful 3
| b_5   : beautiful 5
| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).

(** *** *)
(**
    The rules introduced this way have the same status as proven
    theorems; that is, they are true axiomatically.
    So we can use Coq's [apply] tactic with the rule names to prove
    that particular numbers are [beautiful].  *)

Theorem three_is_beautiful: beautiful 3.
Proof.
   (* This simply follows from the rule [b_3]. *)
   apply b_3.
Qed.

Theorem eight_is_beautiful: beautiful 8.
Proof.
   (* First we use the rule [b_sum], telling Coq how to
      instantiate [n] and [m]. *)
   apply b_sum with (n:=3) (m:=5).
   (* To solve the subgoals generated by [b_sum], we must provide
      evidence of [beautiful 3] and [beautiful 5]. Fortunately we
      have rules for both. *)
   apply b_3.
   apply b_5.
Qed.

(** *** *)
(** As you would expect, we can also prove theorems that have
hypotheses about [beautiful]. *)

Theorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).
Proof.
  intros n B.
  apply b_sum with (n:=8) (m:=n).
  apply eight_is_beautiful.
  apply B.
Qed.

(** **** Exercise: 2 stars (b_times2)  *)
Theorem b_times2: forall n, beautiful n -> beautiful (2*n).
Proof.
  intros n B. simpl. apply b_sum with (n:=n) (m:=n+0).
    apply B.
    apply b_sum.
      apply B.
      apply b_0.
  Qed.
(** [] *)

(** **** Exercise: 3 stars (b_timesm)  *)
Theorem b_timesm: forall n m, beautiful n -> beautiful (m*n).
Proof.
   (* FILL IN HERE *) Admitted.
(** [] *)

(* ####################################################### *)
(** * Using Evidence in Proofs *)
(** ** Induction over Evidence *)

(** Besides _constructing_ evidence that numbers are beautiful, we can
    also _reason about_ such evidence. *)

(** The fact that we introduced [beautiful] with an [Inductive]
    declaration tells Coq not only that the constructors [b_0], [b_3],
    [b_5] and [b_sum] are ways to build evidence, but also that these
    four constructors are the _only_ ways to build evidence that
    numbers are beautiful. *)

(** In other words, if someone gives us evidence [E] for the assertion
    [beautiful n], then we know that [E] must have one of four shapes:

      - [E] is [b_0] (and [n] is [O]),
      - [E] is [b_3] (and [n] is [3]),
      - [E] is [b_5] (and [n] is [5]), or
      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is
        evidence that [n1] is beautiful and [E2] is evidence that [n2]
        is beautiful). *)

(** *** *)
(** This permits us to _analyze_ any hypothesis of the form [beautiful
    n] to see how it was constructed, using the tactics we already
    know.  In particular, we can use the [induction] tactic that we
    have already seen for reasoning about inductively defined _data_
    to reason about inductively defined _evidence_.

    To illustrate this, let's define another property of numbers: *)

Inductive gorgeous : nat -> Prop :=
  g_0 : gorgeous 0
| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)
| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).

(** **** Exercise: 1 star (gorgeous_tree)  *)
(** Write out the definition of [gorgeous] numbers using inference rule
    notation.

(* FILL IN HERE *)
[]
*)

(** **** Exercise: 1 star (gorgeous_plus13)  *)
Theorem gorgeous_plus13: forall n,
  gorgeous n -> gorgeous (13+n).
Proof.
  intros n H.
  apply g_plus3. apply g_plus5. apply g_plus5. apply H. Qed.
(** [] *)

(** *** *)
(** It seems intuitively obvious that, although [gorgeous] and
    [beautiful] are presented using slightly different rules, they are
    actually the same property in the sense that they are true of the
    same numbers.  Indeed, we can prove this. *)

Theorem gorgeous__beautiful_FAILED : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros. induction n as [| n'].
   Case "n = 0". apply b_0.
   Case "n = S n'". (* We are stuck! *)
Abort.

(** The problem here is that doing induction on [n] doesn't yield a
    useful induction hypothesis. Knowing how the property we are
    interested in behaves on the predecessor of [n] doesn't help us
    prove that it holds for [n]. Instead, we would like to be able to
    have induction hypotheses that mention other numbers, such as [n -
    3] and [n - 5]. This is given precisely by the shape of the
    constructors for [gorgeous]. *)

(** *** *)

(** Let's see what happens if we try to prove this by induction on the evidence [H]
   instead of on [n]. *)

Theorem gorgeous__beautiful : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros n H.
   induction H as [|n'|n'].
   Case "g_0".
       apply b_0.
   Case "g_plus3".
       apply b_sum. apply b_3.
       apply IHgorgeous.
   Case "g_plus5".
       apply b_sum. apply b_5. apply IHgorgeous.
Qed.

(* These exercises also require the use of induction on the evidence. *)

(** **** Exercise: 2 stars (gorgeous_sum)  *)
Theorem gorgeous_sum : forall n m,
  gorgeous n -> gorgeous m -> gorgeous (n + m).
Proof.
  intros n m Hn Hm.
  induction Hn as [ | n' | n'].
    simpl. apply Hm.
    apply g_plus3 with (n:=n'+m). apply IHHn.
    apply g_plus5 with (n:=n'+m). apply IHHn.
  Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (beautiful__gorgeous)  *)
Theorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.
Proof.
 (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (g_times2)  *)
(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].
    You might find the following helper lemma useful. *)

Lemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.
Proof.
   (* FILL IN HERE *) Admitted.

Theorem g_times2: forall n, gorgeous n -> gorgeous (2*n).
Proof.
   intros n H. simpl.
   induction H.
   (* FILL IN HERE *) Admitted.
(** [] *)

(** Here is a proof that the inductive definition of evenness implies
the computational one. *)

Theorem ev__even : forall n,
  ev n -> even n.
Proof.
  intros n E. induction E as [| n' E'].
  Case "E = ev_0".
    unfold even. reflexivity.
  Case "E = ev_SS n' E'".
    unfold even. apply IHE'.
Qed.

(** **** Exercise: 1 star (ev__even)  *)
(** Could this proof also be carried out by induction on [n] instead
    of [E]?  If not, why not? *)

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

(** Intuitively, the induction principle [ev n] evidence [ev n] is
    similar to induction on [n], but restricts our attention to only
    those numbers for which evidence [ev n] could be generated. *)

(** **** Exercise: 1 star (l_fails)  *)
(** The following proof attempt will not succeed.
     Theorem l : forall n,
       ev n.
     Proof.
       intros n. induction n.
         Case "O". simpl. apply ev_0.
         Case "S".
           ...
   Intuitively, we expect the proof to fail because not every
   number is even. However, what exactly causes the proof to fail?

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

(** Here's another exercise requiring induction on evidence. *)
(** **** Exercise: 2 stars (ev_sum)  *)

Theorem ev_sum : forall n m,
   ev n -> ev m -> ev (n+m).
Proof.
  intros n m Hn Hm.
  induction Hn.
    Case "n = 0". simpl. apply Hm.
    Case "n = S n". simpl. apply ev_SS with (n:=n+m). apply IHHn.
  Qed.
(** [] *)

(* ####################################################### *)
(** ** Inversion on Evidence *)

(** Having evidence for a proposition is useful while proving, because we
   can _look_ at that evidence for more information. For example, consider
    proving that, if [n] is even, then [pred (pred n)] is
    too.  In this case, we don't need to do an inductive proof.  Instead
    the [inversion] tactic provides all of the information that we need.

 *)

Theorem ev_minus2: forall n,  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  inversion E as [| n' E'].
  Case "E = ev_0". simpl. apply ev_0.
  Case "E = ev_SS n' E'". simpl. apply E'.  Qed.

(** **** Exercise: 1 star, optional (ev_minus2_n)  *)
(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)

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

(** *** *)
(** Here is another example, in which [inversion] helps narrow down to
the relevant cases. *)

Theorem SSev__even : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  apply E'. Qed.

(** ** The Inversion Tactic Revisited *)

(** These uses of [inversion] may seem a bit mysterious at first.
    Until now, we've only used [inversion] on equality
    propositions, to utilize injectivity of constructors or to
    discriminate between different constructors.  But we see here
    that [inversion] can also be applied to analyzing evidence
    for inductively defined propositions.

    (You might also expect that [destruct] would be a more suitable
    tactic to use here. Indeed, it is possible to use [destruct], but
    it often throws away useful information, and the [eqn:] qualifier
    doesn't help much in this case.)

    Here's how [inversion] works in general.  Suppose the name
    [I] refers to an assumption [P] in the current context, where
    [P] has been defined by an [Inductive] declaration.  Then,
    for each of the constructors of [P], [inversion I] generates
    a subgoal in which [I] has been replaced by the exact,
    specific conditions under which this constructor could have
    been used to prove [P].  Some of these subgoals will be
    self-contradictory; [inversion] throws these away.  The ones
    that are left represent the cases that must be proved to
    establish the original goal.

    In this particular case, the [inversion] analyzed the construction
    [ev (S (S n))], determined that this could only have been
    constructed using [ev_SS], and generated a new subgoal with the
    arguments of that constructor as new hypotheses.  (It also
    produced an auxiliary equality, which happens to be useless here.)
    We'll begin exploring this more general behavior of inversion in
    what follows. *)

(** **** Exercise: 1 star (inversion_practice)  *)
Theorem SSSSev__even : forall n,
  ev (S (S (S (S n)))) -> ev n.
Proof.
  intros n H.
  inversion H.
  inversion H1.
  apply H3.
  Qed.

(** The [inversion] tactic can also be used to derive goals by showing
    the absurdity of a hypothesis. *)

Theorem even5_nonsense :
  ev 5 -> 2 + 2 = 9.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (ev_ev__ev)  *)
(** Finding the appropriate thing to do induction on is a
    bit tricky here: *)

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)
(** Here's an exercise that just requires applying existing lemmas.  No
    induction or even case analysis is needed, but some of the rewriting
    may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ####################################################### *)
(** * Discussion and Variations *)
(** ** Computational vs. Inductive Definitions *)

(** We have seen that the proposition "[n] is even" can be
    phrased in two different ways -- indirectly, via a boolean testing
    function [evenb], or directly, by inductively describing what
    constitutes evidence for evenness.  These two ways of defining
    evenness are about equally easy to state and work with.  Which we
    choose is basically a question of taste.

    However, for many other properties of interest, the direct
    inductive definition is preferable, since writing a testing
    function may be awkward or even impossible.

    One such property is [beautiful].  This is a perfectly sensible
    definition of a set of numbers, but we cannot translate its
    definition directly into a Coq Fixpoint (or into a recursive
    function in any other common programming language).  We might be
    able to find a clever way of testing this property using a
    [Fixpoint] (indeed, it is not too hard to find one in this case),
    but in general this could require arbitrarily deep thinking.  In
    fact, if the property we are interested in is uncomputable, then
    we cannot define it as a [Fixpoint] no matter how hard we try,
    because Coq requires that all [Fixpoint]s correspond to
    terminating computations.

    On the other hand, writing an inductive definition of what it
    means to give evidence for the property [beautiful] is
    straightforward. *)

(* ####################################################### *)
(** ** Parameterized Data Structures *)

(** So far, we have only looked at propositions about natural numbers. However,
   we can define inductive predicates about any type of data. For example,
   suppose we would like to characterize lists of _even_ length. We can
   do that with the following definition.  *)

Inductive ev_list {X:Type} : list X -> Prop :=
  | el_nil : ev_list []
  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).

(** Of course, this proposition is equivalent to just saying that the
length of the list is even. *)

Lemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).
Proof.
    intros X l H. induction H.
    Case "el_nil". simpl. apply ev_0.
    Case "el_cc".  simpl.  apply ev_SS. apply IHev_list.
Qed.

(** However, because evidence for [ev] contains less information than
evidence for [ev_list], the converse direction must be stated very
carefully. *)

Lemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.
Proof.
  intros X n H.
  induction H.
  Case "ev_0". intros l H. destruct l.
    SCase "[]". apply el_nil.
    SCase "x::l". inversion H.
  Case "ev_SS". intros l H2. destruct l.
    SCase "[]". inversion H2. destruct l.
    SCase "[x]". inversion H2.
    SCase "x :: x0 :: l". apply el_cc. apply IHev. inversion H2. reflexivity.
Qed.

(** **** Exercise: 4 stars (palindromes)  *)
(** A palindrome is a sequence that reads the same backwards as
    forwards.

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor
        c : forall l, l = rev l -> pal l
      may seem obvious, but will not work very well.)

    - Prove that
       forall l, pal (l ++ rev l).
    - Prove that
       forall l, pal l -> l = rev l.
*)

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

(* Again, the converse direction is much more difficult, due to the
lack of evidence. *)

(** **** Exercise: 5 stars, optional (palindrome_converse)  *)
(** Using your definition of [pal] from the previous exercise, prove
    that
     forall l, l = rev l -> pal l.
*)

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

(* ####################################################### *)
(** ** Relations *)

(** A proposition parameterized by a number (such as [ev] or
    [beautiful]) can be thought of as a _property_ -- i.e., it defines
    a subset of [nat], namely those numbers for which the proposition
    is provable.  In the same way, a two-argument proposition can be
    thought of as a _relation_ -- i.e., it defines a set of pairs for
    which the proposition is provable. *)

Module LeModule.

(** One useful example is the "less than or equal to"
    relation on numbers. *)

(** The following definition should be fairly intuitive.  It
    says that there are two ways to give evidence that one number is
    less than or equal to another: either observe that they are the
    same number, or give evidence that the first is less than or equal
    to the predecessor of the second. *)

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

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

(** Proofs of facts about [<=] using the constructors [le_n] and
    [le_S] follow the same patterns as proofs about properties, like
    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]
    goals (e.g., to show that [3<=3] or [3<=6]), and we can use
    tactics like [inversion] to extract information from [<=]
    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)

(** *** *)
(** Here are some sanity checks on the definition.  (Notice that,
    although these are the same kind of simple "unit tests" as we gave
    for the testing functions we wrote in the first few lectures, we
    must construct their proofs explicitly -- [simpl] and
    [reflexivity] don't do the job, because the proofs aren't just a
    matter of simplifying computations.) *)

Theorem test_le1 :
  3 <= 3.
Proof.
  (* WORKED IN CLASS *)
  apply le_n.  Qed.

Theorem test_le2 :
  3 <= 6.
Proof.
  (* WORKED IN CLASS *)
  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.

Theorem test_le3 :
  (2 <= 1) -> 2 + 2 = 5.
Proof.
  (* WORKED IN CLASS *)
  intros H. inversion H. inversion H2.  Qed.

(** *** *)
(** The "strictly less than" relation [n < m] can now be defined
    in terms of [le]. *)

End LeModule.

Definition lt (n m:nat) := le (S n) m.

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

(** Here are a few more simple relations on numbers: *)

Inductive square_of : nat -> nat -> Prop :=
  sq : forall n:nat, square_of n (n * n).

Inductive next_nat : nat -> nat -> Prop :=
  | nn : forall n:nat, next_nat n (S n).

Inductive next_even : nat -> nat -> Prop :=
  | ne_1 : forall n, ev (S n) -> next_even n (S n)
  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).

(** **** Exercise: 2 stars (total_relation)  *)
(** Define an inductive binary relation [total_relation] that holds
    between every pair of natural numbers. *)

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

(** **** Exercise: 2 stars (empty_relation)  *)
(** Define an inductive binary relation [empty_relation] (on numbers)
    that never holds. *)

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

(** **** Exercise: 2 stars, optional (le_exercises)  *)
(** Here are a number of facts about the [<=] and [<] relations that
    we are going to need later in the course.  The proofs make good
    practice exercises. *)

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
 unfold lt.
 (* FILL IN HERE *) Admitted.

Theorem lt_S : forall n m,
  n < m ->
  n < S m.
Proof.
  (* FILL IN HERE *) Admitted.

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

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
  (* Hint: This may be easiest to prove by induction on [m]. *)
  (* FILL IN HERE *) Admitted.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
  (* Hint: This theorem can be easily proved without using [induction]. *)
  (* FILL IN HERE *) Admitted.

(** **** Exercise: 2 stars, optional (ble_nat_false)  *)
Theorem ble_nat_false : forall n m,
  ble_nat n m = false -> ~(n <= m).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (R_provability2)  *)
Module R.
(** We can define three-place relations, four-place relations,
    etc., in just the same way as binary relations.  For example,
    consider the following three-place relation on numbers: *)

Inductive R : nat -> nat -> nat -> Prop :=
   | c1 : R 0 0 0
   | c2 : forall m n o, R m n o -> R (S m) n (S o)
   | c3 : forall m n o, R m n o -> R m (S n) (S o)
   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o
   | c5 : forall m n o, R m n o -> R n m o.

(** - Which of the following propositions are provable?
      - [R 1 1 2]
      - [R 2 2 6]

    - If we dropped constructor [c5] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

    - If we dropped constructor [c4] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

(* FILL IN HERE *)
[]
*)

(** **** Exercise: 3 stars, optional (R_fact)  *)
(** Relation [R] actually encodes a familiar function.  State and prove two
    theorems that formally connects the relation and the function.
    That is, if [R m n o] is true, what can we say about [m],
    [n], and [o], and vice versa?
*)

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

End R.

(** **** Exercise: 4 stars, advanced (subsequence)  *)
(** A list is a _subsequence_ of another list if all of the elements
    in the first list occur in the same order in the second list,
    possibly with some extra elements in between. For example,
    [1,2,3]
    is a subsequence of each of the lists
    [1,2,3]
    [1,1,1,2,2,3]
    [1,2,7,3]
    [5,6,1,9,9,2,7,3,8]
    but it is _not_ a subsequence of any of the lists
    [1,2]
    [1,3]
    [5,6,2,1,7,3,8]

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)

    - Prove that subsequence is reflexive, that is, any list is a
      subsequence of itself.

    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a
      subsequence of [l2], then [l1] is also a subsequence of [l2 ++
      l3].

    - (Optional, harder) Prove that subsequence is transitive -- that
      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence
      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your
      induction carefully!
*)

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

(** **** Exercise: 2 stars, optional (R_provability)  *)
(** Suppose we give Coq the following definition:
    Inductive R : nat -> list nat -> Prop :=
      | c1 : R 0 []
      | c2 : forall n l, R n l -> R (S n) (n :: l)
      | c3 : forall n l, R (S n) l -> R n l.
    Which of the following propositions are provable?

    - [R 2 [1,0]]
    - [R 1 [1,2,1,0]]
    - [R 6 [3,2,1,0]]
*)

(** [] *)

(* ##################################################### *)
(** * Programming with Propositions Revisited *)

(** As we have seen, a _proposition_ is a statement expressing a factual claim,
    like "two plus two equals four."  In Coq, propositions are written
    as expressions of type [Prop]. . *)

Check (2 + 2 = 4).
(* ===> 2 + 2 = 4 : Prop *)

Check (ble_nat 3 2 = false).
(* ===> ble_nat 3 2 = false : Prop *)

Check (beautiful 8).
(* ===> beautiful 8 : Prop *)

(** *** *)
(** Both provable and unprovable claims are perfectly good
    propositions.  Simply _being_ a proposition is one thing; being
    _provable_ is something else! *)

Check (2 + 2 = 5).
(* ===> 2 + 2 = 5 : Prop *)

Check (beautiful 4).
(* ===> beautiful 4 : Prop *)

(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions
    of type [Prop]. *)

(** *** *)
(** We've mainly seen one place that propositions can appear in Coq: in
    [Theorem] (and [Lemma] and [Example]) declarations. *)

Theorem plus_2_2_is_4 :
  2 + 2 = 4.
Proof. reflexivity.  Qed.

(** But they can be used in many other ways.  For example, we have also seen that
    we can give a name to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. *)

Definition plus_fact : Prop  :=  2 + 2 = 4.
Check plus_fact.
(* ===> plus_fact : Prop *)

(** We can later use this name in any situation where a proposition is
    expected -- for example, as the claim in a [Theorem] declaration. *)

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

(** *** *)
(** We've seen several ways of constructing propositions.

       - We can define a new proposition primitively using [Inductive].

       - Given two expressions [e1] and [e2] of the same type, we can
         form the proposition [e1 = e2], which states that their
         values are equal.

       - We can combine propositions using implication and
         quantification. *)
(** *** *)
(** We have also seen _parameterized propositions_, such as [even] and
    [beautiful]. *)

Check (even 4).
(* ===> even 4 : Prop *)
Check (even 3).
(* ===> even 3 : Prop *)
Check even.
(* ===> even : nat -> Prop *)

(** *** *)
(** The type of [even], i.e., [nat->Prop], can be pronounced in
    three equivalent ways: (1) "[even] is a _function_ from numbers to
    propositions," (2) "[even] is a _family_ of propositions, indexed
    by a number [n]," or (3) "[even] is a _property_ of numbers."  *)

(** Propositions -- including parameterized propositions -- are
    first-class citizens in Coq.  For example, we can define functions
    from numbers to propositions... *)

Definition between (n m o: nat) : Prop :=
  andb (ble_nat n o) (ble_nat o m) = true.

(** ... and then partially apply them: *)

Definition teen : nat->Prop := between 13 19.

(** We can even pass propositions -- including parameterized
    propositions -- as arguments to functions: *)

Definition true_for_zero (P:nat->Prop) : Prop :=
  P 0.

(** *** *)
(** Here are two more examples of passing parameterized propositions
    as arguments to a function.

    The first function, [true_for_all_numbers], takes a proposition
    [P] as argument and builds the proposition that [P] is true for
    all natural numbers. *)

Definition true_for_all_numbers (P:nat->Prop) : Prop :=
  forall n, P n.

(** The second, [preserved_by_S], takes [P] and builds the proposition
    that, if [P] is true for some natural number [n'], then it is also
    true by the successor of [n'] -- i.e. that [P] is _preserved by
    successor_: *)

Definition preserved_by_S (P:nat->Prop) : Prop :=
  forall n', P n' -> P (S n').

(** *** *)
(** Finally, we can put these ingredients together to define
a proposition stating that induction is valid for natural numbers: *)

Definition natural_number_induction_valid : Prop :=
  forall (P:nat->Prop),
    true_for_zero P ->
    preserved_by_S P ->
    true_for_all_numbers P.

(** **** Exercise: 3 stars (combine_odd_even)  *)
(** Complete the definition of the [combine_odd_even] function
    below. It takes as arguments two properties of numbers [Podd] and
    [Peven]. As its result, it should return a new property [P] such
    that [P n] is equivalent to [Podd n] when [n] is odd, and
    equivalent to [Peven n] otherwise. *)

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  (* FILL IN HERE *) admit.

(** To test your definition, see whether you can prove the following
    facts: *)

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

(* ##################################################### *)
(** One more quick digression, for adventurous souls: if we can define
    parameterized propositions using [Definition], then can we also
    define them using [Fixpoint]?  Of course we can!  However, this
    kind of "recursive parameterization" doesn't correspond to
    anything very familiar from everyday mathematics.  The following
    exercise gives a slightly contrived example. *)

(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere)  *)
(** Define a recursive function
    [true_upto_n__true_everywhere] that makes
    [true_upto_n_example] work. *)

(*
Fixpoint true_upto_n__true_everywhere
(* FILL IN HERE *)

Example true_upto_n_example :
    (true_upto_n__true_everywhere 3 (fun n => even n))
  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).
Proof. reflexivity.  Qed.
*)
(** [] *)

(* $Date: 2014-09-18 22:39:20 +0900 (2014年09月18日 (木)) $ *)


Inductive natlist : Type :=
  | nil  : natlist
  | cons : nat -> natlist -> natlist.

Notation "[ ]" := nil.
Notation "h :: t" := (cons h t)
                     (at level 60, right associativity).
Notation "[ x ; .. ; y ]" := (cons x .. (cons y []) ..).

Fixpoint repeat (n count : nat) : natlist :=
  match count with
  | O   => []
  | S c => n :: (repeat n c)
  end.

Fixpoint length xs : nat :=
  match xs with
  | []    => O
  | h::t => S (length t)
  end.

Fixpoint concat xs ys : natlist :=
  match xs with
  | []   => ys
  | h::t => h :: (concat t ys)
  end.

Notation "xs ++ ys" := (concat xs ys)
                       (at level 60, right associativity).

Axiom N0 : nat.
Axiom L0 : natlist.

Definition head xs : nat :=
  match xs with
  | []   => N0
  | h::_ => h
  end.

Definition tail xs : natlist :=
  match xs with
  | []   => []
  | _::t => t
  end.

Fixpoint nonZeros xs : natlist :=
  match xs with
  | []   => []
  | h::t => match h with
            | O   => nonZeros t
            | S _ => h :: nonZeros t
            end
  end.

Fixpoint notb b : bool :=
  match b with | true => false | false => true end.

Fixpoint eqb m n : bool :=
  match (m,n) with
  | (O,O) => true
  | (S m,S n) => eqb m n
  | _ => false
  end.

Fixpoint gtb m n : bool :=
  match (m,n) with
  | (O,_) => false
  | (_,O) => true
  | (S m,S n) => gtb m n
  end.

Fixpoint isEven n : bool :=
  match n with
  | O    => true
  | S n' => notb (isEven n')
  end.

Fixpoint oddMembers xs : natlist :=
  match xs with
  | []   => []
  | h::t => if isEven h
            then oddMembers t
            else h :: oddMembers t
  end.

Definition countOddMembers xs : nat :=
  length (oddMembers xs).

Fixpoint alternate xs ys : natlist :=
  match (xs,ys) with
  | ([],ys) => ys
  | (xs,[]) => xs
  | (x::xs,y::ys) => x :: y :: (alternate xs ys)
  end.

Fixpoint count n xs : nat :=
  match xs with
  | []   => O
  | h::t => if eqb n h
            then 1 + count n t
            else count n t
  end.

Definition bag := natlist.

Definition sum : bag -> bag -> bag := concat.

Definition add : nat -> bag -> bag := cons.

Definition member : nat -> bag -> bool := fun n b => gtb (count n b) 0.

Theorem nil_concat : forall l, [] ++ l = l.
Proof.
  simpl. reflexivity.
Qed.

Theorem nil_concat_right : forall l, l ++ [] = l.
Proof.
  induction l as [| x l'].
    simpl. reflexivity.
    simpl. rewrite IHl'. reflexivity.
Qed.

Theorem tail_length_pred : forall l, pred (length l) = length (tail l).
Proof.
  intros l.
  destruct l as [| x l'].
    simpl. reflexivity.
    simpl. reflexivity.
Qed.

Fixpoint reverse l : natlist :=
  match l with
  | []   => []
  | h::t => reverse t ++ [h]
  end.

Theorem concat_length : forall l l', length (l ++ l') = length l + length l'.
Proof.
  intros.
  induction l. destruct l'.
    simpl. reflexivity.
    simpl. reflexivity.
    simpl. rewrite IHl. reflexivity.
Qed.

Theorem add_1_is_S : forall n, S n = n + 1.
Proof.
  intro n. simpl.
  induction n.
    simpl. reflexivity.
    simpl. rewrite <- IHn. reflexivity.
Qed.

Theorem reverse_preserves_length : forall l, length l = length (reverse l).
Proof.
  intros l.
  induction l.
    simpl. reflexivity.
    simpl. rewrite IHl.
    rewrite concat_length.
    simpl. rewrite add_1_is_S. reflexivity.
Qed.

Theorem concat_associative : forall a b c, (a ++ b) ++ c = a ++ b ++ c.
Proof.
  intros.
  induction a. destruct b. destruct c.
    simpl. reflexivity.
    simpl. reflexivity.
    simpl. reflexivity.
    simpl. rewrite IHa. reflexivity.
Qed.

Theorem reverse_distributes_concat :
  forall l l', reverse (l ++ l') = reverse l' ++ reverse l.
Proof.
  intros.
  induction l. destruct l'.
    simpl. reflexivity.
    simpl. rewrite nil_concat_right. reflexivity.
    simpl. rewrite IHl. rewrite concat_associative. reflexivity.
Qed.

Theorem reverse_append : forall l n, reverse (l ++ [n]) = n :: reverse l.
Proof.
  intros.
  induction l.
    simpl. reflexivity.
    simpl. rewrite IHl. simpl. reflexivity.
Qed.

Theorem reverse_prepend : forall l n, reverse (n :: l) = reverse l ++ [n].
Proof.
  intros.
  destruct l as [| h t].
    simpl. reflexivity.
    simpl. reflexivity.
Qed.

Theorem reverse_involutive : forall l, reverse (reverse l) = l.
Proof.
  intros.
  induction l.
    simpl. reflexivity.
    simpl. rewrite reverse_append. rewrite IHl. reflexivity.
Qed.

Fixpoint andb b b' : bool :=
  match (b,b') with
  | (true,true) => true
  | _ => false
  end.

Fixpoint eqb_natlist l l' : bool :=
  match l,l' with
  | [],[] => true
  | h::t,[] => false
  | [],h::t => false
  | h::t,h'::t' => andb (eqb h h') (eqb_natlist t t')
  end.

Fixpoint leb m n : bool :=
  match m,n with
  | _,O => false
  | O,S _ => true
  | S m, S n => leb m n
  end.

Theorem count_member_nonzero :
  forall s, leb 0 (count 1 (1::s)) = true.
Proof.
  intros.
  simpl. reflexivity.
Qed.

Theorem concat_count : forall x l l', count x l + count x l' = count x (l ++ l').
  intros.
  induction l. destruct l'.
    simpl. reflexivity.
    simpl. reflexivity. simpl.
    case (eqb x n).
      simpl. rewrite IHl. reflexivity.
      simpl. rewrite IHl. reflexivity.
Qed.

Theorem rev_eq_natlist : forall l l', l = l' -> reverse l = reverse l'.
Proof.
  intros.
  induction l. destruct l'.
    simpl. reflexivity.
    simpl. rewrite <- reverse_prepend.
    rewrite <- H. simpl. reflexivity.
    rewrite H. reflexivity.
Qed.


(*Inductive predicates*)
Inductive even : nat -> Prop :=
| even0 : even 0
| evenS : forall x:nat, even x -> even (S (S x)).

Lemma even_0: even 0.
Proof.
    apply even0.
Qed.

Lemma even_20: even 20.
Proof.
    repeat (apply evenS).
    apply even0.
Qed.

Require Import Arith.

Lemma even_mult : forall x, even x -> exists y, x = 2*y.
Proof.
    intros x H.
    induction H.
    exists 0.
    ring.
    destruct IHeven as [y Heq].
    rewrite Heq.
    exists (S y).
    ring.
Qed.

Lemma not_even_1 : ~even 1.
Proof.
    intros even1.
    inversion even1.
Qed.

Lemma even_inv : forall x, even (S (S x)) -> even x.
Proof.
    intros x H.
    inversion H.
    assumption.
Qed.


From LF Require Export Basics.

Theorem plus_n_O : forall n:nat, n = n + 0.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *) reflexivity.
  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.

Theorem multi_0_r : forall n:nat,
    n * 0 = 0.
Proof.
  intros n. induction n as [| n' IHn'].
  - reflexivity.
  - simpl.
    rewrite plus_n_O.
    rewrite IHn'.
    reflexivity.
Qed.

Theorem plus_n_sm : forall n m:nat,
    S(n + m) = n + (S m).
Proof.
  intros.
  induction n.
  simpl.
  reflexivity.
  simpl.
  rewrite -> IHn.
  reflexivity.
Qed.

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

Lemma double_plus : forall n, double n = n + n.
Proof.
  intros n. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl.
    rewrite -> IHn'.
    rewrite -> plus_n_sm.
    reflexivity.
Qed.

Theorem plus_comm : forall n m : nat,
    (n + m) = (m + n).
Proof.
  intros n m.
  induction n as [| n' IHn'].
  - simpl.
    rewrite <- plus_n_O.
    reflexivity.
  - simpl.
    rewrite -> IHn'.
    rewrite -> plus_n_sm.
    reflexivity.
Qed.


Require Import Setoid.

Class Group (A : Type) := GroupDef {
  zero     : A;
  op       : A -> A -> A;
  inv      : A -> A;
  l_op_id  : forall x: A, op zero x = x;
  r_op_id  : forall x: A, op x zero = x;
  l_op_inv : forall x: A, op (inv x) x = zero;
  r_op_inv : forall x: A, op x (inv x) = zero;
  op_assoc : forall x y z: A, op (op x y) z = op x (op y z);
}.

Definition sub {A: Type} `{Group A} (x y: A) := op x (inv y).

Lemma op_sub {A: Type} `{Group A} (x y : A) : op (sub x y) y = x.
Proof.
  unfold sub. rewrite op_assoc. rewrite l_op_inv. rewrite r_op_id. auto.
Qed.

Lemma sub_op {A: Type} `{Group A} (x y : A) : sub (op x y) y = x.
Proof.
  unfold sub. rewrite op_assoc. rewrite r_op_inv. rewrite r_op_id. auto.
Qed.

Lemma group_equation_l_simp {A: Type} `{Group A} (a b c : A) : op a b = op a c -> b = c.
Proof.
  intro H0. assert (op (inv a) (op a b) = op (inv a) (op a c)).
  - rewrite H0. auto.
  - rewrite <- op_assoc, <- op_assoc, l_op_inv, l_op_id, l_op_id in H1. auto.
Qed.

Lemma group_equation_r_simp {A: Type} `{Group A} (a b c : A) : op a c = op b c -> a = b.
Proof.
  intro H0. assert (op (op a c) (inv c) = op (op b c) (inv c)).
  - rewrite H0. auto.
  - rewrite op_assoc, op_assoc, r_op_inv, r_op_id, r_op_id in H1. auto.
Qed.

Lemma sub_zero_uniq {A: Type} `{Group A} (x y: A) : sub x y = zero -> x = y.
Proof.
  unfold sub. rewrite <- (r_op_inv y). intros H0.
  apply group_equation_r_simp with (c := inv y). auto.
Qed.

Lemma group_op_inv {A: Type} `{Group A} (x y: A) : inv (op x y) = op (inv y) (inv x).
Proof.
  unfold sub. apply group_equation_l_simp with (a := y).
  rewrite <- op_assoc, r_op_inv, l_op_id.
  apply group_equation_l_simp with (a := x).
  rewrite r_op_inv, <- op_assoc, r_op_inv. auto.
Qed.

Class Field (A : Type) `{Group A} := FieldDef {
  one       : A;
  mul       : A -> A -> A;
  mul_inv   : A -> A;
  op_comm   : forall x y: A, op x y = op y x;
  mul_comm  : forall x y: A, mul x y = mul y x;
  l_mul_id  : forall x: A, mul one x = x;
  r_mul_id  : forall x: A, mul x one = x;
  l_mul_inv : forall x: A, mul (mul_inv x) x = one;
  r_mul_inv : forall x: A, mul x (mul_inv x) = one;
  mul_assoc : forall x y z: A, mul (mul x y) z = mul x (mul y z);
  distr     : forall x y z: A, mul x (op y z) = op (mul x y) (mul x z);
}.

Lemma field_zero_mul_l {A: Type} `{Field A} (x: A) : mul x zero = zero.
Proof.
  assert (zero = op (mul x (op zero one)) (inv x)). {
    rewrite l_op_id, r_mul_id, r_op_inv. auto.
  }
  rewrite H1 at 2. rewrite distr, r_mul_id, op_assoc, r_op_inv, r_op_id. auto.
Qed.