Require Import Arith.

(* Quelques tactiques utiles, qu'on verra au fur et a mesure :
  - assert (un énoncé) H12
  - replace (un terme) with (un autre)
  - inversion H.
  - ((auto with arith : seulement quand la tactique est EXPLICITEMENT autorisée)) *)

(** Partie I : Petits prédicats inductifs *)

(* Réflechissez un peu au sens de nat -> Prop *)

(*A.nat -> Prop est un predicat sur les entiers*)

(* En plus des types de données inductifs, Coq permet de définir des
propriétés inductives. Par exemple, la propriété que un nat est pair
peut être définie de la facon suivante : *)

Inductive even : nat -> Prop :=
  | even_zero : even 0
  | even_succ : forall n, even n -> even (S (S n)).

(*                   even n
   --------       --------------
    even 0        even (S (S n))     *)

(* Définissez vous-même le prédicat "odd" pour designer les
impairs. Essayez de trouver une définition avec UN SEUL
constructeur. *)

Inductive odd : nat -> Prop :=
  | odd_succ : forall n, even n -> odd (S n).

(* [inversion H] est une tactique compliquée qui élimine les cas
impossibles dans les types inductifs. Servez-vous en pour prouver : *)

Lemma not_even: ~ odd 0.
  intros H.
  inversion H.
Qed.

Lemma odd_even : forall n, odd n -> even (S n).
  intros.
  inversion H.
  apply even_succ.
  apply H0.
Qed.

Lemma eventwo_times : forall n, even (n * 2).
  intros.
  induction n.
  *
    simpl.
    apply even_zero.
  *
    simpl.
    apply even_succ.
    apply IHn.
Qed.

Lemma odd_or_even : forall n, even n \/ odd n.
  intros.
  induction n.
  *
    left.
    apply even_zero.
  *
    destruct IHn.
    right.
    apply odd_succ.
    apply H.
    left.
    apply odd_even.
    apply H.
Qed.

Lemma evenS_odd : forall n, even (S n) -> odd n.
  intros.
  inversion H.
  apply odd_succ.
  apply H1.
Qed.

Lemma oddS_even : forall n, odd (S n) -> even n.
  intros.
  inversion H.
  apply H1.
Qed.

(* Conseil: utilisez inversion. *)
Lemma odd_and_even : forall n, ~ (even n /\ odd n).
  induction n.
  *
    unfold not.
    intros.
    destruct H.
    apply not_even.
    apply H0.
  *
    unfold not.
    intros H0.
    destruct IHn.
    destruct H0.
    split.
    apply oddS_even.
    apply H0.
    apply evenS_odd.
    apply H.
Qed.

(** Prédicats inductifs : relations *)

(* Le type [A -> A -> Prop] des formules paramétrées par deux éléments
de A sert à représenter les relations sur A. *)
Definition relation A := A -> A -> Prop.

(* Par exemple la relation [div] est une [relation nat] *)

