(**************************************************************************
* TLC: A library for Coq                                                  *
* Graphs                                                                  *
**************************************************************************)

(* under construction *)

Set Implicit Arguments.
Require Import LibCore LibSet.

(*-----------------------------------------------------------*)

Definition value_nonneg A (f:A->int) (P:A->Prop) :=
  forall x, P x -> f x >= 0.

(*-----------------------------------------------------------*)

Parameter graph : Type -> Type.
Parameter nodes : forall A, graph A -> set int.
Parameter edges : forall A, graph A -> set (int*int*A).

Definition has_edge A (g:graph A) x y w :=
  (x,y,w) \in edges g.

Parameter has_edge_nodes : forall A (g : graph A) x y w,
  has_edge g x y w -> x \in nodes g /\ y \in nodes g.

Lemma has_edge_in_nodes_l : forall A (g : graph A) x y w,
  has_edge g x y w -> x \in nodes g.
Proof using. intros. forwards*: has_edge_nodes. Qed.

Lemma has_edge_in_nodes_r : forall A (g : graph A) x y w,
  has_edge g x y w -> y \in nodes g.
Proof using. intros. forwards*: has_edge_nodes. Qed.

Definition nonneg_edges (g:graph int) :=
  forall x y w, has_edge g x y w -> w >= 0.
  (* forall x y, value_nonneg id (has_edge g x y) *)

(*-----------------------------------------------------------*)

Definition path A := list (int*int*A).

Inductive is_path A (g:graph A) : int -> int -> path A -> Prop :=
  | is_path_nil : forall x,
      x \in nodes g ->
      is_path g x x nil
  | is_path_cons : forall x y z w p,
      is_path g x y p ->
      has_edge g y z w ->
      is_path g x z ((y,z,w)::p).

Lemma is_path_in_nodes_l : forall A (g:graph A) x y p,
  is_path g x y p -> x \in nodes g.
Proof using. introv H. induction~ H. Qed.

Lemma is_path_in_nodes_r : forall A (g:graph A) x y p,
  is_path g x y p -> y \in nodes g.
Proof using. introv H. inverts~ H. apply* has_edge_in_nodes_r. Qed.

Lemma is_path_cons_has_edge : forall A (g:graph A) x y z w p,
  is_path g x z ((y,z,w)::p) -> has_edge g y z w.
Proof using. introv H. inverts~ H. Qed.

(*-----------------------------------------------------------*)

