From LF Require Export Basics.

Theorem plus_n_0_firsttry : 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.

(*Exercise*)

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

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

(* 加法交换律 *)
Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros n m. induction m as [| m' IHm'].
  - rewrite <- (plus_n_0_firsttry n). reflexivity.
  - simpl. rewrite <- IHm'. rewrite -> (plus_n_Sm n m'). reflexivity.
Qed.

(*加法结合律*)
Theorem plus_assoc : forall n m p : nat,
    (n + m) + p = n + (m + p).
Proof.
  intros n m p. induction n as [| n IHn'].
  - 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: nat,
    double n = n + n.
Proof.
  intros n. induction n as [| n' IHn'].
  - reflexivity.
  - simpl. rewrite <- plus_comm. simpl. rewrite <- IHn'. reflexivity.
Qed.

Theorem evenb_S : forall n : nat,
    evenb (S n) = negb (evenb n).
Proof.
  intros n. induction n as [| n' IHn'].
  - reflexivity.
  - rewrite -> IHn'. simpl. rewrite -> (negb_involutive (evenb n')).
    reflexivity.
Qed.

(*proofs within proofs*)

Theorem mult_0_plus' : forall n m: nat,
    (0 + n) * m = n * m.
Proof.
  intros n m.
  assert (H: 0 + n = n). { reflexivity. }
                         rewrite -> H.
  reflexivity.
Qed.