(* Mais on peut aussi définir des relations de relations comme par
example l'inclusion entre les relations. *)
Definition incl A : relation (relation A) := fun R1 R2 =>
  forall x y, R1 x y -> R2 x y.

(* Definissez la relation maximale, la relation minimale (i.e. la
relation vide) ainsi que la relation identité. *)
Definition rel_full A : relation A :=
  fun x y => True.
Definition rel_empty A : relation A :=
  fun x y => False.
Definition rel_id A : relation A :=
  fun x y => x=y.

(* Étant donnée une relation, définissez la relation réciproque. *)
Definition converse A (R : relation A) :=
  fun x y => R y x.

(* On peut aussi définir des propriétés sur les relations comme par
exemple la transitivité : *)
Definition transitive A (R : relation A) : Prop  :=
  forall x y z, R x y -> R y z -> R x z.

(* Définissez la réflexivité et la symétrie: *)
Definition reflexive A (R : relation A) : Prop :=
  forall x, R x x.
Definition symmetric A (R : relation A) : Prop :=
  forall x y, R x y -> R y x.

(* Pour vous chauffer, prouvez le lemme suivant. Indice: Utilisez la
tactique [unfold D] pour déplier la définition D. La tactique [compute
in H] permet de normaliser le type de H *)
Lemma incl_conv : forall A R, incl A R (converse A R) -> symmetric A R.
  intros.
  compute in H.
  compute.
  apply H.
Qed.

(* Dans cette section nous allons fabriquer la cloture reflexive
transitive d'une relation. *)

Section Star.

(* On suppose qu'on dispose d'un type A et d'une relation sur A. *)
Variable A : Type.
Variable R : A -> A -> Prop.

(* On définit le prédicat inductif suivant : *)
Inductive star : A -> A -> Prop :=
  | star_refl : forall a, star a a
  | star_R : forall a b c, R a b -> star b c -> star a c.

(* Prouvez que R est incluse dans sa cloture. *)
Lemma R_star : incl A R star.
  compute.
  intros.
  apply star_R with y.
  apply H.
  apply star_refl.
Qed.

(* Prouvez que la cloture est transitive. Indice : Dans [apply h with
t], le mot-clef 'with' permet de donner à apply les arguments qu'il
n'arrive pas à inférer. *)
Lemma star_trans : transitive _ star.
  compute.
  intros.
  induction H.
  *
    apply H0.
  *
    apply IHstar in H0.
    apply star_R with b.
    apply H.
    apply H0.
Qed.

(* En passant, vous pouvez démontrer ça aussi. *)
Lemma star_ass : forall a b c, star a b -> R b c -> star a c.
Proof.
  intros.
  apply R_star in H0.
  apply star_trans with b.
  apply H.
  apply H0.
Qed.

Lemma star_sym : symmetric _ R -> symmetric _ star.
Proof.
  compute.
  intros.
  induction H0.
  apply star_refl.
  apply H in H0.
  apply star_ass with b.
  apply IHstar.
  apply H0.
Qed.

Check star_trans.
End Star.
Check star_trans.

(** Partie II : Sémantique à grands pas *)

(* Considérons la grammaire d'expressions suivante, avec les mots
inhabituels "Randombit" et "AssertZero", qui sont expliqués plus
bas. *)

Inductive expr : Set :=
  | N : nat -> expr
  (*| Randombit : expr*)
  | Zero : expr
  | Un : expr
  | Plus : expr -> expr -> expr
  | Mult : expr -> expr -> expr
  | Minus : expr -> expr -> expr
  | AssertZero : expr -> expr -> expr.

(* Donnez une sémantique à grand pas avec le sens suivant :
  - N n
      représente l'entier n

      -------
      N n → n

  - Plus, Mult et Minus
      comme en cours

      e₁ → n₁     e₂ → n₂
      -------------------
      Plus e₁ e₂ → n₁ + n₂

  - Randombit
      peut engendrer 0
      peut engendrer 1

      ------------       ------------
      Randombit → 0      Randombit → 1

  - AssertZero e1 e2
      s'assure que e1 peut réduire vers 0 et se comporte comme e2 dans
      ce cas.

      e₁ → 0        e₂ → n₂
      ---------------------
      AssertZero e₁ e₂ → n₂
*)

Inductive bs : expr -> nat -> Prop :=
  | bs_nat : forall n, bs (N n) n
  (*| bs_Randombit0 : bs Randombit 0
  | bs_Randombit1 : bs Randombit 1*)
  | bs_Zero : bs Zero 0
  | bs_Un : bs Un 1
  | bs_Plus : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Plus e1 e2) (n+m)
  | bs_Mult : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Mult e1 e2) (n*m)
  | bs_Minus : forall e1 e2 n m, bs e1 n -> bs e2 m -> bs (Minus e1 e2) (n-m)
  | bs_AssertZero : forall e1 e2 n, bs e1 0 -> bs e2 n -> bs (AssertZero e1 e2) n
.
(* Question :

Essayez de définir une telle sémantique pour faire en sorte que
"AssertZero e1 e2" se comporte comme "e2" si "e1" ne peut PAS se
réduire vers 0. Coq accepte-t'il la définition ? Pourquoi ? *)
(*
Lemma expression_example :
  bs (AssertZero (Minus (Minus (N 2) Randombit) Randombit) (Mult (N 5) (N 3))) 15.
  (* replace expr1 with expr2 => substitue expr1 par expr2 et un but apparait pour prouver l'égalité *)
  apply bs_AssertZero.
  *
    replace 0 with (1-1).
    apply bs_Minus.
    simpl.
    replace 1 with (2-1).
    apply bs_Minus.
    simpl.
    apply bs_nat.
    apply bs_Randombit1.
    simpl.
    reflexivity.
    apply bs_Randombit1.
    simpl.
    reflexivity.
  *
    replace 15 with(5*3).
    apply bs_Mult.
    apply bs_nat.
    apply bs_nat.
    simpl.
    reflexivity.
Qed.
*)

(* On va vouloir définir une fonction d'évaluation des expressions; pour ça, on se débarasse de RandomBit et
    on le remplace par Zero et Un, qui valent toujours zero et un! Commentez les expressions et redéfinissez-les ainsi. *)

(* Définissez maintenant une fonction récursive eval qui calcule la valeur d'une expression
    arithmétique. Pour le cas ou un AssertZero échoue, considérez que la valeur retournée par l'assert est 0. *)

Fixpoint eval (e : expr) : nat :=
  match e with
  |N(n) => n
  |Zero => 0
  |Un => 1
  |Plus e1 e2 => (eval e1) + (eval e2)
  |Mult e1 e2 => (eval e1) * (eval e2)
  |Minus e1 e2 => (eval e1) - (eval e2)
  |AssertZero e1 e2 =>
   match eval e1 with
   |0 => eval e2
   |_ => 0
   end
end.

(* On va maintenant prouver  qu'on a défini une fonction qui est correcte vis-à-vis de
	la sémantique à grand pas des expressions *)

Lemma eval_correct : forall (e : expr) (n : nat), bs e n -> eval e = n.
  intros.
  inversion H.
  *
    simpl.
    reflexivity.
  *
    simpl.
    reflexivity.
  *
    simpl.
    reflexivity.
  *
    simpl.
    induction e.
Qed.

(* Peut-on prouver le lemme opposé? (c'est-à-dire que si eval e = n, alors on a bs e n). Pourquoi? *)


Module Playground1.

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

Check true.
Check bool.

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

End Playground1.

Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n'
  end.

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

Definition admit {T: Type} : T.  Admitted.
(* Haskell: undefined *)

Module Playground2.

Fixpoint plus (n : nat) (m : nat) {struct n} : nat :=
  match n with
    | O => m
    | S n' => S (plus n' m)
  end.

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

Fixpoint minus (n m : nat) : nat :=
  match n, m with
    | O   , _    => O
    | _   , O    => n          (* make this non-overlapping *)
    | S n', S m' => minus n' m'
  end.

End Playground2.

Theorem plus_O_n : forall n:nat, 0 + n = n.
Proof.
  intro n.
  simpl.
  reflexivity.
Qed.

(* End of seminar 1. *)

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

(* Looking up info *)

(* Require Import Arith. *)
Search nat.
SearchAbout nat.
(* SearchPattern (_ -> nat).    (* Doesn't work in older coq versions *) *)
SearchRewrite (0 + _).

(* More tactics. *)

Theorem plus_id_example : forall n m,
                            n = m -> n + n = m + m.
Proof.
  intros k l.
  intros H.
  rewrite <- H.                    (* show directions *)
  reflexivity.
Qed.

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

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

Print beq_nat.

Theorem plus_1_neq_0_b : forall n : nat,
                           beq_nat (n+1) 0 = false.
Proof.
  intros.
  (* destruct n; reflexivity. *)
  destruct n.
    reflexivity.

    reflexivity.
Qed.

Axiom convenient : forall n, n+1 = S n.

Theorem plus_1_neq_0 : forall n : nat, n + 1 <> 0.
Proof.
  intros.
  (* rewrite convenient. *)
  (* discriminate. *)
  destruct n.
    discriminate.

    simpl.
    discriminate.
Qed.

Theorem eq_beq_nat : forall n m : nat,
    n = m <-> beq_nat n m = true.
Proof.
  intros.
  split.
    intro.
    rewrite H.
(* Finish from here. Hard. Good HW! :) *)
Admitted.

Theorem plus_0_r : forall n, n + 0 = n.
Proof.
  intros.
  induction n.
    reflexivity.

    simpl.
    rewrite IHn.
    reflexivity.
Qed.

Theorem minus_diag : forall n : nat, n - n = 0.
Proof.
  intros.
  induction n.
    reflexivity.

    simpl.
    assumption.
Qed.

Theorem plus_comm : forall n m, n + m = m + n.
Proof.
  intros n m.
  induction n.
    simpl.
    rewrite plus_0_r.
    reflexivity.

    simpl.
    rewrite IHn.
    assert (forall k l, k + S l = S (k + l)).
      clear IHn n m.
      intros.
      induction k.
        reflexivity.

        simpl.
        rewrite IHk.
        reflexivity.

    rewrite H.
    reflexivity.
Qed.
(* HW: do without assert, but with induction within induction. *)

(* Induction more closely *)

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

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros.
  generalize dependent m.
  induction n.
    intros.
    destruct m.
      reflexivity.

      simpl in H.
      discriminate H.

    intros.
    destruct m.
      discriminate H.

      f_equal.
      apply IHn.
      simpl in H.
      inversion H.
      trivial.
Qed.
(*   intros n. *)
(*   induction n. *)
(*     intros. *)
(*     simpl in H. *)
(*     destruct m. *)
(*       reflexivity. *)

(*       simpl in H. *)
(*       discriminate H. *)

(*    (* induction side *) *)
(*    intros. *)
(*    destruct m. *)
(*      discriminate H. *)

(*      (* apply a hypothesis to the goal *) *)
(*      f_equal.                   (* remove the same constructor *) *)
(*      apply IHn. *)
(*      simpl in H. *)
(*      (* TODO(klao): look up how to introduce S-es to the goal. *) *)
(*      (* union of 'discriminate' and 'f_equal in hypothesis' *) *)
(*      inversion H. *)
(*      reflexivity. *)
(* Qed. *)
(* TODO(klao): look into: printing readable proofs. *)

(* End of Seminar 2. *)

(* ********************************************************************** *)
(* Seminar 3 starts here. *)

(* revert, generalize dependent, and induction in |- *)

Theorem plus_rearrange : forall n m p q,
    (n + m) + (p + q) = (m + n) + (q + p).
Proof.
  intros.
  rewrite plus_comm.
  rewrite plus_comm.
  Check plus_comm.

  rewrite (plus_comm n m).
  (* rewrite (plus_comm p q). *)
  (* reflexivity. *)
  replace (p + q) with (q + p).
  reflexivity.
  apply plus_comm.
Qed.

(* ************* *)
(* 'Apply' and other tactic examples *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  (* intros. *)
  (* apply H. *)
  (* exact H0. *)

  intro H.
  (* apply H. *)
  exact (H 3).
Qed.

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

  symmetry.
  (* simpl. *) (* Actually, this [simpl] is unnecessary, since
            [apply] will do a [simpl] step first. *)
  apply H.
Qed.

(* Reasoning in assumptions, aka forward reasoning. *)
Theorem silly3' : forall (n : nat),
  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
     true = beq_nat n 5  ->
     true = beq_nat (S (S n)) 7.
Proof.
  intros n eq H.
  remember H as H1.
  clear HeqH1.
  symmetry in H. apply eq in H. symmetry in H.
  apply H.
Qed.

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* Hint: use the plus_n_Sm lemma *)
    intros. destruct m as [| m']. reflexivity.
    simpl in H. discriminate H.

    intros. destruct m as [| m']. discriminate H.
    simpl in H. rewrite <- !plus_n_Sm in H.  (* rewrite modifiers *)
    inversion H. apply IHn' in H1. rewrite H1. reflexivity.
Qed.

(* Remember and destruct expression. *)

Require String. Open Scope string_scope.

Ltac move_to_top x :=
  match reverse goal with
  | H : _ |- _ => try move x after H
  end.

Tactic Notation "assert_eq" ident(x) constr(v) :=
  let H := fresh in
  assert (x = v) as H by reflexivity;
  clear H.

Tactic Notation "Case_aux" ident(x) constr(name) :=
  first [
    set (x := name); move_to_top x
  | assert_eq x name; move_to_top x
  | fail 1 "because we are working on a different case" ].

Tactic Notation "Case" constr(name) := Case_aux Case name.
Tactic Notation "SCase" constr(name) := Case_aux SCase name.
Tactic Notation "SSCase" constr(name) := Case_aux SSCase name.
Tactic Notation "SSSCase" constr(name) := Case_aux SSSCase name.
Tactic Notation "SSSSCase" constr(name) := Case_aux SSSSCase name.
Tactic Notation "SSSSSCase" constr(name) := Case_aux SSSSSCase name.
Tactic Notation "SSSSSSCase" constr(name) := Case_aux SSSSSSCase name.
Tactic Notation "SSSSSSSCase" constr(name) := Case_aux SSSSSSSCase name.

Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f b.
  destruct b.
  Case "b = true".
  remember (f true) as ftrue.
    destruct ftrue.
    SCase "f true = true".
      rewrite <- Heqftrue.
      symmetry.
      apply Heqftrue.
    SCase "f true = false".
      remember (f false) as ffalse.
      destruct ffalse.
      SSCase "f false = true".
        symmetry.
        apply Heqftrue.
      SSCase "f false = false".
        symmetry.
        apply Heqffalse.
  remember (f false) as ffalse.
    destruct ffalse.
    SCase "f false = true".
      remember (f true) as ftrue.
      destruct ftrue.
      SSCase "f true = true".
        symmetry.
        apply Heqftrue.
      SSCase "f true = false".
        symmetry.
        apply Heqffalse.
    SCase "f false = false".
      rewrite <- Heqffalse.
      symmetry.
      apply Heqffalse.
Qed.

(* HW *)
Theorem bool_funcs : forall (f : bool -> bool),
  (forall b, f (f b) = f b) \/ (forall b, f b = negb b).
Admitted.

Theorem bool_fn_applied_thrice' :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intro f.
  destruct (bool_funcs f).
    intro.
    rewrite H.
    rewrite H.
    reflexivity.

    intro.
    rewrite !H.
    (* SearchAbout negb. *)
    rewrite Bool.negb_involutive.
    reflexivity.
Qed.

(* Seminar 3 ended here. *)
(* ********************************************************** *)
(* Seminar 4 starts here. *)

Module ExampleList1.

Inductive list (T : Type) : Type :=
  | nil : list T
  | cons : T -> list T -> list T.

Check (cons nat 2 (cons nat 1 (nil nat))).

Check (cons _ 2 (cons _ 1 (nil _))).

Check cons.
Check nil.

End ExampleList1.

Module ExampleList2.

Set Implicit Arguments.

Inductive list (T : Type) : Type :=
  | nil
  | cons : T -> list T -> list T.
Print list.

Check (cons 2 (cons 1 (nil _))).

Implicit Arguments nil [[T]].
(* Deprecated, use: Arguments nil [T]. *)

Check (cons 2 (cons 1 nil)).

Check @nil nat.

Unset Implicit Arguments.

(* Fixpoint length {X:Type} (l:list X) : nat :=  *)
(*   match l with *)
(*   | nil      => 0 *)
(*   | cons h t => S (length t) *)
(*   end. *)

Fixpoint length (X:Type) (l:list X) : nat :=
  match l with
  | nil      => 0
  | cons h t => S (length X t)
  end.
Check length.
Implicit Arguments length [[X]].

Eval compute in length (cons 2 (cons 1 nil)).

Check @length.

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

(* Define app! *)
Fixpoint app {X : Type} (l1 l2 : list X) : list X :=
  match l1 with
    | [] => l2
    | h :: t => h :: app t l2
  end.

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

Eval compute in [1,2,3] ++ 4::5::[].

Fixpoint repeat {X : Type} (x : X) (count : nat) : list X :=
  match count with
    | O => nil
    | S c' => x :: repeat x c'
  end.

Eval compute in repeat true 3.

Theorem repeat_length : forall n X (x : X), length (repeat x n) = n.
Proof.
  intros.
  pattern n.
  apply nat_ind.
    simpl.
    reflexivity.

    intros.
    simpl.
    rewrite <- H at 2.
    reflexivity.
Qed.

(* Induction priciple for induction definition. *)

Check nat_ind.
Check list_ind.

Theorem app_assoc : forall X (l1 l2 l3 : list X), l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.
Proof.
  intros.
  induction l1.
    simpl.
    reflexivity.

    simpl.
    rewrite IHl1.
    reflexivity.
Qed.

(* HW: trivial *)
Theorem app_length : forall X (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.
Admitted.

(* HW: involved. What should the induction go on? *)
Theorem app_length2 : forall X (l1 l2 : list X) n1 n2,
     length l1 = n1 -> length l2 = n2 -> length (l1 ++ l2) = n1 + n2.
Admitted.

Inductive vector (T : Type) : nat -> Type :=
  | nilv : vector T 0
  | consv n : T -> vector T n -> vector T (S n).

Implicit Arguments nilv [[T]].
Implicit Arguments consv [[T] [n]].

Check consv 1 (consv 2 nilv).
Check consv true (consv false nilv).

Definition lengthv {T : Type} {n : nat} (v : vector T n) : nat := n.

Fixpoint repeatv {X : Type} (x : X) (n : nat) : vector X n :=
  match n with
    | 0 => nilv
    | S n' => consv x (repeatv x n')
  end.

Theorem lengthv_repeatv : forall n X (x : X), lengthv (repeatv x n) = n.
Proof.
  intros.
  reflexivity.
Qed.
(* Show that simpl is not enough here, but compute is, or unfold. *)

Check @repeat.
 (* : forall X : Type, X -> nat -> list X *)
Check @repeatv.
 (* : forall X : Type, X -> forall n : nat, vector X n *)

(* Relation of 'forall' and '->' *)

Parameter p q : Prop.

Print p.

Definition p_to_q := forall h : p, q.

Print p_to_q.

Check forall n : nat, bool.

Check forall n : nat, p.

End ExampleList2.

Parameter A B : Prop.

Theorem a_to_b_to_a : A -> B -> A.
Proof.
  intros.
  assumption.
  Show Proof.
Qed.

Definition a_to_b_to_a' : A -> B -> A := fun x => fun _ => x.

Check a_to_b_to_a.
Check a_to_b_to_a'.

Theorem two_times_n_plus_3 : nat -> nat.
Proof.
  intros n.
  induction n.
    exact 3.

    exact (S (S IHn)).
  Show Proof.
Defined.

Eval compute in two_times_n_plus_3 5.

Definition true_all : forall P : Prop, P -> True := fun _ => fun _ => I.

Theorem true_all' : forall P : Prop, P -> True.
Proof.
  intros.
  trivial.
  Show Proof.
Qed.

Definition true_all'' (P : Prop) (H : P) := I.

Check true_all''.

Print False.

(* Definition false_all : forall (P : Prop), False -> P := *)

Definition false_all (P : Prop) (H : False) : P :=
  match H with
  end.

Check false_all.

(* Homework: hard! *)
Definition O_not_1 : not (eq O (S 0)).

Print not.
Print eq.


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

Require Export Induction.
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 here: *)

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

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

Check (pair 3 5).

(** Here are two simple functions 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.

Compute (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 works because the pair notation is actually
    provided as part of the standard library): *)

Compute (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 to prove a few simple facts about pairs.

    If we state things in a particular (and slightly peculiar) way, we
    can complete proofs 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.

(** But [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]. *)

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

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

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

(** As with pairs, it is more convenient to write lists in
    familiar programming notation.  The following 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 understand the details of 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.

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

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

Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil    => l2
  | h :: t => h :: (app t l2)
  end.

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

(** *** Head (with default) and Tail *)
(** 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.  *)

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.

(** *** Exercises *)
(** **** Exercise: 2 stars, recommended (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
  | x::xs  => match x with
              | 0   => nonzeros xs
              | _   => x :: (nonzeros xs)
              end
  end.

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

Fixpoint oddmembers (l:natlist) : natlist := match l with
  | nil   => nil
  | x::xs => match oddb x with
             | true  => x::(oddmembers xs)
             | _     => oddmembers xs
             end
  end.

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

Fixpoint countoddmembers (l:natlist) : nat := length (oddmembers l).

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

Example test_countoddmembers2:
  countoddmembers [0;2;4] = 0.
Proof. 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,l2 with
  | nil  , nil   => nil
  | x::xs, nil   => l1
  | nil  , x::xs => l2
  | x::xs, y::ys => x::y::(alternate xs ys)
  end.

Example test_alternate1:
  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
Proof. reflexivity. Qed.

Example test_alternate2:
  alternate [1] [4;5;6] = [1;4;5;6].
Proof. reflexivity. Qed.

Example test_alternate3:
  alternate [1;2;3] [4] = [1;4;2;3].
Proof. reflexivity. Qed.

Example test_alternate4:
  alternate [] [20;30] = [20;30].
Proof. reflexivity. Qed.

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

(** A [bag] (or [multiset]) is like a set, except that each element
    can appear multiple times rather than just once.  One possible
    implementation is to represent a bag of numbers as a list. *)

Definition bag := natlist.

(** **** Exercise: 3 stars, recommended (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   => 0
  | x::xs => if beq_nat x v
             then S (count v xs)
             else count v xs
  end.

(** All these proofs can be done just by [reflexivity]. *)

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

Example test_count2:              count 6 [1;2;3;1;4;1] = 0.
Proof. 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. reflexivity. Qed.

Definition add (v:nat) (s:bag) : bag :=  v :: s.

Example test_add1:                count 1 (add 1 [1;4;1]) = 3.
Proof. reflexivity. Qed.

Example test_add2:                count 5 (add 1 [1;4;1]) = 0.
Proof. reflexivity. Qed.

Definition member (v:nat) (s:bag) : bool :=
  match count v s with
  | O => false
  | _ => true
  end.

Example test_member1:             member 1 [1;4;1] = true.
Proof. reflexivity. Qed.

Example test_member2:             member 2 [1;4;1] = false.
Proof. reflexivity. Qed.

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

  (* When remove_one is applied to a bag without the number to remove,
     it should return the same bag unchanged. *)
Fixpoint remove_one (v:nat) (s:bag) : bag := match s with
  | nil   => s
  | x::xs => match beq_nat x v with
             | true => xs
             | _    => x :: (remove_one v xs)
             end
  end.

Example test_remove_one1:
  count 5 (remove_one 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_one2:
  count 5 (remove_one 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_one3:
  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.

Example test_remove_one4:
  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
Proof. reflexivity. Qed.

Fixpoint remove_all (v:nat) (s:bag) : bag := match s with
  | nil   => s
  | x::xs => match beq_nat x v with
             | true => remove_all v xs
             | _    => x :: (remove_all v xs)
             end
  end.

Example test_remove_all1:          count 5 (remove_all 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_all2:          count 5 (remove_all 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_all3:          count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.

Example test_remove_all4:          count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
Proof. reflexivity. Qed.

(* check if s1 subset of s2 *)
Fixpoint subset (s1:bag) (s2:bag) : bool := match s1 with
  | nil   => true
  | x::xs => match (member x s2) with
                 | true  => subset xs (remove_one x s2)
                 | _     => false
             end
  end.

Example test_subset1:              subset [1;2] [2;1;4;1] = true.
Proof. reflexivity. Qed.

Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
Proof. reflexivity. Qed.

(** **** Exercise: 3 stars, recommended (bag_theorem)  *)
(** Write down an interesting theorem [bag_theorem] about bags
    involving the functions [count] and [add], and prove it.  For
    this, replace the [admit] command below with the statement of your
    theorem. 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! *)

(*
  (count x ls) + 1   ==  count x (add x ls)
*)
Theorem bag_theorem : forall x : nat, forall l : bag,
  S (count x l)  = count x (add x l).
Proof.
  intros x l. induction l as [|n l' IHl'].
    + simpl. induction x as [|x' IHx'].
        - simpl. reflexivity.
        - simpl. rewrite <- IHx'. reflexivity.
    + simpl. induction x as [|x' IHx'].
        - simpl. reflexivity.
        - simpl. induction n as [|n' IHn'].
            * simpl. rewrite <- beq_nat_refl. reflexivity.
            * simpl. rewrite <- beq_nat_refl. reflexivity.
Qed.

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

(** 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
    "scrutinee" 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'].
  - (* l = nil *)
    reflexivity.
  - (* 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 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 when you
    get to them.  'Nuff said. *)

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

(** Proofs by induction over datatypes like [natlist] are a
    little less familiar than standard natural number induction, but
    the idea is equally simple.  Each [Inductive] declaration defines
    a set of data values that can be built up using the declared
    constructors: a boolean can be either [true] or [false]; a number
    can be either [O] or [S] applied to another 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 arguments 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' IHl1'].
  - (* l1 = nil *)
    reflexivity.
  - (* l1 = cons n l1' *)
    simpl. rewrite -> IHl1'. reflexivity.  Qed.

(** Notice that, as when doing induction on natural numbers, the
    [as...] clause provided to the [induction] tactic gives a name to
    the induction hypothesis corresponding to the smaller list [l1']
    in the [cons] case. Once 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. *)

(** For comparison, here is an informal proof of the same theorem. *)

(** _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.  []
*)

(** *** Reversing a list *)
(** For a slightly more involved example of inductive proof over
    lists, suppose we use [app] to define a list-reversing function
    [rev]: *)

Fixpoint rev (l:natlist) : natlist :=
  match l with
  | nil    => nil
  | h :: t => rev t ++ [h]
  end.

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 theorems about our newly defined [rev].
    For something a bit more challenging than what we've seen, let's
    prove that reversing a list does not change its length.  Our first
    attempt 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' IHl'].
  - (* l = [] *)
    reflexivity.
  - (* 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 [++], but we don't have any useful equations
       in either the immediate context or in the global
       environment!  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 relating [++] and [length] that
    would have enabled us to make progress and prove it as a separate
    lemma.
*)

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' IHl1'].
  - (* l1 = nil *)
    reflexivity.
  - (* l1 = cons *)
    simpl. rewrite -> IHl1'. reflexivity.  Qed.

(** Note that, to make the lemma as general as possible, 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 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' IHl'].
  - (* l = nil *)
    reflexivity.
  - (* l = cons *)
    simpl. rewrite -> app_length, plus_comm.
    rewrite -> IHl'. simpl. reflexivity.
Qed.

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

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

    _Proof_: By induction on [l1].

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

    - Next, suppose [l1 = n::l1'], with
        length (l1' ++ l2) = length l1' + length l2.
      We must show
        length ((n::l1') ++ l2) = length (n::l1') + length l2).
      This follows directly from the definitions of [length] and [++]
      together with 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 ((rev l') ++ [n]) = S (length l')
        which, by the previous lemma, is the same as
          length (rev l') + length [n] = S (length l').
        This follows directly from the induction hypothesis and the
        definition of [length]. [] *)

(** 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 (which can easily work 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
    like this: *)

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

    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]
     for any [l] (this follows by a straightforward induction on [l]).
     The main property again follows by 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 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 our
    present purposes. *)

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

(** We've seen that proofs can make use of other theorems we've
    already proved, e.g., using [rewrite].  But in order to refer to a
    theorem, we need to know its name!  Indeed, it is often hard even
    to remember what theorems have been proven, much less what they
    are called.

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

SearchAbout rev.

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

    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_r : forall l : natlist,
  l ++ [] = l.
Proof.
  intros l. induction l as [|n l' IHl'].
    + simpl. reflexivity.
    + simpl. rewrite -> IHl'. reflexivity.
Qed.

(* may be redundant as it follows from the def directly
Theorem cons_app_equiv : forall l : natlist, forall x : nat,
  x::l = [x] ++ l.
Proof.
  intros l x. induction l.
    + simpl. reflexivity.
    + simpl. reflexivity.
Qed.
*)

(*
  question: how do you use variable declaration in proofs?
*)
Theorem rev_distrb : forall l1 : natlist, forall l2 : natlist,
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  intros l1 l2.
  induction l1 as [|n l1' IHl1'].
    + simpl. rewrite -> app_nil_r. reflexivity.
    + simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.
Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  intros l. induction l as [|x l' IHl'].
    + simpl. reflexivity.
    + simpl. rewrite -> rev_distrb. simpl. rewrite -> IHl'. reflexivity.
Qed.

(** There is a short solution to the next one.  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 l1 l2 l3 l4.
  rewrite -> app_assoc. 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 l1 l2.
  induction l1 as [|x l1' IHl1'].
    + simpl. reflexivity.
    + simpl. rewrite -> IHl1'. destruct x.
        - reflexivity.
        - 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, l2 with
  | nil, nil             => true
  | cons _ _,  nil       => false
  | nil,  cons _ _       => false
  | cons x xs, cons y ys => match beq_nat x y with
                            | true => beq_natlist xs ys
                            | _    => 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 l. induction l as [|n l' IHl'].
    + simpl. reflexivity.
    + simpl. induction n as [|n' IHn'].
        - simpl. rewrite <- IHl'. reflexivity.
        - simpl. rewrite <- IHn'. reflexivity.
Qed.

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

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

(* 1 <= count 1 (1::s)  *)
Theorem count_member_nonzero : forall (s : bag),
  leb 1 (count 1 (1 :: s)) = true.
Proof.
  intros s. induction s as [|n s' IHs'].
    + simpl. reflexivity.
    + simpl. reflexivity.
Qed.

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

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

(*  count 0 (remove_one 0 s) <= count 0 s *)
Theorem remove_decreases_count: forall (s : bag),
  leb (count 0 (remove_one 0 s)) (count 0 s) = true.
Proof.
  intros s. induction s as [|n s' IHs'].
    + simpl. reflexivity.
    + simpl. induction n as [|n' IHn'].
        - simpl. rewrite -> ble_n_Sn. reflexivity.
        - 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.*)

(* 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 do this.)
*)

Fact rev_list_of_one : forall n : nat,
  rev [n] = [n].
Proof. intros n. simpl. reflexivity. Qed.

Fact cons_app_equiv : forall n : nat, forall l : natlist,
  [n] ++ l = n :: l.
Proof. intros n l. simpl. reflexivity. Qed.

Theorem rev_injective : forall (l1 l2 : natlist),
  rev l1 = rev l2 -> l1 = l2.
Proof.
  intros l1 l2 H.
  rewrite <- rev_involutive.
  rewrite <- H.
  rewrite -> rev_involutive.
  reflexivity.
Qed.

(*
  in class quiz

Theorem foo2 : forall n m : nat, forall l : natlist,
                 repeat n m = l -> length l = m.
Proof.
  intros n m l H.
  induction m as [|m' IHm'].
    + rewrite <- H. simpl. reflexivity.
    + destruct l.
        - inversion H.
        - inversion H.
*)

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

(** 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 choose some number to return when the list is
    too short...
    *)

Fixpoint nth_bad (l:natlist) (n:nat) : nat :=
  match l with
  | nil => 42  (* arbitrary! *)
  | a :: l' => match beq_nat n O with
               | true => a
               | false => nth_bad l' (pred n)
               end
  end.

(** This solution is not so good: If [nth_bad] returns [42], we
    can't tell whether that value actually appears on the input
    without further processing. A better alternative is to change the
    return type of [nth_bad] to include an error value as a possible
    outcome. We call this type [natoption]. *)

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

(** We can then change the above definition of [nth_bad] to
    return [None] when the list is too short and [Some a] when the
    list has enough members and [a] appears at position [n]. We call
    this new function [nth_error] to indicate that it may result in an
    error. *)

Fixpoint nth_error (l:natlist) (n:nat) : natoption :=
  match l with
  | nil => None
  | a :: l' => match beq_nat n O with
               | true => Some a
               | false => nth_error l' (pred n)
               end
  end.

Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.
Proof. reflexivity. Qed.
Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.
Proof. reflexivity. Qed.
Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.
Proof. reflexivity. Qed.

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

Fixpoint nth_error' (l:natlist) (n:nat) : natoption :=
  match l with
  | nil => None
  | a :: l' => if beq_nat n O then Some a
               else nth_error' l' (pred n)
  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.

(** **** Exercise: 2 stars (hd_error)  *)
(** 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_error (l : natlist) : natoption :=
  match l with
  | nil      => None
  | cons x _ => Some x
  end.

Example test_hd_error1 : hd_error [] = None.
Proof. reflexivity. Qed.

Example test_hd_error2 : hd_error [1] = Some 1.
Proof. reflexivity. Qed.

Example test_hd_error3 : hd_error [5;6] = Some 5.
Proof. reflexivity. Qed.

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

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_error l).
Proof.
  intros l default. induction l as [|n l' IHl'].
    + simpl. reflexivity.
    + simpl. reflexivity.
Qed.

End NatList.

(* ###################################################### *)
(** * Partial Maps *)

(** As a final illustration of how data structures can be defined in
    Coq, here is a simple _partial map_ data type, analogous to the
    map or dictionary data structures found in most programming
    languages. *)

(** First, we define a new inductive datatype [id] to serve as the
    "keys" of our partial maps. *)

Inductive id : Type :=
  | Id : nat -> id.

(** Internally, an [id] is just a number.  Introducing a separate type
    by wrapping each nat with the tag [Id] makes definitions more
    readable and gives us the flexibility to change representations
    later if we wish.

    We'll also need an equality test for [id]s: *)

Definition extract_id (i : id) : nat := match i with
  | Id n => n
  end.

Theorem extract_id_n : forall n : nat,
  extract_id (Id n) = n.
Proof. intros n. simpl. reflexivity. Qed.

Definition beq_id x1 x2 :=
  match x1, x2 with
  | Id n1, Id n2 => beq_nat n1 n2
  end.

(** **** Exercise: 1 star (beq_id_refl)  *)
Theorem beq_id_refl : forall x, true = beq_id x x.
Proof.
  intros x. destruct x. simpl. induction n as [|n' IHn'].
    + simpl. reflexivity.
    + simpl. rewrite -> IHn'. reflexivity.
Qed.

Theorem beq_id_equiv : forall n : nat,
  beq_id (Id n) (Id n) = beq_nat n n.
Proof. intros n. simpl. reflexivity. Qed.

(** Now we define the type of partial maps: *)

Module PartialMap.
Import NatList.

Inductive partial_map : Type :=
  | empty  : partial_map
  | record : id -> nat -> partial_map -> partial_map.

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

(** The [update] function overrides the entry for a given key in a
    partial map (or adds a new entry if the given key is not already
    present). *)

Definition update (d : partial_map)
                  (key : id) (value : nat)
                  : partial_map :=
  record key value d.

(** Last, the [find] function searches a [partial_map] for a given
    key.  It returns [None] if the key was not found and [Some val] if
    the key was associated with [val]. If the same key is mapped to
    multiple values, [find] will return the first one it
    encounters. *)

Fixpoint find (key : id) (d : partial_map) : natoption :=
  match d with
  | empty         => None
  | record k v d' => if beq_id key k
                     then Some v
                     else find key d'
  end.

(** **** Exercise: 1 star (update_eq)  *)
Theorem update_eq :
  forall (d : partial_map) (k : id) (v: nat),
    find k (update d k v) = Some v.
Proof.
  intros d k v. induction d.
    + simpl. destruct k. induction n as [|n' IHn'].
        - simpl. reflexivity.
        - simpl. rewrite <- beq_id_equiv. rewrite -> IHn'. reflexivity.
    + simpl. destruct k as [x]. induction n as [|n' IHn'].
        - simpl. rewrite <- beq_nat_refl. reflexivity.
        - simpl. rewrite <- beq_nat_refl. reflexivity.
Qed.

(** **** Exercise: 1 star (update_neq)  *)
Theorem update_neq :
  forall (d : partial_map) (m n : id) (o: nat),
    beq_id m n = false -> find m (update d n o) = find m d.
Proof.
  intros d m n o H.
  induction d.
    + simpl. rewrite -> H. reflexivity.
    + simpl. rewrite -> H. reflexivity.
Qed.

End PartialMap.

(** **** Exercise: 2 stars (baz_num_elts)  *)
(** Consider the following inductive definition: *)

Inductive baz : Type :=
  | Baz1 : baz -> baz
  | Baz2 : baz -> bool -> baz.

(** How _many_ elements does the type [baz] have?

(* FILL IN HERE *)

  [baz] is not inhabited so it has no elements. In order to construct
  some [Baz1], we need some [x : baz], but we do not have this type.
  Similarly to construct [Baz2], we need some term of type [baz],
  which we do not have.

*)

(** $Date: 2016-01-13 11:14:59 -0500 (Wed, 13 Jan 2016) $ *)


Inductive nat : Set :=
  | zero : nat
  | succ : nat -> nat.

Fixpoint add (a b: nat): nat :=
  match a with
  | zero => b
  | succ n => succ (add n b)
  end.

Theorem add_zero: forall a : nat, add a zero = a.
Proof.
  intros a.
  induction a as [ | a Ha].
  + simpl; reflexivity.
  + simpl; rewrite Ha; reflexivity.
Qed.

Theorem add_succ: forall a b : nat, succ (add a b) = add a (succ b).
Proof.
  intros a b.
  elim a.
  - simpl; trivial.
  - intros n Ha. simpl. rewrite Ha. trivial.
Qed.

Theorem add_sym: forall a b: nat, add a b = add b a.
Proof.
  intros a b.
  induction a.
  + simpl. pose (add_zero b) as H. rewrite H. trivial.
  + simpl. rewrite IHa. exact (add_succ b a).
Qed.

Theorem add_assoc: forall a b c: nat, add a (add b c) = add (add a b) c.
Proof.
  intros a b.
  elim a.
  - intros c. simpl. trivial.
  - intros n H1 c. simpl. rewrite (H1 c). trivial.
Qed.


(* Solution for exercieses in Tsinghua Coq Summber School.
  Exercise for leture 2: Datatypes, pattern-matching, and recursion by Yves Bertot. *)
Section Exercise_2_Work.

Require Import List.
Require Import ZArith.

(* Define a datatype of binary trees where non-atomic nodes have only two
  components which are binary trees, and only atomic nodes carry an integer
  value.  Include a case for empty trees. *)

Inductive PolymorphicBalancedTree (A : Type) : Type :=
  | Empty
  | Atomic (value : A)
  | Branch (l : PolymorphicBalancedTree A) (r : PolymorphicBalancedTree A).

Implicit Arguments Empty [A].
Implicit Arguments Atomic [A].
Implicit Arguments Branch [A].

(* Option type as a polymorphic datatype. *)
Inductive option (A : Type) : Type :=
  | Some : A -> option A
  | None : option A.

Inductive ZBalancedTree : Type :=
  | ZEmpty
  | ZAtomic (value : Z)
  | ZBranch (l : ZBalancedTree) (r : ZBalancedTree).

(* Define a function that takes a list as input and constructs a balanced
  binary tree carrying the same values.  The trick is to interchange the
  the two components of each node after inserting an integer into the first
  node. *)

Inductive NatBalancedTree : Type :=
  | NatEmpty
  | NatAtomic (value : nat)
  | NatBranch (l : NatBalancedTree) (r : NatBalancedTree).

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

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

Fixpoint maximum_val (t : NatBalancedTree) : nat :=
  match t with
    | NatEmpty      => O
    | NatAtomic v   => v
    | NatBranch l r =>
      if (nat_ge_bool_local (maximum_val l) (maximum_val r))
        then maximum_val l
        else maximum_val r
  end.

Fixpoint insert_element (x : nat) (t : NatBalancedTree) : NatBalancedTree :=
  match t with
    | NatEmpty      => NatAtomic x
    | NatAtomic val => NatBranch (NatAtomic x) (NatAtomic val)
    | NatBranch l r =>
      if (nat_le_bool_local x (maximum_val l))
        then NatBranch (insert_element x l) r
        else NatBranch l (insert_element x r)
  end.

Fixpoint construct_tree (xs : list nat) : NatBalancedTree :=
  match xs with
    | nil         => NatEmpty
    | cons x rest => insert_element x (construct_tree rest)
  end.

(* Define a function with three arguments: a natural number and two
  lists, which builds a new list by always taking the least element
  of the heads of the two lists.  The length of the resulting list should
  be the natural number given as first input (if the two lists are long enough).

  This is a merge function as in the "merge sort" algorithm, except that the
  natural number argument should be the sum of the lengths of the two input
  lists.
*)

Fixpoint merge_nat_list_n (n : nat) (us : list nat) (vs : list nat) : list nat :=
  match n with
    | O   => nil
    | S p =>
      match us, vs with
        | cons a uss, cons b vss =>
          if (nat_le_bool_local a b)
            then a :: merge_nat_list_n p uss vs
            else b :: merge_nat_list_n p us vss
        | cons _ _, nil          => us
        | nil, cons _ _          => vs
        | nil, nil               => nil
      end
    end.

(* Define a function that merges two lists bu first computing the sum of their
  lengths and then calling the previous function. *)

Definition merge_nat_list (us vs : list nat) : list nat :=
  merge_nat_list_n (length us + length vs) us vs.

(* Eval compute in merge_nat_list (1::3::5::7::9::nil) (2::4::6::8::10::nil). *)

(* Define a recursive function on binary trees which returns a sorted list:
  - on empty trees it returns the empty list
  - on leaf treeas carrying one value, it returns a singleton list
  - on binary nodes, it returns the merge of the two sorted lists obtained
    from the sub-components. *)

Fixpoint destruct_tree (t : NatBalancedTree) : list nat :=
  match t with
    | NatEmpty      => nil
    | NatAtomic v   => v::nil
    | NatBranch l r => merge_nat_list (destruct_tree l) (destruct_tree r)
  end.

(* Eval compute in destruct_tree (construct_tree (1::3::5::7::9::2::4::6::8::10::nil)). *)

(* Define a function that sorts a list by first constructing a balanced binary
  tree and then by calling the function above. *)

Fixpoint sort_via_tree (xs : list nat) : list nat :=
  destruct_tree (construct_tree xs).

(* Eval compute in sort_via_tree (1::3::5::7::9::2::4::6::8::10::nil). *)

End Exercise_2_Work.