Definition weight (p:path int) :=
  nosimpl (fold_right (fun e acc => let '(_,_,w) := e in w+acc) 0 p).

Lemma weight_nil :
  weight (nil : path int) = 0.
Proof using. auto. Qed.

Lemma weight_cons : forall (p:path int) x y w,
  weight ((x,y,w)::p) = w + weight p.
Proof using. intros. unfold weight. rew_list~. Qed.

(** A graph with nonnegative edges has only paths
    of nonnegative weight *)

Lemma nonneg_edges_to_path : forall g,
  nonneg_edges g -> forall x y,
  value_nonneg weight (is_path g x y).
Proof using.
  introv NG H. induction H.
  rewrite weight_nil. math.
  rewrite weight_cons. forwards: NG H0. math.
Qed.


Require Export Unicode.Utf8_core.
Require Import Bool List Le String Showable HoTT.

Set Implicit Arguments.
Set Universe Polymorphism.

(** * The Decidable Class *)

(** This code is mostly imported from
[https://github.com/HoTT/HoTT]. We are defining it here to be
independent of the Coq/HoTT library.

We can not use the Decidable class of Coq because its definition is in
[Prop] (using [\/]) instead of [Type] (using [+]). All the predicates
defined in this file are proof-relevant.
*)

(** ** Decidability *)

(* =Decidable= *)
Class Decidable (A: HProp) := dec: A + (not A).
(* =end= *)

Arguments dec A {_}.

(**

A [DecidableProp] [A] is, essentially, isomorphic to [Bool]: it is
either [true] or [false].

 *)

(* Class DecidableProp (A : Type) := { *)
(*     dec_p :> Decidable A; *)
(*     is_hprop_p :> IsHProp A }. *)

(* Instance DecidableProp_Decidable_HProp (A : Type) {Hdec: Decidable A} *)
(*          {Hprop:IsHProp A} : DecidableProp A := *)
(*   {|dec_p := Hdec ; is_hprop_p := Hprop |}. *)

(**

The canonical example of a [DecidableProp] is the decidable equality
for a type [A], as per Hedberg theorem. We package it in a dedicated
class.

*)

Class DecidablePaths (A : HSet) := {
  dec_paths : forall a b : A, Decidable (hprop (a = b))
}.

(**

Hedberg theorem is a standard theorem of HoTT: it states that if a
type [A] has decidable equality, then it is a hSet, i.e. its equality
is proof-irrelevant. See the proof at [https://github.com/HoTT] in
[HoTT/theories/Basics/Decidable.v] *)

Instance Hedberg A (dec_paths_ : forall a b : A, ((a = b) + (not (a = b)))%type)
  : IsHSet A.
Proof.
intros a b.
assert (lemma: forall p: a = b,
    match dec_paths_ a a, dec_paths_ a b with
    | inl r, inl s => p = r^ @ s
    | _, _ => False
    end).
{
  destruct p.
  destruct (dec_paths_ a a) as [pr | f].
  apply inverse_left_inverse.
  specialize (f eq_refl).
  inversion f.
}

intros p q.
assert (p_given_by_dec := lemma p).
assert (q_given_by_dec := lemma q).
destruct (dec_paths_ a a); try contradiction.
destruct (dec_paths_ a b); try contradiction.
apply (p_given_by_dec @ q_given_by_dec ^).
Defined.

Instance DecidablePaths_DecidableProp A
   (DecidablePaths_A : DecidablePaths A)
  : forall (a b : A), Decidable (hprop (a = b)).
intros. exact (@dec_paths _ DecidablePaths_A _ _).
Defined.

(** ** Checkability *)

(**

  A [Checkable] type is a type that contains a decidable subset
  [checkP]. Moreover, it is [CheckableProp] if its elements are
  proof-irrelevant.

 *)

(* =Checkable= *)
Class Checkable (A: HProp) := {
    check: HProp;
    check_dec: Decidable check ;
    convert: check -> A
}.
(* =end= *)

Arguments check _ {_}.

(** A decidable type is checkable (over all its elements). *)

Instance decidable_is_checkable A {H:Decidable A} : Checkable A
  := {| check := A ; check_dec := H ; convert := id |}.

(** We can project the [Decidable] property out of [Checkable]: *)

Instance checkable_decidable A {H:Checkable A} : Decidable (@check _ H)
  := check_dec.

(** ** A few instances *)

(** ***  Reflecting a boolean as a decidable property *)

Instance Decidable_bool (t : bool) : Decidable (hprop (Is_true t)) :=
  match t with
    | true => inl tt
    | false => inr id
  end.

(* Connexion to a boolean version of decidable as in
   native-coq/theories/Classes/DecidableClass.v
*)

(*
Class Decidable_relate (P : Type) := {
  Decidable_witness : bool;
  Decidable_spec : Decidable_witness = true <-> P
}.

(* Decidable_relate and Decidable are equivalent *)

Instance Dec_relate_Decidable P (HP: Decidable_relate P) :
  Decidable P.
destruct HP as [witness spec]. destruct witness.
- left. exact (proj1 spec eq_refl).
- right. intro p. pose (proj2 spec p). inversion e.
Defined.

Definition Decidable_Dec_relate P (HP: Decidable P) :
  Decidable_relate P.
case HP; intro p.
- refine {| Decidable_witness := true |}.  split; auto.
- refine {| Decidable_witness := false |}. split; auto.
  intro e; inversion e.
Defined.
*)

(** ***  Instances for bool *)

Definition absurd_eq_bool : not (true = false).
Proof.
  inversion 1.
Defined.

(* =Decidable_eq_bool= *)
Definition Decidable_eq_bool (x y : bool) : (x = y) + not (x = y) :=
  match x,y with
    true, true   => inl eq_refl
  | false, false => inl eq_refl
  | true, false  => inr absurd_eq_bool
  | false, true  => inr (absurd_eq_bool ° inverse)
  end.
(* =end= *)

Instance IsHSet_bool : IsHSet bool := Hedberg Decidable_eq_bool.

Instance DecidablePaths_bool : DecidablePaths (hset bool) :=
  { dec_paths := Decidable_eq_bool }.

(** ***  Instances for nat *)

Definition Decidable_eq_nat : forall (x y : nat),  (x = y) + not (x = y).
induction x.
- destruct y.
 + left ;reflexivity.
 + right; intro H; inversion H.
- induction y.
  + right; intro H; inversion H.
  + case (IHx y). intro H. left. exact (f_equal S H).
    intro H; right. intro e. inversion e. apply (H H1).
Defined.

Instance IsHSet_nat : IsHSet nat := Hedberg Decidable_eq_nat.

Instance DecidablePaths_nat : DecidablePaths (hset nat) :=
  { dec_paths := Decidable_eq_nat }.

Definition Hnat : HSet := hset nat.

(** *** Instances for list *)

Definition Decidable_eq_list : forall (A:HSet) (HA: DecidablePaths A)
  (x y: list A),  (x = y) + not (x = y).
intros A HA. induction x.
- destruct y.
  + left; reflexivity.
  + right; intro H; inversion H.
- induction y.
  + right; intro H; inversion H.
  + case (dec_paths a a0); intro H.
    * case (IHx y); intro Hl.
      left. rewrite H. rewrite Hl. reflexivity.
      right. rewrite H. unfold not in *.
      intro Hc. inversion Hc. exact (Hl H1).
    * right. unfold not in *.
      intro Hc. inversion Hc. exact (H H1).
Defined.

(** *** Instance for decidable equality on list *)

Instance IsHSet_list (A:HSet) HA : IsHSet (list A) := Hedberg (@Decidable_eq_list A HA).

Instance DecidablePaths_list :
  forall A (HA: DecidablePaths A), DecidablePaths (hset (list A)) :=
    { dec_paths := Decidable_eq_list HA }.

(** *** Instance for less than *)

Definition Decidable_le_nat : forall (x y : nat), (x <= y) + not (x <= y).
induction x.
- destruct y.
 + left; reflexivity.
 + left. apply le_S, le_0_n.
- induction y.
  + right. intro e. destruct (le_Sn_0 _ e).
  + case (IHx y). intro H. left. exact (le_n_S _ _ H).
    intro H; right. intro. apply H. exact (le_S_n _ _ H0).
Defined.

(** *** Instances for option *)

Definition Decidable_eq_option : forall A (HA: DecidablePaths A)
  (x y: option A), (x = y) + not (x = y).
intros. destruct x as [a|]; destruct y as [a0 |].
- case (dec_paths a a0); intro H.
  + left. rewrite H. reflexivity.
  + right. unfold not in *. intro Hc. inversion Hc.
    exact (H H1).
- right. unfold not. intro Hc. inversion Hc.
- right. unfold not. intro Hc. inversion Hc.
- left. reflexivity.
Defined.

Instance IsHSet_option (A:HSet) HA : IsHSet (option A) := Hedberg (@Decidable_eq_option A HA).

Instance DecidablePaths_option :
  forall A (HA: DecidablePaths A), DecidablePaths (hset (option A)) :=
    { dec_paths := Decidable_eq_option HA }.

(** *** Instances for logical connectives *)

Instance Decidable_and P Q (HP : Decidable P)
 (HQ : Decidable Q) : Decidable (hprop (P * Q)).
destruct HP as [p | n].
- destruct HQ as [q| n].
  + exact (inl (p, q)).
  + apply inr. intro H. exact (n (snd H)).
- apply inr. intro H. exact (n (fst H)).
Defined.

(* Instance Decidable_or P Q (HP : Decidable P) *)
(*         (HQ : Decidable Q) : Decidable (hprop (P + Q) _). *)
(* destruct HP. *)
(* - exact (inl (inl p)). *)
(* - destruct HQ.  *)
(*   + exact (inl (inr q)). *)
(*   + apply inr. intro H. case H; auto. *)
(* Defined. *)

Instance Decidable_not P (HP : Decidable P):
  Decidable (hprop (not P)).
case HP; intro H.
- exact (inr (fun X => X H)).
- exact (inl H).
Defined.

Instance Decidable_implies P Q (HP : Decidable P)
  (HQ : Decidable Q) : Decidable (hprop (P -> Q)).
destruct HQ as [q | n].
- exact (inl (fun _ => q)).
- destruct HP as [p | n0].
  + apply inr. intro H. exact (n (H p)).
  + apply inl. intro p. destruct (n0 p).
Defined.

Instance Decidable_True : Decidable (hprop True) := inl I.

Instance Decidable_False : Decidable (hprop False).
right. destruct 1.
Defined.

Instance Hprop_unit : IsHProp unit.
Proof.
  intros x y. destruct x, y; reflexivity.
Defined.

Instance DecidablePaths_unit : DecidablePaths (hset unit).
econstructor. intros x y. destruct x, y. exact (inl eq_refl).
Defined.

(** *** Decidability of proven properties *)

Instance Decidable_proven (P : HProp) (ev :  P):  Decidable P :=
  inl ev.

(*
Instance DecidablePaths_prod A B `{DecidablePaths A} `{DecidablePaths B}:
  DecidablePaths (hset (A*B) _).
econstructor. intros (a,b) (a',b').
destruct (dec (a = a')), (dec (b=b'));
  try solve [apply inr; intro H'; inversion H'; auto].
apply inl. subst. reflexivity.
Defined.

Instance DecidablePaths_fun A B A'
         (H : forall a, DecidablePaths (B a)) (f : A' -> A)
  a' : DecidablePaths (B (f a')) .
Proof.
  auto with typeclass_instances.
Defined.

*)


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

Require Export Poly.

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

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

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

(** We often encounter situations where the goal to be proved is
    exactly the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.
  (* At this point, we could finish with
     "[rewrite -> eq2. reflexivity.]" as we have
     done several times above. But we can achieve the
     same effect in a single step by using the
     [apply] tactic instead: *)
  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
     n = m  ->
     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] binding some _universal variables_.  When
    Coq matches the current goal against the conclusion of [H], it
    will try to find appropriate values for these variables.  For
    example, when we do [apply eq2] in the following proof, the
    universal variable [q] in [eq2] gets instantiated with [n] and [r]
    gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** **** Exercise: 2 stars, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal _exactly_ -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  simpl.
  (* Here we cannot use [apply] directly *)
Abort.

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

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

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

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  Are there situations where both can usefully be
    applied?
  (* FILL IN HERE *)
*)
(** [] *)

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

(** The following silly example uses two rewrites in a row to
    get from [[a,b]] to [[e,f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.

(** Since this is a common pattern, we might
    abstract it out as a lemma recording once and for all
    the fact that equality is transitive. *)

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

(** Now, we should be able to use [trans_eq] to
    prove the above example.  However, to do this we need
    a slight refinement of the [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  (* If we simply tell Coq [apply trans_eq] at this point,
     it can tell (by matching the goal against the
     conclusion of the lemma) that it should instantiate [X]
     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].
     However, the matching process doesn't determine an
     instantiation for [m]: we have to supply one explicitly
     by adding [with (m:=[c,d])] to the invocation of
     [apply]. *)
  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.

(**  Actually, we usually don't have to include the name [m]
    in the [with] clause; Coq is often smart enough to
    figure out which instantiation we're giving. We could
    instead write: [apply trans_eq with [c,d]]. *)

(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros. rewrite H0. apply H.
Qed.
(** [] *)

(* ###################################################### *)
(** * The [inversion] tactic *)

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is clear from this definition that every number has one of two
    forms: either it is the constructor [O] or it is built by applying
    the constructor [S] to another number.  But there is more here than
    meets the eye: implicit in the definition (and in our informal
    understanding of how datatype declarations work in other
    programming languages) are two other facts:

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

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

(** Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor is
    injective and [nil] is different from every non-empty list.  For
    booleans, [true] and [false] are unequal.  (Since neither [true]
    nor [false] take any arguments, their injectivity is not an issue.) *)

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

    The [inversion] tactic is used like this.  Suppose [H] is a
    hypothesis in the context (or a previously proven lemma) of the
    form
      c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] instructs Coq to "invert" this
    equality to extract the information it contains about these terms:

    - If [c] and [d] are the same constructor, then we know, by the
      injectivity of this constructor, that [a1 = b1], [a2 = b2],
      etc.; [inversion H] adds these facts to the context, and tries
      to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory.  That is, a false assumption has crept
      into the context, and this means that any goal whatsoever is
      provable!  In this case, [inversion H] marks the current goal as
      completed and pops it off the goal stack. *)

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

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

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

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

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

(** **** Exercise: 1 star (sillyex1)  *)
Example sillyex1 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = z :: j ->
     y :: l = x :: j ->
     x = y.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

Theorem silly6 : forall (n : nat),
     S n = O ->
     2 + 2 = 5.
Proof.
  intros n contra. inversion contra. Qed.

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

(** **** Exercise: 1 star (sillyex2)  *)
Example sillyex2 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = [] ->
     y :: l = z :: j ->
     x = z.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

(** **** Exercise: 2 stars, optional (practice)  *)
(** A couple more nontrivial but not-too-complicated proofs to work
    together in class, or for you to work as exercises. *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic [simpl in H] performs simplification in
    the hypothesis named [H] in the context. *)

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

(** Similarly, the tactic [apply L in H] matches some
    conditional statement [L] (of the form [L1 -> L2], say) against a
    hypothesis [H] in the context.  However, unlike ordinary
    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),
    [apply L in H] matches [H] against [L1] and, if successful,
    replaces it with [L2].

    In other words, [apply L in H] gives us a form of "forward
    reasoning" -- from [L1 -> L2] and a hypothesis matching [L1], it
    gives us a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning" -- it says that if we know [L1->L2] and we
    are trying to prove [L2], it suffices to prove [L1].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

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

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, Coq tends to favor backward reasoning, but in some
    situations the forward style can be easier to use or to think
    about.  *)

(** **** Exercise: 3 stars (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise. *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* Hint: use the plus_n_Sm lemma *)
    (* FILL IN HERE *) Admitted.
(** [] *)

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

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that the [double] function is injective -- i.e.,
    that it always maps different arguments to different results:
    Theorem double_injective: forall n m, double n = double m -> n = m.
    The way we _start_ this proof is a little bit delicate: if we
    begin it with
      intros n. induction n.
]]
    all is well.  But if we begin it with
      intros n m. induction n.
    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *) intros eq. destruct m as [| m'].
    + (* m = O *) inversion eq.
    + (* m = S m' *)  apply f_equal.
      (* Here we are stuck.  The induction hypothesis, [IHn'], does
         not give us [n' = m'] -- there is an extra [S] in the
         way -- so the goal is not provable. *)
      Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular
    [n] and [m]..." and we now have to prove that, if [double n =
    double m] for _these particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove that
    the proposition

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

    holds for all [n] by showing

      - [P O]

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

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: it says that, for a _particular_ [m], if we know

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

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular [m] --
    say, [5].  The statement is then saying that, if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help with proving [R]!  (If we
    tried to prove [R] from [Q], we would say something like "Suppose
    [double (S n) = 10]..." but then we'd be stuck: knowing that
    [double (S n)] is [10] tells us nothing about whether [double n]
    is [10], so [Q] is useless at this point.) *)

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

(** The good proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *)
    (* Notice that both the goal and the induction
       hypothesis have changed: the goal asks us to prove
       something more general (i.e., to prove the
       statement for _every_ [m]), but the IH is
       correspondingly more flexible, allowing us to
       choose any [m] we like when we apply the IH.  *)
    intros m eq.
    (* Now we choose a particular [m] and introduce the
       assumption that [double n = double m].  Since we
       are doing a case analysis on [n], we need a case
       analysis on [m] to keep the two "in sync." *)
    destruct m as [| m'].
    + (* m = O *)
      (* The 0 case is trivial *)
      inversion eq.
    + (* m = S m' *)
      apply f_equal.
      (* At this point, since we are in the second
         branch of the [destruct m], the [m'] mentioned
         in the context at this point is actually the
         predecessor of the one we started out talking
         about.  Since we are also in the [S] branch of
         the induction, this is perfect: if we
         instantiate the generic [m] in the IH with the
         [m'] that we are talking about right now (this
         instantiation is performed automatically by
         [apply]), then [IHn'] gives us exactly what we
         need to finish the proof. *)
      apply IHn'. inversion eq. reflexivity. Qed.

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

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

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

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

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

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

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

_Theorem_: For any nats [n] and [m], if [double n = double m], then
  [n = m].

_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
  any [n], if [double n = double m] then [n = m].

  - First, suppose [m = 0], and suppose [n] is a number such
    that [double n = double m].  We must show that [n = 0].

    Since [m = 0], by the definition of [double] we have [double n =
    0].  There are two cases to consider for [n].  If [n = 0] we are
    done, since this is what we wanted to show.  Otherwise, if [n = S
    n'] for some [n'], we derive a contradiction: by the definition of
    [double] we would have [double n = S (S (double n'))], but this
    contradicts the assumption that [double n = 0].

  - Otherwise, suppose [m = S m'] and that [n] is again a number such
    that [double n = double m].  We must show that [n = S m'], with
    the induction hypothesis that for every number [s], if [double s =
    double m'] then [s = m'].

    By the fact that [m = S m'] and the definition of [double], we
    have [double n = S (S (double m'))].  There are two cases to
    consider for [n].

    If [n = 0], then by definition [double n = 0], a contradiction.
    Thus, we may assume that [n = S n'] for some [n'], and again by
    the definition of [double] we have [S (S (double n')) = S (S
    (double m'))], which implies by inversion that [double n' = double
    m'].

    Instantiating the induction hypothesis with [n'] thus allows us to
    conclude that [n' = m'], and it follows immediately that [S n' = S
    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted
    to show. [] *)

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

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

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

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

(** It might be tempting to start proving the above theorem
    by introducing [n] and [eq] at the outset.  However, this leads
    to an induction hypothesis that is not strong enough.  Compare
    the above to the following (aborted) attempt: *)

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

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

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

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

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

(** **** Exercise: 3 stars (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem index_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     index n l = None.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)
(** Write an informal proof corresponding to your Coq proof
    of [index_after_last]:

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

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

(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)
(** Prove this by induction on [l]. *)

Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : list X),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (app_length_cons)  *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, optional (app_length_twice)  *)
(** Prove this by induction on [l], without using [app_length] from [Lists]. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (double_induction)  *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  intros P POO PmO POn Pmn m n.
  induction m.
  - induction n.
    +  apply POO.
    + apply POn. apply IHn.
  - induction n.
    +  apply PmO. apply IHm.
    + apply Pmn. admit.
(** [] *)

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

(** We have seen many examples where the [destruct] tactic is
    used to perform case analysis of the value of some variable.  But
    sometimes we need to reason by cases on the result of some
    _expression_.  We can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (beq_nat n 3).
    - (* beq_nat n 3 = true *) reflexivity.
    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).
      + (* beq_nat n 5 = true *) reflexivity.
      + (* beq_nat n 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,
    either [n] is equal to [3] or it isn't, so we use [destruct
    (beq_nat n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c].

*)

(** **** Exercise: 1 star (override_shadow)  *)
Theorem override_shadow : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  (override (override f k1 x2) k1 x1) k2 = (override f k1 x1) k2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
(** Complete the proof below *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** Sometimes, doing a [destruct] on a compound expression (a
    non-variable) will erase information we need to complete a proof. *)
(** For example, suppose
    we define a function [sillyfun1] like this: *)

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

(** And suppose that we want to convince Coq of the rather
    obvious observation that [sillyfun1 n] yields [true] only when [n]
    is odd.  By analogy with the proofs we did with [sillyfun] above,
    it is natural to start the proof like this: *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3).
  (* stuck... *)
Abort.

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution peformed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat n 3], but we need to keep some
    memory of this expression and how it was destructed, because we
    need to be able to reason that since, in this branch of the case
    analysis, [beq_nat n 3 = true], it must be that [n = 3], from
    which it follows that [n] is odd.

    What we would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation (with whatever
    name we choose). *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got stuck
    above, except that the context contains an extra equality
    assumption, which is exactly what we need to make progress. *)
    - (* e3 = true *) apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (* When we come to the second equality test in the body of the
       function we are reasoning about, we can use [eqn:] again in the
       same way, allow us to finish the proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

(** **** Exercise: 2 stars (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars (override_same)  *)
Theorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),
  f k1 = x1 ->
  (override f k1 x1) k2 = f k2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

(** We've now seen a bunch of Coq's fundamental tactics.  We'll
    introduce a few more as we go along through the coming lectures,
    and later in the course we'll introduce some more powerful
    _automation_ tactics that make Coq do more of the low-level work
    in many cases.  But basically we've got what we need to get work
    done.

    Here are the ones we've seen:

      - [intros]:
        move hypotheses/variables from goal to context

      - [reflexivity]:
        finish the proof (when the goal looks like [e = e])

      - [apply]:
        prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]:
        apply a hypothesis, lemma, or constructor to a hypothesis in
        the context (forward reasoning)

      - [apply... with...]:
        explicitly specify values for variables that cannot be
        determined by pattern matching

      - [simpl]:
        simplify computations in the goal

      - [simpl in H]:
        ... or a hypothesis

      - [rewrite]:
        use an equality hypothesis (or lemma) to rewrite the goal

      - [rewrite ... in H]:
        ... or a hypothesis

      - [symmetry]:
        changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]:
        changes a hypothesis of the form [t=u] into [u=t]

      - [unfold]:
        replace a defined constant by its right-hand side in the goal

      - [unfold... in H]:
        ... or a hypothesis

      - [destruct... as...]:
        case analysis on values of inductively defined types

      - [destruct... eqn:...]:
        specify the name of an equation to be added to the context,
        recording the result of the case analysis

      - [induction... as...]:
        induction on values of inductively defined types

      - [inversion]:
        reason by injectivity and distinctness of constructors

      - [assert (e) as H]:
        introduce a "local lemma" [e] and call it [H]

      - [generalize dependent x]:
        move the variable [x] (and anything else that depends on it)
        from the context back to an explicit hypothesis in the goal
        formula
*)

(* ###################################################### *)
(** * Additional Exercises *)

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

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

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We have just proven that for all lists of pairs, [combine] is the
    inverse of [split].  How would you formalize the statement that
    [split] is the inverse of [combine]? When is this property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)

Definition split_combine_statement : Prop :=
(* FILL IN HERE *) admit.

Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.

(** [] *)

(** **** Exercise: 3 stars (override_permute)  *)
Theorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your IH. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  intros X test x l lf.
  induction l.
  + intros. unfold filter in H. inversion H.
  + intros.
    destruct (test x0) eqn: testH.
    - unfold filter in H. rewrite testH in H. fold (filter test) in H. inversion H. rewrite <- H1. apply testH.
    - unfold filter in H. rewrite testH in H. fold (filter test) in H. apply IHl. apply H.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:
      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (beq_nat 5) [] = true
    The second checks whether there exists an element in the list that
    satisfies a given predicate:
      existsb (beq_nat 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

      existsb evenb [] = false
    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

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

Fixpoint forallb {X : Type} (p : X -> bool) (l : list X) :=
  match l with
  | []       => true
  | x :: l'  => if p x then forallb p l' else false
end.

Fixpoint existsb {X : Type} (p : X -> bool) (l : list X) :=
  match l with
  | []       => false
  | x :: l'  => if p x then true else existsb p l'
end.

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

Theorem existsb_existsb': forall (X : Type) (p : X -> bool)
                             (l : list X),
     existsb p l = existsb' p l.
Proof.
  intros.
  induction l.
  - simpl. unfold existsb'. unfold forallb. simpl. reflexivity.
  - destruct (p x) eqn: Hpx.
    + simpl.
      unfold existsb'. unfold forallb.
      rewrite Hpx. simpl. reflexivity.
    + simpl. unfold existsb'. unfold forallb. rewrite Hpx.
      simpl. fold (forallb (fun x0 : X => negb (p x0))).
      unfold existsb' in IHl. rewrite IHl. reflexivity.
Qed.

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

(** $Date: 2015-08-11 03:46:09 +0200 (Tue, 11 Aug 2015) $ *)


(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

Require Export Field.
Require Export QArith_base.
Require Import NArithRing.

(** * field and ring tactics for rational numbers *)

Definition Qsrt : ring_theory 0 1 Qplus Qmult Qminus Qopp Qeq.
Proof.
  constructor.
  exact Qplus_0_l.
  exact Qplus_comm.
  exact Qplus_assoc.
  exact Qmult_1_l.
  exact Qmult_comm.
  exact Qmult_assoc.
  exact Qmult_plus_distr_l.
  reflexivity.
  exact Qplus_opp_r.
Qed.

Definition Qsft : field_theory 0 1 Qplus Qmult Qminus Qopp Qdiv Qinv Qeq.
Proof.
  constructor.
  exact Qsrt.
  discriminate.
  reflexivity.
  intros p Hp.
  rewrite Qmult_comm.
  apply Qmult_inv_r.
  exact Hp.
Qed.

Lemma Qpower_theory : power_theory 1 Qmult Qeq Z.of_N Qpower.
Proof.
constructor.
intros r [|n];
reflexivity.
Qed.

Ltac isQcst t :=
  match t with
  | inject_Z ?z => isZcst z
  | Qmake ?n ?d =>
    match isZcst n with
      true => isPcst d
    | _ => false
    end
  | _ => false
  end.

Ltac Qcst t :=
  match isQcst t with
    true => t
    | _ => NotConstant
  end.

Ltac Qpow_tac t :=
  match t with
  | Z0 => N0
  | Zpos ?n => Ncst (Npos n)
  | Z.of_N ?n => Ncst n
  | NtoZ ?n => Ncst n
  | _ => NotConstant
  end.

Add Field Qfield : Qsft
 (decidable Qeq_bool_eq,
  completeness Qeq_eq_bool,
  constants [Qcst],
  power_tac Qpower_theory [Qpow_tac]).

(** Exemple of use: *)

Section Examples.

Let ex1 : forall x y z : Q, (x+y)*z ==  (x*z)+(y*z).
  intros.
  ring.
Qed.

Let ex2 : forall x y : Q, x+y == y+x.
  intros.
  ring.
Qed.

Let ex3 : forall x y z : Q, (x+y)+z == x+(y+z).
  intros.
  ring.
Qed.

Let ex4 : (inject_Z 1)+(inject_Z 1)==(inject_Z 2).
  ring.
Qed.

Let ex5 : 1+1 == 2#1.
  ring.
Qed.

Let ex6 : (1#1)+(1#1) == 2#1.
  ring.
Qed.

Let ex7 : forall x : Q, x-x== 0.
  intro.
  ring.
Qed.

Let ex8 : forall x : Q, x^1 == x.
  intro.
  ring.
Qed.

Let ex9 : forall x : Q, x^0 == 1.
  intro.
  ring.
Qed.

Let ex10 : forall x y : Q, ~(y==0) -> (x/y)*y == x.
intros.
field.
auto.
Qed.

End Examples.

Lemma Qopp_plus : forall a b,  -(a+b) == -a + -b.
Proof.
  intros; ring.
Qed.

Lemma Qopp_opp : forall q, - -q==q.
Proof.
  intros; ring.
Qed.


(* Exercise 19 *)

Require Import BenB.

Variable D : Set.
Variables P Q S T : D -> Prop.
Variable R : D -> D -> Prop.

Theorem exercise_019 : (exists x : D, P x \/ Q x) -> (exists x : D, P x) \/ (exists x : D, Q x).
Proof.
imp_i a1.
exi_e (exists x:D, P x \/ Q x) a a2.
hyp a1.
dis_e (P a \/ Q a) a3 a3.
hyp a2.
dis_i1.
exi_i a.
hyp a3.
dis_i2.
exi_i a.
hyp a3.
Qed.


(* Exercise 73 *)

Require Import BenB.

Variable D : Set.
Variables P Q S T : D -> Prop.
Variable R : D -> D -> Prop.

Theorem exercise_073 : (exists x : D, exists y : D, R x y) -> (exists x : D, x=x).
Proof.
imp_i a1.
exi_e (exists x:D, exists y:D, R x y) a a2.
hyp a1.
exi_e (exists y:D, R a y) b a3.
hyp a2.
exi_i a.
lin_solve.
Qed.


Require Import ZArith.
Require Import Coq.Logic.Decidable.

Definition divides a b := exists k, b = k * a.
Definition prime p := 2 <= p /\ forall k, divides k p -> (k = 1 \/ k = p).

Lemma divides_comm : forall a b, divides a b <-> exists k, b = a * k.
  intros; cbv [divides]; firstorder; exists x; rewrite Nat.mul_comm; assumption.
Qed.

Definition divides' a b := Nat.modulo b a = 0.

Lemma divides_eq : forall a b, b <> 0 -> divides' b a <-> divides b a.
  cbv [divides']; intros; split; rewrite divides_comm; apply Nat.mod_divides; assumption.
Qed.

Infix "==n" := eq_nat_dec (no associativity, at level 50).

Theorem divides_dec : forall n m : nat, {divides n m} + {~divides n m}.
  destruct n.
  { destruct m; cbv [divides].
    { left; exists 0; omega. }
    { right; intro H; destruct H; omega. }
  }
  { intro; destruct (m mod (S n) ==n 0).
    { left; apply divides_eq; auto. }
    { right; rewrite <- divides_eq; auto. }
  }
Qed.

Fixpoint prime_decider' (n m : nat) : bool :=
  match m with
    | 0 => true
    | S m => prime_decider' n m &&
            if divides_dec (S m) n then
              if (S m ==n 1) then true else
                if (S m ==n n) then true else false
            else true
  end.

Definition prime_decider (n : nat) : bool := if (le_dec 2 n) then prime_decider' n n else false.

Ltac simpl_prime_decider :=
  match goal with
  | [ H : prime_decider' _ _ = _ |- _ ] =>
    unfold prime_decider' in H; fold prime_decider' in H;
    rewrite Bool.andb_true_iff in H; firstorder
  | [ |- prime_decider' _ _ = _ ] =>
    unfold prime_decider'; fold prime_decider';
    rewrite Bool.andb_true_iff; firstorder
  end.

Lemma prime_decider_eq_prime' : forall (n m : nat), 2 <= n -> (prime_decider' n m = true) <-> (forall k : nat, k <= m -> divides k n -> k = 1 \/ k = n).
  induction m; firstorder.
  { destruct (le_lt_eq_dec k 0); [assumption | omega | subst; omega]. }
  { destruct (le_lt_eq_dec k (S m)).
    { assumption. }
    { apply H3.
      { simpl_prime_decider. }
      { apply (lt_n_Sm_le k m l). }
      { cbv [divides]; exists x; assumption. }
    }
    { simpl_prime_decider; rewrite e in H2; destruct (divides_dec (S m) n).
      { destruct (S m ==n 1).
        { firstorder. }
        { destruct (S m ==n n); firstorder; discriminate. }
      }
      { destruct n0; cbv [divides]; exists x; assumption. }
    }
  }
  { simpl_prime_decider; destruct (divides_dec (S m) n).
    { destruct (S m ==n 1).
      { trivial. }
      { destruct (S m ==n n).
        { trivial. }
        { specialize (H0 (S m) (le_n (S m))); firstorder; trivial. }
      }
    }
    { trivial. }
  }
Qed.

Lemma le_sufficient : forall (n : nat), 2 <= n -> (forall k : nat, k <= n -> divides k n -> k = 1 \/ k = n) <-> prime n.
  intros; cbv [prime]; split.
  { intros; split.
    { assumption. }
    { intro; destruct (le_gt_dec k n).
      { specialize (H0 k l); assumption. }
      { intros; rewrite <- divides_eq in H1.
        { cbv [divides'] in H1; pose proof (Nat.mod_small n k); omega. }
        { intro; subst; omega. }
      }
    }
  }
  { firstorder. }
Qed.

Lemma prime_decider_eq_prime : forall n, (prime_decider n = true) <-> prime n.
  intros; cbv [prime_decider]; destruct (le_dec 2 n).
  { pose proof (prime_decider_eq_prime' n n l); rewrite H; apply le_sufficient; assumption. }
  { firstorder; discriminate. }
Qed.

Theorem prime_dec : forall n : nat, {prime n} + {~ prime n}.
  intros; destruct (Bool.bool_dec (prime_decider n) true) as [dec | dec];
            rewrite prime_decider_eq_prime in dec; firstorder.
Qed.

Fixpoint mult_primes_up_to' (n prod : nat) :=
  match n with
  | 0 => prod
  | S n => if prime_dec n then mult_primes_up_to' n prod * (S n) else mult_primes_up_to' n prod
  end.

Definition mult_primes_up_to (n : nat) := mult_primes_up_to' n 1.

Lemma not_prime_impl_prime_factor : forall (n : nat), 2 <= n -> ~ prime n -> exists x, divides x n /\ prime x.
Admitted.

Lemma checking_primes_sufficient : forall (n : nat), 2 <= n -> (forall k : nat, prime k -> divides k n -> k = 1 \/ k = n) <-> prime n.
  intros; split.
  { intros; split.
    { assumption. }
    { cut (forall k : nat, divides k n -> ~ ~(k = 1 \/ k = n)).
      { intros; specialize (H1 k H2); apply not_not.
        { apply dec_or; apply dec_eq_nat; assumption. }
        { assumption. }
      }
      { cut (~ exists k, divides k n /\ ~(k = 1 \/ k = n)).
        { firstorder. }
        { intro.
          destruct H1.
          destruct (prime_dec x).
          specialize (H0 x); firstorder.
          pose proof (not_prime_impl_prime_factor x).
          Admitted.

Lemma succ_doesnt_divide : forall (n : nat), 2 <= n -> (forall k : nat, 2 <= k -> divides k n -> ~ divides k (S n)).
  intros; intro. rewrite <- divides_eq in H1.
  { rewrite <- divides_eq in H2.
    { cbv [divides'] in H1; cbv [divides'] in H2; rewrite <- Nat.add_1_r in H2; rewrite Nat.add_mod in H2.
      { rewrite H1 in H2; simpl in H2; rewrite Nat.mod_mod in H2.
        { pose proof (Nat.mod_small 1 k); omega. }
        { omega. }
      }
      { omega. }
    }
    { omega. }
  }
  { omega. }
Qed.

Lemma succ_mult_primes_up_to_prime : forall n, prime (S (mult_primes_up_to n)).
Admitted.

Lemma succ_mult_primes_up_to_gt : forall n, S (mult_primes_up_to n) > n.
  intros; destruct (le_gt_dec (S (mult_primes_up_to n)) n).
  { pose proof (succ_mult_primes_up_to_prime n); exfalso; admit. }
  { assumption. }
Admitted.

Theorem primes_infinite : forall n, exists p, p > n /\ prime p.
  intros; exists (S (mult_primes_up_to n)); split.
  { apply succ_mult_primes_up_to_gt. }
  { apply succ_mult_primes_up_to_prime. }
Qed.


Set Implicit Arguments.

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

Implicit Arguments LNil [A].

CoInductive Infinite {A:Type} : LList A -> Prop :=
    Infinite_LCons :
      forall (a:A) (l:LList A), Infinite l -> Infinite (LCons a l).

Hint Constructors Infinite: llists.

Definition Infinite_ok {A: Type} (X:LList A -> Prop) : Prop :=
  forall l:LList A,
    X l ->  exists a : A, exists l' : LList A, l = LCons a l' /\ X l'.

Definition Infinite1 {A: Type} (l:LList A) :=
   exists X : LList A -> Prop, Infinite_ok X /\ X l.

Lemma ok_LNil {A: Type}:
 forall X:LList A -> Prop, Infinite_ok X -> ~ X LNil.
Proof.
 unfold Infinite_ok.
 intros X H H0;  case (H LNil).
 - assumption.
 - intros x H1; case H1; intros x0 H2; case H2; discriminate 1.
Qed.

Lemma ok_LCons {A: Type} :
  forall  (X:LList A -> Prop) (a:A) (l:LList A),
   Infinite_ok X -> X (LCons a l) -> X l.
Proof.
 intros  X a l H H0; case (H (LCons a l)).
 -  assumption.
 -  simple destruct 1; intros x0 H2; case H2; injection 1.
    simple destruct 1; auto.
Qed.

Lemma Infinite1_LNil {A: Type} :  ~ Infinite1 (LNil (A:=A)).
Proof.
 intros  H; destruct H as [X [H1 H2]].
 now apply (ok_LNil H1).
Qed.

Lemma Infinite1_LCons  {A: Type} :
 forall  (a:A) (l:LList A), Infinite1 (LCons a l) -> Infinite1 l.
Proof.
 intros  a l H.
 case H; intros X HX; case HX; intros H1 H2; clear HX.
  exists (fun u:LList A =>  exists b : A, X (LCons b u)); split.
 -  unfold Infinite_ok in |- *.
    intros l0 [b Hb].
    assert (H4 : X l0) by apply (ok_LCons _ _  H1 Hb);eauto.
    case (H1 l0 H4);  intros x [l' [el' Hl']].
    exists x, l'; split; try assumption.
    exists x; rewrite <- el'; auto.
-  exists a; auto.
Qed.

(* equivalence between both definitions of infinity *)

Lemma Inf_Inf1 {A : Type} : forall l:LList A, Infinite l -> Infinite1 l.
Proof.
 intros l ;  exists (Infinite (A:=A)).
 split; try assumption.
 unfold Infinite_ok in |- *.
 simple destruct l0.
 -  inversion 1.
 - inversion_clear 1.
   exists a; exists l1; auto.
Qed.

Lemma Inf1_Inf {A : Type}: forall l:LList A, Infinite1 l -> Infinite l.
Proof.
 cofix.
 simple destruct l.
 - intro H;  case (Infinite1_LNil H).
 -  intros a l0 H0;  generalize (Infinite1_LCons H0); constructor.
    now apply Inf1_Inf.
Qed.


Require Export Induction.

Module NatList.

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

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

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

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

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

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

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

  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.

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

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

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

  Fixpoint repeat (n count : nat) : natlist :=
    match count with
      | 0 => nil
      | S count' => n :: (repeat n count')
    end.

  Fixpoint length (l:natlist) : nat :=
    match l with
      | nil => 0
      | h :: t => S (length t)
    end.

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

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

  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.

  Fixpoint nonzeros (l:natlist) : natlist :=
    match l with
      | nil => nil
      | 0 :: t => nonzeros t
      | n :: t => n :: (nonzeros t)
    end.

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

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

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

  Fixpoint countoddmembers (l:natlist) : nat :=
    match l with
      | nil => 0
      | n :: t => if oddb n then 1 + (countoddmembers t) else countoddmembers t
    end.

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

  Fixpoint alternate (l1 l2 : natlist) : natlist :=
    match l1, l2 with
      | nil, _ => l2
      | _, nil => l1
      | h :: t, h' :: t' => h :: h' :: (alternate t t')
    end.

  Example test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
  Proof. reflexivity. Qed.
  Example test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].
  Proof. reflexivity. Qed.
  Example test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].
  Proof. reflexivity. Qed.
  Example test_alternate4: alternate [] [20;30] = [20;30].
  Proof. reflexivity. Qed.

  Definition bag := natlist.

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

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

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

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

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

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

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

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

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

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

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

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

  Fixpoint subset (s1:bag) (s2:bag) : bool :=
    match s1 with
      | nil => true
      | h :: t => andb (member h s2) (subset t (remove_one h s2))
    end.

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

  Theorem bag_theorem :
    forall (b : bag) (n : nat),
      count n (add n b) = (count n b) + 1.
  Proof.
    intros b n.
    simpl.
    rewrite <- beq_nat_refl. rewrite <- plus_1_l. rewrite -> plus_comm.
    reflexivity.
  Qed.

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

  Theorem tl_length_pred : forall l : natlist,
                             pred (length l) = length (tl l).
  Proof.
    intros l. destruct l; reflexivity.
  Qed.

  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.

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

  Fixpoint snoc (l:natlist) (v:nat) : natlist :=
    match l with
      | nil => [v]
      | h :: t => h :: (snoc t v)
    end.

  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.

  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.

  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.

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

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

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

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

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

  Theorem distr_rev : forall l1 l2 : natlist,
                        rev (l1 ++ l2) = (rev l2) ++ (rev l1).
  Proof.
    intros l1 l2. induction l1 as [| n l1'].
    Case "l1 = nil".
      simpl.
      rewrite -> app_nil_end.
      reflexivity.
    Case "l1 = n :: l1'".
      simpl.
      rewrite -> IHl1'.
      assert (H: snoc (rev l1') n = (rev l1') ++ [n]).
      SCase "Assertion".
        rewrite -> snoc_append.
        reflexivity.
      rewrite -> H.
      rewrite -> snoc_append. rewrite -> app_assoc.
      reflexivity.
  Qed.

  Lemma nonzeros_app : forall l1 l2 : natlist,
                         nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
  Proof.
    intros l1 l2. induction l1 as [|n l1'].
    Case "l1 = nil". reflexivity.
    Case "l1 = n :: l1'".
      destruct n as [|n']; simpl; rewrite -> IHl1'; reflexivity.
  Qed.

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

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

  Theorem bew_natlist_refl : forall l : natlist,
                               true = beq_natlist l l.
  Proof.
    intros l. induction l as [|n l'].
    Case "l = nil". reflexivity.
    Case "l = n :: l'".
      simpl.
      rewrite <- beq_nat_refl.
      rewrite -> IHl'.
      reflexivity.
  Qed.

  Theorem count_member_nonzero : forall (s:bag),
                                   ble_nat 1 (count 1 (1 :: s)) = true.
  Proof.
    intros s. reflexivity.
  Qed.

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

  Theorem bag_count_sum: 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 [|n' s1'].
    Case "s1 = nil". reflexivity.
    Case "s1 = n' :: s1'".
      simpl.
      rewrite -> IHs1'.
      destruct (beq_nat n' n); reflexivity.
  Qed.

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

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

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

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

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

  Theorem option_elim_hd : forall (l:natlist) (default:nat),
                             hd default l = option_elim default (hd_opt l).
  Proof.
    intros l default. destruct l; reflexivity.
  Qed.

  Module Dictionary.

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

    Definition insert (key value : nat) (d:dictionary) :
      dictionary := (record key value d).

    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.

    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.

    Theorem dictioniary_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.


Require Import List. Import ListNotations.
Require Import Recdef.
Require Import Lia.

Inductive tree : Type :=
| Node : nat -> list tree -> tree.

Function binary_tree start n { wf lt n } :=
  match n with
  | 0 => Node start []
  | S n =>
    let p := Nat.div2 n in
    match n - p with
    | 0 => Node start []
    | _ =>
      let l := binary_tree start (n-p) in
      match p with
      | 0 => Node start [l]
      | _ =>
        let r := binary_tree start p in
        Node start [l;r]
      end
    end
  end.
Proof.
  - intros; subst.
    destruct n0; [discriminate|].
    rewrite PeanoNat.Nat.sub_0_r in teq0.
    inversion teq0; subst.
    apply le_n.
  - intros; subst.
    destruct n0; [discriminate|].
    destruct n0; [discriminate|].
    inversion teq1; subst.
    destruct n0.
    + simpl. apply le_n_S, le_n_S, le_0_n.
    + apply le_n_S, le_S, le_S. apply PeanoNat.Nat.lt_div2. apply le_n_S, le_0_n.
  - intros; subst. lia.
  - Search well_founded lt. apply Wf_nat.lt_wf.
Defined.

Definition t_1024 := Eval compute in binary_tree 0 1024.
Definition t_1025 := Eval compute in binary_tree 1 1024.

From elpi.apps Require Import feqb.

feqb nat.
feqb list.
feqb tree.

Scheme Boolean Equality for tree.

Eval compute in tree_beq t_1024 t_1025.
Eval compute in tree_eqb t_1024 t_1025.


Require Import PolTac.

Theorem pols_test1: forall x y, x < y ->  (x + x < y + x).
intros.
pols.
auto.
Qed.

Theorem pols_test2: forall x y, y < 0 ->  (x + y < x).
intros.
pols.
auto.
Qed.

Theorem pols_test4:
 forall x y,
 x * x  < y * y ->  ((x + y) * (x + y) < 2 * (x * y + y * y)).
intros.
pols.
auto.
Qed.

Theorem pols_test5:
 forall x y z, x + y * (y + z) = 2 * z ->  2 * x + y * (y + z) = (x + z) + z.
intros.
pols.
auto.
Qed.

Theorem polf_test1: forall x y, (1 <= y -> x  <= x  * y).
intros.
polf.
Qed.

Theorem polf_test2: forall x y, 0 < x -> x  <= x  * y -> 1 <= y.
intros.
hyp_polf H0.
auto.
Qed.

Theorem polr_test1: forall x y z, (x + z) < y -> x + y + z < 2*y.
intros x y z H.
polr H.
pols.
auto.
pols.
auto.
Qed.


Require Export P04.

Theorem dist_not_exists : forall (X:Type) (P : X -> Prop),
  (forall x, P x) -> ~ (exists x, ~ P x).
Proof.
  intros X P Hall Hexist.
  destruct Hexist as [x HPnot].
  unfold not in HPnot. apply HPnot. apply Hall.
Qed.


Require Import HoTT.Classes.interfaces.abstract_algebra
               HoTT.Classes.interfaces.orders
               HoTT.HSet HoTT.Basics.Trunc HProp HSet
               Types.Universe UnivalenceImpliesFunext
               TruncType UnivalenceAxiom Types.Sigma
               FunextVarieties.

Require Import HoTTClasses.partiality
               sierpinsky
               dedekind.

(** * Definition of wCpo on A:hSet *)

Section Mono.

Context {A : hSet}.
Context {LA : Le A}.
Context {B : hSet}.
Context {LB : Le B}.

Definition monotonic  {OA : PartialOrder LA}
                     {OB : PartialOrder LB}
                     (f : A -> B) := forall (x y:A),
                                 LA x y -> LB (f x) (f y).

Record fmono {OA : PartialOrder  LA}
             {OB : PartialOrder  LB} : Type :=
              mk_fmono{ fmonot :> A -> B;
                        fmonotonic: monotonic fmonot}.

Definition fmon {OA : PartialOrder LA}
                {OB : PartialOrder LB} : Le fmono.
Proof.
refine (fun f g:fmono => BuildhProp (forall x, LB (fmonot f x) (fmonot g x))).
Defined.

End Mono.

Section Cpo.

Context {A : hSet}.
Context {LA : Le A}.
Context {B : hSet}.
Context {LB : Le B}.

Class cpo C {LC : Le C} := mkcpo{
     cpobot : C;
     lub : forall (f : IncreasingSequence C), C;
     le_lub : forall (f : IncreasingSequence C) n,
                                      LC (f n) (lub f);
     lub_le : forall (f : IncreasingSequence C) x,
               (forall n, LC (f n) x) -> LC (lub f) x ;
     cpobot_bot : forall x, LC cpobot x
}.

End Cpo.


(**
CoLoR, a Coq library on rewriting and termination.
See the COPYRIGHTS and LICENSE files.

- Sebastien Hinderer, 2004-04-20
- Frederic Blanqui, 2005-02-24

polynomials with multiple variables and integer coefficients

- Kim Quyen Ly, 2013-08-23

Polynomials with multiple variables and rational coefficients.

*)

Set Implicit Arguments.

Require Import VecUtil LogicUtil List ZArith Arith RingType2 QArith.

(***********************************************************************)
(** monomials with n variables *)

Notation monom := (vector nat).

Lemma monom_eq_dec : forall n (m1 m2 : monom n), {m1 = m2} + {~m1 = m2}.

Proof.
  intros. eapply eq_vec_dec. apply eq_nat_dec.
Qed.

(***********************************************************************)
(** polynomials on a ring *)

Notation A := Q.
Notation "0" := QA0.
Notation "1" := QA1.

Notation "x + y" := (QAadd x y).
Notation "x * y" := (QAmul x y).
Notation "- x" := (QAopp x).

Definition Qpoly n := list (A * monom n).

Delimit Scope Qpoly_scope with Qpoly.

Bind Scope Qpoly_scope with Qpoly.

(***********************************************************************)
(** coefficient of monomial m in polynomial p *)

Open Local Scope Q_scope.

Fixpoint Qcoef n (m : monom n) (p : Qpoly n) {struct p} : A :=
  match p with
    | nil => 0
    | cons (c,m') p' =>
      match monom_eq_dec m m' with
	| left _ => c + Qcoef m p'
	| right _ => Qcoef m p'
      end
  end.

(***********************************************************************)
(** simple polynomials *)

(* monomial 1 *)

Open Local Scope nat_scope.

Notation mone := (Vconst O).

(* monomial x_i^1 *)

Fixpoint Qmxi n : forall i, lt i n -> monom n :=
  match n as n return forall i, lt i n -> monom n with
    | O => fun i h => False_rec (monom O) (lt_n_O h)
    | S n' => fun i =>
      match i as i return lt i (S n') -> monom (S n') with
        | O => fun _ => Vcons (S O) (mone n')
	| S _ => fun h => Vcons O (Qmxi (lt_S_n h))
      end
  end.

Close Scope nat_scope.

(* polynomial x_i for i<n *)

(* REMARK: mxi in the improving has kmax in the NewPolynom.v *)

Definition Qpxi n i (h : lt i n) : list (A * monom n) := (1, Qmxi h) :: nil.

(* null polynomial *)

Definition Qpzero n : Qpoly n := nil.

(* constant polynomial *)

Definition Qpconst n (c : A) : Qpoly n := (c, mone n) :: nil.

(***********************************************************************)
(** multiplication by a constant *)

Definition cpmult c n (p : Qpoly n) := map (fun cm => (c * fst cm, snd cm)) p.

(***********************************************************************)
(** opposite *)

Definition popp n (p : Qpoly n) := map (fun cm => (- fst cm, snd cm)) p.

Notation "'-' p" := (popp p) (at level 35, right associativity) : Qpoly_scope.

(***********************************************************************)
(** addition *)

Fixpoint mpadd n (c : A) (m : monom n) (p : Qpoly n) {struct p} : Qpoly n :=
  match p with
    | nil => (c,m) :: nil
    | cons (c',m') p' =>
      match monom_eq_dec m m' with
	| left _ => (c+c',m) :: p'
	| right _ => (c',m') :: mpadd c m p'
      end
  end.

Fixpoint padd n (p1 p2 : Qpoly n) {struct p1} : Qpoly n :=
  match p1 with
    | nil => p2
    | cons (c,m) p' => mpadd c m (padd p' p2)
  end.

Infix "+" := padd : Qpoly_scope.

(***********************************************************************)
(** substraction *)

Open Local Scope Qpoly_scope.

Definition pminus n (p1 p2 : Qpoly n) := p1 + (- p2).

Infix "-" := pminus : Qpoly_scope.

(***********************************************************************)
(** multiplication *)

(* monomial multiplication *)

Definition mmult n (m1 m2 : monom n) := Vmap2 plus m1 m2.

Definition mpmult n c (m : monom n) (p : Qpoly n) :=
  map (fun cm => (c * fst cm, mmult m (snd cm))) p.

Fixpoint pmult n (p1 p2 : Qpoly n) {struct p1} : Qpoly n :=
  match p1 with
    | nil => nil
    | cons (c,m) p' => mpmult c m p2 + pmult p' p2
  end.

Infix "*" := pmult : Qpoly_scope.

(***********************************************************************)
(** power *)

Fixpoint ppower n (p : Qpoly n) (k : nat) {struct k} : Qpoly n :=
  match k with
    | O => Qpconst n 1
    | S k' => p * ppower p k'
  end.

Infix "^" := ppower : Qpoly_scope.

(***********************************************************************)
(** composition *)

Fixpoint mcomp n : monom n -> forall k, vector (Qpoly k) n -> Qpoly k :=
  match n as n return monom n -> forall k, vector (Qpoly k) n -> Qpoly k with
    | O => fun _ k _ => Qpconst k 1
    | S _ => fun m _ ps => Vhead ps ^ Vhead m * mcomp (Vtail m) (Vtail ps)
  end.

Fixpoint pcomp n (p : Qpoly n) k (ps : vector (Qpoly k) n) {struct p} : Qpoly k :=
  match p with
    | nil => nil
    | cons (c,m) p' => cpmult c (mcomp m ps) + pcomp p' ps
  end.

Close Local Scope Qpoly_scope.

(***********************************************************************)
(** evaluation *)

Notation vec := (vector A).

Notation "x * y" := (QAmul x y).
Notation "x + y" := (QAadd x y).

(* Using Qpower Because power has type A and not define in Q. *)

Fixpoint meval n : monom n -> vec n -> A :=
  match n as n return monom n -> vec n -> A with
    | O => fun _ _ => 1
    | S _ => fun m v => Qpower (Vhead v) (Z.of_nat (Vhead m)) * meval (Vtail m) (Vtail v)
  end.

Fixpoint peval n (p : Qpoly n) (v : vec n) {struct p} : A :=
  match p with
    | nil => 0
    | cons (c,m) p' => c * meval m v + peval p' v
  end.

Require Import BoolUtil RelExtras2.

Notation "x =A= y" := (QeqA x y) (at level 70).

Lemma meval_eqA : forall n (m : monom n) (v1 v2 : vec n),
  beq_vec QbeqA v1 v2 = true -> meval m v1 =A= meval m v2.

Proof.
  induction n; simpl; intros. refl. gen H. VSntac v1. VSntac v2. simpl.
  rewrite andb_eq. rewrite QbeqA_ok. intuition.
  rewrite H3. rewrite (IHn _ _ _ H4). refl.
Qed.

Implicit Arguments meval_eqA [n m v1 v2].

Lemma peval_eqA : forall n (p : Qpoly n) (v1 v2 : vec n),
  beq_vec QbeqA v1 v2 = true -> peval p v1 =A= peval p v2.

Proof.
  induction p; simpl; intros. refl. destruct a. rewrite (IHp _ _ H).
  rewrite (meval_eqA H). refl.
Qed.

Lemma meval_app : forall n1 (m1 : monom n1) (v1 : vec n1)
  n2 (m2 : monom n2) (v2 : vec n2),
  meval (Vapp m1 m2) (Vapp v1 v2) =A= meval m1 v1 * meval m2 v2.

Proof.
  induction m1. intros. VOtac. simpl in *. unfold QeqA. ring.
  intros. VSntac v1. simpl. rewrite IHm1. unfold QeqA. ring.
Qed.

Lemma meval_one : forall n (v : vec n), meval (mone n) v =A= 1.

Proof.
  intros n v. induction v; simpl. refl. rewrite IHv. unfold QeqA.
  ring.
Qed.

Lemma meval_xi : forall (n i: nat) (H: lt i n) (v: vec n),
  meval (Qmxi H) v =A= Vnth v H.

Proof.
  induction n. intros. absurd(lt i 0). omega. hyp.
  intro. destruct i; intros; VSntac v. simpl.
  rewrite meval_one. unfold QeqA. ring. simpl. rewrite IHn.
  unfold QeqA. ring.
Qed.

Lemma peval_const : forall n c (v : vec n), peval (Qpconst n c) v =A= c.

Proof.
  intros. simpl. rewrite meval_one. unfold QeqA. ring.
Qed.

Lemma peval_app : forall n (p1 p2 : Qpoly n) (v : vec n),
  peval (p1 ++ p2) v =A= peval p1 v + peval p2 v.

Proof.
  intros. elim p1. simpl. auto. unfold QeqA. ring.
  intros (c, m). intros. simpl. rewrite H. unfold QeqA. ring.
Qed.

Lemma peval_opp : forall n (p : Qpoly n) (v : vec n),
  peval (- p) v =A= - peval p v.

Proof.
  intros. elim p. simpl. unfold QeqA. ring.
  intros (c, m). intros. simpl. rewrite H. unfold QeqA. ring.
Qed.

Lemma peval_mpadd : forall n c (m : monom n) (p : Qpoly n) (v : vec n),
  peval (mpadd c m p) v =A= c * meval m v + peval p v.

Proof.
  intros. elim p. simpl in *. unfold QeqA. ring.
  intros (c', m'). intros. simpl.
  case (monom_eq_dec m m'); simpl; intro. subst m'. unfold QeqA. ring.
  rewrite H. unfold QeqA. ring.
Qed.

Lemma peval_add : forall n (p1 p2 : Qpoly n) (v : vec n),
  peval (p1 + p2) v =A= peval p1 v + peval p2 v.

Proof. intros. elim p1. simpl. unfold QeqA. ring. auto.
  intros (c, m). intros. simpl. rewrite peval_mpadd. rewrite H.
  unfold QeqA. ring.
Qed.

Lemma peval_minus : forall n (p1 p2 : Qpoly n) (v : vec n),
  peval (p1 - p2) v =A= peval p1 v - peval p2 v.

Proof.
  intros. unfold pminus. rewrite peval_add. rewrite peval_opp.
  unfold QeqA. ring.
Qed.

Lemma Qpower_add : forall x n1 n2, Qpower x (n1 + n2) =A= Qpower x n1 * Qpower x n2.
Proof.
Admitted.

Lemma meval_mult : forall n (m1 m2 : monom n) (v : vec n),
  meval (mmult m1 m2) v =A= meval m1 v * meval m2 v.

Proof.
  induction n; intros. VOtac. refl.
  VSntac m1. VSntac m2. simpl. unfold mmult in IHn.
  rewrite IHn.
  (* TODO: new lemma for power_add in Q. *)
  (*rewrite Qpower_add. ring.
     Qed.*)
Admitted.

Lemma peval_mpmult : forall n c (m : monom n) (p : Qpoly n) (v : vec n),
  peval (mpmult c m p) v =A= c * meval m v * peval p v.

Proof.
  induction p; intros; simpl. unfold QeqA. ring.
  destruct a. simpl. rewrite IHp.
  rewrite meval_mult. unfold QeqA. ring.
Qed.

Lemma peval_mult : forall n (p1 p2 : Qpoly n) (v : vec n),
  peval (p1 * p2) v =A= peval p1 v * peval p2 v.

Proof.
  induction p1; intros; simpl. unfold QeqA. ring.
  destruct a. simpl. rewrite peval_add.
  rewrite peval_mpmult. rewrite IHp1. unfold QeqA. ring.
Qed.

Lemma peval_power : forall n (p : Qpoly n) (k : nat) (v : vec n),
  peval (ppower p k) v =A= Qpower (peval p v) (Z.of_nat k).

Proof.
  induction k; intros; simpl. rewrite meval_one. unfold QeqA. ring.
  rewrite peval_mult. rewrite IHk.
  (* TODO *)
  (*ring.
     Qed.*)
Admitted.

Lemma peval_mcomp : forall n k (m: monom n) (ps: vector (Qpoly k) n)
  (v: vec k), peval (mcomp m ps) v =A= meval m (Vmap (fun p => peval p v) ps).

Proof.
  induction n; intros. VOtac. simpl. rewrite meval_one.
  unfold QeqA. ring.
  VSntac m. VSntac ps. simpl. rewrite peval_mult. rewrite peval_power.
  rewrite IHn. refl.
Qed.

Lemma peval_cpmult : forall n c (p : Qpoly n) (v : vec n),
  peval (cpmult c p) v =A= c * peval p v.

Proof.
  induction p; intros; simpl. unfold QeqA. ring.
  destruct a. simpl. rewrite IHp.
  unfold QeqA. ring.
Qed.

Lemma peval_comp : forall n k (p: Qpoly n) (ps: vector (Qpoly k) n) (v: vec k),
  peval (pcomp p ps) v =A= peval p (Vmap (fun p => peval p v) ps).

Proof.
  induction p; intros; simpl.
  unfold QeqA. ring. destruct a. rewrite peval_add.
  rewrite peval_cpmult. rewrite IHp. rewrite peval_mcomp.
  unfold QeqA. ring.
Qed.


Require Import Omega.

Require Import bigstep.
Require Import coinduction.
Require Import datatypes.
Require Import Ndiv2oo.
Require Import streams_vs_lists.

(* Function div2(n) = n/2       if n is even
                      undefined otherwise

   Example machine:
      1 1 -> 1 B
      1 B -> 2 R
      2 1 -> 3 R
      3 B -> 3 R
      3 1 -> 4 B
      4 B -> 2 R

Definition div2: Spec := (1, one, W B, 1) ::
                         (1, B  ,   R, 2) ::
                         (2, one,   R, 3) ::
                         (3, B  ,   R, 3) ::
                         (3, one, W B, 4) ::
                         (4, B  ,   R, 2) :: nil.
*)

(************************ Convergence proof ************************)

Fixpoint repeat (n:nat): list Sym :=
         match n with
         | 0 => nil
         | (S m) => (cons B (cons one (repeat m)))
         end.

Lemma repeat_comm: forall n l,
      (Cons B (Cons one (app_ls (repeat n) l))) =
      (app_ls (repeat n) (Cons B (Cons one l))).
induction n.
simpl. reflexivity.
simpl. intro. rewrite <- IHn. reflexivity.
Qed.

(*
cycle from the state 2, if an even number of ones
*)

Lemma div2_stops_2even: forall n l,
      bf div2 (pair l
                    (app_ls (ones (2*n)) Bs)) 2
              (pair (app_ls (repeat n) l)
                    Bs)                       2.
induction n.

simpl. intro. apply bfH.
unfold is_value. auto.

simpl. intro. apply bfR with 3.
auto.
simpl. replace (n + S (n + 0)) with (S (2*n)).
simpl. apply bfW with 4 B.
auto.
simpl. apply bfR with 2.
auto.
simpl. replace (n + (n + 0)) with (2*n).
rewrite repeat_comm. apply IHn.
omega. omega.
Qed.

(*
stop from the starting state 1
*)

Lemma div2_stops: forall n,
      bf div2 (pair Bs
                    (Cons one (app_ls (ones (2*n)) Bs))) 1
              (pair (app_ls (repeat n) (Cons B Bs))
                    Bs)                                  2.
intros. apply bfW with 1 B.
auto.
simpl. apply bfR with 2.
auto.
simpl. replace (n + (n + 0)) with (2*n). apply div2_stops_2even.
omega.
Qed.


Require Import Bool Arith List Cpdt.CpdtTactics.
Set Implicit Arguments.
Set Asymmetric Patterns.

Inductive binop  : Set := Plus | Times.
Inductive exp : Set :=
| Const : nat -> exp
| Binop : binop -> exp -> exp -> exp.

Definition binopDenote (b : binop) : nat -> nat -> nat :=
  match b with
  | Plus => plus
  | Times => mult
  end.

Fixpoint expDenote (e : exp) : nat :=
  match e with
  | Const n => n
  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
  end.

Eval simpl in expDenote (Const 42).

Eval simpl in expDenote (Binop Plus (Const 2) (Const 2)).

Eval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).

Inductive instr : Set :=
  | iConst : nat -> instr
  | iBinop : binop -> instr.

Definition prog := list instr.
Definition stack := list nat.

Definition instrDenote (i : instr) (s : stack) : option stack :=
  match i with
  | iConst n => Some (n :: s)
  | iBinop b =>
    match s with
    | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')
    | _ => None
    end
  end.

Fixpoint progDenote (p : prog) (s : stack) : option stack :=
  match p with
  | nil => Some s
  | i :: p' =>
    match instrDenote i s with
    | None => None
    | Some s' => progDenote p' s'
    end
  end.

Fixpoint compile (e : exp) : prog :=
  match e with
  | Const n =>  iConst n :: nil
  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil
  end.

Eval simpl in compile (Const 42).

(* Eliding other eval examples... *)

Theorem compile_correct : forall e, progDenote (compile e) nil
                                    = Some (expDenote e :: nil).
Abort.

Lemma compile_correct' : forall e p s,
    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).
  induction e. intros.
  unfold compile. unfold expDenote.
  unfold progDenote at 1. simpl.
  fold progDenote. reflexivity.

  intros. unfold compile. fold compile.
  unfold expDenote. fold expDenote.
  rewrite app_assoc_reverse.
  rewrite IHe2.
  rewrite app_assoc_reverse.
  rewrite IHe1.
  unfold progDenote at 1. simpl.
  fold progDenote. reflexivity.
Abort.

Lemma compile_correct' : forall e s p, progDenote (compile e ++ p) s =
                                       progDenote p (expDenote e :: s).
  induction e; crush.
Qed.

Theorem compile_correct : forall e, progDenote (compile e) nil
                                    = Some (expDenote e :: nil).
  intros.
  rewrite (app_nil_end (compile e)).
  rewrite compile_correct'.
  reflexivity.
Qed.

Inductive type : Set := Nat | Bool.

Inductive tbinop : type -> type -> type -> Set :=
| TPlus : tbinop Nat Nat Nat
| TTimes : tbinop Nat Nat Nat
| TEq : forall t, tbinop t t Bool
| TLt : tbinop Nat Nat Bool.

Inductive texp : type -> Set :=
| TNConst : nat -> texp Nat
| TBConst : bool -> texp Bool
| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.

Definition typeDenote (t : type) : Set :=
  match t with
  | Nat => nat
  | Bool => bool
  end.

Definition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)
  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
  match b with
  | TPlus => plus
  | TTimes => mult
  | TEq Nat => beq_nat
  | TEq Bool => eqb
  | TLt => leb
  end.

Fixpoint texpDenote t (e : texp t) : typeDenote t :=
  match e with
  | TNConst n => n
  | TBConst b => b
  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)
  end.

(* Eliding example translations... *)

Definition tstack := list type.

Inductive tinstr : tstack -> tstack -> Set :=
| TiNConst : forall s, nat -> tinstr s (Nat :: s)
| TiBConst : forall s, bool -> tinstr s (Bool :: s)
| TiBinop : forall arg1 arg2 res s,
    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).

Inductive tprog : tstack -> tstack -> Set :=
| TNil : forall s, tprog s s
| TCons : forall s1 s2 s3,
    tinstr s1 s2
    -> tprog s2 s3
    -> tprog s1 s3.

Fixpoint vstack (ts : tstack) : Set :=
  match ts with
  | nil => unit
  | t :: ts' => typeDenote t * vstack ts'
  end%type.

Definition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=
  match i with
  | TiNConst _ n => fun s => (n, s)
  | TiBConst _ b => fun s => (b, s)
  | TiBinop _ _ _ _ b => fun s =>
                           let '(arg1, (arg2, s')) := s in
                           ((tbinopDenote b) arg1 arg2, s')
  end.

Fixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=
  match p with
  | TNil _ => fun s => s
  | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)
  end.

Fixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=
  match p with
  | TNil _ => fun p' => p'
  | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')
  end.

Fixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=
  match e with
  | TNConst n => TCons (TiNConst _ n) (TNil _)
  | TBConst b => TCons (TiBConst _ b) (TNil _)
  | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)
                                    (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))
  end.

Print tcompile.

Eval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.

(* Eliding other examples... *)

Theorem tcompile_correct : forall t (e : texp t),
    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
Abort.

Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
    tprogDenote (tcompile e ts) s = (texpDenote e, s).
  induction e; crush.
Abort.

Lemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')
                               (s : vstack ts),
    tprogDenote (tconcat p p') s = tprogDenote p' (tprogDenote p s).
  induction p; crush.
Qed.

Hint Rewrite tconcat_correct.

Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
    tprogDenote (tcompile e ts) s = (texpDenote e, s).
  induction e; crush.
Qed.

Hint Rewrite tcompile_correct'.

Theorem tcompile_correct : forall t (e : texp t),
    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
  crush.
Qed.

Require Extraction.
Extraction tcompile.