Theorem plus_rearrange_firsttry : forall n m p q: nat,
    (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  rewrite -> (plus_comm n m).
  reflexivity.
Qed.

(*更多练习*)

Theorem plus_swap : forall n m p: nat,
    n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite -> (plus_comm n p).
  rewrite -> (plus_comm n (m + p)).
  rewrite <- (plus_assoc m p n).
  reflexivity.
Qed.

(*乘法交换律*)

Lemma mult_0_eq_0 : forall n: nat,
    0 = n * 0.
Proof.
  intros n. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite <- IHn'. reflexivity.
Qed.

Lemma mult_plus_1 : forall n m : nat,
    m * n + m = m * S n.
Proof.
  intros n m. induction m as [| m' IHm'].
  - simpl. reflexivity.
  - simpl. rewrite <- IHm'.
    rewrite <- (plus_assoc n (m' * n) m').
    rewrite <- (plus_n_Sm (n + m' * n) m').
    reflexivity.
Qed.

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

(*练习*)

Theorem leb_refl : forall n: nat,
    true = (n <=? n).
Proof.
  intros n. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite <- IHn'. reflexivity.
Qed.

Theorem zero_nbeq_S : forall n : nat,
    0 =? (S n) = false.
Proof.
  intros n. destruct n as [| n'].
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

Theorem andb_false_r : forall b: bool,
    andb b false = false.
Proof.
  intros b. destruct b.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

Theorem plus_ble_compat_l : forall n m p: nat,
    n <=? m = true -> (p + n) <=? (p + m) = true.
Proof.
  intros n m p. intros H. induction p as [| p' IHp'].
  - simpl. rewrite -> H. reflexivity.
  - simpl. rewrite -> IHp'. reflexivity.
Qed.

(*乘法结合律*)

Theorem mult_plus_distr_r : forall n m p: nat,
    (n + m) * p = (n * p) + (m * p).
Proof.
  intros n m p. induction p as [| p' IHp'].
  - simpl. rewrite -> (mult_0_r n). rewrite -> (mult_0_r m). rewrite -> (mult_0_r (n + m)). reflexivity.
  - rewrite <- (mult_plus_1 p' (n + m)).
    rewrite <- (mult_plus_1 p' n).
    rewrite <- (mult_plus_1 p' m).
    rewrite -> IHp'.
    rewrite -> (plus_assoc (n * p')  (m * p') (n + m)).
    rewrite -> (plus_assoc (n * p')  n (m * p' + m)).
    rewrite -> (plus_comm (n * p') (m * p' + (n + m))).
    rewrite -> (plus_comm (n * p') (n + (m * p' + m))).
    rewrite -> (plus_swap n (m * p') m).
    reflexivity.
Qed.

Theorem mult_assoc : forall n m p : nat,
    n * (m * p) = (n * m) * p.
Proof.
  intros n m p. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite -> IHn'.
    rewrite -> (mult_plus_distr_r m (n' * m) p).
    reflexivity.
Qed.

Theorem eqb_refl : forall n: nat,
    true = (n <=? n).
Proof.
  intros n. induction n.
  - simpl. reflexivity.
  - simpl. rewrite <- IHn. reflexivity.
Qed.

Theorem plus_swap' : forall n m p: nat,
    n + (m + p) = m + (n + p).
Proof.
  intros n m p.
Admitted.

(**)
Inductive bin : Type :=
| Z
| Bin0 : bin -> bin (* B_0 n = 2*n  *)
| Bin1 : bin -> bin. (* B_1 =  2*n + 1  *)

Fixpoint incr (m: bin) : bin :=
  match m with
  | Z => Bin1 Z
  | Bin0 m' => Bin1 m'
  | Bin1 m' => Bin0 (incr m')
  end.

(* bin 转化为 nat *)

Fixpoint bin_to_nat (m: bin) : nat :=
  match m with
  | Z => O
  | Bin0 m' => 2 * (bin_to_nat m')
  | Bin1 m' => 2 * (bin_to_nat m') + 1
  end.

Lemma plus_1_eq_S : forall n : nat,
    n + 1 = S n.
Proof.
  intros n. induction n.
  - simpl. reflexivity.
  - simpl. rewrite <- IHn. reflexivity.
Qed.

Lemma plus_0_equal : forall n: nat,
    n + 0 = n.
Proof.
  intros. induction n.
  - reflexivity.
  - simpl. rewrite -> IHn. reflexivity.
Qed.

Theorem bin_to_nat_pres_inrc : forall b : bin,
    S (bin_to_nat b) = bin_to_nat (incr b).
Proof.
  intros b. induction b.
  - simpl. reflexivity.
  - simpl. rewrite <- plus_1_eq_S. reflexivity.
  - simpl. rewrite <- IHb. rewrite -> plus_0_equal.
    rewrite -> (plus_0_equal (S (bin_to_nat b))).
    rewrite <- plus_1_eq_S.
    rewrite <- (plus_1_eq_S (bin_to_nat b)).
    rewrite -> (plus_assoc (bin_to_nat b) 1 (bin_to_nat b + 1)).
    rewrite -> (plus_swap 1 (bin_to_nat b) 1).
    rewrite <- (plus_assoc (bin_to_nat b) (bin_to_nat b) (1 + 1)).
    rewrite -> plus_assoc. reflexivity.
Qed.

Fixpoint nat_to_bin (n: nat) : bin :=
  match n with
  | O => Z
  | S n' => incr (nat_to_bin n')
  end.

Theorem nat_bin_nat : forall n: nat,
    bin_to_nat (nat_to_bin n) = n.
Proof.
  intros n. induction n.
  - reflexivity.
  - simpl. rewrite <- (bin_to_nat_pres_inrc (nat_to_bin n)).
    rewrite -> IHn. reflexivity.
Qed.

(* 不明白 normalize 函数的意思  *)


(* Example of proof by simplification *)
Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof. intros n. simpl. reflexivity. Qed.

(*
In Coq, we use tactics to manipulate the goal and context, where Coq
will keep track of the goal and context for us

Tactics (used in the previous proof) :
  "intros" - introduces things into our context
             whatever been quantified
  "simpl" - simplifies our goal running a few steps of computation
  "reflexivity" - named after the property of equality (all things are equal to themselves
  "Qed" - quod erat demonstrandum, latin for 'that which was to be proved'

*)

(* Example of proof by rewriting *)
Theorem plus_id_example : forall (n m: nat),
  n = m -> n + n = m + m.

(* The way a proof with implies ('->') works is: you have to prove what's to the right of
the arrow... but you may assume what's to the left. *)

Proof.
  (* move both quantifiers into the context *)
  intros n m .
  (* move the hypothesis into the context *)
  intros H.
  (* rewrite the goal usign the hypothesis *)
  rewrite -> H.
  reflexivity. Qed.

(* (The arrow symbol in the rewrite has nothing to do with implication:
 it tells Coq to apply the rewrite from left to right. To rewrite from
right to left, you can use rewrite <-.  *)

(* Exercise *)
Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.

Proof. intros n m o. intros H. rewrite <- H.
intros G. rewrite -> G. reflexivity. Qed.

Theorem mult_S_1 : forall n m : nat,
  m = S n->
  m * (1 + n) = m * m.

Proof. intros n m. intros H. rewrite -> H.
simpl. reflexivity. Qed.

(* Example of proof by case analysis *)

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

Theorem plus_1_neq_firsttry : forall n : nat,
  beq_nat (n + 1) 0 = false.

Proof. intros n. simpl. Abort.

(* More tactics
  "Abort" - ends the proof but doesn't prove it
  "destruct" - tells Coq to consider seperate cases on a
                a variable in the context

*)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.

Proof.
  intros n. destruct n as [| n'].
  - reflexivity.
  - reflexivity. Qed.

(* The annotation "as [| n']" is called an intro pattern.
It tells Coq what variable names to introduce in each subgoal

The - signs on the second and third lines are called bullets,
and they mark the parts of the proof that correspond to each generated subgoal.

The destruct tactic can be used with any inductively defined datatype.
 *)

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.

Proof. intros b. destruct b.
  - reflexivity.
  - reflexivity. Qed.

(* Note that the destruct here has no as clause because none of the subcases
of the destruct need to bind any variables, so there is no need to specify
any names. (We could also have written as [|], or as [].)
*)

Theorem andb_commutative : forall b c, andb b c = andb c b.

Proof. intros b c. destruct b.
  - destruct c.
    + reflexivity.
    + reflexivity.
  - destruct c.
    + reflexivity.
    + reflexivity.
 Qed.

Theorem and3b_commutative : forall b c d, andb (andb b c) d = andb (andb b d ) c.

Proof.
  intros b c d. destruct b.
  - destruct c.
    { destruct d.
      - reflexivity.
      - reflexivity. }
    { destruct d.
      - reflexivity.
      - reflexivity. }
  - destruct c.
    { destruct d.
      - reflexivity.
      - reflexivity. }
    { destruct d.
      - reflexivity.
      - reflexivity. }
Qed.

(* You can perform the destructing in the same
 command as the intros. *)

Theorem plus_1_neg_0' : forall n : nat,
  beq_nat (n + 1) 0 = false.

Proof.
  intros [|n].
      - reflexivity.
      - reflexivity.
Qed.

(* Exercise 1 *)

Lemma minus_n_O : forall n : nat, n = n - 0.

Proof. intros n. destruct n as [a|b].
  - reflexivity.
  - reflexivity.
 Qed.

Theorem andb_commutative'' :
  forall b c : bool, andb b c = andb c b.

(* If there are no arguments to name, we can just write [] *)
Proof. intros [] [].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.

(* Exercise 2 need to come back and finish this one*)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.

Proof. intros b c. destruct c as [c'|c']. Abort.

(* Exercise 3 *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.

Proof. intros [].
  - reflexivity.
  - reflexivity.
Qed.

(* I should come back to this section to understand
 how i can translate coq proofs into paper proofs *)


(* Exercise for the reader: look into what these standard-library modules contain :-) *)
Require Import Coq.Unicode.Utf8 Arith Bool Ring Setoid.

(** This next command (roughly) turns on the sort of implicit-argument behavior we're used to from Haskell or ML: type arguments to polymorphic functions need not be passed explicitly. *)
Set Implicit Arguments.

(** * A simple state machine for factorial *)

(** Here's a classic recursive, functional program for factorial. *)
Fixpoint fact (n : nat) : nat :=
  match n with
  | O => 1
  | S n' => fact n' * S n'
  end.

(** But let's reformulate factorial relationally, as an example to explore treatment of inductive relations in Coq.  First, these are the states of our state machine. *)
Inductive fact_state : Set :=
| AnswerIs : nat -> fact_state
| WithAccumulator : nat -> nat -> fact_state.

(** This predicate captures which states are starting states. *)
Inductive fact_init (original_input : nat) : fact_state -> Prop :=
| FactInit : fact_init original_input (WithAccumulator original_input 1).

(** And here are the states where we declare execution complete. *)
Inductive fact_final : fact_state -> Prop :=
| FactFinal : forall ans, fact_final (AnswerIs ans).

(** The most important part: the relation to step between states *)
Inductive fact_step : fact_state -> fact_state -> Prop :=
| FactDone : forall acc,
  fact_step (WithAccumulator O acc) (AnswerIs acc)
| FactStep : forall n acc,
  fact_step (WithAccumulator (S n) acc) (WithAccumulator n (acc * S n)).

(** To prove that our state machine really computes factorial, we introduce an *invariant* on states. *)
Definition fact_invariant (original_input : nat) (st : fact_state) : Prop :=
  match st with
  | AnswerIs ans => fact original_input = ans
  | WithAccumulator n acc => fact original_input = fact n * acc
  end.

(** It should hold at the start. *)
Theorem fact_invariant_init : forall original_input st,
  fact_init original_input st
  -> fact_invariant original_input st.
Proof.
  destruct 1; simpl.
  (** Notice that here we have done case analysis (with [destruct]) on *which*rule*was*used*to*derive*a*predicate*, in the same way that we would use case analysis on e.g. whether a list is [nil] or [cons]. *)
  ring.
  (** Here's a handy tactic for proving goals that follow from the axioms of the algebraic structure *ring*.  Actually, it's generalized to semirings, and here we appeal to the semiring structure of the naturals. *)
Qed.

(** And every step should preserve the invariant. *)
Theorem fact_invariant_preserve : forall original_input st st',
  fact_step st st'
  -> fact_invariant original_input st
  -> fact_invariant original_input st'.
Proof.
  destruct 1; simpl; intros.

  rewrite H.
  ring.

  rewrite H.
  ring.
Qed.

(** Finally, when the state machine completes, the state must look how we expected. *)
Theorem fact_invariant_final : forall original_input st,
  fact_final st
  -> fact_invariant original_input st
  -> st = AnswerIs (fact original_input).
Proof.
  destruct 1; simpl; intros.

  rewrite H.
  reflexivity.
Qed.

(** * Transition systems in general *)

(** Let's define a polymorphic type of states machines, packaging the components we coded in an ad-hoc way for factorial. *)
Record transition_system' (State : Set) := {
  Init : State -> Prop;
  Step : State -> State -> Prop;
  Final : State -> Prop
}.

(** Here's a fun construction, to package a type along with its associated polymorphic value.  The [:>] declares a *coercion*, where the [transition_system'] within a [transition_system] is automatically extracted as required by typing. *)
Record transition_system := {
  State : Set;
  Super :> transition_system' State
}.

(** As an example, here's factorial in the new format. *)
Definition fact_ts (original_input : nat) := {|
  State := fact_state;
  Super := {| Init := fact_init original_input;
              Step := fact_step;
              Final := fact_final |}
|}.

(** Now a general relation to capture zero or more steps of transition-system execution *)
Inductive runFrom (ts : transition_system) : State ts -> State ts -> Prop :=
| RunFinal : forall st,
  Final ts st
  -> runFrom ts st st
| RunStep : forall st st' st'',
  Step ts st st'
  -> runFrom ts st' st''
  -> runFrom ts st st''.

(** Wrapping it with an extra check that we start in an initial state *)
Inductive run (ts : transition_system) (st : State ts) : Prop :=
| Run : forall st0,
  Init ts st0
  -> runFrom ts st0 st
  -> run ts st.

(** Here's our first example of *rule*induction*, using the inductive tree structure of proofs.  Let's show that [runFrom] only finishes in final states. *)
Lemma runFrom_final : forall ts st st',
  runFrom ts st st'
  -> Final ts st'.
Proof.
  induction 1.

  assumption.

  assumption.
Qed.

(** It's a simple corollary to lift to [run] insteadof [runFrom]. *)
Lemma run_final : forall ts st,
  run ts st
  -> Final ts st.
Proof.
  destruct 1.

  eapply runFrom_final.
  (** [eapply]: like [apply], but leaves *unification*variables* to be determined later *)
  eassumption.
  (** [eassumption]: like [assumption], but will try to fill in *unification*variables *)
Qed.

(** A formal characterization for when a predicate is an invariant of a transition system *)
Inductive isInvariant (ts : transition_system) (inv : State ts -> Prop) : Prop :=
| IsInvariant : (forall st, Init ts st -> inv st)
  -> (forall st st', Step ts st st' -> inv st -> inv st')
  -> isInvariant ts inv.

(** Let's prove that the conditions we chose are strong enough to show that the invariant is preserved by [runFrom]. *)
Theorem invariant_preserved : forall ts (inv : State ts -> Prop),
  (forall st st', Step ts st st' -> inv st -> inv st')
  -> forall st st', runFrom ts st st'
    -> inv st
    -> inv st'.
Proof.
  induction 2; intros.

  assumption.

  apply IHrunFrom.
  eapply H.
  eassumption.
  assumption.
Qed.

(** And it's easy to lift to [run] again. *)
Theorem invariant_final : forall ts inv st,
  isInvariant ts inv
  -> run ts st
  -> inv st.
Proof.
  destruct 1.
  destruct 1.
  eapply invariant_preserved.
  assumption.
  eassumption.
  apply H.
  assumption.
Qed.

(** So now we can do another proof of factorial via our generic machinery. *)
Theorem fact_ts_correct : forall original_input st,
  run (fact_ts original_input) st
  -> st = AnswerIs (fact original_input).
Proof.
  intros.

  assert (Final (fact_ts original_input) st).
  (** [assert]: a kind of "cut": prove an extra fact, then have it as a new hypothesis *)
  apply run_final.
  assumption.

  assert (fact_invariant original_input st).
  apply invariant_final.
  apply IsInvariant.
  apply fact_invariant_init.
  apply fact_invariant_preserve.
  assumption.

  destruct H0.
  simpl in H1.
  rewrite H1.
  reflexivity.
Qed.

(** * Running transition systems in parallel *)

(** Consider two transition systems with a common notion of shared state and (potentially) their own notions of private state.  Let's build a transition system for running them in parallel with nondeterministic interleaving. *)
Inductive parallel_init (Shared Private1 Private2 : Set)
  (Init1 : Shared * Private1 -> Prop)
  (Init2 : Shared * Private2 -> Prop)
  : Shared * Private1 * Private2 -> Prop :=
| Pinit : forall sh pr1 pr2,
  Init1 (sh, pr1)
  -> Init2 (sh, pr2)
  -> parallel_init Init1 Init2 (sh, pr1, pr2).

Inductive parallel_step (Shared Private1 Private2 : Set)
          (Step1 : Shared * Private1 -> Shared * Private1 -> Prop)
          (Step2 : Shared * Private2 -> Shared * Private2 -> Prop)
          : Shared * Private1 * Private2 -> Shared * Private1 * Private2 -> Prop :=
| Pstep1 : forall sh pr1 pr2 sh' pr1',
  Step1 (sh, pr1) (sh', pr1')
  -> parallel_step Step1 Step2 (sh, pr1, pr2) (sh', pr1', pr2)
| Pstep2 : forall sh pr1 pr2 sh' pr2',
  Step2 (sh, pr2) (sh', pr2')
  -> parallel_step Step1 Step2 (sh, pr1, pr2) (sh', pr1, pr2').

Inductive parallel_final (Shared Private1 Private2 : Set)
          (Final1 : Shared * Private1 -> Prop)
          (Final2 : Shared * Private2 -> Prop)
  : Shared * Private1 * Private2 -> Prop :=
| Pfinal : forall sh pr1 pr2,
  Final1 (sh, pr1)
  -> Final2 (sh, pr2)
  -> parallel_final Final1 Final2 (sh, pr1, pr2).

Definition parallel (Shared Private1 Private2 : Set)
           (ts1 : transition_system' (Shared * Private1))
           (ts2 : transition_system' (Shared * Private2)) := {|
  State := Shared * Private1 * Private2;
  Super := {| Init := parallel_init (Init ts1) (Init ts2);
              Step := parallel_step (Step ts1) (Step ts2);
              Final := parallel_final (Final ts1) (Final ts2) |}
|}.

(** * A simple example of another program as a state transition system *)

(** We'll formalize this pseudocode for one thread of a concurrent, shared-memory program.
  thread(me, other):
    flag[me] = true; (I'm going to wait)
    turn = other;  (You go ahead)
    while (flag[other] && turn == other); (I'll wait until you're done)
    local = global; (Access the global state)
    global = local + 1; (increment the global state)
    flag[me] = false; (I'm done)
 *)

(** This inductive state effectively encodes all possible combinations of two kinds of *local*state* in a thread:
    * program counter
    * values of local variables that may be ready eventually *)

Inductive peterson_program : Set :=
| Flag: peterson_program
| Wait: peterson_program
| Read : peterson_program
| Write : nat -> peterson_program
| Unlock : peterson_program
| Done : peterson_program.

(** Next, a type for state shared between threads, using Coq's handy record facility, which desugars to single-constructor inductive definitions. *)
Record pet_state := {
    FlagOne : bool;
    FlagTwo : bool;
    Turn : bool;
    Global : nat   (** A shared counter *)
}.

(** The combined state, from one thread's perspective.  [%type] gets [*] to be parsed as Cartesian product instead of numeric multiplication. *)
Definition peterson_state := (pet_state * peterson_program)%type.

(** Now a routine definition of the three key relations of a state-transition system.  The most interesting logic surrounds saving the counter value in the local state after reading. *)

Inductive peterson_init : peterson_state -> Prop :=
| IncInit :
  peterson_init ({| FlagOne := false;
                    FlagTwo := false;
                    Turn := false;
                    Global := O |}, Flag).

Inductive peterson_step : peterson_state -> peterson_state -> Prop :=
| IncFlag : forall g t,
  peterson_step ({| FlagOne := false; FlagTwo := false; Turn := t; Global := g |}, Flag)
                 ({| FlagOne := true; FlagTwo := false; Turn := false; Global := g |}, Wait)
| IncWait : forall f1 f2 t g,
  peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Wait)
                 ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Read)
| IncRead : forall f1 f2 t g,
  peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Read)
                 ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Write g)
| IncWrite : forall f1 f2 t g v,
  peterson_step ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := g |}, Write v)
                 ({| FlagOne := f1; FlagTwo := f2; Turn := t; Global := S v |}, Unlock)
| IncUnlock : forall f1 f2 t g,
  peterson_step ({| FlagOne := f1;    FlagTwo := f2; Turn := t; Global := g |}, Unlock)
                 ({| FlagOne := false; FlagTwo := f2; Turn := t; Global := g |}, Done).

Inductive peterson_final : peterson_state -> Prop :=
| IncFinal : forall p: pet_state,
  peterson_final (p, Done).

Definition peterson_ts := {|
  State := peterson_state;
  Super := {| Init := peterson_init;
              Step := peterson_step;
              Final := peterson_final |}
|}.

(** * Running transition systems in parallel *)

(** Consider two transition systems with a common notion of shared state and (potentially) their own notions of private state.  Let's build a transition system for running them in parallel with nondeterministic interleaving. *)

(** Example: composing two threads of the kind we formalized earlier *)
Definition peterson2_ts := parallel peterson_ts peterson_ts.

(** Let's prove that the counter is always 2 when the composed program terminates. *)

(** First big idea: the program counter of a thread tells us how much it has added to the shared counter so far. *)
Definition contribution_from (pr : peterson_program) : nat :=
  match pr with
  | Unlock | Done => 1
  | _ => 0
  end.

(** Second big idea: the program counter also tells us whether a thread holds the lock. *)
Definition has_lock (pr : peterson_program) : bool :=
  match pr with
  | Read => true
  | Write _ => true
  | Unlock => true
  | _ => false
  end.

(** Now we see that the shared state is a function of the two program counters, as follows. *)
Definition shared_from_private (pr1 pr2 : peterson_program) :=
  {| FlagOne := has_lock pr1;
     FlagTwo := has_lock pr2;
     Global :=  contribution_from pr1 + contribution_from pr2 |}.

(** We also need a condition to formalize compatibility between program counters, e.g. that they shouldn't both be in the critical section at once. *)
Definition instruction_ok (self other : peterson_program): Prop :=
  match self with
  | Flag => True
  | Wait => True
  | Read => has_lock other = false
  | Write n => has_lock other = false /\ n = contribution_from other
  | Unlock => has_lock other = false
  | Done => True
  end.

(** Now we have the ingredients to state the invariant. *)
Inductive peterson2_invariant : State peterson2_ts -> Prop :=
| Inc2Inv : forall pr1 pr2,
  instruction_ok pr1 pr2
  -> instruction_ok pr2 pr1
  -> peterson2_invariant (shared_from_private pr1 pr2, pr1, pr2).

(** It's convenient to prove this alternative equality-based "constructor" for the invariant. *)
Lemma Inc2Inv' : forall sh pr1 pr2,
  sh = shared_from_private pr1 pr2
  -> instruction_ok pr1 pr2
  -> instruction_ok pr2 pr1
  -> peterson2_invariant (sh, pr1, pr2).
Proof.
  intros.
  rewrite H.
  apply Inc2Inv; assumption.
Qed.

Lemma final_eq : forall st,
  Final peterson2_ts st
  -> peterson2_invariant st
  -> st = ({| FlagOne := false; FlagTwo := false; Turn := false; Global := 2 |}, Done, Done).
Proof.
  destruct 1.
  inversion H; subst.
  inversion H0; subst.
  intros.
  inversion H1; subst. compute.
  reflexivity.
Qed.

Hint Resolve run_final.

(** Now we can prove that the system only runs to happy states. *)
Theorem increment2_ts_correct : forall st,
  run peterson2_ts st
  -> st = ({| FlagOne := false; FlagTwo := false; Turn := false; Global := 2 |}, Done, Done).
Proof.
  intros.
  apply final_eq; eauto.
  apply invariant_final; auto.
  constructor.
  (** [constructor]: a convenient shorthand for [apply] that picks the rule to apply for you, by searching through the constructors for the inductive type you're trying to prove *)

  destruct 1.
  inversion H0; subst.
  inversion H1; subst.
  change {| FlagOne := false; FlagTwo := false; Turn := false; Global := 0 |} with (shared_from_private Flag Flag).
  (** [change]: replace one term with another, when it is sufficiently easy for Coq to see that the two terms are equal (actually when they are *definitionally*equal*, but I won't go into the details here). *)
  constructor; simpl; intuition.
  (** [intuition] simplifies goals according to the rules of propositional (Boolean) logic.  (The name tells us that it follows *intuitionistic*, rather than classical, logic.) *)

  destruct 1.

  (** Some long tactic chains help us consider many cases whether bothering with the details manually.  Details are a bit beyond the scope of this lecture.  We use [subst], which finds equalities over variables and then eliminates those variables, replacing them with the terms they are equated to. *)

  destruct pr2; inversion H0; subst; inversion 1; subst; apply Inc2Inv'; simpl in *; intuition; subst. compute.
  reflexivity || congruence.

  destruct pr1; inversion H0; subst; inversion 1; subst; apply Inc2Inv'; simpl in *; intuition; subst;
  reflexivity || congruence.
Qed.

(* assignment *)


(** * Lists: Working with Structured Data *)

Require Export Induction.

Check orb.
Check plus_assoc.
Module NatList.

(* ###################################################### *)
(** * Pairs of Numbers *)

(** In an [Inductive] type definition, each constructor can take
    any number of arguments -- none (as with [true] and [O]), one (as
    with [S]), or more than one, as in this definition: *)

Inductive natprod : Type :=
  pair : nat -> nat -> natprod.

(** This declaration can be read: "There is just one way to
    construct a pair of numbers: by applying the constructor [pair] to
    two arguments of type [nat]." *)

(** We can construct an element of [natprod] like this: *)

Check (pair 3 5).

(** *** *)

(** Here are two simple function definitions for extracting the
    first and second components of a pair.  (The definitions also
    illustrate how to do pattern matching on two-argument
    constructors.) *)

Definition fst (p : natprod) : nat :=
  match p with
  | pair x y => x
  end.
Definition snd (p : natprod) : nat :=
  match p with
  | pair x y => y
  end.

Eval compute in (fst (pair 3 5)).
(* ===> 3 *)

(** *** *)

(** Since pairs are used quite a bit, it is nice to be able to
    write them with the standard mathematical notation [(x,y)] instead
    of [pair x y].  We can tell Coq to allow this with a [Notation]
    declaration. *)

Notation "( x , y )" := (pair x y).

(** The new notation can be used both in expressions and in
    pattern matches (indeed, we've seen it already in the previous
    chapter -- this notation is provided as part of the standard
    library): *)

Eval compute in (fst (3,5)).

Definition fst' (p : natprod) : nat :=
  match p with
  | (x,y) => x
  end.
Definition snd' (p : natprod) : nat :=
  match p with
  | (x,y) => y
  end.

Definition swap_pair (p : natprod) : natprod :=
  match p with
  | (x,y) => (y,x)
  end.

(** *** *)

(** Let's try and prove a few simple facts about pairs.  If we
    state the lemmas in a particular (and slightly peculiar) way, we
    can prove them with just reflexivity (and its built-in
    simplification): *)

Theorem surjective_pairing' : forall (n m : nat),
  (n,m) = (fst (n,m), snd (n,m)).
Proof.
  reflexivity.  Qed.

(** Note that [reflexivity] is not enough if we state the lemma in a
    more natural way: *)

Theorem surjective_pairing_stuck : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  simpl. (* Doesn't reduce anything! *)
Abort.

(** *** *)
(** We have to expose the structure of [p] so that [simpl] can
    perform the pattern match in [fst] and [snd].  We can do this with
    [destruct].

    Notice that, unlike for [nat]s, [destruct] doesn't generate an
    extra subgoal here.  That's because [natprod]s can only be
    constructed in one way.  *)

Theorem surjective_pairing : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.

(** **** Exercise: 1 star (snd_fst_is_swap)  *)
Theorem snd_fst_is_swap : forall (p : natprod),
  (snd p, fst p) = swap_pair p.
Proof.
  intros p. destruct p as [n m].
  simpl. reflexivity. Qed.
(** [] *)

(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)
Theorem fst_swap_is_snd : forall (p : natprod),
  fst (swap_pair p) = snd p.
Proof.
  intros p. destruct p as [n m].
  simpl. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** * Lists of Numbers *)

(** Generalizing the definition of pairs a little, we can
    describe the type of _lists_ of numbers like this: "A list is
    either the empty list or else a pair of a number and another
    list." *)

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

(** For example, here is a three-element list: *)

Definition mylist := cons 1 (cons 2 (cons 3 nil)).
Check mylist.

(** *** *)
(** As with pairs, it is more convenient to write lists in
    familiar programming notation.  The following two declarations
    allow us to use [::] as an infix [cons] operator and square
    brackets as an "outfix" notation for constructing lists. *)

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

(** It is not necessary to fully understand these declarations,
    but in case you are interested, here is roughly what's going on.

    The [right associativity] annotation tells Coq how to parenthesize
    expressions involving several uses of [::] so that, for example,
    the next three declarations mean exactly the same thing: *)

Definition mylist1 := 1 :: (2 :: (3 :: nil)).
Definition mylist2 := 1 :: 2 :: 3 :: nil.
Definition mylist3 := [1;2;3].

(** The [at level 60] part tells Coq how to parenthesize
    expressions that involve both [::] and some other infix operator.
    For example, since we defined [+] as infix notation for the [plus]
    function at level 50,
Notation "x + y" := (plus x y)
                    (at level 50, left associativity).
   The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]
   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1
   + (2 :: [3])].

   (By the way, it's worth noting in passing that expressions like "[1
   + 2 :: [3]]" can be a little confusing when you read them in a .v
   file.  The inner brackets, around 3, indicate a list, but the outer
   brackets, which are invisible in the HTML rendering, are there to
   instruct the "coqdoc" tool that the bracketed part should be
   displayed as Coq code rather than running text.)

   The second and third [Notation] declarations above introduce the
   standard square-bracket notation for lists; the right-hand side of
   the third one illustrates Coq's syntax for declaring n-ary
   notations and translating them to nested sequences of binary
   constructors. *)

(** *** Repeat *)
(** A number of functions are useful for manipulating lists.
    For example, the [repeat] function takes a number [n] and a
    [count] and returns a list of length [count] where every element
    is [n]. *)

Fixpoint repeat (n count : nat) : natlist :=
  match count with
  | O => nil
  | S count' => n :: (repeat n count')
  end.
Eval compute in (repeat 3 5).
(** *** Length *)
(** The [length] function calculates the length of a list. *)

Fixpoint length (l:natlist) : nat :=
  match l with
  | nil => O
  | h :: t => S (length t)
  end.
Eval compute in (length [1;1;1;1]).

(** *** Append *)
(** The [app] ("append") function concatenates two lists. *)

Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil    => l2
  | h :: t => h :: (app t l2)
  end.
Eval compute in (app [1;2] [2;3;4]).
(** Actually, [app] will be used a lot in some parts of what
    follows, so it is convenient to have an infix operator for it. *)

Notation "x ++ y" := (app x y)
                     (right associativity, at level 60).

Example test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].
Proof. reflexivity.  Qed.
Example test_app2:             nil ++ [4;5] = [4;5].
Proof. reflexivity.  Qed.
Example test_app3:             [1;2;3] ++ nil = [1;2;3].
Proof. reflexivity.  Qed.

(** Here are two smaller examples of programming with lists.
    The [hd] function returns the first element (the "head") of the
    list, while [tl] returns everything but the first
    element (the "tail").
    Of course, the empty list has no first element, so we
    must pass a default value to be returned in that case.  *)

(** *** Head (with default) and Tail *)
Definition hd (default:nat) (l:natlist) : nat :=
  match l with
  | nil => default
  | h :: t => h
  end.

Definition tl (l:natlist) : natlist :=
  match l with
  | nil => nil
  | h :: t => t
  end.

Example test_hd1:             hd 0 [1;2;3] = 1.
Proof. reflexivity.  Qed.
Example test_hd2:             hd 0 [] = 0.
Proof. reflexivity.  Qed.
Example test_tl:              tl [1;2;3] = [2;3].
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (list_funs)  *)
(** Complete the definitions of [nonzeros], [oddmembers] and
    [countoddmembers] below. Have a look at the tests to understand
    what these functions should do. *)

Fixpoint nonzeros (l:natlist) : natlist :=
match l with
| nil => nil
| h :: t => match h with
            | O => nonzeros t
            | S n' => S n' :: (nonzeros t)
            end
end.

Example test_nonzeros:            nonzeros [0;1;0;2;3;0;0] = [1;2;3].
Proof. simpl. reflexivity. Qed.

Fixpoint oddmembers (l:natlist) : natlist :=
match l with
| nil => nil
| h :: t => if(oddb h) then h::(oddmembers t) else oddmembers t
end.

Example test_oddmembers:            oddmembers [0;1;0;2;3;0;0] = [1;3].
Proof. simpl. reflexivity. Qed.

Fixpoint countoddmembers (l:natlist) : nat :=
match l with
| nil => O
| h :: t => if(oddb h) then (plus (S O) (countoddmembers t)) else countoddmembers t
end.

Example test_countoddmembers1:    countoddmembers [1;0;3;1;4;5] = 4.
Proof. simpl. reflexivity. Qed.

Example test_countoddmembers2:    countoddmembers [0;2;4] = 0.
Proof. simpl. reflexivity. Qed.
Example test_countoddmembers3:    countoddmembers nil = 0.
Proof. reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (alternate)  *)
(** Complete the definition of [alternate], which "zips up" two lists
    into one, alternating between elements taken from the first list
    and elements from the second.  See the tests below for more
    specific examples.

    Note: one natural and elegant way of writing [alternate] will fail
    to satisfy Coq's requirement that all [Fixpoint] definitions be
    "obviously terminating."  If you find yourself in this rut, look
    for a slightly more verbose solution that considers elements of
    both lists at the same time.  (One possible solution requires
    defining a new kind of pairs, but this is not the only way.)  *)

Fixpoint alternate (l1 l2 : natlist) : natlist :=
match l1 with
| nil => l2
| h :: t => match l2 with
            | nil => h :: t
            | h' :: t' => h::h'::(alternate t t')
            end
end.
Example test_alternate1:        alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
Proof. simpl. reflexivity. Qed.
Example test_alternate2:        alternate [1] [4;5;6] = [1;4;5;6].
Proof. simpl. reflexivity. Qed.
Example test_alternate3:        alternate [1;2;3] [4] = [1;4;2;3].
Proof. simpl. reflexivity. Qed.
Example test_alternate4:        alternate [] [20;30] = [20;30].
Proof. simpl. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** ** Bags via Lists *)

(** A [bag] (or [multiset]) is like a set, but each element can appear
    multiple times instead of just once.  One reasonable
    implementation of bags is to represent a bag of numbers as a
    list. *)

Definition bag := natlist.

(** **** Exercise: 3 stars (bag_functions)  *)
(** Complete the following definitions for the functions
    [count], [sum], [add], and [member] for bags. *)

Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil => O
| h :: t=> if(beq_nat v h) then (plus (S O) (count v t)) else (count v t)
end.
(** All these proofs can be done just by [reflexivity]. *)

Example test_count1:              count 1 [1;2;3;1;4;1] = 3.
Proof. simpl. reflexivity. Qed.
Example test_count2:              count 6 [1;2;3;1;4;1] = 0.
Proof. simpl. reflexivity. Qed.

(** Multiset [sum] is similar to set [union]: [sum a b] contains
    all the elements of [a] and of [b].  (Mathematicians usually
    define [union] on multisets a little bit differently, which
    is why we don't use that name for this operation.)
    For [sum] we're giving you a header that does not give explicit
    names to the arguments.  Moreover, it uses the keyword
    [Definition] instead of [Fixpoint], so even if you had names for
    the arguments, you wouldn't be able to process them recursively.
    The point of stating the question this way is to encourage you to
    think about whether [sum] can be implemented in another way --
    perhaps by using functions that have already been defined.  *)

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

Example test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.
Proof. simpl. reflexivity. Qed.

Definition add (v:nat) (s:bag) : bag := v::s.
Example test_add1:                count 1 (add 1 [1;4;1]) = 3.
Proof. simpl. reflexivity. Qed.
Example test_add2:                count 5 (add 1 [1;4;1]) = 0.
Proof. simpl. reflexivity. Qed.

Definition member (v:nat) (s:bag) : bool := ble_nat 1 (count v s).
Example test_member1:             member 1 [1;4;1] = true.
Proof. simpl. reflexivity. Qed.
Example test_member2:             member 2 [1;4;1] = false.
Proof. simpl. reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (bag_more_functions)  *)
(** Here are some more bag functions for you to practice with. *)

Fixpoint remove_one (v:nat) (s:bag) : bag :=
match s with
| nil => nil
| h :: t => if(beq_nat v h) then t else h :: (remove_one v t)
end.

Example test_remove_one1:         count 5 (remove_one 5 [2;1;5;4;1]) = 0.
Proof. simpl. reflexivity. Qed.
Example test_remove_one2:         count 5 (remove_one 5 [2;1;4;1]) = 0.
Proof. simpl. reflexivity. Qed.
Eval compute in (remove_one 5 [2;1;4;5;1;4]).
Example test_remove_one3:         count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
Proof. simpl. reflexivity. Qed.
Example test_remove_one4:         count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
Proof. simpl. reflexivity. Qed.
Eval compute in (remove_one 1 [1;1;1;1;2;3]).

Fixpoint remove_all (v:nat) (s:bag) : bag :=
match s with
| nil => nil
| h :: t => if beq_nat v h then remove_all v t else h :: (remove_all v t)
end.
Example test_remove_all1:          count 5 (remove_all 5 [2;1;5;4;1]) = 0.
Proof. simpl. reflexivity. Qed.
Example test_remove_all2:          count 5 (remove_all 5 [2;1;4;1]) = 0.
Proof. simpl. reflexivity. Qed.
Example test_remove_all3:          count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
Proof. simpl. reflexivity. Qed.
Example test_remove_all4:          count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
Proof. simpl. reflexivity. Qed.

Fixpoint subset (s1:bag) (s2:bag) : bool :=
match s1 with
| nil => true
| h :: t => if ble_nat (count h s1) (count h s2) then subset t s2 else false
end.
Example test_subset1:              subset [1;2] [2;1;4;1] = true.
Proof. simpl. reflexivity. Qed.
Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
Proof. simpl. reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars (bag_theorem)  *)
(** Write down an interesting theorem [bag_theorem] about bags involving
    the functions [count] and [add], and prove it.  Note that, since this
    problem is somewhat open-ended, it's possible that you may come up
    with a theorem which is true, but whose proof requires techniques
    you haven't learned yet.  Feel free to ask for help if you get
    stuck! *)
Theorem bag_theorem : forall n:nat, forall s:bag,
count n (add n s) = (count n s) + 1.
Proof.
  intros.
  simpl.
  rewrite <- beq_nat_refl.
  rewrite <- plus_comm.
  simpl.
  reflexivity.
Qed.
(* FILL IN HERE *)
(** [] *)

(* ###################################################### *)
(** * Reasoning About Lists *)

(** Just as with numbers, simple facts about list-processing
    functions can sometimes be proved entirely by simplification. For
    example, the simplification performed by [reflexivity] is enough
    for this theorem... *)

Theorem nil_app : forall l:natlist,
  [] ++ l = l.
Proof. reflexivity. Qed.

(** ... because the [[]] is substituted into the match position
    in the definition of [app], allowing the match itself to be
    simplified. *)

(** Also, as with numbers, it is sometimes helpful to perform case
    analysis on the possible shapes (empty or non-empty) of an unknown
    list. *)

Theorem tl_length_pred : forall l:natlist,
  pred (length l) = length (tl l).
Proof.
  intros l. destruct l as [| n l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n l'".
    reflexivity.  Qed.

(** Here, the [nil] case works because we've chosen to define
    [tl nil = nil]. Notice that the [as] annotation on the [destruct]
    tactic here introduces two names, [n] and [l'], corresponding to
    the fact that the [cons] constructor for lists takes two
    arguments (the head and tail of the list it is constructing). *)

(** Usually, though, interesting theorems about lists require
    induction for their proofs. *)

(* ###################################################### *)
(** ** Micro-Sermon *)

(** Simply reading example proof scripts will not get you very far!
    It is very important to work through the details of each one,
    using Coq and thinking about what each step achieves.  Otherwise
    it is more or less guaranteed that the exercises will make no
    sense... *)

(* ###################################################### *)
(** ** Induction on Lists *)

(** Proofs by induction over datatypes like [natlist] are
    perhaps a little less familiar than standard natural number
    induction, but the basic idea is equally simple.  Each [Inductive]
    declaration defines a set of data values that can be built up from
    the declared constructors: a boolean can be either [true] or
    [false]; a number can be either [O] or [S] applied to a number; a
    list can be either [nil] or [cons] applied to a number and a list.

    Moreover, applications of the declared constructors to one another
    are the _only_ possible shapes that elements of an inductively
    defined set can have, and this fact directly gives rise to a way
    of reasoning about inductively defined sets: a number is either
    [O] or else it is [S] applied to some _smaller_ number; a list is
    either [nil] or else it is [cons] applied to some number and some
    _smaller_ list; etc. So, if we have in mind some proposition [P]
    that mentions a list [l] and we want to argue that [P] holds for
    _all_ lists, we can reason as follows:

      - First, show that [P] is true of [l] when [l] is [nil].

      - Then show that [P] is true of [l] when [l] is [cons n l'] for
        some number [n] and some smaller list [l'], assuming that [P]
        is true for [l'].

    Since larger lists can only be built up from smaller ones,
    eventually reaching [nil], these two things together establish the
    truth of [P] for all lists [l].  Here's a concrete example: *)

Theorem app_assoc : forall l1 l2 l3 : natlist,
  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
Proof.
  intros l1 l2 l3. induction l1 as [| n l1'].
  Case "l1 = nil".
    reflexivity.
  Case "l1 = cons n l1'".
    simpl. rewrite -> IHl1'. reflexivity.  Qed.

(** Again, this Coq proof is not especially illuminating as a
    static written document -- it is easy to see what's going on if
    you are reading the proof in an interactive Coq session and you
    can see the current goal and context at each point, but this state
    is not visible in the written-down parts of the Coq proof.  So a
    natural-language proof -- one written for human readers -- will
    need to include more explicit signposts; in particular, it will
    help the reader stay oriented if we remind them exactly what the
    induction hypothesis is in the second case.  *)

(** *** Informal version *)

(** _Theorem_: For all lists [l1], [l2], and [l3],
   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].

   _Proof_: By induction on [l1].

   - First, suppose [l1 = []].  We must show
       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),
     which follows directly from the definition of [++].

   - Next, suppose [l1 = n::l1'], with
       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)
     (the induction hypothesis). We must show
       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).
]]
     By the definition of [++], this follows from
       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),
     which is immediate from the induction hypothesis.  []
*)

(** *** Another example *)
(**
  Here is a similar example to be worked together in class: *)

Theorem app_length : forall l1 l2 : natlist,
  length (l1 ++ l2) = (length l1) + (length l2).
Proof.
  (* WORKED IN CLASS *)
  intros l1 l2. induction l1 as [| n l1'].
  Case "l1 = nil".
    reflexivity.
  Case "l1 = cons".
    simpl. rewrite -> IHl1'. reflexivity.  Qed.

(** *** Reversing a list *)
(** For a slightly more involved example of an inductive proof
    over lists, suppose we define a "cons on the right" function
    [snoc] like this... *)

Fixpoint snoc (l:natlist) (v:nat) : natlist :=
  match l with
  | nil    => [v]
  | h :: t => h :: (snoc t v)
  end.
Eval compute in (snoc [1;2;3] 4).

(** ... and use it to define a list-reversing function [rev]
    like this: *)

Fixpoint rev (l:natlist) : natlist :=
  match l with
  | nil    => nil
  | h :: t => snoc (rev t) h
  end.
Eval compute in (rev [1;2;3;4]).

Example test_rev1:            rev [1;2;3] = [3;2;1].
Proof. reflexivity.  Qed.
Example test_rev2:            rev nil = nil.
Proof. reflexivity.  Qed.

(** *** Proofs about reverse *)
(** Now let's prove some more list theorems using our newly
    defined [snoc] and [rev].  For something a little more challenging
    than the inductive proofs we've seen so far, let's prove that
    reversing a list does not change its length.  Our first attempt at
    this proof gets stuck in the successor case... *)

Theorem rev_length_firsttry : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l'].
  Case "l = []".
    simpl.
    reflexivity.
  Case "l = n :: l'".
    (* This is the tricky case.  Let's begin as usual
       by simplifying. *)
    simpl.
    (* Now we seem to be stuck: the goal is an equality
       involving [snoc], but we don't have any equations
       in either the immediate context or the global
       environment that have anything to do with [snoc]!

       We can make a little progress by using the IH to
       rewrite the goal... *)
    rewrite <- IHl'.
    (* ... but now we can't go any further. *)
Abort.

(** So let's take the equation about [snoc] that would have
    enabled us to make progress and prove it as a separate lemma.
*)

Theorem length_snoc : forall n : nat, forall l : natlist,
  length (snoc l n) = S (length l).
Proof.
  intros n l. induction l as [| n' l'].
  Case "l = nil".
    simpl.
    reflexivity.
  Case "l = cons n' l'".
    simpl. rewrite -> IHl'. reflexivity.  Qed.

(**
    Note that we make the lemma as _general_ as possible: in particular,
    we quantify over _all_ [natlist]s, not just those that result
    from an application of [rev]. This should seem natural,
    because the truth of the goal clearly doesn't depend on
    the list having been reversed.  Moreover, it is much easier
    to prove the more general property.
*)

(** Now we can complete the original proof. *)

Theorem rev_length : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l'].
  Case "l = nil".
    simpl.
    reflexivity.
  Case "l = cons".
    simpl. rewrite -> length_snoc.
    rewrite -> IHl'. reflexivity.  Qed.

(** For comparison, here are informal proofs of these two theorems:

    _Theorem_: For all numbers [n] and lists [l],
       [length (snoc l n) = S (length l)].

    _Proof_: By induction on [l].

    - First, suppose [l = []].  We must show
        length (snoc [] n) = S (length []),
      which follows directly from the definitions of
      [length] and [snoc].

    - Next, suppose [l = n'::l'], with
        length (snoc l' n) = S (length l').
      We must show
        length (snoc (n' :: l') n) = S (length (n' :: l')).
      By the definitions of [length] and [snoc], this
      follows from
        S (length (snoc l' n)) = S (S (length l')),
]]
      which is immediate from the induction hypothesis. [] *)

(** _Theorem_: For all lists [l], [length (rev l) = length l].

    _Proof_: By induction on [l].

      - First, suppose [l = []].  We must show
          length (rev []) = length [],
        which follows directly from the definitions of [length]
        and [rev].

      - Next, suppose [l = n::l'], with
          length (rev l') = length l'.
        We must show
          length (rev (n :: l')) = length (n :: l').
        By the definition of [rev], this follows from
          length (snoc (rev l') n) = S (length l')
        which, by the previous lemma, is the same as
          S (length (rev l')) = S (length l').
        This is immediate from the induction hypothesis. [] *)

(** Obviously, the style of these proofs is rather longwinded
    and pedantic.  After the first few, we might find it easier to
    follow proofs that give fewer details (since we can easily work
    them out in our own minds or on scratch paper if necessary) and
    just highlight the non-obvious steps.  In this more compressed
    style, the above proof might look more like this: *)

(** _Theorem_:
     For all lists [l], [length (rev l) = length l].

    _Proof_: First, observe that
       length (snoc l n) = S (length l)
     for any [l].  This follows by a straightforward induction on [l].
     The main property now follows by another straightforward
     induction on [l], using the observation together with the
     induction hypothesis in the case where [l = n'::l']. [] *)

(** Which style is preferable in a given situation depends on
    the sophistication of the expected audience and on how similar the
    proof at hand is to ones that the audience will already be
    familiar with.  The more pedantic style is a good default for
    present purposes. *)

(* ###################################################### *)
(** ** [SearchAbout] *)

(** We've seen that proofs can make use of other theorems we've
    already proved, using [rewrite], and later we will see other ways
    of reusing previous theorems.  But in order to refer to a theorem,
    we need to know its name, and remembering the names of all the
    theorems we might ever want to use can become quite difficult!  It
    is often hard even to remember what theorems have been proven,
    much less what they are named.

    Coq's [SearchAbout] command is quite helpful with this.  Typing
    [SearchAbout foo] will cause Coq to display a list of all theorems
    involving [foo].  For example, try uncommenting the following to
    see a list of theorems that we have proved about [rev]: *)

(*  SearchAbout rev. *)

(** Keep [SearchAbout] in mind as you do the following exercises and
    throughout the rest of the course; it can save you a lot of time! *)

(** Also, if you are using ProofGeneral, you can run [SearchAbout]
    with [C-c C-a C-a]. Pasting its response into your buffer can be
    accomplished with [C-c C-;]. *)

(* ###################################################### *)
(** ** List Exercises, Part 1 *)

(** **** Exercise: 3 stars (list_exercises)  *)
(** More practice with lists. *)

Theorem app_nil_end : forall l : natlist,
  l ++ [] = l.
Proof.
  intros l. induction l as [| n l'].
  Case "l = nil".
  simpl. reflexivity.
  Case "l = n :: l'".
  simpl. rewrite -> IHl'.
  reflexivity.
Qed.
Theorem rev_snoc : forall l: natlist, forall n: nat,
rev (snoc l n) = n :: (rev l).
Proof.
  intros l n. induction l.
  Case "l = nil".
  simpl. reflexivity.
  Case "l = cons".
  simpl.
  rewrite -> IHl.
  simpl. reflexivity.
Qed.
Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  intros l. induction l as [| n l].
  Case "l = nil".
  simpl. reflexivity.
  Case "l = n :: l".
  simpl.
  rewrite -> rev_snoc.
  simpl. rewrite -> IHl.
  reflexivity.
Qed.

(** There is a short solution to the next exercise.  If you find
    yourself getting tangled up, step back and try to look for a
    simpler way. *)

Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,
  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.
Proof.
  intros.
  rewrite -> app_assoc.
  rewrite -> app_assoc.
  reflexivity.
Qed.

Theorem snoc_append : forall (l:natlist) (n:nat),
  snoc l n = l ++ [n].
Proof.
  intros. induction l as [| n' l'].
  Case "l = nil".
  simpl.
  reflexivity.
  Case "l = n l".
  simpl.
  rewrite -> IHl'.
  reflexivity.
Qed.

Theorem distr_rev : forall l1 l2 : natlist,
  rev (l1 ++ l2) = (rev l2) ++ (rev l1).
Proof.
  intros. induction l1 as [| n l'].
  Case "l1 = nil".
  simpl. rewrite -> app_nil_end.
  reflexivity.
  Case "l1 = cons".
  simpl. rewrite -> IHl'.
  rewrite -> snoc_append.
  rewrite -> snoc_append.
  rewrite -> app_assoc.
  reflexivity.
Qed.

(** An exercise about your implementation of [nonzeros]: *)

Lemma nonzeros_app : forall l1 l2 : natlist,
  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
Proof.
  intros.
  induction l1.
  Case "l1 = nil".
  simpl.
  reflexivity.
  Case "l1 = cons".
  simpl.
  rewrite -> IHl1.
  destruct n.
  SCase "n = O".
  simpl. reflexivity.
  SCase "n = S O".
  simpl. reflexivity.
Qed.

(** **** Exercise: 2 stars (beq_natlist)  *)
(** Fill in the definition of [beq_natlist], which compares
    lists of numbers for equality.  Prove that [beq_natlist l l]
    yields [true] for every list [l]. *)

Fixpoint beq_natlist (l1 l2 : natlist) : bool :=
match l1 with
| nil => match l2 with
         | nil => true
         | _ => false
         end
| h :: t => match l2 with
            | nil => false
            | h' :: t' => if beq_nat h h' then beq_natlist t t' else false
            end
end.

Example test_beq_natlist1 :   (beq_natlist nil nil = true).
Proof. reflexivity. Qed.
Example test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.
Proof. reflexivity. Qed.
Example test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.
Proof. reflexivity. Qed.
Theorem beq_natlist_refl : forall l:natlist,
  true = beq_natlist l l.
Proof.
  intros. induction l.
  Case "l = nil".
  simpl. reflexivity.
  Case "l = cons".
  simpl. rewrite <- beq_nat_refl.
  rewrite -> IHl.
  reflexivity.
Qed.
(** [] *)

(* ###################################################### *)
(** ** List Exercises, Part 2 *)

(** **** Exercise: 2 stars (list_design)  *)
(** Design exercise:
     - Write down a non-trivial theorem [cons_snoc_app]
       involving [cons] ([::]), [snoc], and [app] ([++]).
     - Prove it. *)
Theorem app_cons_snoc_app: forall l1 l2:natlist, forall n:nat,
l1 ++ (n::l2) = (snoc l1 n) ++ l2.
Proof.
  intros.
  rewrite -> snoc_append.
  rewrite -> app_assoc.
  assert (H: n :: l2 = [n] ++ l2).
    Case "Proof of H".
    simpl. reflexivity.
  rewrite -> H.
  reflexivity.
Qed.
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 3 stars, advanced (bag_proofs)  *)
(** Here are a couple of little theorems to prove about your
    definitions about bags earlier in the file. *)

Theorem count_member_nonzero : forall (s : bag),
  ble_nat 1 (count 1 (1 :: s)) = true.
Proof.
  intros.
  destruct s.
  Case "s = nil".
  simpl. reflexivity.
  Case "s = cons".
  simpl. reflexivity.
Qed.

(** The following lemma about [ble_nat] might help you in the next proof. *)

Theorem ble_n_Sn : forall n,
  ble_nat n (S n) = true.
Proof.
  intros n. induction n as [| n'].
  Case "0".
    simpl.  reflexivity.
  Case "S n'".
    simpl.  rewrite IHn'.  reflexivity.  Qed.

Theorem remove_decreases_count: forall (s : bag),
  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.
Proof.
  intros.
  induction s.
  Case "s = nil".
  simpl. reflexivity.
  Case "s = cons".
  simpl.
  destruct n.
  SCase "n = O".
  rewrite -> ble_n_Sn. reflexivity.
  SCase "n = S n".
  simpl.
  rewrite -> IHs.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (bag_count_sum)  *)
(** Write down an interesting theorem [bag_count_sum] about bags
    involving the functions [count] and [sum], and prove it.*)
Theorem bag_sum_count: forall s1 s2:bag, forall n:nat,
count n (sum s1 s2) = (count n s1) + (count n s2).
Proof.
  intros s1 s2 n. induction s1 as [| h1 t1].
  Case "s1 = []". reflexivity.
  Case "s1 = h1::t1".
  simpl. rewrite IHt1.
  destruct (beq_nat n h1) as [false | true].
  SCase "beq_nat n h1 = false".
  simpl. reflexivity.
  SCase "beq_nat n h1 = true".
  reflexivity.
Qed.
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 4 stars, advanced (rev_injective)  *)
(** Prove that the [rev] function is injective, that is,

    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.

There is a hard way and an easy way to solve this exercise.
*)
Theorem rev_injective: forall l1 l2:natlist,
rev l1 = rev l2 -> l1 = l2.
Proof.
  intros.
  rewrite <- rev_involutive.
  rewrite <- H.
  rewrite -> rev_involutive.
  reflexivity.
Qed.
(* FILL IN HERE *)
(** [] *)

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

(** One use of [natoption] is as a way of returning "error
    codes" from functions.  For example, suppose we want to write a
    function that returns the [n]th element of some list.  If we give
    it type [nat -> natlist -> nat], then we'll have to return some
    number when the list is too short! *)

Fixpoint index_bad (n:nat) (l:natlist) : nat :=
  match l with
  | nil => 42  (* arbitrary! *)
  | a :: l' => match beq_nat n O with
               | true => a
               | false => index_bad (pred n) l'
               end
  end.
Eval compute in (index_bad 2 [1;2;3;4]).
(** *** *)
(** On the other hand, if we give it type [nat -> natlist ->
    natoption], then we can return [None] when the list is too short
    and [Some a] when the list has enough members and [a] appears at
    position [n]. *)

Inductive natoption : Type :=
  | Some : nat -> natoption
  | None : natoption.

Fixpoint index (n:nat) (l:natlist) : natoption :=
  match l with
  | nil => None
  | a :: l' => match beq_nat n O with
               | true => Some a
               | false => index (pred n) l'
               end
  end.
Eval compute in (index 2 [1;2;2]).

Example test_index1 :    index 0 [4;5;6;7]  = Some 4.
Proof. reflexivity.  Qed.
Example test_index2 :    index 3 [4;5;6;7]  = Some 7.
Proof. reflexivity.  Qed.
Example test_index3 :    index 10 [4;5;6;7] = None.
Proof. reflexivity.  Qed.

(** This example is also an opportunity to introduce one more
    small feature of Coq's programming language: conditional
    expressions... *)

(** *** *)

Fixpoint index' (n:nat) (l:natlist) : natoption :=
  match l with
  | nil => None
  | a :: l' => if beq_nat n O then Some a else index' (pred n) l'
  end.

(** Coq's conditionals are exactly like those found in any other
    language, with one small generalization.  Since the boolean type
    is not built in, Coq actually allows conditional expressions over
    _any_ inductively defined type with exactly two constructors.  The
    guard is considered true if it evaluates to the first constructor
    in the [Inductive] definition and false if it evaluates to the
    second. *)

(** The function below pulls the [nat] out of a [natoption], returning
    a supplied default in the [None] case. *)

Definition option_elim (d : nat) (o : natoption) : nat :=
  match o with
  | Some n' => n'
  | None => d
  end.
Eval compute in (option_elim 1 None).

(** **** Exercise: 2 stars (hd_opt)  *)
(** Using the same idea, fix the [hd] function from earlier so we don't
   have to pass a default element for the [nil] case.  *)

Definition hd_opt (l : natlist) : natoption :=
match l with
| nil => None
| h::t=> Some h
end.

Example test_hd_opt1 : hd_opt [] = None.
Proof. reflexivity. Qed.
Example test_hd_opt2 : hd_opt [1] = Some 1.
Proof. reflexivity. Qed.
Example test_hd_opt3 : hd_opt [5;6] = Some 5.
Proof. reflexivity. Qed.
(** [] *)

(** **** Exercise: 1 star, optional (option_elim_hd)  *)
(** This exercise relates your new [hd_opt] to the old [hd]. *)

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_opt l).
Proof.
  intros.
  induction l.
  simpl. reflexivity.
  simpl. reflexivity.
Qed.
(** [] *)

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

(** As a final illustration of how fundamental data structures
    can be defined in Coq, here is the declaration of a simple
    [dictionary] data type, using numbers for both the keys and the
    values stored under these keys.  (That is, a dictionary represents
    a finite map from numbers to numbers.) *)

Module Dictionary.

Inductive dictionary : Type :=
  | empty  : dictionary
  | record : nat -> nat -> dictionary -> dictionary.

(** This declaration can be read: "There are two ways to construct a
    [dictionary]: either using the constructor [empty] to represent an
    empty dictionary, or by applying the constructor [record] to
    a key, a value, and an existing [dictionary] to construct a
    [dictionary] with an additional key to value mapping." *)

Definition insert (key value : nat) (d : dictionary) : dictionary :=
  (record key value d).
Eval compute in (insert 1 2 (record 3 4 empty)).

(** Here is a function [find] that searches a [dictionary] for a
    given key.  It evaluates evaluates to [None] if the key was not
    found and [Some val] if the key was mapped to [val] in the
    dictionary. If the same key is mapped to multiple values, [find]
    will return the first one it finds. *)

Fixpoint find (key : nat) (d : dictionary) : natoption :=
  match d with
  | empty         => None
  | record k v d' => if (beq_nat key k)
                       then (Some v)
                       else (find key d')
  end.
Eval compute in (find 1 empty).
Eval compute in (find 1 (record 1 2 empty)).

(** **** Exercise: 1 star (dictionary_invariant1)  *)
(** Complete the following proof. *)

Theorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),
  (find k (insert k v d)) = Some v.
Proof.
  intros.
  simpl.
  rewrite <- beq_nat_refl.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 1 star (dictionary_invariant2)  *)
(** Complete the following proof. *)

Theorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),
  beq_nat m n = false -> find m d = find m (insert n o d).
Proof.
  intros.
  simpl.
  rewrite -> H.
  reflexivity.
Qed.
(** [] *)

End Dictionary.

End NatList.

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


(* week-15_two-by-two-matrices.v *)
(* YSC3236 2017-2018, Sem1 *)
(* Olivier Danvy <danvy@yale-nus.edu.sg> *)
(* Version of Tue 21 Nov 2017 *)

(* ********** *)

(*
   name:Jeremy Yew
   student ID number:A0156262H
   e-mail address:jeremy.yew@u.yale-nus.edu.sg
*)

(* ********** *)

Ltac unfold_tactic name :=
  intros;
  unfold name; (* fold name; *)
  reflexivity.

Require Import Arith Bool.

(* ********** *)

(* The goal of this project is to study 2x2 matrices,
   along the lines of Section 5 of
     http://users-cs.au.dk/danvy/more-about-induction-proofs.pdf
*)

Inductive m22 : Type :=
| M22 : nat -> nat -> nat -> nat -> m22.

(*
1. Definition 9: Multiplication of 2*2 matrices
 *)

(*
|x11 x12|   |y11 y12|
|x21 x22| * |y21 y22|
 *)

Definition mul_m22 (X Y : m22) : m22 :=
  match X with
  | M22 x11 x12
        x21 x22 =>
    match Y with
    | M22 y11 y12
          y21 y22 =>
      M22 (x11 * y11 + x12 * y21) (x11 * y12 + x12 * y22)
          (x21 * y11 + x22 * y21) (x21 * y12 + x22 * y22)
    end
  end.

Compute mul_m22 (M22 1 2 3 4) (M22 1 0 0 1).

  (*
2. Addition of Matrices
*)

Definition add_m22 (X Y : m22) : m22 :=
  match X with
  | M22 x11 x12
        x21 x22 =>
    match Y with
    | M22 y11 y12
          y21 y22 =>
      M22 (x11 + y11) (x12 + y12)
          (x21 + y21) (x22 + y22)
    end
  end.

(*
3. Definitions 11 and 13
*)

Definition I :=
  M22 1 0 0 1.

Fixpoint exp_m22 (n : nat) (M : m22) : m22 :=
  match n with
  | O =>
    I
  | S n' => mul_m22 (exp_m22 n' M) M
  end.

Lemma unfold_exp_m22_O:
  forall (M : m22),
    exp_m22 0 M = I.
Proof.
  unfold_tactic exp_m22.
Qed.
Lemma unfold_exp_m22_S:
  forall (n' : nat) (M : m22),
    exp_m22 (S n') M = mul_m22 (exp_m22 n' M) M.
Proof.
  unfold_tactic exp_m22.
Qed.

(*
4. Properties 10 and 12
 *)

Lemma shuffle_helper:
  forall (n m p q : nat),
    n + m + p + q = n + p + m + q.
Proof.
  intros n m p q.
  Check (Nat.add_assoc).
  rewrite <- Nat.add_assoc.
  rewrite -> Nat.add_shuffle1.
  rewrite -> Nat.add_assoc.
  reflexivity.
Qed.

Theorem mul_m22_associative:
  forall (X Y Z : m22),
    mul_m22 X (mul_m22 Y Z) = mul_m22 (mul_m22 X Y) Z.
Proof.
  intros [x11 x12 x21 x22] [y11 y12 y21 y22] [z11 z12 z21 z22].
  unfold mul_m22.
  Check (Nat.mul_add_distr_l).
  rewrite ->8 Nat.mul_add_distr_l.
  rewrite ->8 Nat.mul_add_distr_r.
  Check (Nat.mul_assoc).
  rewrite -> 16 Nat.mul_assoc.
  rewrite ->8 Nat.add_assoc.
  rewrite -> (shuffle_helper _ (x11 * y12 * z21) (x12 * y21 * z11) _).
  rewrite -> (shuffle_helper _ (x11 * y12 * z22) (x12 * y21 * z12) _).
  rewrite -> (shuffle_helper _ (x21 * y12 * z21) (x22 * y21 * z11) _).
  rewrite -> (shuffle_helper _ (x21 * y12 * z22) (x22 * y21 * z12) _).
  reflexivity.
Qed.

Theorem I_neutral_mul_m22_l:
  forall (M : m22),
    mul_m22 I M = M.
Proof.
  intros [x11 x12 x21 x22].
  unfold I.
  unfold mul_m22.
  rewrite ->4 Nat.mul_1_l.
  rewrite ->4 Nat.mul_0_l.
  rewrite ->2 Nat.add_0_l.
  rewrite ->2 Nat.add_0_r.
  reflexivity.
Qed.

Theorem I_neutral_mul_m22_r:
  forall (M : m22),
    mul_m22 M I = M.
Proof.
  intros [x11 x12 x21 x22].
  unfold I.
  unfold mul_m22.
  rewrite ->4 Nat.mul_1_r.
  rewrite ->4 Nat.mul_0_r.
  rewrite ->2 Nat.add_0_l.
  rewrite ->2 Nat.add_0_r.
  reflexivity.
Qed.

(*
5.
Proposition 14
*)

Proposition exponentiation_M22_1101:
  forall (n : nat),
    exp_m22 n (M22 1 1 0 1) = (M22 1 n 0 1).
Proof.
  intro n.
  induction n as [ | n' IHn'].
  rewrite -> unfold_exp_m22_O.
  unfold I.
  reflexivity.

  rewrite -> unfold_exp_m22_S.
  rewrite -> IHn'.
  unfold mul_m22.
  rewrite -> Nat.mul_0_l.
  rewrite ->2 Nat.mul_0_r.
  rewrite ->2 Nat.mul_1_r.
  rewrite ->2 Nat.add_0_r.
  rewrite -> Nat.add_0_l.
  rewrite -> Nat.add_1_l at 1.
  reflexivity.
Qed.
(*
6. Exercise 28
*)

Fixpoint exp_m22_alt (n : nat) (M : m22) : m22 :=
  match n with
  | O =>
    I
  | S n' => mul_m22 M (exp_m22_alt n' M)
  end.

Lemma unfold_exp_m22_alt_O:
  forall (M : m22),
    exp_m22_alt 0 M = I.
Proof.
  unfold_tactic exp_m22_alt.
Qed.
Lemma unfold_exp_m22_alt_S:
  forall (n' : nat) (M : m22),
    exp_m22_alt (S n') M = mul_m22 M (exp_m22_alt n' M).
Proof.
  unfold_tactic exp_m22_alt.
Qed.

Proposition exponentiation_M22_1101':
  forall (n : nat),
    exp_m22_alt n (M22 1 1 0 1) = (M22 1 n 0 1).
Proof.
  intro n.
  induction n as [ | n' IHn'].
  rewrite -> unfold_exp_m22_alt_O.
  unfold I.
  reflexivity.

  rewrite -> unfold_exp_m22_alt_S.
  rewrite -> IHn'.
  unfold mul_m22.
  rewrite ->2 Nat.mul_0_l.
  rewrite -> Nat.mul_0_r.
  rewrite -> Nat.mul_1_r.
  rewrite -> Nat.mul_1_l.
  rewrite ->2 Nat.add_0_r.
  rewrite -> Nat.add_0_l.
  rewrite -> Nat.add_1_r.
  reflexivity.
Qed.

(*
7. Proposition 29
*)

Proposition about_exp_m22_S:
  forall (n : nat) (M : m22),
    mul_m22 M (exp_m22 n M) = mul_m22 (exp_m22 n M) M.
Proof.
  intros n M.
  induction n as [ | n' IHn'].

  rewrite -> unfold_exp_m22_O.
  rewrite -> I_neutral_mul_m22_l.
  rewrite -> I_neutral_mul_m22_r.
  reflexivity.

  rewrite -> unfold_exp_m22_S.
  rewrite -> mul_m22_associative.
  rewrite -> IHn'.
  reflexivity.
Qed.

(*
8. Exercise 31
*)

Proposition about_exp_m22_S':
  forall (n : nat) (M : m22),
    mul_m22 M (exp_m22_alt n M) = mul_m22 (exp_m22_alt n M) M.
Proof.
  intros n M.
  induction n as [ | n' IHn'].

  rewrite -> unfold_exp_m22_alt_O.
  rewrite -> I_neutral_mul_m22_l.
  rewrite -> I_neutral_mul_m22_r.
  reflexivity.

  rewrite -> unfold_exp_m22_alt_S.
  rewrite -> IHn'.
  rewrite -> mul_m22_associative.
  rewrite -> IHn'.
  reflexivity.
Qed.

(*
9. Corollary 32
*)

Corollary equivalence_of_exp_m22_and_exp_m22_alt:
  forall (n : nat) (M : m22),
    exp_m22 n M = exp_m22_alt n M.
Proof.
  intros n M.
  induction n as [ | n IHn'].

  rewrite -> unfold_exp_m22_O.
  rewrite -> unfold_exp_m22_alt_O.
  reflexivity.

  rewrite -> unfold_exp_m22_S.
  rewrite -> unfold_exp_m22_alt_S.
  rewrite <- IHn'.
  rewrite -> about_exp_m22_S.
  reflexivity.
Qed.

(*
10. Exercise 34
 *)

Proposition exponentiation_M22_1011:
  forall (n : nat),
    exp_m22 n (M22 1 0 1 1) = M22 1 0 n 1.
Proof.
  intro n.
  induction n as [ | n' IHn'].

  rewrite -> unfold_exp_m22_O.
  unfold I.
  reflexivity.

  rewrite -> unfold_exp_m22_S.
  rewrite -> IHn'.
  unfold mul_m22.
  rewrite -> Nat.mul_0_l.
  rewrite ->2 Nat.mul_0_r.
  rewrite ->2 Nat.add_0_r.
  rewrite -> Nat.add_0_l.
  rewrite ->2 Nat.mul_1_r.
  rewrite -> Nat.add_1_r at 1.
  reflexivity.
Qed.

(*
11. Definition 35
 *)

Definition transpose_m22 (M : m22) : m22 :=
 match M with
  | M22 x11 x12
        x21 x22 =>
    M22 x11 x21
        x12 x22
   end.

Compute transpose_m22 (M22 1 2 3 4).

(*
12. Proposition 36
*)

Proposition transposition_involutive:
  forall (M : m22),
    transpose_m22 (transpose_m22 M) = M.
Proof.
  intros [x11 x12 x21 x22].
  unfold transpose_m22.
  unfold transpose_m22.
  reflexivity.
Qed.

(*
13. Lemma 37
*)

Lemma transposition_distr_over_mul:
  forall (X Y : m22),
  transpose_m22 (mul_m22 X Y) = mul_m22 (transpose_m22 Y) (transpose_m22 X).
Proof.
  intros [x11 x12 x21 x22] [y11 y12 y21 y22].
  unfold mul_m22 at 1.
  unfold transpose_m22.
  unfold mul_m22.

  rewrite -> (Nat.mul_comm x11 y11).
  rewrite -> (Nat.mul_comm x12 y21).
  rewrite -> (Nat.mul_comm x21 y11).
  rewrite -> (Nat.mul_comm x22 y21).
  rewrite -> (Nat.mul_comm x11 y12).
  rewrite -> (Nat.mul_comm x12 y22).
  rewrite -> (Nat.mul_comm x21 y12).
  rewrite -> (Nat.mul_comm x22 y22).
  reflexivity.
Qed.

(*
14. Proposition 38
 *)
Proposition transp_and_exp_commutative:
  forall (n : nat) (M : m22),
    transpose_m22 (exp_m22 n M) = exp_m22 n (transpose_m22 M).
Proof.
  intros n [x11 x12 x21 x22].
  induction n as [ | n' IHn'].

  rewrite -> unfold_exp_m22_O.
  unfold transpose_m22 at 2.
  rewrite -> unfold_exp_m22_O.
  unfold I.
  unfold transpose_m22.
  reflexivity.

  unfold transpose_m22 at 2.
  rewrite ->2 unfold_exp_m22_S.
  rewrite -> transposition_distr_over_mul.
  rewrite -> IHn'.
  unfold transpose_m22.
  rewrite -> about_exp_m22_S.
  reflexivity.
Qed.

(*
15. Exercise 40
 *)

Proposition exponentiation_M22_1011':
  forall (n : nat),
    exp_m22 n (M22 1 0 1 1) = M22 1 0 n 1.
Proof.
  intro n.
  rewrite <- (transposition_involutive (M22 1 0 n 1)).
  rewrite <- (transposition_involutive (M22 1 0 1 1)).
  unfold transpose_m22 at 2.
  unfold transpose_m22 at 3.
  rewrite <- (exponentiation_M22_1101 n).
  rewrite -> transp_and_exp_commutative.
  reflexivity.
Qed.

(*
16. Exercise 25.
 *)
Definition F:= M22 1 1 1 0.
Compute (exp_m22 0 F). (* M22 1 0 0 1 *)
Compute (exp_m22 1 F). (* M22 1 1 1 0 *)
Compute (exp_m22 2 F). (* M22 2 1 1 1 *)
Compute (exp_m22 3 F). (* M22 3 2 2 1 *)
Compute (exp_m22 4 F). (* M22 5 3 3 2 *)
Compute (exp_m22 5 F). (* M22 8 5 5 3 *)
Compute (exp_m22 6 F). (* M22 13 8 8 5 *)
Compute (exp_m22 7 F). (* M22 21 13 13 8 *)
Compute (exp_m22 8 F). (* M22 34 21 21 13 *)

Notation "A =n= B" :=
  (beq_nat A B) (at level 70, right associativity).

Definition test_fib (candidate: nat -> nat) : bool :=
  (candidate 0 =n= 0)
  &&
  (candidate 1 =n= 1)
  &&
  (candidate 2 =n= 1)
  &&
  (candidate 3 =n= 2)
  &&
  (candidate 4 =n= 3)
  &&
  (candidate 5 =n= 5)
  &&
  (candidate 6 =n= 8)
  &&
  (candidate 7 =n= 13)
  &&
  (candidate 8 =n= 21)
.

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

Compute (test_fib fib).

Lemma unfold_fib_0:
  fib 0 = 0.
Proof.
  unfold_tactic fib.
Qed.

Lemma unfold_fib_1:
  fib 1 = 1.
Proof.
  unfold_tactic fib.
Qed.

Lemma unfold_fib_SSn:
  forall (n'': nat),
  fib (S (S n'')) = fib (S n'') + fib n''.
Proof.
  unfold_tactic fib.
Qed.

Proposition powers_of_F:
  forall (n : nat),
    exp_m22 (S n) F = M22 (fib (S (S n)))
                         (fib (S n))
                         (fib (S n))
                         (fib n).
Proof.
  intro n.
  induction n as [ | n' IHn'].

  unfold exp_m22.
  rewrite -> I_neutral_mul_m22_l.
  unfold F.
  rewrite -> unfold_fib_SSn.
  rewrite -> unfold_fib_0.
  rewrite -> unfold_fib_1.
  rewrite -> Nat.add_0_r.
  reflexivity.

  rewrite -> unfold_exp_m22_S.
  rewrite -> IHn'.
  unfold F.
  unfold mul_m22.
  rewrite ->3 Nat.mul_1_r.
  rewrite ->2 Nat.mul_0_r.
  rewrite ->2 Nat.add_0_r.

  rewrite ->2 unfold_fib_SSn.
  reflexivity.
Qed.

Fixpoint visit_fib_v3 (n : nat) : nat * nat :=
  match n with
  | 0 => (0, 1)
  | S n' => match visit_fib_v3 n' with
              | (a1, a2) => (a2, a1 + a2)
            end
  end.

Definition fib_v3 (n : nat) : nat :=
  match visit_fib_v3 n with
    | (a1, a2) => a1
  end.

Compute (test_fib fib_v3).

Definition fib_v4 (n : nat) : nat :=
  match exp_m22 n F with
    | M22 m11 m12 m21 m22 => m12
  end.

Compute (test_fib fib_v4).

Definition fib_v5 (n : nat) : nat :=
  match n with
  | O =>
     0
  | S n =>
    match n with
    | O =>
      1
    | S n' =>
      match (exp_m22 n' F) with
      | M22 m11 m12 m21 m22 => m11 + m12
      end
    end
  end.

Compute (test_fib fib_v5).

Proposition fibonacci_addition_of_powers_of_F:
  forall (n : nat),
    add_m22 (exp_m22 n F) (exp_m22 (S n) F) = (exp_m22 (S (S n)) F).
Proof.
  intro n.
  induction n as [ | n' IHn'].

  unfold F.
  unfold exp_m22.
  rewrite -> I_neutral_mul_m22_l.
  unfold mul_m22.
  unfold I.
  unfold add_m22.
  rewrite ->2 Nat.mul_0_r.
  rewrite -> Nat.mul_0_l.
  rewrite ->2 Nat.add_0_r.
  rewrite -> Nat.add_0_l.
  rewrite -> Nat.mul_1_r.
  rewrite -> Nat.add_1_r.
  reflexivity.

  rewrite ->3 powers_of_F.
  unfold add_m22.
  rewrite -> (Nat.add_comm (fib (S (S n'))) (fib (S (S (S n'))))).
  rewrite <- (unfold_fib_SSn (S (S n'))).
  rewrite -> (Nat.add_comm (fib (S n')) (fib (S (S n')))).
  rewrite <- (unfold_fib_SSn (S n')).
  rewrite -> (Nat.add_comm (fib n') (fib (S n'))).
  rewrite <- (unfold_fib_SSn n').
  reflexivity.
Qed.

  (*
 X * implement Definition 9 (i.e., the multiplication of 2*2-matrices),

 X * implement the addition of 2*2-matrices

 X * implement Definitions 11 and 13,

 X * prove Properties 10 and 12,

 X * formalize Proposition 14 and its proof in Coq,

 X * implement Definition 27,

 X * solve Exercise 28,

 X * formalize Proposition 29 and its proof in Coq,

 X * solve Exercise 31,

 X * implement Corollary 32,

 X * solve Exercise 34,

 X * implement Definition 35,

 X * prove Property 36,

 X * formalize Proposition 37 and its proof in Coq,

 X * formalize Proposition 38 and its proof in Coq,

 X * solve Exercise 40, and to

 X * solve Exercise 25.

 X Subsidiary question for Exercise 25:
   characterize the result of adding F^n and F^(n+1), for any n : nat
*)

(* ********** *)

(* end of week-15_two-by-two-matrices.v *)


Require Import Arith.
Require Import ArithRing Ring.

Theorem invert : forall a b : nat, a + a = b + b -> a = b.
Proof.
  induction a.
  -intros b H. destruct b.
   +auto.
   +discriminate.
  -intros b H. destruct b.
   +discriminate.
   +inversion H.
    rewrite <- plus_n_Sm in H1.
    rewrite <- plus_n_Sm in H1.
    inversion H1.
    rewrite (IHa b H2).
    auto.
Qed.

(*Tsinghua Class1*)

Definition f := fun x y => x^2+y^2.

Example f_test : f 3 4 = 25.
Proof. auto. Qed.

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

Example sum_test : sum 2 = 5.
Proof. auto. Qed.

Lemma Sn_exp : forall n : nat,
    S n = n + 1.
Proof.
  induction n.
-auto.
-simpl.
 rewrite IHn.
 auto.
Qed.

Lemma mult_distr_r : forall n m p : nat,
    n * (m + p) = n * m + n * p.
Proof.
  intros n m p.
  induction n.
  -auto.
  -simpl.
   rewrite IHn.
   ring.
Qed.

Lemma sum_helper : forall n : nat,
    sum (S n) = sum n + (n + 1)^2.
Proof.
  induction n.
  -auto.
  -rewrite IHn.
   simpl.
   ring.
Qed.

Lemma n_sum_helper : forall n : nat,
    S n * (S n + 1) * (2 * S n + 1) = n * (n + 1) * (2*n+1) + 6 * (n + 1)^2.
Proof.
  destruct n.
  -auto.
  -simpl. rewrite Sn_exp.
   ring.
Qed.

Theorem sum_exp : forall n : nat,
    6 * sum n = n * (n+1) * (2*n+1).
Proof.
  induction n.
  -auto.
  -rewrite sum_helper.
   rewrite mult_distr_r.
   rewrite IHn.
   rewrite n_sum_helper.
   auto.
Qed.


Inductive day : Type :=
  | monday : day
  | tuesday : day
  | wednesday : day
  | thursday : day
  | friday : day
  | saturday : day
  | sunday : day.

Definition next_weekday (d:day) : day :=
  match d with
    | monday => tuesday
    | tuesday => wednesday
    | wednesday => thursday
    | thursday => friday
    | friday => monday
    | saturday => monday
    | sunday => monday
  end.

Example test_next_weekday:
  (next_weekday (next_weekday saturday)) = tuesday.

Proof. simpl. reflexivity. Qed.

(* Booleans type *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

(* !函数 *)
Definition negb (b: bool) : bool :=
	match b with
	| true => false
	| false => true
	end.

(* and *)
Definition andb (b1: bool) (b2: bool) : bool :=
	match b1 with
	| true => b2
	| false => false
	end.

Definition orb (b1: bool) (b2: bool) : bool :=
	match b1 with
	| true => true
	| false => b2
	end.

(* 符号定义 宏定义方法 *)
Notation "x && y" := (andb x y).
Notation "x || y" := (orb x y).

Example test_andb_notation:
  true && true = true .
Proof. simpl. reflexivity. Qed.

(* Compound Types *)
Inductive rgb : Type :=
  | red : rgb
  | green : rgb
  | blue : rgb.

(* 如果 p 属于集合 rgb, 则 primary p 属于集合 color *)
Inductive color : Type :=
  | black : color
  | white : color
  | primary : rgb -> color.

Check primary red. (* color 类型 *)

Definition monochrome (c : color) : bool :=
  match c with
  | black => true
  | white => true
  | primary p => false
  end.

Example test_monochrome1: (monochrome black) = true.
Proof. simpl. reflexivity. Qed.
Example test_monochrime2: (monochrome white) = true.
Proof. simpl. reflexivity. Qed.
Example test_monochrime3: (monochrome (primary red)) = false.
Proof. simpl. reflexivity. Qed.

Definition isred (c : color) : bool :=
  match c with
  | black => false
  | white => false
  | primary red => true
  | primary _ => false
  end.

Example test_isred1: ( isred black ) = false.
Proof. simpl. reflexivity. Qed.
Example test_isred2: ( isred white ) = false.
Proof. simpl. reflexivity. Qed.
Example test_isred3: ( isred (primary red) ) = true.
Proof. simpl. reflexivity. Qed.
Example test_isrea4: ( isred (primary blue) ) = false.
Proof. simpl. reflexivity. Qed.

(* 定义自己的自然数，防止和libraries冲突 *)
Module NatPlayground.

(*
1. O 是一个自然数
2. S 提供一个自然数 n 可以产生下一个自然数，也就是说 n 是一个自然数的话, S n 也是一个自然数

O => 0
S O => 1
S (S O) => 2
S (S (S O)) => 3
S (S (S (S O))) => 4
S (S (S (S (S O)))) => 5
S (S (S (S (S (S O))))) => 6
S (S (S (S (S (S (S O)))))) => 7
S (S (S (S (S (S (S (S O))))))) => 8
S (S (S (S (S (S (S (S (S O)))))))) => 9
S (S (S (S (S (S (S (S (S (S O))))))))) => 10
*)

Inductive nat : Type :=
  | O : nat
  | S : nat -> nat.

(*
  O 没有前置
  S n' 前置为 n'
*)
Definition pred (n : nat) : nat :=
  match n with
  | O => O
  | S n' => n'
  end.

Example test_pred1: ( pred O ) = O.
Proof. simpl. reflexivity. Qed.
Example test_pred2: ( pred (S O) ) = O.
Proof. simpl. reflexivity. Qed.
Example test_pred3: ( pred (S (S O)) ) = S O.
Proof. simpl. reflexivity. Qed.
Example test_pred4: ( pred (S (S (S O))) ) = (S (S O)).
Proof. simpl. reflexivity. Qed.

End NatPlayground.
Check (O).
Check (S (S (S O))).

(* 定义一个自然数减2 *)
Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n' (* S (S n') 减去 外面两层，得到内层 n' *)
  end.

Compute (minustwo 7).

Check S.
Check pred.
Check minustwo.

(* 偶数定义: 递归减2 *)
Fixpoint evenb (n : nat) : bool :=
  match n with
    | O => true
    | S O => false
    | S (S n') => evenb n'
  end.

Definition oddb (n : nat) : bool := negb (evenb n).

Example test_oddb1 : oddb 1 = true.
Proof. simpl. reflexivity. Qed.
Example test_oddb2 : oddb 4 = false.
Proof. simpl. reflexivity. Qed.

Module NatPlayground2.
  (*
    计算过程演算
    Compute plus (S (S( S O))) (S (S O))
    1. (S plus (S (S O)) (S (S O)))
    2. (S (S (plus (S O) (S (S O)))))
    3. (S (S (S (plus O (S (S O)))))
    4. (S (S (S (S (S O))))) 结束.
  *)
  Fixpoint plus (n : nat) (m : nat) :=
    match n with
      | O => m
      | S n' => S ( plus n' m )
    end.
  Compute (plus 3 2).

  (* 乘法：
  3 * 4
  4 + 2 * 4
  4 + 4 + 1 * 4
  4 + 4 + 4 + 0 * 4
  = 12
  *)
  Fixpoint mult (n m : nat) :=
    match n with
      | O => O
      | S n' => plus m ( mult n' m )
    end.

  Compute (mult 3 4).

  Fixpoint minus (n m : nat) :=
    match n, m with
      | O, _ => O
      | S _, O => n
      | S n', S m' => minus n' m'
    end.
  Example test_mult1: (mult 3 3) = 9.
  Proof. simpl. reflexivity. Qed.
  Example test_minus1: (minus 9 3) = 6.
  Proof. simpl. reflexivity. Qed.

End NatPlayground2.

Fixpoint exp (base power : nat) : nat :=
    match power with
      | O => S O (* 任意自然数的一次方等于 1 *)
      | S p => mult base (exp base p)
    end.

Example test_exp: (exp 2 2) = 4.
Proof. simpl. reflexivity. Qed.

Example test_exp1: (exp 2 3) = 8.
Proof. simpl. reflexivity. Qed.

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

Example test_factorial1: (factorial 5) = (mult 10 12).
Proof. simpl. reflexivity. Qed.

Notation "x + y" :=
  (plus x y)
  (at level 50, left associativity)
  : nat_scope.

Notation "x - y" :=
  (minus x y)
  (at level 50, left associativity)
  : nat_scope.

Notation "x * y" :=
  (mult x y)
  (at level 40, left associativity)
  : nat_scope.

Check ( (0 + 1) + 1 ).

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

Compute ( beq_nat 12 12 ).

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

Example test_leb1: (leb 2 2) = true.
Proof. simpl. reflexivity. Qed.
Example test_leb2: (leb 2 4) = true.
Proof. simpl. reflexivity. Qed.
Example test_leb3: (leb 4 2) = false.
Proof. simpl. reflexivity. Qed.

(*Exercise: 1 star (blt nat)*)
Fixpoint blt_nat (n m : nat) : bool :=
  match n, m with
  | O, O => false
  | O, _ => true
  | _, O => false
  | S n', S m' => blt_nat n' m'
  end.

Example test_blt_nat1: (blt_nat 2 2) = false.
Proof. simpl. reflexivity. Qed.
Example test_blt_nat2: (blt_nat 2 4) = true.
Proof. simpl. reflexivity. Qed.
Example test_blt_nat3: (blt_nat 4 2) = false.
Proof. simpl. reflexivity. Qed.

(*Proof by Simplification*)

Theorem plus_0_n: forall n : nat, O + n = n.
Proof.
  intros n. simpl. reflexivity. Qed.

Theorem plus_0_n': forall n : nat, 0 + n = n.
Proof.
  intros n. reflexivity.
Qed.

Theorem plus_id_example: forall n m : nat,
  n = m ->
  n + n = m + m.
Proof.
  intros n m.
  intros H.
  rewrite <- H.
  reflexivity.
Qed.

Theorem plus_id_exercise: forall n m o : nat,
  n = m -> m = o -> n + m = m + o .
Proof.
  intros n.
  intros m.
  intros o.
  intros H.
  intros I.
  rewrite -> H.
  rewrite -> I.
  simpl.
  reflexivity.
Qed.

Theorem mult_0_plus: forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_0_n.
  reflexivity.
Qed.

Theorem mult_S_1: forall n m: nat,
  m = S n ->
  m * ( 1 + n) = m * m.
Proof.
  intros n m.
  intros H.
  rewrite -> H.
  simpl.
  reflexivity.
Qed.

Theorem plus_1_neq_0_firsttry: forall n : nat,
  beq_nat (n + 1) 0 = false .
Proof.
  intros n. destruct n as [| n'].
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

Theorem andb_true_elim2: forall b c : bool,
  andb b c = true -> c = true .
Proof.
  intros [] [].
  - simpl. reflexivity.
  - intros H.  rewrite <- H. simpl. reflexivity.
  - simpl. reflexivity.
  - intros H.  rewrite <- H. simpl. reflexivity.
Qed.

Theorem zero_nbeq_plus_1: forall n : nat,
  beq_nat 0 (n + 1) = false .
Proof.
  intros [].
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.