(* --- Homework 1, Part 2: Introduction to Coq, continued with Frap --- *)

(*
 * In this part of the homework, we get some practice with lists and other data structures
 * and use Frap tactics.
 *
 * Step through this file with CoqIDE (or another IDE for Coq), and complete the problems.
 * (Search for "PROBLEM" to be sure you find them all.)
 *
 * Throughout, we include the approximate lines of code (LOC) or number of tactics
 * for each of our solutions to these problems.  These are rough guidelines to help
 * you figure out if you are getting off-track.
 *
 * There is no penalty for writing a shorter or longer solution! However, if you find
 * yourself writing a much longer solution, see if you can figure out a simpler way.
 *
 *)

(* --- Making sure Frap is installed --- *)

(*
 * PROBLEM 0 [0 points, 0 LOC]
 * Set up Frap as described in README.md
 *
 * Once Coq is installed according to directions, you should be able to step over
 * the following line in your IDE.
 *)

Require Import Frap.
Set Implicit Arguments.

(* --- More arithmetic --- *)

(* This module creates a namespace where we can travel back in time to part 1.
 * Later in part 2, we're going to start using the Coq standard library version of
 * nat, so we hide our own definitions in this namespace so we can close it later.
 *)
Module leftover_from_part_1.

(*
 * Here are some definitions again from part 1 of the homework.
 *)
Inductive nat : Type :=
| O : nat
| S : nat -> nat.

Fixpoint add (n1 : nat) (n2 : nat) : nat :=
  match n1 with
  | O => n2
  | S m1 => S (add m1 n2)
  end.

Fixpoint mult (n1 : nat) (n2 : nat) : nat :=
  match n1 with
  | O => O
  | S m1 => add n2 (mult m1 n2)
  end.

(*
 * PROBLEM 1 [8 points, ~10 tactics, plus 3-4 helper lemmas, each needing <10 tactics]
 * Prove that multiplication is commutative, as stated by the lemma below.
 *
 * This was a challenge problem on part 1. If you already did it, feel free to
 * copy-paste your solution here.
 *
 * Hints from last time are reproduced below.
 *
 * Hint: Proceed by induction.
 *
 * Hint: Don't use more than one induction inside a single proof.  Instead, figure out
 * lemmas that might be useful, and then prove those separately (by induction, probably).
 *
 * Hint: It might be useful to review all the lemmas about `add` in part 1.
 * Feel free to copy them over if you need to use them. You might need to state and prove
 * some analogous lemmas about `mult`.
 *
 * Hint: In order to prove your helpers about `mult`, you might need 1 or 2 additional
 * facts about `add`.  Try to keep these simple, based on facts you know from math, and
 * prove them by induction.
 *)

Lemma add_one_2nd_arg:
  forall n1 n2,
    S (add n1 n2) = add n1 (S n2).
Proof.
  induction n1; intro n2.
  - simpl. reflexivity.
  - simpl. rewrite IHn1. reflexivity.
Qed.

Lemma add_swap:
  forall n1 n2 n3,
    add n1 (add n2 n3) = add n2 (add n1 n3).
Proof.
  induction n1; intro n2.
  - simpl. reflexivity.
  - simpl. intro n3. rewrite IHn1. rewrite add_one_2nd_arg. reflexivity.
Qed.

Lemma mult_zero:
  forall n1,
    mult n1 O = O.
Proof.
  induction n1.
  - simpl. reflexivity.
  - simpl. rewrite IHn1. reflexivity.
Qed.

Lemma mult_add_one:
  forall n1 n2,
    add n1 (mult n1 n2) = mult n1 (S n2).
Proof.
  induction n1; intro n2.
  - simpl. reflexivity.
  - simpl. rewrite add_swap. rewrite IHn1. reflexivity.
Qed.

Lemma mult_comm :
  forall n1 n2,
    mult n1 n2 = mult n2 n1.
Proof.
  induction n1; intro n2.
  - simpl. rewrite mult_zero. reflexivity.
  - simpl. rewrite IHn1. rewrite mult_add_one. reflexivity.
Qed.

(*
 * PROBLEM 2 [10 points, 5-10 tactics, plus 1-3 helper lemmas, each needing 5-10 tactics]
 * State and prove that the `mult` function is associative.
 *
 * Hint: Feel free to look up what associative means.
 *
 * Hint: You'll probably need 1-2 more lemmas about mult and/or add.
 *)
(*
 * PROBLEM 2 [10 points, 5-10 tactics, plus 1-3 helper lemmas, each needing 5-10 tactics]
 * State and prove that the `mult` function is associative.
 *
 * Hint: Feel free to look up what associative means.
 *
 * Hint: You'll probably need 1-2 more lemmas about mult and/or add.
 *)

Lemma add_assoc :
  forall n1 n2 n3,
    add n1 (add n2 n3) = add (add n1 n2) n3.
Proof.
  intros.
  induct n1.
  - simplify. reflexivity.
  - simplify. rewrite IHn1. reflexivity.
Qed.

Lemma add_S :
  forall n1 n2,
    add n1 (S n2) = S (add n1 n2).
Proof.
    induction n1; intro n2; simpl.
  - reflexivity.
  - rewrite IHn1. reflexivity.
Qed.

Lemma add_O :
  forall n1,
    add n1 O = n1.
Proof.
  intros.
  induct n1.
  - simplify. reflexivity.
  - simplify. rewrite IHn1. reflexivity.
Qed.

Lemma add_comm :
  forall n1 n2,
    add n1 n2 = add n2 n1.
Proof.
  induction n1; intro n2; simpl.
  - rewrite add_O. reflexivity.
  - rewrite add_S. rewrite IHn1. reflexivity.
Qed.

Lemma add_four_swap_middle :
  forall n1 n2 n3 n4,
    add (add n1 n2) (add n3 n4) = add (add n1 n3) (add n2 n4).
Proof.
  intros.
  rewrite <- (add_assoc n1).
  rewrite -> (add_assoc n2).
  rewrite -> (add_comm n2).
  rewrite <- (add_assoc n3).
  rewrite -> (add_assoc n1).
  reflexivity.
Qed.

Lemma mult_dist :
  forall n1 n2 n3,
    mult n1 (add n2 n3) = add (mult n1 n2) (mult n1 n3).
Proof.
  intros.
  induct n1.
  - simplify. reflexivity.
  - simplify. rewrite IHn1. rewrite add_four_swap_middle. reflexivity.
Qed.

Lemma mult_assoc :
  forall n1 n2 n3,
    mult n1 (mult n2 n3) = mult (mult n1 n2) n3.
Proof.
  intros.
  induct n1.
  - simplify. reflexivity.
  - simplify.
    rewrite IHn1.
    rewrite (mult_comm (add n2 (mult n1 n2)) n3).
    rewrite mult_dist.
    rewrite (mult_comm n3 n2).
    rewrite (mult_comm n3 (mult n1 n2)).
    reflexivity.
Qed.

End leftover_from_part_1. (* close the namespace *)

(*
 * Now that you've seen how nat, add, and mult are defined under the hood,
 * from now on we'll use the versions in Coq's standard library. These come
 * with nice notations like `1 + 3 * 4`, and with lots of free lemmas.
 *
 * There are also some useful tactics for working with arithmetic. Please
 * see FRAP section 2.4 for a discussion.
 *
 * Here are some automated proofs that the Coq standard library versions
 * of add and mult are commutative. (These lemmas are also in the standard
 * library, but we prove them from scratch just to demonstrate the tactics.)
 *)

Lemma add_comm_again :
  forall a b, a + b = b + a.
Proof.
  intros.
  linear_arithmetic.
Qed.

Lemma mult_comm_again :
  forall a b, a * b = b * a.
Proof.
  intros.
  Fail linear_arithmetic. (* doesn't work!! *)
  ring. (* works!! *)
Qed.

(*
 * PROBLEM 3 [8 points, 2 clear yes/no answers and ~4 sentences of explanation]
 * Answer the following in ~1 sentence each.  If the bullet point starts with a yes/no question,
 * be sure to state your yes/no answer clearly before proceeding to explain.
 *
 *   - Why does `linear_arithmetic` succeed on `add_comm_again`, but fail on `mult_comm_again`?
       Linear_arithmetic supports only addition. It supports multiplication by constants.

 *   - Why does `ring` succeed on `mult_comm_again`?
       Ring is used to normalize any ring structure(i.e. structures having rings and semi-rings
       like x(3+yx+25(1−z))+zx). A ring in a basic sense satisfies
       all the properties of addition and multiplication. The basic use of ring is to simplify
       ring expressions, so that the user does not have to deal manually with the
       theorems of associativity and commutativity. In a ring structure, associativity and
       distributivity of multiplication is supported.

 *   - Will `ring` succeed on `add_comm_again`? Why or why not?
       It will succeed. In ring structure addition is commutative and associative.

 *   - Is `ring` always more powerful than `linear_arithmetic`? Why or why not?
       I think 'ring' is a superset of linear arithmetic. So it should be more powerful than
       linear_arithmetic always.
 *)

(* --- Curry-Howard practice --- *)

Module curry_howard.
(*
 * In lecture, we looked at an inductive definition of the types `True` and `False`,
 * and talked about how they encode logical ideas as types.
 *
 * One of the deep connections in type theory is between logic and programming.
 * In fact, there are programming analogues to `True` and `False`.
 *)

Inductive unit : Type :=
| tt : unit.

Inductive empty : Type :=
.

(*
 * PROBLEM 4 [5 points, 1-2 sentences]
 * Explain in your own words the relationship between `unit` and `True`, and between
 * `empty` and `False`.
   unit is just any type. Whenever a label "tt" occurs we specify it as true.
   "empty" is a type which does not match to anything. So we cannot create false
   from anything.
 *)

(*
 * Here are two ways of defining the identity function on `unit`.
 *)

Definition unit_id1 (x : unit) : unit := x.  (* first way: just return the argument *)
Definition unit_id2 (x : unit) : unit :=
  match x with (* second way: take the argument apart and put it back together again *)
  | tt => tt
  end.

(*
 * PROBLEM 5 [5 points, ~3 tactics]
 * Prove that the two definition of the identity function on `unit` are the same
 * by proving the following lemma.
 *)
Lemma unit_id_same :
  forall x,
    unit_id1 x = unit_id2 x.
Proof.
  intros.
  rewrite unit_id1.
  rewrite unit_id2.
  reflexivity.
Qed.

(*
 * By analogy, we can also present two different proofs that True implies True.
 *)
Lemma True_implies_True1 :
  True -> True.
Proof.
  intro H. (* first way: just take the evidence of True and use it directly *)
  apply H.
Qed.

Lemma True_implies_True2 :
  True -> True.
Proof.
  intro H. (* second way: take apart the evidence of True and put it back together *)
  cases H.
  exact I.
Qed.

(*
 * We can ask Coq to print definitions using the `Print` command. This works
 * not only for things defined with Definition/Fixpoint, but also for things
 * defined via Lemma/Theorem.
 *
 * Coq prints things in a "de-sugared" form, with more type annotations, but
 * usually it's pretty easy to see how it corresponds to what you wrote.
 *)

Print unit_id1.
(*
 * This command prints `fun x : unit => x`, which is syntax for a function
 * that takes an argument `x` of type `unit` and just returns it,  which
 * is exactly what we wrote in the definition of `unit_id1`.
 *)

(*
 * We can also ask Coq to print the underlying proof term for the lemma
 * `True_implies_True1`.
 *)
Print True_implies_True1.

(*
 * We can similarly print the definitions for the second versions.
 *)
Print unit_id2.
Print True_implies_True2.

(*
 * PROBLEM 6 [8 points, 2 proofs, each with <5 tactics, and 2 definitions, each with <5 LOC]
 * Prove that False implies False in two different ways, one that just takes
 * the evidence of False and uses it directly, and one which takes it apart
 * and puts it back together again.
 *
 * For each proof, also print its proof term using the Print command. If you
 * see anything interesting or surprising, write a comment here. (worth 0 pts)
 *
 * Then, define two identity functions on `empty`, one which just returns its argument,
 * and one which takes its argument apart and puts it back together again.
 *
 * Hint: If you're stuck on the definitions, you can work by analogy to the proof terms
 * you saw by using the Print command on your proofs.
 *)
Lemma False_implies_False1 :
  False -> False.
Proof.
  intro H. (* first way: just take the evidence of True and use it directly *)
  apply H.
Qed.

Lemma False_implies_False2 :
  False -> False.
Proof.
  intro H. (* second way: take apart the evidence of True and put it back together *)
  cases H.
Qed.

Print False_implies_False1.
Print False_implies_False2.

Definition empty_id1 (x : empty) : empty := x.  (* first way: just return the argument *)
Definition empty_id2 (x : empty) : empty :=     (* second way: take the argument apart *)
  match x with
  end.

End curry_howard.

(* --- List practice --- *)

(* Here are some copied definitions from FRAP. *)
Inductive list (A : Type) : Type :=
| nil
| cons (hd : A) (tl : list A).

Arguments nil [A].
Infix "::" := cons.
Notation "[ ]" := nil.
Notation "[ x1 ; .. ; xN ]" := (cons x1 (.. (cons xN nil) ..)).

Fixpoint length {A} (ls : list A) : nat :=
  match ls with
  | nil => 0
  | _ :: ls' => 1 + length ls'
  end.

Fixpoint app {A} (ls1 ls2 : list A) : list A :=
  match ls1 with
  | nil => ls2
  | x :: ls1' => x :: app ls1' ls2
  end.
Infix "++" := app.

Fixpoint rev {A} (ls : list A) : list A :=
  match ls with
  | nil => nil
  | x :: ls' => rev ls' ++ [x]
  end.

Fixpoint rev_append {A} (ls acc : list A) : list A :=
  match ls with
  | nil => acc
  | x :: ls' => rev_append ls' (x :: acc)
  end.

Definition rev' {A} (ls : list A) : list A :=
  rev_append ls [].

(*
 * PROBLEM 7 [12 points, ~6 tactics plus 1 copy-pasted helper lemma from lecture]
 * Prove the following theorem about the length of a reversed list.
 *
 * Hint: Proceed by induction on l.
 *
 * Hint: You'll need a helper lemma from lecture. Feel free to copy-paste it
 * when you find it.
 *)

Theorem length_app : forall A (ls1 ls2 : list A),
    length (ls1 ++ ls2) = length ls1 + length ls2.
Proof.
  induct ls1; simplify; equality.
Qed.

Lemma length_rev :
  forall A (l : list A),
    length (rev l) = length l.
Proof.
  induct l.
  - simplify. reflexivity.
  - simplify. rewrite length_app. rewrite IHl. simplify. linear_arithmetic.
Qed.

(*
 * PROBLEM 8 [10 points, (1 alternate proof and a few sentences comparing to Adam's proof)
 *                      OR (an explanation of how to come up with rev_append_ok)]
 * Go back to rev'_ok and proceed directly by induction on `ls` and assume you did
 * not have access to the lemma rev_append_ok (or had not thought of it yet).
 *
 * Can you find an alternative proof? If so, provide it, and also explain what makes it
 * better/worse/different from Adam's proof. If you can't find an alternative (or if
 * you strongly dislike all the alternatives you can find), instead explain how
 * you might "come up" with the lemma rev_append_ok based on your experience getting
 * stuck during a direct proof.
 *)

(* The proof below works, but is more complex and less intuitive than Adam's proof.
   The natural approach to the proof -- the one I, at least, would come up with just
   on instinct -- would involve rev_append_ok.  The proof here "worked backward" in
   a sense -- note the step where it applies a reverse rewrite of the inductive
   hypothesis in the rev'_ok proof.

   On the other hand, inverting the theorem itself might have made this a more
   natural-feeling approach. *)
Lemma app_assoc :
  forall A (ls1 : list A) (ls2 : list A) (ls3 : list A),
    (ls1 ++ ls2) ++ ls3 = ls1 ++ (ls2 ++ ls3).
Proof.
  intros.
  induct ls1.
  - simplify. reflexivity.
  - simplify. rewrite IHls1. reflexivity.
Qed.

Lemma rev_append_empty_acc :
  forall A (ls1 : list A) (ls2 : list A),
    rev_append ls1 ls2 = rev_append ls1 [] ++ ls2.
Proof.
  intros.
  induct ls1.
  - simplify. reflexivity.
  - simplify.
    rewrite IHls1.
    rewrite (IHls1 [hd]).
    rewrite app_assoc.
    simplify.
    reflexivity.
Qed.

Theorem rev'_ok :
  forall A (ls : list A),
    rev' ls = rev ls.
Proof.
  induct ls.
  - simplify. reflexivity.
  - simplify.
    rewrite <- IHls.
    unfold rev'.
    simplify.
    rewrite rev_append_empty_acc.
    reflexivity.
Qed.

(* --- Binary Tree practice --- *)

(* More definitions copied from FRAP. *)
Inductive tree (A : Type) : Type :=
| Leaf
| Node : tree A -> A -> tree A -> tree A.
Arguments Leaf [A].

Fixpoint reverse {A} (t : tree A) : tree A :=
  match t with
  | Leaf => Leaf
  | Node l d r => Node (reverse r) d (reverse l)
  end.

(*
 * Here is a function that adds up all the elements of a list of nats.
 *)
Fixpoint sum_list (l : list nat) : nat :=
  match l with
  | [] => 0
  | x :: xs => x + sum_list xs
  end.

(*
 * PROBLEM 9 [5 points, ~5 LOC]
 * Define a function that adds up all the elements of a tree of nats.
 *)
Fixpoint sum_tree (t : tree nat) : nat :=
  match t with
  | Leaf => 0
  | Node l d r => (sum_tree l) + d + (sum_tree r)
  end.

(*
 * PROBLEM 10 [5 points, ~5 tactics]
 * Prove that `reverse` has no effect on the sum of the elements in a tree.
 *)
Lemma sum_tree_reverse :
  forall t,
    sum_tree (reverse t) = sum_tree t.
Proof.
  intros. induct t.
  - simplify. reflexivity.
  - simplify. rewrite IHt1. rewrite IHt2. linear_arithmetic.
Qed.

(*
 * PROBLEM 11 [12 points, 5-10 tactics, plus 1 helper lemma needing ~5 tactics]
 * Prove the following similar lemma about `sum_list` and `rev`.
 *
 * Hint: Proceed by induction on l.
 *
 * Hint: You'll need a helper lemma about sum_list.
 *)

Lemma sum_list_app :
  forall l1 l2,
    sum_list (l1 ++ l2) = sum_list l1 + sum_list l2.
Proof.
  intros. induct l1.
  - simplify. reflexivity.
  - simplify. rewrite IHl1. ring.
Qed.

Lemma sum_list_rev :
  forall l,
    sum_list (rev l) = sum_list l.
Proof.
  intros. induct l.
  - simplify. reflexivity.
  - simplify. rewrite sum_list_app. simplify. rewrite IHl. ring.
Qed.

(* --- Syntax practice --- *)

Module ArithWithConstants.
(* Copied from FRAP. *)
Inductive arith : Set :=
| Const (n : nat)
| Plus (e1 e2 : arith)
| Times (e1 e2 : arith).

(*
 * Here's a function that kind of sums up the constants in the syntax tree,
 * just like sum_tree did in the previous section. The difference is that
 * at a `Times` node, we multiply the values instead of adding them.
 *)
Fixpoint kinda_sum (e : arith) : nat :=
  match e with
  | Const n => n
  | Plus e1 e2 => kinda_sum e1 + kinda_sum e2
  | Times e1 e2 => kinda_sum e1 * kinda_sum e2
  end.

Compute kinda_sum (Plus (Const 1) (Const 1)). (* 2 *)
Compute kinda_sum (Times (Const 2) (Const 3)). (* 6 *)

(* From FRAP. *)
Fixpoint commuter (e : arith) : arith :=
  match e with
  | Const _ => e
  | Plus e1 e2 => Plus (commuter e2) (commuter e1)
  | Times e1 e2 => Times (commuter e2) (commuter e1)
  end.

(*
 * PROBLEM 12 [12 points, 5-10 tactics]
 * Prove the following theorem about kinda_sum and commuter.
 *)
Lemma kind_sum_commuter :
  forall e,
    kinda_sum e = kinda_sum (commuter e).
Proof.
  intros. induct e.
  - simplify. reflexivity.
  - simplify. rewrite IHe1. rewrite IHe2. ring.
  - simplify. rewrite IHe1. rewrite IHe2. ring.
Qed.

(* --- The End --- *)

(*
 * This is the end of part 2 of homework 1.
 *
 * To submit your homework, please follow the instructions at the end of the
 * README.md file in this directory.
 *
 * Please also see the README.md file to read about how we will grade this homework.
 *)

(* --- Challenge problem --- *)

(*
 * There's one more challenge problem below, which you can try if you like.
 * It will not be worth any points on this homework, or any future one,
 * but you will get to continue to play the video game called Coq.
 *
 * You already have all the techniques you need to solve it, but it is slightly
 * longer than the previous problems.
 *)

(*
 * We can define a version of constant folding from FRAP, but for arithmetic
 * without variables.
 *)

Fixpoint constantFold (e : arith) : arith :=
  match e with
  | Const _ => e
  | Plus e1 e2 =>
    let e1' := constantFold e1 in
    let e2' := constantFold e2 in
    match e1', e2' with
    | Const n1, Const n2 => Const (n1 + n2)
    | Const 0, _ => e2'
    | _, Const 0 => e1'
    | _, _ => Plus e1' e2'
    end
  | Times e1 e2 =>
    let e1' := constantFold e1 in
    let e2' := constantFold e2 in
    match e1', e2' with
    | Const n1, Const n2 => Const (n1 * n2)
    | Const 1, _ => e2'
    | _, Const 1 => e1'
    | Const 0, _ => Const 0
    | _, Const 0 => Const 0
    | _, _ => Times e1' e2'
    end
  end.

(*
 * PROBLEM 13 [0 points, ~15 tactics if taking advantage of `repeat match goal`,
 *                      many more tactics otherwise]
 *
 * Hint: You may want to copy some useful `repeat match goal` techniques from
 * the other FRAP proofs about constantFold.
 *)
Lemma kinda_sum_constantFold :
  forall e,
    kinda_sum (constantFold e) = kinda_sum e.
Proof.
  (* YOUR CODE HERE *)
Admitted. (* Change to Qed when done *)

End ArithWithConstants.


(** ** Определение натуральных чисел *)

Module NatNumbers.

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

Check nat.
Check O.
Check S.
Check (S O).
Check (S (S O)).

Definition pred (n : nat) : nat :=
match n with
| O => O
| S m => m
end.

Compute pred (S (S (S (S O)))).
  (* = S (S (S O))
     : nat *)
Compute pred O.

End NatNumbers.

Compute (S (S (S (S O)))).
Compute pred (S (S (S (S O)))).
  (* = 4
     : nat *)

Check pred (S (S (S (S O)))).
  (* ===> 4 : nat *)

Print NatNumbers.pred.

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

Check minustwo.

Compute (minustwo 5).
  (* ===> 2 : nat *)

Check S.
Check pred.
Check minustwo.

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

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

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

Module NatNumbers2.

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

Compute (plus 3 2).

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

Example test_mult1 :
  (mult 3 3) = 9.
Proof.
  reflexivity.
Qed.

Fixpoint minus (n m : nat) : nat :=
match n, m with
| O   , _    => O
| S _ , O    => n
| S n', S m' => minus n' m'
end.

End NatNumbers2.

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

Fixpoint factorial (n : nat) : nat :=
  (* написать определени факторила *)
match n with
| O => S O
| S p => mult n (factorial p)
end.

Example test_factorial1 :
  (factorial 3) = (plus 2 4).
Proof.
  reflexivity.
Qed.

Example test_factorial2 :
  (factorial 5) = (mult 10 12).
Proof.
  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.

Compute (2 + 3 * 4).

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.

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.

(*

Definition blt_nat (n m : nat) : bool :=
  (* написать фуекцию не используя рекурсию *)

Example test_blt_nat1 :
  (blt_nat 2 2) = false.
  (* проверить функцию *)

Example test_blt_nat2 :
  (blt_nat 2 4) = true.
  (* проверить функцию *)

Example test_blt_nat3 :
  (blt_nat 4 2) = false.
  (* проверить функцию *)
*)

(* ################################################################# *)
(** Доказательство простых теорем о натуральных числах *)

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

Theorem plus_1_l :
  forall n : nat,
  1 + n = S n.
Proof.
  intros n.
  reflexivity.
Qed.

Theorem mult_0_l :
  forall n:nat,
  0 * n = 0.
Proof.
  intros n.
  reflexivity.
Qed.

Theorem plus_id_example :
  forall n m : nat,
  n = m ->
  n + n = m + m.
Proof.
  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 *.
intros H1 H2.
rewrite H1.
rewrite H2.
reflexivity.
Qed.

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

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

Theorem plus_1_neq_0_firsttry :
  forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n.
  simpl.
Abort.

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

Theorem negb_involutive :
  forall b : bool,
  negb (negb b) = b.
Proof.
  intros b.
  destruct b.
  - reflexivity.
  - reflexivity.
Qed.

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 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 andb3_exchange :
  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.

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

Theorem andb_commutative'' :
  forall b c,
  andb b c = andb c b.
Proof.
  intros [] [].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.

(** Упражнение *)

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

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

(* пример неудачной функции *)

(*
Fixpoint plusx (n m : nat) : nat :=
  match n with
  | O => m
  | S p => S (plusx (pred n) m)
  end.
*)

(** Упражнения *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros * H b.
  repeat rewrite (H b).
  reflexivity.
Qed.

Theorem negation_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = negb x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros * H1 b.
  rewrite (H1 b).
  rewrite (H1 (negb b)).
  case b; reflexivity.
  (* построить доказательство *)
Qed.
Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  intros * H.
  case b, c; simpl in H;try reflexivity; rewrite H; reflexivity.

  (* построить доказательство *)
Qed.


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

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

(** *** 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] ("append") function concatenates 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.

(** 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
              | 0 => nonzeros t
              | n => n :: nonzeros t
              end
  end.

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

Fixpoint oddmembers (l:natlist) : natlist :=
  match l with
  | nil => nil
  | h :: t => match (oddb h) with
              | true  => h :: oddmembers t
              | false => oddmembers t
              end
  end.

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

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

Example test_countoddmembers1:    countoddmembers [1;0;3;1;4;5] = 4.
  reflexivity. Qed.
Example test_countoddmembers2:    countoddmembers [0;2;4] = 0.
  reflexivity. Qed.
Example test_countoddmembers3:    countoddmembers nil = 0.
  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 : natlist) := fix alternate_r (l2 : natlist) :=
  match l1, l2 with
  | nil,      nil      => nil
  | nil,      h2 :: t2 => h2 :: alternate_r t2           (* l1 does not reduce in this case, use inner fixpoint *)
  | h1 :: t1, nil      => h1 :: alternate t1 l2
  | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2
  end.

Example test_alternate1:        alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
  reflexivity. Qed.
Example test_alternate2:        alternate [1] [4;5;6] = [1;4;5;6].
  reflexivity. Qed.
Example test_alternate3:        alternate [1;2;3] [4] = [1;4;2;3].
  reflexivity. Qed.
Example test_alternate4:        alternate [] [20;30] = [20;30].
  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    => 0
  | n :: t => match (beq_nat n v) with
              | true  => S (count v t)
              | false => count v t
              end
  end.

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

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

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

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

Definition member (v:nat) (s:bag) : bool := negb (beq_nat 0 (count v s)).

Example test_member1:             member 1 [1;4;1] = true.
  reflexivity. Qed.
Example test_member2:             member 2 [1;4;1] = false.
  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 :=
  (* When remove_one is applied to a bag without the number to remove,
     it should return the same bag unchanged. *)
  match s with
  | nil    => nil
  | n :: t => match (beq_nat n v) with
              | true  => t
              | false => n :: (remove_one v t)
              end
  end.

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

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

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

Fixpoint subset (s1:bag) (s2:bag) : bool :=
  match s1 with
  | nil     => true
  | v :: t1 => if (member v s2) then subset t1 (remove_one v s2)
                                else false
  end.

Example test_subset1:              subset [1;2] [2;1;4;1] = true.
  reflexivity. Qed.
Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
  reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars (bag_theorem) *)
(** Write down an interesting 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 list_add_length_increases:
  forall (l : natlist) (v : nat),
    S (length l) = length (add v l).
Proof.
  reflexivity.
Qed.

(** [] *)

(* ###################################################### *)
(** * 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 proofs 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 of the proof 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.

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

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 = []".
    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".
    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".
    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 [|v l'].
  Case "l = []". reflexivity.
  Case "l = v :: l'". simpl. rewrite IHl'. reflexivity.
Qed.

Theorem rev_snoc : forall n : nat, forall l : natlist,
  rev (snoc l n) = n :: rev l.
Proof.
  intros n l. induction l as [|h l'].
  Case "l = []". reflexivity.
  Case "l = h::l'". simpl. rewrite IHl'. reflexivity.
Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  induction l as [|v l'].
  Case "l = []". reflexivity.
  Case "l = v::l'". simpl. rewrite rev_snoc. 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 l1 l2 l3 l4. rewrite app_assoc. rewrite app_assoc. reflexivity.
Qed.

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

Theorem distr_rev : forall l1 l2 : natlist,
  rev (l1 ++ l2) = (rev l2) ++ (rev l1).
Proof.
  intros l1 l2. induction l1 as [|v l'].
  Case "l1 = []". simpl. rewrite app_nil_end. reflexivity.
  Case "l1 = v::l'". 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 l1 l2. induction l1 as [|v l'].
  Case "l1 = []". reflexivity.
  Case "l1 = v::l'". induction v as [|v'].
    SCase "v = 0". simpl. rewrite IHl'. reflexivity.
    SCase "v = S v'". simpl. rewrite IHl'. 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
  | h1 :: t1, h2 :: t2 => if (beq_nat h1 h2) then (beq_natlist t1 t2) else false
  | _, _               => false
  end.

Example test_beq_natlist1 :   (beq_natlist nil nil = true).
  reflexivity. Qed.
Example test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.
  reflexivity. Qed.
Example test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.
  reflexivity. Qed.

Theorem beq_natlist_refl : forall l:natlist,
  true = beq_natlist l l.
Proof.
  intros l. induction l as [|v l'].
  Case "l = []". reflexivity.
  Case "l = v::l'". 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 involving [cons]
       ([::]), [snoc], and [app] ([++]).
     - Prove it. *)

Theorem app_cons_snoc_sandwiched : forall (l1 l2 : natlist) (v : nat),
  l1 ++ (v :: l2) = (snoc l1 v) ++ l2.
Proof.
  intros l1 l2 v. induction l1 as [|v1 t1].
  Case "l1 = []". simpl. reflexivity.
  Case "l1 = v1::t1". simpl. rewrite IHt1. reflexivity.
Qed.
(** [] *)

(** **** 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 s. 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.
  induction s as [|v s'].
  Case "s = []". simpl. reflexivity.
  Case "s = v::s'". destruct v as [|v'].
    SCase "v = 0". simpl. rewrite ble_n_Sn. reflexivity.
    SCase "v = S n'". simpl. rewrite IHs'. reflexivity.
Qed.
(** [] *)

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

(** **** 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 l1 l2 H. rewrite <- rev_involutive. rewrite <- H. rewrite rev_involutive. reflexivity.
Qed.
(** [] *)

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

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

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.

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

Example test_hd_opt2 : hd_opt [1] = Some 1.
  reflexivity. Qed.

Example test_hd_opt3 : hd_opt [5;6] = Some 5.
  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 l default. destruct l as [|v l'].
  Case "l = []". simpl. reflexivity.
  Case "l = v::l'". 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).

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

(** **** 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 d k v. 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 d m n o H. simpl. rewrite H. reflexivity.
Qed.
(** [] *)

End Dictionary.

End NatList.

(* $Date: 2014-01-28 13:19:45 -0500 (Tue, 28 Jan 2014) $ *)


Require Import Coq.Arith.Arith.
Require Import Coq.Lists.List.
Import ListNotations.

(* A monoid is a type equipped with an append operation and an empty element
that "does nothing" with respect to the append operation. It turns out that
monoids are a very useful and general abstract data type.

In Coq, we can add "proof obligations" to this datatype, that show that an
instance of monoid behaves the right way. In particular, we want the empty
value to behave like unit, and append must be associative. *)
Record Monoid (A : Type) := {

  (* Empty element is an instance of A. *)
  empty : A;

  (* The append binary operation. *)
  append : A -> A -> A;

  (* The proof obligations (i.e., a formal specification). *)
  left_identity : forall m, append empty m = m;
  right_identity : forall m, append m empty = m;
  assoc : forall m n o, append m (append n o) = append (append m n) o;
}.

(* Natural numbers form a monoid under addition, with 0 as empty element. *)
Program Definition NatAddMonoid : Monoid nat := {|
  empty  := 0;
  append := plus;
|}.

(* Coq can prove left_identity (that is, forall n, 0 + n = n) and
right_identity (forall n, n + 0 = n) automatically, but it fails on assoc so
we need to help. To satisify this obligation we have to prove that
forall m n o, m + (n + o) = (m + n) + o.*)
Next Obligation. apply Nat.add_assoc. Qed.

(* Natural numbers also form a monoid under multiplication, with 1 as the
empty element. *)
Program Definition NatMultMonoid : Monoid nat := {|
  empty  := 1;
  append := mult;
|}.
Next Obligation. apply Nat.mul_1_r. Qed.
Next Obligation. apply Nat.mul_assoc. Qed.

(* Next we define a (very simple) algorithm on monoids. The key idea is that
reduce will work for *any* monoid, without knowing anything beyond the
abstract Monoid specification.

Moreover, in Coq we can use our monoid facts (identity and assoc) to *prove*
reduce will behave as per a specification without knowing anything else about
any particular monoid.

It's like saying, "give me a monoid, and I will give you a reduce operation on
that monoid. And if you can prove your monoid really does behave like a
monoid, then I will prove that reduce will behave like reduce ought to."
*)
Section Reduce.
  Variable A : Type.
  Variable m : Monoid A.
  (* It might help to think of m as *evidence* that A implements Monoid. *)

  Fixpoint reduce (xs : list A) : A :=
    match xs with
    | [] => empty _ m
    | x::xs' => append _ m x (reduce xs')
    end.

  Theorem reduce_one :
    forall x, reduce [x] = x.
  Proof.
    intros x.
    simpl.
    apply (right_identity _ m).
  Qed.

  Theorem reduce_app :
    forall l1 l2,
      reduce (l1 ++ l2) = append _ m (reduce l1) (reduce l2).
  Proof.
    intros l1 l2.
    induction l1; simpl.
    - symmetry.
      apply (left_identity _ m).
    - rewrite IHl1.
      apply (assoc _ m).
  Qed.
End Reduce.

(* Using the abstract idea of reduce, along with our concrete monoid instance
of natural numbers under addition, it is very easy to define summation... *)
Definition sum : list nat -> nat := reduce _ NatAddMonoid.
Compute (sum [1;2;3;4;5]).

(* ... and to prove useful, concrete things about how it behaves. *)
Theorem sum_app :
  forall ns ms, sum (ns ++ ms) = sum ns + sum ms.
Proof.
  (* This is just an instance of our reduce_app proof from above. *)
  exact (reduce_app _ NatAddMonoid).
Qed.

(* Same idea but for product. *)
Definition product : list nat -> nat := reduce _ NatMultMonoid.
Compute (product [1;2;3;4;5]).

Theorem product_app :
  forall ns ms, product (ns ++ ms) = product ns * product ms.
Proof.
  exact (reduce_app _ NatMultMonoid).
Qed.

(* One more example. Lists of elements drawn from some arbitrary type form a
monoid under concatenation. This definition has to be parametric in the list
element type. We are effectively defining a *family* of monoids here -- for
every type A, the type list A is a monoid. *)
Program Definition ListMonoid (A : Type) : Monoid (list A) := {|
  empty  := [];
  append := @app A;
|}.

Next Obligation. apply app_nil_r. Qed.
Next Obligation. apply app_assoc. Qed.

(* Flatten takes a list of lists and combines them all into one list. *)
Definition flatten {A : Type} : list (list A) -> list A :=
  reduce _ (ListMonoid _).

Compute (flatten [[1;2;3]; [4;5]; []; [6;7;8;9;10]]).

(* Exercise: come up with a monoid instance for bool (as with nat, which we
saw had instances for both add and mult, for bool there's more than one
possible instance). What would be a good function name for reduce on your
instance? *)

(** FILL IN HERE
Program Definition BoolMonoid : Monoid bool := {|
  empty  := *a boolean value* ;
  append := *a binary operation on bool* ;
|}.

Next Obligation. ****

Definition **** : list bool -> bool := reduce _ BoolMonoid.
*)


Require Import Arith List Bool.

(* EXAMPLES *)

(* The following function takes two arguments a and b
which are numbers of type nat and returns b + 2 * (a + b) *)
Definition f_ex (a b : nat) := b + 2 * (a + b).

(* When p is a pair, you can access its components by the "pattern-matching"
  construct illustrated in the following function. *)

Definition add_pair_components (p : nat * nat) :=
  match p with (a, b) => a + b end.

(* f_ex is a function with two arguments.  add_pair_components is a
  function with one argument, which is a pair. *)

(* END OF EXAMPLES *)

(* 1/ Define a function that takes two numbers as arguments and returns
  the sum of the squares of these numbers. *)

Definition f1_1 (x y : nat) : nat := x * x + y * y.

(* 2/ Define a function that takes 5 arguments a b c d e, which are all
   numbers and returns the sum of all these numbers. *)

Definition f1_2 (a b c d e : nat) := a + b + c + d + e.

(* 3/ Define a function named add5 that takes a number as argument and returns
   this number plus 5. *)

Definition add5 (x : nat) := x + 5.

(* The following should return 8 *)
Compute add5 3.

(* The following commands make it possible to find pre-defined functions *)

(* 4/ Write a function swap of type list nat -> list nat such that
  swap (a::b::l) = (b::a::l)  and
  swap l' = l' if l' has less than 2 elements. *)

Definition swap (l : list nat) : list nat :=
 match l with
   a::b::l => b::a::l
 | _ => l
 end.

(* 5/ Write a function proc2 of type list nat -> nat, such that
   proc2 (a::b::l) = (b + 3) and
   proc2 l' = 0 if l' has less than 2 elements.

   In other words, proc2 only processes the 2nd argument of the list and
   returns that number plus 3.  If there is no second argument to the list,
   proc2 returns 0.  *)

Definition proc2 (l : list nat) : nat :=
  match l with
    a::b::l => b + 3
  | _ => 0
  end.

(* 6/ Write a function ms of type list nat -> list nat such that
      ms (a::b::...::nil) = a+2::b+2::...::nil
      For instance
      ms (2::3::5::nil) = (4::5::7::nil) *)

Fixpoint ms (l : list nat) : list nat :=
  match l with
    a::l' => a + 2 :: ms l'
  | nil => nil
  end.

(* 7/ Write a function sorted of type list nat -> bool, such that
    sorted l = true exactly when the natural numbers in
   l are in increasing order. *)
Locate leb.
Fixpoint sorted (l : list nat) : bool :=
  match l with
    a::l' =>
    match l' with b::_ =>
                  if Nat.leb a b then sorted l' else false | _ => true end
  | nil => true
  end.

(* 8/ Write a function p2 of type nat -> nat such that
    p2 n = 2 ^ n *)

Fixpoint p2 (n : nat) :=
  match n with 0 => 1 | S p => 2 * p2 p end.

(* 9/ Write a function salt of type nat -> nat -> nat such that
   salt x n = x ^ n - x^ (n-1) + x^(n-2) .... + 1 or -1, if x <> 0,
   depending on the parity of n, thus
   salt x 3 = x^3 - x^2 + x - 1
   salt x 4 = x^4 - x^3 + x^2 - x + 1
   salt 2 3 = 5

   You may have to define auxiliary functions. *)

Fixpoint even n :=
  match n with 0 => true | 1 => false | S (S p) => even p end.

Fixpoint salt (x n : nat) :=
  match n with
    0 => 1
  | S p => if even n then x * salt x p + 1 else x * salt x p - 1
  end.

Fixpoint pow x n :=
  match n with 0 => 1 | S p => x * pow x p end.


Inductive nat : Set :=
 | O : nat
 | S : nat->nat.
Check nat.
Check O.
Check S.

Reset nat.
Print nat.

Print le.

Theorem zero_leq_three: 0 <= 3.

Proof.
 constructor 2.
 constructor 2.
 constructor 2.
 constructor 1.

Qed.

Print zero_leq_three.

Lemma zero_leq_three': 0 <= 3.
 repeat constructor.
Qed.

Lemma zero_lt_three : 0 < 3.
Proof.
 unfold lt.
 repeat constructor.
Qed.

Require Import List.

Print list.

Check list.

Check (nil (A:=nat)).

Check (nil (A:= nat -> nat)).

Check (fun A: Set => (cons (A:=A))).

Check (cons 3 (cons 2 nil)).

Require Import Bvector.

Print vector.

Check (Vnil nat).

Check (fun (A:Set)(a:A)=> Vcons _ a _ (Vnil _)).

Check (Vcons _ 5 _ (Vcons _ 3 _ (Vnil _))).

Lemma eq_3_3 : 2 + 1 = 3.
Proof.
 reflexivity.
Qed.
Print eq_3_3.

Lemma eq_proof_proof : refl_equal (2*6) = refl_equal (3*4).
Proof.
 reflexivity.
Qed.
Print eq_proof_proof.

Lemma eq_lt_le : ( 2 < 4) = (3 <= 4).
Proof.
 reflexivity.
Qed.

Lemma eq_nat_nat : nat = nat.
Proof.
 reflexivity.
Qed.

Lemma eq_Set_Set : Set = Set.
Proof.
 reflexivity.
Qed.

Lemma eq_Type_Type : Type = Type.
Proof.
 reflexivity.
Qed.

Check (2 + 1 = 3).

Check (Type = Type).

Goal Type = Type.
reflexivity.
Qed.

Print or.

Print and.

Print sumbool.

Print ex.

Require Import ZArith.
Require Import Compare_dec.

Check le_lt_dec.

Definition max (n p :nat) := match le_lt_dec n p with
                             | left _ => p
                             | right _ => n
                             end.

Theorem le_max : forall n p, n <= p -> max n p = p.
Proof.
 intros n p ; unfold max ; case (le_lt_dec n p); simpl.
 trivial.
 intros; absurd (p < p); eauto with arith.
Qed.

Extraction max.

Inductive tree(A:Set)   : Set :=
    node : A -> forest A -> tree A
with
  forest (A: Set)    : Set :=
    nochild  : forest A |
    addchild : tree A -> forest A -> forest A.

Inductive
  even    : nat->Prop :=
    evenO : even  O |
    evenS : forall n, odd n -> even (S n)
with
  odd    : nat->Prop :=
    oddS : forall n, even n -> odd (S n).

Lemma odd_49 : odd (7 * 7).
 simpl; repeat constructor.
Qed.

Definition nat_case :=
 fun (Q : Type)(g0 : Q)(g1 : nat -> Q)(n:nat) =>
    match n return Q with
    | 0 => g0
    | S p => g1 p
    end.

Eval simpl in (nat_case nat 0 (fun p => p) 34).

Eval simpl in (fun g0 g1 => nat_case nat g0 g1 34).

Eval simpl in (fun g0 g1 => nat_case nat g0 g1 0).

Definition pred (n:nat) := match n with O => O | S m => m end.

Eval simpl in pred 56.

Eval simpl in pred 0.

Eval simpl in fun p => pred (S p).

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

 Definition pred_spec (n:nat) := {m:nat | n=0 /\ m=0  \/ n = S m}.

 Definition predecessor : forall n:nat, pred_spec n.
  intro n;case n.
  unfold pred_spec;exists 0;auto.
  unfold pred_spec; intro n0;exists n0; auto.
 Defined.

Print predecessor.

Extraction predecessor.

Theorem nat_expand :
  forall n:nat, n = match n with 0 => 0 | S p => S p end.
 intro n;case n;simpl;auto.
Qed.

Check (fun p:False => match p return 2=3 with end).

Theorem fromFalse : False -> 0=1.
 intro absurd.
 contradiction.
Qed.

Section equality_elimination.
 Variables (A: Type)
           (a b : A)
           (p : a = b)
           (Q : A -> Type).
 Check (fun H : Q a =>
  match p in (eq _  y) return Q y with
     refl_equal => H
  end).

End equality_elimination.

Theorem trans : forall n m p:nat, n=m -> m=p -> n=p.
Proof.
 intros n m p eqnm.
 case eqnm.
 trivial.
Qed.

Lemma Rw :  forall x y: nat, y = y * x -> y * x * x = y.
 intros x y e; do 2 rewrite <- e.
 reflexivity.
Qed.

Require Import Arith.

Check mult_1_l.
(*
mult_1_l
     : forall n : nat, 1 * n = n
*)

Check mult_plus_distr_r.
(*
mult_plus_distr_r
     : forall n m p : nat, (n + m) * p = n * p + m * p

*)

Lemma mult_distr_S : forall n p : nat, n * p + p = (S n)* p.
 simpl;auto with arith.
Qed.

Lemma four_n : forall n:nat, n+n+n+n = 4*n.
 intro n;rewrite <- (mult_1_l n).

 Undo.
 intro n; pattern n at 1.

 rewrite <- mult_1_l.
 repeat rewrite   mult_distr_S.
 trivial.
Qed.

Section Le_case_analysis.
 Variables (n p : nat)
           (H : n <= p)
           (Q : nat -> Prop)
           (H0 : Q n)
           (HS : forall m, n <= m -> Q (S m)).
 Check (
    match H in (_ <= q) return (Q q)  with
    | le_n => H0
    | le_S m Hm => HS m Hm
    end
  ).

End Le_case_analysis.

Lemma predecessor_of_positive : forall n, 1 <= n ->  exists p:nat, n = S p.
Proof.
 intros n  H; case H.
 exists 0; trivial.
 intros m Hm; exists m;trivial.
Qed.

Definition Vtail_total
   (A : Set) (n : nat) (v : vector A n) : vector A (pred n):=
match v in (vector _ n0) return (vector A (pred n0)) with
| Vnil => Vnil A
| Vcons _ n0 v0 => v0
end.

Definition Vtail' (A:Set)(n:nat)(v:vector A n) : vector A (pred n).
 case v.
 simpl.
 exact (Vnil A).
 simpl.
 auto.
Defined.

(*
Inductive Lambda : Set :=
  lambda : (Lambda -> False) -> Lambda.

Error: Non strictly positive occurrence of "Lambda" in
 "(Lambda -> False) -> Lambda"

*)

Section Paradox.
 Variable Lambda : Set.
 Variable lambda : (Lambda -> False) ->Lambda.

 Variable matchL  : Lambda -> forall Q:Prop, ((Lambda ->False) -> Q) -> Q.
 (*
  understand matchL Q l (fun h : Lambda -> False => t)

  as match l return Q with lambda h => t end
 *)

 Definition application (f x: Lambda) :False :=
   matchL f False (fun h => h x).

 Definition Delta : Lambda := lambda (fun x : Lambda => application x x).

 Definition loop : False := application Delta Delta.

 Theorem two_is_three : 2 = 3.
 Proof.
  elim loop.
 Qed.

End Paradox.

Require Import ZArith.

Inductive itree : Set :=
| ileaf : itree
| inode : Z-> (nat -> itree) -> itree.

Definition isingle l := inode l (fun i => ileaf).

Definition t1 := inode 0 (fun n => isingle (Z_of_nat (2*n))).

Definition t2 := inode 0
                      (fun n : nat =>
                               inode (Z_of_nat n)
                                     (fun p => isingle (Z_of_nat (n*p)))).

Inductive itree_le : itree-> itree -> Prop :=
  | le_leaf : forall t, itree_le  ileaf t
  | le_node  : forall l l' s s',
                       Zle l l' ->
                      (forall i, exists j:nat, itree_le (s i) (s' j)) ->
                      itree_le  (inode  l s) (inode  l' s').

Theorem itree_le_trans :
  forall t t', itree_le t t' ->
               forall t'', itree_le t' t'' -> itree_le t t''.
 induction t.
 constructor 1.

 intros t'; case t'.
 inversion 1.
 intros z0 i0 H0.
 intro t'';case t''.
 inversion 1.
 intros.
 inversion_clear H1.
 constructor 2.
 inversion_clear H0;eauto with zarith.
 inversion_clear H0.
 intro i2; case (H4 i2).
 intros.
 generalize (H i2 _ H0).
 intros.
 case (H3 x);intros.
 generalize (H5 _ H6).
 exists x0;auto.
Qed.

Inductive itree_le' : itree-> itree -> Prop :=
  | le_leaf' : forall t, itree_le'  ileaf t
  | le_node' : forall l l' s s' g,
                       Zle l l' ->
                      (forall i, itree_le' (s i) (s' (g i))) ->
                       itree_le'  (inode  l s) (inode  l' s').

Lemma t1_le_t2 : itree_le t1 t2.
 unfold t1, t2.
 constructor.
 auto with zarith.
 intro i; exists (2 * i).
 unfold isingle.
 constructor.
 auto with zarith.
 exists i;constructor.
Qed.

Lemma t1_le'_t2 :  itree_le' t1 t2.
 unfold t1, t2.
 constructor 2  with (fun i : nat => 2 * i).
 auto with zarith.
 unfold isingle;
 intro i ; constructor 2 with (fun i :nat => i).
 auto with zarith.
 constructor .
Qed.

Require Import List.

Inductive ltree  (A:Set) : Set :=
          lnode   : A -> list (ltree A) -> ltree A.

Inductive prop : Prop :=
 prop_intro : Prop -> prop.

Lemma prop_inject: prop.
Proof prop_intro prop.

Inductive ex_Prop  (P : Prop -> Prop) : Prop :=
  exP_intro : forall X : Prop, P X -> ex_Prop P.

Lemma ex_Prop_inhabitant : ex_Prop (fun P => P -> P).
Proof.
  exists (ex_Prop (fun P => P -> P)).
 trivial.
Qed.

(*

Check (fun (P:Prop->Prop)(p: ex_Prop P) =>
      match p with exP_intro X HX => X end).
Error:
Incorrect elimination of "p" in the inductive type
"ex_Prop", the return type has sort "Type" while it should be
"Prop"

Elimination of an inductive object of sort "Prop"
is not allowed on a predicate in sort "Type"
because proofs can be eliminated only to build proofs

*)

(*
Check (match prop_inject with (prop_intro P p) => P end).

Error:
Incorrect elimination of "prop_inject" in the inductive type
"prop", the return type has sort "Type" while it should be
"Prop"

Elimination of an inductive object of sort "Prop"
is not allowed on a predicate in sort "Type"
because proofs can be eliminated only to build proofs

*)
Print prop_inject.

(*
prop_inject =
prop_inject = prop_intro prop (fun H : prop => H)
     : prop
*)

Inductive  typ : Type :=
  typ_intro : Type -> typ.

Definition typ_inject: typ.
split.
exact typ.
(*
Defined.

Error: Universe Inconsistency.
*)
Abort.
(*

Inductive aSet : Set :=
  aSet_intro: Set -> aSet.

User error: Large non-propositional inductive types must be in Type

*)

Inductive ex_Set  (P : Set -> Prop) : Type :=
  exS_intro : forall X : Set, P X -> ex_Set P.

Inductive comes_from_the_left (P Q:Prop): P \/ Q -> Prop :=
  c1 : forall p, comes_from_the_left P Q (or_introl (A:=P) Q p).

Goal (comes_from_the_left _ _ (or_introl  True I)).
split.
Qed.

Goal ~(comes_from_the_left _ _ (or_intror True I)).
 red;inversion 1.
 (* discriminate H0.
 *)
Abort.

Reset comes_from_the_left.

(*

 Definition comes_from_the_left (P Q:Prop)(H:P \/ Q): Prop :=
  match H with
         |  or_introl p => True
         |  or_intror q => False
  end.

Error:
Incorrect elimination of "H" in the inductive type
"or", the return type has sort "Type" while it should be
"Prop"

Elimination of an inductive object of sort "Prop"
is not allowed on a predicate in sort "Type"
because proofs can be eliminated only to build proofs

*)

Definition comes_from_the_left_sumbool
            (P Q:Prop)(x:{P}+{Q}): Prop :=
  match x with
         |  left  p => True
         |  right q => False
  end.

Close Scope Z_scope.

Theorem S_is_not_O : forall n, S n <> 0.

Definition Is_zero (x:nat):= match x with
                                     | 0 => True
                                     | _ => False
                             end.
 Lemma O_is_zero : forall m, m = 0 -> Is_zero m.
 Proof.
  intros m H; subst m.
  (*
  ============================
   Is_zero 0
  *)
  simpl;trivial.
 Qed.

 red; intros n Hn.
 apply O_is_zero with (m := S n).
 assumption.
Qed.

Theorem disc2 : forall n, S (S n) <> 1.
Proof.
 intros n Hn; discriminate.
Qed.

Theorem disc3 : forall n, S (S n) = 0 -> forall Q:Prop, Q.
Proof.
  intros n Hn Q.
  discriminate.
Qed.

Theorem inj_succ  : forall n m, S n = S m -> n = m.
Proof.

Lemma inj_pred : forall n m, n = m -> pred n = pred m.
Proof.
 intros n m eq_n_m.
 rewrite eq_n_m.
 trivial.
Qed.

 intros n m eq_Sn_Sm.
 apply inj_pred with (n:= S n) (m := S m); assumption.
Qed.

Lemma list_inject : forall (A:Set)(a b :A)(l l':list A),
                     a :: b :: l = b :: a :: l' -> a = b /\ l = l'.
Proof.
 intros A a b l l' e.
 injection e.
 auto.
Qed.

Theorem not_le_Sn_0 : forall n:nat, ~ (S n <= 0).
Proof.
 red; intros n H.
 case H.
Undo.

Lemma not_le_Sn_0_with_constraints :
  forall n p , S n <= p ->  p = 0 -> False.
Proof.
 intros n p H; case H ;
   intros; discriminate.
Qed.

eapply not_le_Sn_0_with_constraints; eauto.
Qed.

Theorem not_le_Sn_0' : forall n:nat, ~ (S n <= 0).
Proof.
 red; intros n H ; inversion H.
Qed.

Derive Inversion le_Sn_0_inv with (forall n :nat, S n <=  0).
Check le_Sn_0_inv.

Theorem le_Sn_0'' : forall n p : nat, ~ S n <= 0 .
Proof.
 intros n p H;
 inversion H using le_Sn_0_inv.
Qed.

Derive Inversion_clear le_Sn_0_inv' with (forall n :nat, S n <=  0).
Check le_Sn_0_inv'.

Theorem le_reverse_rules :
 forall n m:nat, n <= m ->
                   n = m \/
                   exists p, n <=  p /\ m = S p.
Proof.
  intros n m H; inversion H.
  left;trivial.
  right; exists m0; split; trivial.
Restart.
  intros n m H; inversion_clear H.
  left;trivial.
  right; exists m0; split; trivial.
Qed.

Inductive ArithExp : Set :=
     Zero : ArithExp
   | Succ : ArithExp -> ArithExp
   | Plus : ArithExp -> ArithExp -> ArithExp.

Inductive RewriteRel : ArithExp -> ArithExp -> Prop :=
     RewSucc  : forall e1 e2 :ArithExp,
                  RewriteRel e1 e2 -> RewriteRel (Succ e1) (Succ e2)
  |  RewPlus0 : forall e:ArithExp,
                  RewriteRel (Plus Zero e) e
  |  RewPlusS : forall e1 e2:ArithExp,
                  RewriteRel e1 e2 ->
                  RewriteRel (Plus (Succ e1) e2) (Succ (Plus e1 e2)).

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

Fixpoint plus' (n p:nat) {struct p} : nat :=
    match p with
          | 0 => n
          | S q => S (plus' n q)
    end.

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

Fixpoint even_test (n:nat) : bool :=
  match n
  with 0 =>  true
     | 1 =>  false
     | S (S p) => even_test p
  end.

Reset even_test.

Fixpoint even_test (n:nat) : bool :=
  match n
  with
      | 0 =>  true
      | S p => odd_test p
  end
with odd_test (n:nat) : bool :=
  match n
  with
     | 0 => false
     | S p => even_test p
 end.

Eval simpl in even_test.

Eval simpl in (fun x : nat => even_test x).

Eval simpl in (fun x : nat => plus 5 x).
Eval simpl in (fun x : nat => even_test (plus 5 x)).

Eval simpl in (fun x : nat => even_test (plus x 5)).

Section Principle_of_Induction.
Variable    P               : nat -> Prop.
Hypothesis  base_case       : P 0.
Hypothesis  inductive_step   : forall n:nat, P n -> P (S n).
Fixpoint nat_ind  (n:nat)    : (P n) :=
   match n return P n with
          | 0 => base_case
          | S m => inductive_step m (nat_ind m)
   end.

End Principle_of_Induction.

Scheme Even_induction := Minimality for even Sort Prop
with   Odd_induction  := Minimality for odd  Sort Prop.

Theorem even_plus_four : forall n:nat, even n -> even (4+n).
Proof.
 intros n H.
 elim H using Even_induction with (P0 := fun n => odd (4+n));
 simpl;repeat constructor;assumption.
Qed.

Section Principle_of_Double_Induction.
Variable    P               : nat -> nat ->Prop.
Hypothesis  base_case1      : forall x:nat, P 0 x.
Hypothesis  base_case2      : forall x:nat, P (S x) 0.
Hypothesis  inductive_step   : forall n m:nat, P n m -> P (S n) (S m).
Fixpoint nat_double_ind (n m:nat){struct n} : P n m :=
  match n, m return P n m with
         |  0 ,     x    =>  base_case1 x
         |  (S x),    0  =>  base_case2 x
         |  (S x), (S y) =>  inductive_step x y (nat_double_ind x y)
     end.
End Principle_of_Double_Induction.

Section Principle_of_Double_Recursion.
Variable    P               : nat -> nat -> Set.
Hypothesis  base_case1      : forall x:nat, P 0 x.
Hypothesis  base_case2      : forall x:nat, P (S x) 0.
Hypothesis  inductive_step   : forall n m:nat, P n m -> P (S n) (S m).
Fixpoint nat_double_rec (n m:nat){struct n} : P n m :=
  match n, m return P n m with
         |   0 ,     x    =>  base_case1 x
         |  (S x),    0   => base_case2 x
         |  (S x), (S y)  => inductive_step x y (nat_double_rec x y)
     end.
End Principle_of_Double_Recursion.

Definition min : nat -> nat -> nat  :=
  nat_double_rec (fun (x y:nat) => nat)
                 (fun (x:nat) => 0)
                 (fun (y:nat) => 0)
                 (fun (x y r:nat) => S r).

Eval compute in (min 5 8).
Eval compute in (min 8 5).

Lemma not_circular : forall n:nat, n <> S n.
Proof.
 intro n.
 apply nat_ind with (P:= fun n => n <> S n).
 discriminate.
 red; intros n0 Hn0 eqn0Sn0;injection eqn0Sn0;trivial.
Qed.

Definition eq_nat_dec : forall n p:nat , {n=p}+{n <> p}.
Proof.
 intros n p.
 apply nat_double_rec with (P:= fun (n q:nat) => {q=p}+{q <> p}).
Undo.
 pattern p,n.
 elim n using nat_double_rec.
 destruct x; auto.
 destruct x; auto.
 intros n0 m H; case H.
 intro eq; rewrite eq ; auto.
 intro neg; right; red ; injection 1; auto.
Defined.

Definition eq_nat_dec' : forall n p:nat, {n=p}+{n <> p}.
 decide equality.
Defined.

Print Acc.

Require Import Minus.

(*
Fixpoint div (x y:nat){struct x}: nat :=
 if eq_nat_dec x 0
  then 0
  else if eq_nat_dec y 0
       then x
       else S (div (x-y) y).

Error:
Recursive definition of div is ill-formed.
In environment
div : nat -> nat -> nat
x : nat
y : nat
_ : x <> 0
_ : y <> 0

Recursive call to div has principal argument equal to
"x - y"
instead of a subterm of x

*)

Lemma minus_smaller_S: forall x y:nat, x - y < S x.
Proof.
 intros x y; pattern y, x;
 elim x using nat_double_ind.
 destruct x0; auto with arith.
 simpl; auto with arith.
 simpl; auto with arith.
Qed.

Lemma minus_smaller_positive : forall x y:nat, x <>0 -> y <> 0 ->
                                     x - y < x.
Proof.
 destruct x; destruct y;
 ( simpl;intros; apply minus_smaller_S ||
   intros; absurd (0=0); auto).
Qed.

Definition minus_decrease : forall x y:nat, Acc lt x ->
                                         x <> 0 ->
                                         y <> 0 ->
                                         Acc lt (x-y).
Proof.
 intros x y H; case H.
 intros Hz posz posy.
 apply Hz; apply minus_smaller_positive; assumption.
Defined.

Print minus_decrease.

Fixpoint div_aux (x y:nat)(H: Acc lt x):nat.
  refine (if eq_nat_dec x 0
         then 0
         else if eq_nat_dec y 0
              then y
              else div_aux (x-y) y _).
 apply (minus_decrease x y H);assumption.
Defined.

Print div_aux.
(*
div_aux =
(fix div_aux (x y : nat) (H : Acc lt x) {struct H} : nat :=
   match eq_nat_dec x 0 with
   | left _ => 0
   | right _ =>
       match eq_nat_dec y 0 with
       | left _ => y
       | right _0 => div_aux (x - y) y (minus_decrease x y H _ _0)
       end
   end)
     : forall x : nat, nat -> Acc lt x -> nat
*)

Require Import Wf_nat.
Definition div x y := div_aux x y (lt_wf x).

Extraction div.
(*
let div x y =
  div_aux x y
*)

Extraction div_aux.

(*
let rec div_aux x y =
  match eq_nat_dec x O with
    | Left -> O
    | Right ->
        (match eq_nat_dec y O with
           | Left -> y
           | Right -> div_aux (minus x y) y)
*)

Lemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.
Proof.
 intros A v;inversion v.
Abort.

(*
 Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n),
                                  n= 0 -> v = Vnil A.

Toplevel input, characters 40281-40287
> Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n),                                    n= 0 -> v = Vnil A.
>                                                                                ^^^^^^
Error: In environment
A : Set
n : nat
v : vector A n
e : n = 0
The term "Vnil A" has type "vector A 0" while it is expected to have type
 "vector A n"
*)
 Require Import JMeq.

Lemma vector0_is_vnil_aux : forall (A:Set)(n:nat)(v:vector A n),
                                  n= 0 -> JMeq v (Vnil A).
Proof.
 destruct v.
 auto.
 intro; discriminate.
Qed.

Lemma vector0_is_vnil : forall (A:Set)(v:vector A 0), v = Vnil A.
Proof.
 intros a v;apply JMeq_eq.
 apply vector0_is_vnil_aux.
 trivial.
Qed.

Implicit Arguments Vcons [A n].
Implicit Arguments Vnil [A].
Implicit Arguments Vhead [A n].
Implicit Arguments Vtail [A n].

Definition Vid : forall (A : Type)(n:nat), vector A n -> vector A n.
Proof.
 destruct n; intro v.
 exact Vnil.
 exact (Vcons  (Vhead v) (Vtail v)).
Defined.

Eval simpl in (fun (A:Set)(v:vector A 0) => (Vid _ _ v)).

Eval simpl in (fun (A:Set)(v:vector A 0) => v).

Lemma Vid_eq : forall (n:nat) (A:Type)(v:vector A n), v=(Vid _ n v).
Proof.
 destruct v.
 reflexivity.
 reflexivity.
Defined.

Theorem zero_nil : forall A (v:vector A 0), v = Vnil.
Proof.
 intros.
 change (Vnil (A:=A)) with (Vid _ 0 v).
 apply Vid_eq.
Defined.

Theorem decomp :
  forall (A : Set) (n : nat) (v : vector A (S n)),
  v = Vcons (Vhead v) (Vtail v).
Proof.
 intros.
 change (Vcons (Vhead v) (Vtail v)) with (Vid _  (S n) v).
 apply Vid_eq.
Defined.

Definition vector_double_rect :
    forall (A:Set) (P: forall (n:nat),(vector A n)->(vector A n) -> Type),
        P 0 Vnil Vnil ->
        (forall n (v1 v2 : vector A n) a b, P n v1 v2 ->
             P (S n) (Vcons a v1) (Vcons  b v2)) ->
        forall n (v1 v2 : vector A n), P n v1 v2.
 induction n.
 intros; rewrite (zero_nil _ v1); rewrite (zero_nil _ v2).
 auto.
 intros v1 v2; rewrite (decomp _ _ v1);rewrite (decomp _ _ v2).
 apply X0; auto.
Defined.

Require Import Bool.

Definition bitwise_or n v1 v2 : vector bool n :=
   vector_double_rect bool  (fun n v1 v2 => vector bool n)
                        Vnil
                        (fun n v1 v2 a b r => Vcons (orb a b) r) n v1 v2.

Fixpoint vector_nth (A:Set)(n:nat)(p:nat)(v:vector A p){struct v}
                  : option A :=
  match n,v  with
    _   , Vnil => None
  | 0   , Vcons b  _ _ => Some b
  | S n', Vcons _  p' v' => vector_nth A n'  p' v'
  end.

Implicit Arguments vector_nth [A p].

Lemma nth_bitwise : forall (n:nat) (v1 v2: vector bool n) i  a b,
      vector_nth i v1 = Some a ->
      vector_nth i v2 = Some b ->
      vector_nth i (bitwise_or _ v1 v2) = Some (orb a b).
Proof.
 intros  n v1 v2; pattern n,v1,v2.
 apply vector_double_rect.
 simpl.
 destruct i; discriminate 1.
 destruct i; simpl;auto.
 injection 1; injection 2;intros; subst a; subst b; auto.
Qed.

 Set Implicit Arguments.

 CoInductive Stream (A:Set) : Set   :=
 |  Cons : A -> Stream A -> Stream A.

 CoInductive LList (A: Set) : Set :=
 |  LNil : LList A
 |  LCons : A -> LList A -> LList A.

 Definition head (A:Set)(s : Stream A) := match s with Cons a s' => a end.

 Definition tail (A : Set)(s : Stream A) :=
      match s with Cons a s' => s' end.

 CoFixpoint repeat (A:Set)(a:A) : Stream A := Cons a (repeat a).

 CoFixpoint iterate (A: Set)(f: A -> A)(a : A) : Stream A:=
    Cons a (iterate f (f a)).

 CoFixpoint map (A B:Set)(f: A -> B)(s : Stream A) : Stream B:=
  match s with Cons a tl => Cons (f a) (map f tl) end.

Eval simpl in (fun (A:Set)(a:A) => repeat a).

Eval simpl in (fun (A:Set)(a:A) => head (repeat a)).

CoInductive EqSt (A: Set) : Stream A -> Stream A -> Prop :=
  eqst : forall s1 s2: Stream A,
      head s1 = head s2 ->
      EqSt (tail s1) (tail s2) ->
      EqSt s1 s2.

Section Parks_Principle.
Variable A : Set.
Variable    R      : Stream A -> Stream A -> Prop.
Hypothesis  bisim1 : forall s1 s2:Stream A, R s1 s2 ->
                                          head s1 = head s2.
Hypothesis  bisim2 : forall s1 s2:Stream A, R s1 s2 ->
                                          R (tail s1) (tail s2).

CoFixpoint park_ppl     : forall s1 s2:Stream A, R s1 s2 ->
                                               EqSt s1 s2 :=
 fun s1 s2 (p : R s1 s2) =>
      eqst s1 s2 (bisim1  p)
                 (park_ppl  (bisim2  p)).
End Parks_Principle.

Theorem map_iterate : forall (A:Set)(f:A->A)(x:A),
                       EqSt (iterate f (f x)) (map f (iterate f x)).
Proof.
 intros A f x.
 apply park_ppl with
   (R:=  fun s1 s2 => exists x: A,
                      s1 = iterate f (f x) /\ s2 = map f (iterate f x)).

 intros s1 s2 (x0,(eqs1,eqs2));rewrite eqs1;rewrite eqs2;reflexivity.
 intros s1 s2 (x0,(eqs1,eqs2)).
 exists (f x0);split;[rewrite eqs1|rewrite eqs2]; reflexivity.
 exists x;split; reflexivity.
Qed.

Ltac infiniteproof f :=
  cofix f; constructor; [clear f| simpl; try (apply f; clear f)].

Theorem map_iterate' : forall (A:Set)(f:A->A)(x:A),
                       EqSt (iterate f (f x)) (map f (iterate f x)).
infiniteproof map_iterate'.
 reflexivity.
Qed.

Implicit Arguments LNil [A].

Lemma Lnil_not_Lcons : forall (A:Set)(a:A)(l:LList A),
                               LNil <> (LCons a l).
 intros;discriminate.
Qed.

Lemma injection_demo : forall (A:Set)(a b : A)(l l': LList A),
                       LCons a (LCons b l) = LCons b (LCons a l') ->
                       a = b /\ l = l'.
Proof.
 intros A a b l l' e; injection e; auto.
Qed.

Inductive Finite (A:Set) : LList A -> Prop :=
|  Lnil_fin : Finite (LNil (A:=A))
|  Lcons_fin : forall a l, Finite l -> Finite (LCons a l).

CoInductive Infinite  (A:Set) : LList A -> Prop :=
| LCons_inf : forall a l, Infinite l -> Infinite (LCons a l).

Lemma LNil_not_Infinite : forall (A:Set), ~ Infinite (LNil (A:=A)).
Proof.
  intros A H;inversion H.
Qed.

Lemma Finite_not_Infinite : forall (A:Set)(l:LList A),
                                Finite l -> ~ Infinite l.
Proof.
 intros A l H; elim H.
 apply LNil_not_Infinite.
 intros a l0 F0 I0' I1.
 case I0'; inversion_clear I1.
 trivial.
Qed.

Lemma Not_Finite_Infinite : forall (A:Set)(l:LList A),
                            ~ Finite l -> Infinite l.
Proof.
 cofix H.
 destruct l.
 intro; absurd (Finite (LNil (A:=A)));[auto|constructor].
 constructor.
 apply H.
 red; intro H1;case H0.
 constructor.
 trivial.
Qed.