(**************************************************************)
(*   Copyright Dominique Larchey-Wendling [*]                 *)
(*                                                            *)
(*                             [*] Affiliation LORIA -- CNRS  *)
(**************************************************************)
(*      This file is distributed under the terms of the       *)
(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)
(**************************************************************)

(* Require Import Arith Omega Max List. *)

Require Import Arith Omega List Permutation.
Require Import utils pos.

Set Implicit Arguments.

Section vector.

  Variable X : Type.

  Inductive vec : nat -> Type :=
    | vec_nil  : vec 0
    | vec_cons : forall n, X -> vec n -> vec (S n).

  Let vec_decomp_type n :=
    match n with
      | 0   => Prop
      | S n => (X * vec n)%type
    end.

  Definition vec_decomp n (v : vec n) :=
    match v in vec k return vec_decomp_type k with
      | vec_nil  => False
      | @vec_cons n x v => (x,v)
    end.

  Definition vec_head n (v : vec (S n)) := match v with @vec_cons _ x _ => x end.
  Definition vec_tail n (v : vec (S n)) := match v with @vec_cons _ _ w => w end.

  Let vec_head_tail_type n : vec n -> Prop :=
    match n with
      | 0   => fun v => v = vec_nil
      | S n => fun v => v = vec_cons (vec_head v) (vec_tail v)
    end.

  Let vec_head_tail_prop n v :  @vec_head_tail_type n v.
  Proof. induction v; simpl; auto. Qed.

  Fact vec_0_nil (v : vec 0) : v = vec_nil.
  Proof. apply (vec_head_tail_prop v). Qed.

  Fact vec_head_tail n (v : vec (S n)) : v = vec_cons (vec_head v) (vec_tail v).
  Proof. apply (vec_head_tail_prop v). Qed.

  Fixpoint vec_pos n (v : vec n) : pos n -> X.
  Proof.
    refine (match v with
      | vec_nil => fun p => _
      | @vec_cons n x v => fun p => _
    end); invert pos p.
    exact x.
    exact (vec_pos _ v p).
  Defined.

  Fact vec_pos0 n (v : vec (S n)) : vec_pos v pos0 = vec_head v.
  Proof.
    rewrite (vec_head_tail v).
    reflexivity.
  Qed.

  Fact vec_pos_tail n (v : vec (S n)) p : vec_pos (vec_tail v) p = vec_pos v (pos_nxt p).
  Proof.
    rewrite vec_head_tail at 2; simpl; auto.
  Qed.

  Fact vec_pos1 n (v : vec (S (S n))) : vec_pos v pos1 = vec_head (vec_tail v).
  Proof.
    rewrite <- vec_pos0, vec_pos_tail; auto.
  Qed.

  Fact vec_pos_ext n (v w : vec n) : (forall p, vec_pos v p = vec_pos w p) -> v = w.
  Proof.
    revert v w; induction n as [ | n IHn ]; intros v w H.
    rewrite (vec_0_nil v), (vec_0_nil w); auto.
    revert H; rewrite (vec_head_tail v), (vec_head_tail w); f_equal.
    intros H; f_equal.
    apply (H pos0).
    apply IHn.
    intros p; apply (H (pos_nxt p)).
  Qed.

  Fixpoint vec_set_pos n : (pos n -> X) -> vec n :=
    match n return (pos n -> X) -> vec n with
      | 0   => fun _ => vec_nil
      | S n => fun g => vec_cons (g pos0) (vec_set_pos (fun p => g (pos_nxt p)))
    end.

  Fact vec_pos_set n (g : pos n -> X) p : vec_pos (vec_set_pos g) p = g p.
  Proof.
    revert g p; induction n as [ | n IHn ]; intros g p; pos_inv p; auto.
    apply IHn.
  Qed.

  Fixpoint vec_change n (v : vec n) : pos n -> X -> vec n.
  Proof.
    refine (match v with
      | vec_nil         => fun _ _ => vec_nil
      | @vec_cons n y v => fun p x => _
    end).
    pos_inv p.
    exact (vec_cons x v).
    apply (vec_cons y), (vec_change _ v p x).
  Defined.

  Fact vec_change_eq n v p q x : p = q -> vec_pos (@vec_change n v p x) q = x.
  Proof.
    intro; subst q; revert p x.
    induction v; intros p ?; invert pos p; auto.
  Qed.

  Fact vec_change_neq n v p q x : p <> q -> vec_pos (@vec_change n v p x) q = vec_pos v q.
  Proof.
    revert p q x.
    induction v as [ | n y v IH ]; intros p q x H; invert pos p; invert pos q; auto.
    destruct H; auto.
    apply IH; contradict H; subst; auto.
  Qed.

  Fact vec_change_idem n v p x y : vec_change (@vec_change n v p x) p y = vec_change v p y.
  Proof.
    apply vec_pos_ext; intros q.
    destruct (pos_eq_dec p q).
    repeat rewrite vec_change_eq; auto.
    repeat rewrite vec_change_neq; auto.
  Qed.

  Fact vec_change_same n v p : @vec_change n v p (vec_pos v p) = v.
  Proof.
    apply vec_pos_ext; intros q.
    destruct (pos_eq_dec p q).
    repeat rewrite vec_change_eq; subst; auto.
    repeat rewrite vec_change_neq; auto.
  Qed.

  Variable eq_X_dec : forall x y : X, { x = y } + { x <> y }.

  Fixpoint vec_eq_dec n (u v : vec n) : { u = v } + { u <> v }.
  Proof.
    destruct u as [ | n x u ].
    left.
    rewrite vec_0_nil; trivial.
    destruct (eq_X_dec x (vec_head v)) as [ E1 | D ].
    destruct (vec_eq_dec _ u (vec_tail v)) as [ E2 | D ].
    left; subst; rewrite <- vec_head_tail; auto.
    right; contradict D; subst; rewrite <- D; auto.
    right; contradict D; subst; auto.
  Defined.

  Fixpoint vec_list n (v : vec n) :=
    match v with
      | vec_nil      => nil
      | vec_cons x v => x::vec_list v
    end.

  Fact vec_list_length n v : length (@vec_list n v) = n.
  Proof. induction v; simpl; f_equal; auto. Qed.

  Fact vec_list_inv n v x : In x (@vec_list n v) -> exists p, x = vec_pos v p.
  Proof.
    induction v as [ | n y v IHl ].
    intros [].
    intros [ H | H ]; subst.
    exists pos0; auto.
    destruct IHl as (p & Hp); auto.
    subst; exists (pos_nxt p); auto.
  Qed.

End vector.

(* notations *)

Arguments vec_nil { X }.

Infix "##" := vec_cons (at level 60, right associativity).

Section vec_app_split.

  Variable (X : Type) (n m : nat).

  Definition vec_app (v : vec X n) (w : vec X m) : vec X (n+m).
  Proof.
    apply vec_set_pos; intros p.
    destruct (pos_both _ _ p) as [ q | q ]; refine (vec_pos _ q); assumption.
  Defined.

  Definition vec_split (v : vec X (n+m)) : vec X n * vec X m.
  Proof.
    split; apply vec_set_pos; intros p; refine (vec_pos v _).
    + apply pos_left, p.
    + apply pos_right, p.
  Defined.

  Fact vec_app_split u : let (v,w) := vec_split u in vec_app v w = u.
  Proof.
    case_eq (vec_split u); intros v w; unfold vec_split, vec_app; intros H.
    injection H; clear H; intros Hw Hv.
    apply vec_pos_ext; unfold vec_app; simpl.
    intros p; rewrite vec_pos_set.
    case_eq (pos_both n m p); intros q Hq.
    + rewrite <- Hv, vec_pos_set; f_equal.
      apply f_equal with (f := @pos_lr _ _) in Hq.
      simpl in Hq; rewrite <- Hq; apply pos_lr_both.
    + rewrite <- Hw, vec_pos_set; f_equal.
      apply f_equal with (f := @pos_lr _ _) in Hq.
      simpl in Hq; rewrite <- Hq; apply pos_lr_both.
  Qed.

  Fact vec_split_app v w : vec_split (vec_app v w) = (v,w).
  Proof.
    unfold vec_split, vec_app; f_equal; apply vec_pos_ext; intros p; repeat rewrite vec_pos_set.
    + rewrite pos_both_left; auto.
    + rewrite pos_both_right; auto.
  Qed.

  Fact vec_pos_app_left v w i : vec_pos (vec_app v w) (pos_left _ i) = vec_pos v i.
  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_left; auto. Qed.

  Fact vec_pos_app_right v w i : vec_pos (vec_app v w) (pos_right _ i) = vec_pos w i.
  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_right; auto. Qed.

End vec_app_split.

Fact vec_app_nil X n v : @vec_app X 0 n vec_nil v = v.
Proof.
  apply vec_pos_ext; unfold vec_app; simpl; intros p.
  rewrite vec_pos_set; auto.
Qed.

Fact vec_app_cons X n m x v w : @vec_app X (S n) m (x##v) w = x##vec_app v w.
Proof.
  apply vec_pos_ext; unfold vec_app; intros p.
  rewrite vec_pos_set; simpl in p.
  analyse pos p.
  + simpl; auto.
  + simpl vec_pos at 3; rewrite vec_pos_set.
    simpl pos_both.
    destruct (pos_both n m p); auto.
Qed.

Section vec_map.

  Variable (X Y : Type) (f : X -> Y).

  Fixpoint vec_map n (v : vec X n) :=
    match v with
      | vec_nil => vec_nil
      | x ## v  => f x ## vec_map v
    end.

End vec_map.

Section vec_map2.

  (* Definitions taken from stdlib *)

  Definition case0 {A} (P:vec A 0 -> Type) (H:P (@vec_nil A)) v:P v :=
    match v with
    |vec_nil => H
    |_ => fun devil => False_ind (@IDProp) devil (* subterm !!! *)
    end.

  Definition caseS' {A} {n : nat} (v : vec A (S n)) : forall (P : vec A (S n) -> Type)
                                                      (H : forall h t, P (h ## t)), P v :=
    match v with
    | h ## t => fun P H => H h t
    | _ => fun devil => False_rect (@IDProp) devil
    end.

  Definition rect2 {A B} (P:forall {n}, vec A n -> vec B n -> Type)
             (bas : P vec_nil vec_nil) (recvec : forall {n v1 v2}, P v1 v2 ->
                                                              forall a b, P (a ## v1) (b ## v2)) :=
    fix rect2_fix {n} (v1 : vec A n) : forall v2 : vec B n, P v1 v2 :=
      match v1 with
      | vec_nil => fun v2 => case0 _ bas v2
      | @vec_cons _ n' h1 t1 => fun v2 =>
                                 caseS' v2 (fun v2' => P (h1##t1) v2') (fun h2 t2 => recvec (rect2_fix t1 t2) h1 h2)
      end.

  Definition vec_map2 {A B C} (g:A -> B -> C) :
    forall (n : nat), vec A n -> vec B n -> vec C n :=
    @rect2 _ _ (fun n _ _ => vec C n) (@vec_nil C) (fun _ _ _ H a b => (g a b) ## H).
  Global Arguments vec_map2 {A B C} g {n} v1 v2.

End vec_map2.

Fact vec_pos_map X Y (f : X -> Y) n (v : vec X n) p : vec_pos (vec_map f v) p = f (vec_pos v p).
Proof.
  revert p; induction v; intros p; pos_inv p; simpl; auto.
Qed.

Section vec_plus.

  Variable n : nat.

  Definition vec_plus (v w : vec nat n) := vec_set_pos (fun p => vec_pos v p + vec_pos w p).
  Definition vec_zero : vec nat n := vec_set_pos (fun _ => 0).

  Fact vec_pos_plus v w p : vec_pos (vec_plus v w) p = vec_pos v p + vec_pos w p.
  Proof.
    unfold vec_plus; rewrite vec_pos_set; auto.
  Qed.

  Fact vec_zero_plus v : vec_plus vec_zero v = v.
  Proof.
    apply vec_pos_ext.
    intros p; unfold vec_zero, vec_plus.
    repeat rewrite vec_pos_set; auto.
  Qed.

  Fact vec_zero_spec p : vec_pos vec_zero p = 0.
  Proof. unfold vec_zero; rewrite vec_pos_set; trivial. Qed.

  Fact vec_plus_comm v w : vec_plus v w = vec_plus w v.
  Proof.
    apply vec_pos_ext.
    intros p; unfold vec_zero, vec_plus.
    repeat rewrite vec_pos_set; omega.
  Qed.

  Fact vec_plus_assoc u v w : vec_plus u (vec_plus v w) = vec_plus (vec_plus u v) w.
  Proof.
    apply vec_pos_ext.
    intros p; unfold vec_zero, vec_plus.
    repeat rewrite vec_pos_set; omega.
  Qed.

  Fact vec_plus_is_zero u v : vec_zero = vec_plus u v -> u = vec_zero /\ v = vec_zero.
  Proof.
   unfold vec_zero, vec_plus; intros H; split; apply vec_pos_ext;
   intros p; apply f_equal with (f := fun v => vec_pos v p) in H;
   repeat rewrite vec_pos_set in * |- *; omega.
  Qed.

  Definition vec_one p : vec _ n := vec_set_pos (fun q => if pos_eq_dec p q then 1 else 0).

  Fact vec_one_spec_eq p q : p = q -> vec_pos (vec_one p) q = 1.
  Proof.
    intros [].
    unfold vec_one; rewrite vec_pos_set.
    destruct (pos_eq_dec p p) as [ | [] ]; auto.
  Qed.

  Fact vec_one_spec_neq p q : p <> q -> vec_pos (vec_one p) q = 0.
  Proof.
    intros H.
    unfold vec_one; rewrite vec_pos_set.
    destruct (pos_eq_dec p q) as [ | ]; auto.
    destruct H; auto.
  Qed.

End vec_plus.

Arguments vec_plus {n}.
Arguments vec_zero {n}.
Arguments vec_one {n}.

Reserved Notation " e '#>' x " (at level 58).
Reserved Notation " e [ v / x ] " (at level 57, v at level 0, x at level 0, left associativity).

Local Notation " e '#>' x " := (vec_pos e x) (at level 58).
Local Notation " e [ v / x ] " := (vec_change e x v) (at level 57, v at level 0, x at level 0, left associativity).

Tactic Notation "rew" "vec" :=
  repeat lazymatch goal with
    |              |- context[ _[_/?x]#>?x ] => rewrite vec_change_eq with (p := x) (1 := eq_refl)
    | _ : ?x = ?y  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)
    | _ : ?y = ?x  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)
    | _ : ?x <> ?y |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)
    | _ : ?y <> ?x |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)
    |              |- context[ vec_pos vec_zero ?x ] => rewrite vec_zero_spec with (p := x)
    |              |- context[ vec_pos (vec_one ?x) ?x ] => rewrite vec_one_spec_eq with (p := x) (1 := eq_refl)
    | _ : ?x = ?y  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)
    | _ : ?y = ?x  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)
    | _ : ?x <> ?y |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)
    | _ : ?y <> ?x |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)
    | |- context[ _[_/?x][_/?x] ] => rewrite vec_change_idem with (p := x)
    | |- context[ ?v[(?v#>?x)/?x] ] => rewrite vec_change_same with (p := x)
    | |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y); [ | discriminate ]
    | |- context[ vec_plus vec_zero ?x ] => rewrite vec_zero_plus with (v := x)
    | |- context[ vec_plus ?x vec_zero ] => rewrite (vec_plus_comm x vec_zero); rewrite vec_zero_plus with (v := x)
    | |- vec_plus ?x ?y = vec_plus ?y ?x => apply vec_plus_comm
  end; auto.

Tactic Notation "vec" "split" hyp(v) "with" ident(n) :=
  rewrite (vec_head_tail v); generalize (vec_head v) (vec_tail v); clear v; intros n v.

Tactic Notation "vec" "nil" hyp(v) := rewrite (vec_0_nil v).

Fact vec_zero_S n : @vec_zero (S n) = 0##vec_zero.
Proof. auto. Qed.

Fact vec_one_fst n : @vec_one (S n) pos0 = 1##vec_zero.
Proof.
  apply vec_pos_ext.
  intros p; pos_inv p; rew vec.
Qed.

Fact vec_one_nxt n p : @vec_one (S n) (pos_nxt p) = 0##vec_one p.
Proof.
  apply vec_pos_ext.
  unfold vec_one.
  intros q; rewrite vec_pos_set.
  pos_inv q.
  simpl; auto.
  rewrite <- vec_pos_tail.
  simpl vec_tail.
  rewrite vec_pos_set.
  destruct (pos_eq_dec p q) as [ | C ].
  subst.
  destruct (pos_eq_dec (pos_nxt q) (pos_nxt q)) as [ | [] ]; auto.
  destruct (pos_eq_dec (pos_nxt p) (pos_nxt q)) as [ | ]; auto.
  destruct C; apply pos_nxt_inj; auto.
Qed.

Fact vec_plus_cons n x v y w : @vec_plus (S n) (x##v) (y##w) = x+y ## vec_plus v w.
Proof.
  apply vec_pos_ext; unfold vec_plus.
  intros p; pos_inv p; repeat (rewrite vec_pos_set; simpl; auto).
Qed.

Fact vec_change_succ n v p : v[(S (v#>p))/p] = @vec_plus n (vec_one p) v.
Proof.
  apply vec_pos_ext.
  intros q.
  destruct (pos_eq_dec p q); rew vec;
  rewrite vec_pos_plus; rew vec; subst; auto.
Qed.

Fact vec_change_pred n v p u : v#>p = S u -> v = @vec_plus n (vec_one p) (v[u/p]).
Proof.
  intros Hu.
  apply vec_pos_ext.
  intros q.
  destruct (pos_eq_dec p q); rew vec;
  rewrite vec_pos_plus; rew vec; subst; auto.
Qed.

Fixpoint vec_sum n (v : vec nat n) :=
  match v with
    | vec_nil       => 0
    | vec_cons x w  => x + vec_sum w
  end.

Fact vec_sum_plus n v w : @vec_sum n (vec_plus v w) = vec_sum v + vec_sum w.
Proof.
  revert w; induction v; intros w.
  rewrite (vec_0_nil (vec_plus _ _)), (vec_0_nil w); auto.
  rewrite (vec_head_tail w), vec_plus_cons; simpl.
  rewrite IHv; omega.
Qed.

Fact vec_sum_zero n : @vec_sum n vec_zero = 0.
Proof. induction n; simpl; auto. Qed.

Fact vec_sum_one n p : @vec_sum n (vec_one p) = 1.
Proof.
  revert p; induction n; intros p.
  pos_inv p.
  pos_inv p.
  rewrite vec_one_fst.
  simpl; f_equal; apply vec_sum_zero.
  rewrite vec_one_nxt.
  unfold vec_sum; fold vec_sum.
  rewrite IHn; auto.
Qed.

Fact vec_sum_is_zero n v : @vec_sum n v = 0 -> v = vec_zero.
Proof.
  induction v; simpl; auto.
  simpl; rewrite vec_zero_S; intros; f_equal.
  omega.
  apply IHv; omega.
Qed.

Fact vec_sum_is_nzero n v : 0 < @vec_sum n v -> { p : _ & { w | v = vec_plus (vec_one p) w } }.
Proof.
  induction v as [ | n x v IHv ]; intros Hv; simpl in Hv.
  omega.
  destruct x as [ | x ].
  apply IHv in Hv.
  destruct Hv as (p & w & Hw).
  exists (pos_nxt p), (0##w); rewrite vec_one_nxt.
  rewrite vec_plus_cons; f_equal; auto.
  exists pos0, (x##v).
  rewrite vec_one_fst, vec_plus_cons; rew vec.
Qed.

Section vec_nat_induction.

  (* Specialized induction on vec nat n, with constant n *)

  Variable (n : nat) (P : vec nat n -> Type).

  Hypothesis HP0 : P vec_zero.
  Hypothesis HP1 : forall p, P (vec_one p).
  Hypothesis HP2 : forall v w, P v -> P w -> P (vec_plus v w).

  Theorem vec_nat_induction v : P v.
  Proof.
    induction v as [ v IHv ] using (measure_rect (@vec_sum n)).
    case_eq (vec_sum v).

    intros Hv.
    apply vec_sum_is_zero in Hv; subst; auto.

    intros x Hx.
    destruct (vec_sum_is_nzero v) as (p & w & Hw).
    omega.
    subst.
    apply HP2; auto.
    apply IHv.
    rewrite vec_sum_plus, vec_sum_one; auto.
  Qed.

End vec_nat_induction.

Section vec_map_list.

  Variable X : Type.

  (* morphism between vec nat n and (list X)/~p *)

  Fixpoint vec_map_list X n v : (pos n -> X) -> list X :=
    match v in vec _ m return (pos m -> _) -> _ with
      | vec_nil => fun _ => nil
      | a##v    => fun f => list_repeat (f pos0) a ++ vec_map_list v (fun p => f (pos_nxt p))
    end.

  Fact vec_map_list_zero n f : vec_map_list (@vec_zero n) f = @nil X.
  Proof. revert f; induction n; intros f; simpl; auto. Qed.

  Fact vec_map_list_one n p f : vec_map_list (@vec_one n p) f = f p :: @nil X.
  Proof.
    revert f; induction p; intro.
    rewrite vec_one_fst; simpl; rewrite vec_map_list_zero; auto.
    rewrite vec_one_nxt; simpl; rewrite IHp; auto.
  Qed.

  (* The morphism *)

  Fact vec_map_list_plus n v w f : @vec_map_list X n (vec_plus v w) f ~p vec_map_list v f ++ vec_map_list w f.
  Proof.
    revert v w f; induction n as [ | n IHn ]; intros v w f.
    rewrite (vec_0_nil (vec_plus v w)), (vec_0_nil v), (vec_0_nil w); simpl; auto.
    rewrite (vec_head_tail v), (vec_head_tail w), vec_plus_cons.
    generalize (vec_head v) (vec_tail v) (vec_head w) (vec_tail w); clear v w; intros x v y w.
    simpl.
    rewrite list_repeat_plus.
    solve list eq; apply Permutation_app; auto.
    apply Permutation_trans with (list_repeat (f pos0) y
                               ++ vec_map_list v (fun p => f (pos_nxt p))
                               ++ vec_map_list w (fun p => f (pos_nxt p))).
    apply Permutation_app; auto.
    do 2 rewrite <- app_ass.
    apply Permutation_app; auto.
    apply Permutation_app_comm.
  Qed.

End vec_map_list.

Fact map_vec_map_list X Y (f : X -> Y) n v g : map f (@vec_map_list _ n v g) = vec_map_list v (fun p => f (g p)).
Proof.
  revert g; induction v; intro; simpl; auto.
  rewrite map_app; f_equal; auto.
  rewrite map_list_repeat; auto.
Qed.

Definition list_vec X (l : list X) : { v : vec X (length l) | vec_list v = l }.
Proof.
  induction l as [ | x l (v & Hv) ]; simpl.
  exists vec_nil; auto.
  exists (x##v); simpl; f_equal; auto.
Qed.

Fact vec_reif X n (R : pos n -> X -> Prop) : (forall p, ex (R p)) -> exists v, forall p, R p (vec_pos v p).
Proof.
  intros H.
  apply pos_reification in H.
  destruct H as (f & Hf).
  exists (vec_set_pos f).
  intro; rewrite vec_pos_set; trivial.
Qed.

Fact vec_reif_t X n (R : pos n -> X -> Prop) : (forall p, sig (R p)) -> { v | forall p, R p (vec_pos v p) }.
Proof.
  intros H.
  apply pos_reif_t in H.
  destruct H as (f & Hf).
  exists (vec_set_pos f).
  intro; rewrite vec_pos_set; trivial.
Qed.

Section fun2vec.

  Variable X : Type.

  Fixpoint fun2vec i n f : vec X _ :=
    match n with
      | 0   => vec_nil
      | S n => f i##fun2vec (S i) n f
    end.

  Fact fun2vec_id i n f : fun2vec i n f = vec_set_pos (fun p => f (i+pos2nat p)).
  Proof.
    revert i; induction n as [ | n IHn ]; intros i; simpl; f_equal; auto.
    rewrite IHn.
    apply vec_pos_ext; intros; do 2 rewrite vec_pos_set; f_equal.
    rewrite pos2nat_nxt; omega.
  Qed.

  Fact fun2vec_lift i n f : fun2vec i n (fun j => f (S j)) = fun2vec (S i) n f.
  Proof. revert i f; induction n; intros; simpl; f_equal; auto. Qed.

  Fact vec_pos_fun2vec i n f p : vec_pos (fun2vec i n f) p = f (i+pos2nat p).
  Proof. rewrite fun2vec_id, vec_pos_set; auto. Qed.

  Definition vec2fun n (v : vec X n) x i :=
    match le_lt_dec n i with
      | left  _ => x
      | right H => vec_pos v (nat2pos H)
    end.

  Fact fun2vec_vec2fun n v x : fun2vec 0 n (@vec2fun n v x) = v.
  Proof.
    apply vec_pos_ext.
    intros p; rewrite vec_pos_fun2vec; simpl.
    unfold vec2fun.
    generalize (pos2nat_prop p).
    destruct (le_lt_dec n (pos2nat p)); try omega.
    rewrite nat2pos_pos2nat; auto.
  Qed.

  Fact vec2fun_fun2vec n f x i : i < n -> @vec2fun n (fun2vec 0 n f) x i = f i.
  Proof.
    intros H.
    unfold vec2fun.
    destruct (le_lt_dec n i); try omega.
    rewrite vec_pos_fun2vec, pos2nat_nat2pos; auto.
  Qed.

End fun2vec.


From Categories Require Import Essentials.Notations.
From Categories Require Import Essentials.Types.
From Categories Require Import Essentials.Facts_Tactics.
From Categories Require Import Category.Main.

Local Open Scope morphism_scope.

Section PullBack.
  Context {C : Category} {a b x : C} (f : a –≻ x) (g : b –≻ x).

  (**
Given two arrows f : a -> x and g : b -> x, their pullback is an object p
together with two arrows π₁ : p -> a and π₂ : p -> b such that the following
diagram commutes:

#

        π₂
   p ————————–> b
   |            |
π₁ |            | g
   |            |
   ↓            ↓
   a —————————> x
        f

#

Provided that for any object q and arrows p1 : q -> a and p2 : q -> b that the
following diagram commutes:

#

        p2
   q ————————–> b
   |            |
p1 |            | g
   |            |
   ↓            ↓
   a —————————> x
        f

#

there is a unique arrow h : q -> p that makes the following diagram commute:

#

                p2
      q ———————————————————–
      |  \                   |
      |    \ ∃!h             |
      |      \               |
      |        ↘     π₂      ↓
  p1  |         p ————————–> b
      |         |            |
      |      π₁ |            | g
      |         |            |
      |         ↓            ↓
       ——————–> a —————————> x
                    f

#

We usually use a half square in the corner of p to denote p is the pullback of
f and g. Like so:
#

        π₂
   p ————————–> b
   |__|         |
π₁ |            | g
   |            |
   ↓            ↓
   a —————————> x
        f

#
*)
  Record PullBack : Type :=
    {
      pullback : C;

      pullback_morph_1 : pullback –≻ a;

      pullback_morph_2 : pullback –≻ b;

      pullback_morph_com : f ∘ pullback_morph_1 = g ∘ pullback_morph_2;

      pullback_morph_ex (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b) :
        f ∘ pm1 = g ∘ pm2 → p' –≻ pullback;

      pullback_morph_ex_com_1 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
                              (pmc : f ∘ pm1 = g ∘ pm2)
      :
        pullback_morph_1 ∘ (pullback_morph_ex p' pm1 pm2 pmc) = pm1;

      pullback_morph_ex_com_2 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
                              (pmc : f ∘ pm1 = g ∘ pm2)
      :
        pullback_morph_2 ∘ (pullback_morph_ex p' pm1 pm2 pmc) = pm2;

      pullback_morph_ex_unique
        (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
        (pmc : f ∘ pm1 = g ∘ pm2) (u u' : p' –≻ pullback) :
        pullback_morph_1 ∘ u = pm1 →
        pullback_morph_2 ∘ u = pm2 →
        pullback_morph_1 ∘ u' = pm1 →
        pullback_morph_2 ∘ u' = pm2 → u = u'
    }.

  Coercion pullback : PullBack >-> Obj.

  (** Pullbacks are unique up to isomorphism. *)
  Theorem PullBack_iso (p1 p2 : PullBack) : (p1 ≃ p2)%isomorphism.
  Proof.
    apply
      (
        Build_Isomorphism
          _
          _
          _
          (
            pullback_morph_ex
              p2
              _
              (pullback_morph_1 p1)
              (pullback_morph_2 p1)
              (pullback_morph_com p1)
          )
          (
            pullback_morph_ex
              p1
              _
              (pullback_morph_1 p2)
              (pullback_morph_2 p2)
              (pullback_morph_com p2)
          )
      ); eapply pullback_morph_ex_unique;
    match goal with
      | [|- _ ∘ id = _] => simpl_ids; trivial
      | _ => idtac
    end; try apply pullback_morph_com;
    rewrite <- assoc;
    repeat (rewrite pullback_morph_ex_com_1 || rewrite pullback_morph_ex_com_2);
    trivial.
  Qed.

End PullBack.

(** The predicate form of pullback: *)
Section is_PullBack.
  Context {C : Category} {a b x pb : C} (p1 : pb –≻ a)
          (p2 : pb –≻ b) (f : a –≻ x) (g : b –≻ x).

  Local Open Scope morphism_scope.

  Record is_PullBack : Type :=
    {
      is_pullback_morph_com : f ∘ p1 = g ∘ p2;

      is_pullback_morph_ex (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b) :
        f ∘ pm1 = g ∘ pm2 → p' –≻ pb;

      is_pullback_morph_ex_com_1 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
                                 (pmc : f ∘ pm1 = g ∘ pm2)
      :
        p1 ∘ (is_pullback_morph_ex p' pm1 pm2 pmc) = pm1;

      is_pullback_morph_ex_com_2 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
                                 (pmc : f ∘ pm1 = g ∘ pm2)
      :
        p2 ∘ (is_pullback_morph_ex p' pm1 pm2 pmc) = pm2;

      is_pullback_morph_ex_unique
        (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)
        (pmc : f ∘ pm1 = g ∘ pm2) (u u' : p' –≻ pb) :
        p1 ∘ u = pm1 →
        p2 ∘ u = pm2 →
        p1 ∘ u' = pm1 →
        p2 ∘ u' = pm2 → u = u'
    }.

End is_PullBack.

Definition Has_PullBacks (C : Category) : Type :=
  ∀ (a b c : C) (f : a –≻ c) (g : b –≻ c), PullBack f g.

Existing Class Has_PullBacks.

Arguments PullBack _ {_ _ _} _ _, {_ _ _ _} _ _.
Arguments pullback {_ _ _ _ _ _} _.
Arguments pullback_morph_1 {_ _ _ _ _ _} _.
Arguments pullback_morph_2 {_ _ _ _ _ _} _.
Arguments pullback_morph_com {_ _ _ _ _ _} _.
Arguments pullback_morph_ex {_ _ _ _ _ _} _ _ _ _ _.
Arguments pullback_morph_ex_com_1 {_ _ _ _ _ _} _ _ _ _ _.
Arguments pullback_morph_ex_com_2 {_ _ _ _ _ _} _ _ _ _ _.
Arguments pullback_morph_ex_unique {_ _ _ _ _ _} _ _ _ _ _ _ _ _ _ _ _.

Arguments is_PullBack _ { _ _ _ _} _ _ _ _, {_ _ _ _ _ } _ _ _ _.

Arguments is_pullback_morph_com {_ _ _ _ _ _ _ _ _} _.
Arguments is_pullback_morph_ex {_ _ _ _ _ _ _ _ _} _ _ _ _ _.
Arguments is_pullback_morph_ex_com_1 {_ _ _ _ _ _ _ _ _} _ _ _ _ _.
Arguments is_pullback_morph_ex_com_2 {_ _ _ _ _ _ _ _ _} _ _ _ _ _.
Arguments is_pullback_morph_ex_unique {_ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _ _ _ _ _.

Section is_PullBack_PullBack.
  Context {C : Category} {a b x pb : C} {p1 : pb –≻ a} {p2 : pb –≻ b} {f : a –≻ x}
          {g : b –≻ x} (iPB : is_PullBack p1 p2 f g).

  (** The predicate form of pullbacks implies the compact from of pullbacks.
       See above for details.*)
  Definition is_PullBack_PullBack : PullBack f g :=
    {|
      pullback := pb;
      pullback_morph_1 := p1;
      pullback_morph_2 := p2;
      pullback_morph_com := is_pullback_morph_com iPB;
      pullback_morph_ex := fun p' pm1 pm2 => is_pullback_morph_ex iPB p' pm1 pm2;
      pullback_morph_ex_com_1 :=
        fun p' pm1 pm2 pmc => is_pullback_morph_ex_com_1 iPB p' pm1 pm2 pmc;
      pullback_morph_ex_com_2 :=
        fun p' pm1 pm2 pmc => is_pullback_morph_ex_com_2 iPB p' pm1 pm2 pmc;
      pullback_morph_ex_unique :=
        fun p' pm1 pm2 pmc u u' => is_pullback_morph_ex_unique iPB p' pm1 pm2 pmc u u'
    |}.

End is_PullBack_PullBack.

Section PullBack_is_PullBack.
  Context {C : Category} {a b x : C} {f : a –≻ x}
          {g : b –≻ x} (PB : PullBack f g).

  (** Compact form of pullback implies the predicate form of pullback.
      See above for details. *)
  Definition PullBack_is_PullBack :
    is_PullBack (pullback_morph_1 PB) (pullback_morph_2 PB) f g :=
    {|
      is_pullback_morph_com := pullback_morph_com PB;
      is_pullback_morph_ex := fun p' pm1 pm2 => pullback_morph_ex PB p' pm1 pm2;
      is_pullback_morph_ex_com_1 :=
        fun p' pm1 pm2 pmc => pullback_morph_ex_com_1 PB p' pm1 pm2 pmc;
      is_pullback_morph_ex_com_2 :=
        fun p' pm1 pm2 pmc => pullback_morph_ex_com_2 PB p' pm1 pm2 pmc;
      is_pullback_morph_ex_unique :=
        fun p' pm1 pm2 pmc u u' => pullback_morph_ex_unique PB p' pm1 pm2 pmc u u'
    |}.

End PullBack_is_PullBack.

(** PushOut is the dual of PullBack *)
Definition PushOut (C : Category) := @PullBack (C^op).

Arguments PushOut _ {_ _ _} _ _, {_ _ _ _} _ _.

Definition Has_PushOuts (C : Category) : Type :=
  ∀ (a b c : C) (f : c –≻ a) (g : c –≻ b), PushOut f g.

Existing Class Has_PushOuts.


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

(** Well-founded relations and natural numbers *)

Require Import PeanoNat Lt.

Local Open Scope nat_scope.

Implicit Types m n p : nat.

Section Well_founded_Nat.

Variable A : Type.

Variable f : A -> nat.
Definition ltof (a b:A) := f a < f b.
Definition gtof (a b:A) := f b > f a.

Theorem well_founded_ltof : well_founded ltof.
Proof.
  assert (H : forall n (a:A), f a < n -> Acc ltof a).
  { induction n.
    - intros; absurd (f a < 0); auto with arith.
    - intros a Ha. apply Acc_intro. unfold ltof at 1. intros b Hb.
      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }
  intros a. apply (H (S (f a))). auto with arith.
Defined.

Theorem well_founded_gtof : well_founded gtof.
Proof.
  exact well_founded_ltof.
Defined.

(** It is possible to directly prove the induction principle going
   back to primitive recursion on natural numbers ([induction_ltof1])
   or to use the previous lemmas to extract a program with a fixpoint
   ([induction_ltof2])

the ML-like program for [induction_ltof1] is :
[[
let induction_ltof1 f F a =
  let rec indrec n k =
    match n with
    | O -> error
    | S m -> F k (indrec m)
  in indrec (f a + 1) a
]]

the ML-like program for [induction_ltof2] is :
[[
   let induction_ltof2 F a = indrec a
   where rec indrec a = F a indrec;;
]]
*)

Theorem induction_ltof1 :
  forall P:A -> Set,
    (forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.
Proof.
  intros P F.
  assert (H : forall n (a:A), f a < n -> P a).
  { induction n.
    - intros; absurd (f a < 0); auto with arith.
    - intros a Ha. apply F. unfold ltof. intros b Hb.
      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }
  intros a. apply (H (S (f a))). auto with arith.
Defined.

Theorem induction_gtof1 :
  forall P:A -> Set,
    (forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.
Proof.
  exact induction_ltof1.
Defined.

Theorem induction_ltof2 :
  forall P:A -> Set,
    (forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.
Proof.
  exact (well_founded_induction well_founded_ltof).
Defined.

Theorem induction_gtof2 :
  forall P:A -> Set,
    (forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.
Proof.
  exact induction_ltof2.
Defined.

(** If a relation [R] is compatible with [lt] i.e. if [x R y => f(x) < f(y)]
    then [R] is well-founded. *)

Variable R : A -> A -> Prop.

Hypothesis H_compat : forall x y:A, R x y -> f x < f y.

Theorem well_founded_lt_compat : well_founded R.
Proof.
  assert (H : forall n (a:A), f a < n -> Acc R a).
  { induction n.
    - intros; absurd (f a < 0); auto with arith.
    - intros a Ha. apply Acc_intro. intros b Hb.
      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }
  intros a. apply (H (S (f a))). auto with arith.
Defined.

End Well_founded_Nat.

Lemma lt_wf : well_founded lt.
Proof.
  exact (well_founded_ltof nat (fun m => m)).
Defined.

Lemma lt_wf_rec1 :
  forall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.
Proof.
  exact (fun p P F => induction_ltof1 nat (fun m => m) P F p).
Defined.

Lemma lt_wf_rec :
  forall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.
Proof.
  exact (fun p P F => induction_ltof2 nat (fun m => m) P F p).
Defined.

Lemma lt_wf_ind :
  forall n (P:nat -> Prop), (forall n, (forall m, m < n -> P m) -> P n) -> P n.
Proof.
  intro p; intros; elim (lt_wf p); auto with arith.
Qed.

Lemma gt_wf_rec :
  forall n (P:nat -> Set), (forall n, (forall m, n > m -> P m) -> P n) -> P n.
Proof.
  exact lt_wf_rec.
Defined.

Lemma gt_wf_ind :
  forall n (P:nat -> Prop), (forall n, (forall m, n > m -> P m) -> P n) -> P n.
Proof lt_wf_ind.

Lemma lt_wf_double_rec :
 forall P:nat -> nat -> Set,
   (forall n m,
     (forall p q, p < n -> P p q) ->
     (forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.
Proof.
  intros P Hrec p; pattern p; apply lt_wf_rec.
  intros n H q; pattern q; apply lt_wf_rec; auto with arith.
Defined.

Lemma lt_wf_double_ind :
  forall P:nat -> nat -> Prop,
    (forall n m,
      (forall p (q:nat), p < n -> P p q) ->
      (forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.
Proof.
  intros P Hrec p; pattern p; apply lt_wf_ind.
  intros n H q; pattern q; apply lt_wf_ind; auto with arith.
Qed.

Hint Resolve lt_wf: arith.
Hint Resolve well_founded_lt_compat: arith.

Section LT_WF_REL.
  Variable A : Set.
  Variable R : A -> A -> Prop.

  (* Relational form of inversion *)
  Variable F : A -> nat -> Prop.
  Definition inv_lt_rel x y := exists2 n, F x n & (forall m, F y m -> n < m).

  Hypothesis F_compat : forall x y:A, R x y -> inv_lt_rel x y.
  Remark acc_lt_rel : forall x:A, (exists n, F x n) -> Acc R x.
  Proof.
    intros x [n fxn]; generalize dependent x.
    pattern n; apply lt_wf_ind; intros.
    constructor; intros.
    destruct (F_compat y x) as (x0,H1,H2); trivial.
    apply (H x0); auto.
  Qed.

  Theorem well_founded_inv_lt_rel_compat : well_founded R.
  Proof.
    constructor; intros.
    case (F_compat y a); trivial; intros.
    apply acc_lt_rel; trivial.
    exists x; trivial.
  Qed.

End LT_WF_REL.

Lemma well_founded_inv_rel_inv_lt_rel :
  forall (A:Set) (F:A -> nat -> Prop), well_founded (inv_lt_rel A F).
Proof.
  intros; apply (well_founded_inv_lt_rel_compat A (inv_lt_rel A F) F); trivial.
Qed.

(** A constructive proof that any non empty decidable subset of
    natural numbers has a least element *)

Set Implicit Arguments.

Require Import Le.
Require Import Compare_dec.
Require Import Decidable.

Definition has_unique_least_element (A:Type) (R:A->A->Prop) (P:A->Prop) :=
  exists! x, P x /\ forall x', P x' -> R x x'.

Lemma dec_inh_nat_subset_has_unique_least_element :
  forall P:nat->Prop, (forall n, P n \/ ~ P n) ->
    (exists n, P n) -> has_unique_least_element le P.
Proof.
  intros P Pdec (n0,HPn0).
  assert
    (forall n, (exists n', n'<n /\ P n' /\ forall n'', P n'' -> n'<=n'')
               \/ (forall n', P n' -> n<=n')).
  { induction n.
    - right. intros. apply Nat.le_0_l.
    - destruct IHn as [(n' & IH1 & IH2)|IH].
      + left. exists n'; auto with arith.
      + destruct (Pdec n) as [HP|HP].
        * left. exists n; auto with arith.
        * right. intros n' Hn'.
          apply Nat.le_neq; split; auto. intros <-. auto. }
  destruct (H n0) as [(n & H1 & H2 & H3)|H0]; [exists n | exists n0];
   repeat split; trivial;
   intros n' (HPn',Hn'); apply Nat.le_antisymm; auto.
Qed.

Unset Implicit Arguments.

Notation iter_nat n A f x := (nat_rect (fun _ => A) x (fun _ => f) n) (only parsing).


(* 5 Infinite Data and Proofs *)

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

(* 5.1 Computing with Infinite Data *)

Section stream.
  Variable A : Type.
  CoInductive stream : Type :=
  | Cons : A -> stream -> stream
  .
End stream.

(*
Rather, whereas recursive definitions were necessary to use values of recursive
inductive types effectively, here we find that we need co-recursive definitions
to build values of co-inductive types effectively.
*)

CoFixpoint zeroes : stream nat := Cons 0 zeroes.

CoFixpoint trues_falses : stream bool := Cons true falses_trues
with falses_trues : stream bool := Cons false trues_falses
.

Fixpoint approx A (s : stream A) (n : nat) : list A :=
  match n with
  | O => nil
  | S n' =>
    match s with
    | Cons h t => h :: approx t n'
    end
  end
.

Eval simpl in approx zeroes 10.
Eval simpl in approx trues_falses 10.

Section map.
  Variables A B : Type.
  Variable f : A -> B .
  CoFixpoint map (s : stream A) : stream B :=
    match s with
      | Cons h t => Cons (f h) (map t)
    end.
End map.

Section interleave.
  Variable A : Type.
  CoFixpoint interleave (s1 s2 : stream A) : stream A :=
    match s1,s2 with
    | Cons h1 t1 , Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))
    end.
End interleave.

Definition tl A (s : stream A) : stream A :=
  match s with
  | Cons _ s' => s'
  end
.

(* 5.2 Infinite Proofs *)

CoFixpoint ones : stream nat := Cons 1 ones.
Definition ones' := map S zeroes.

Theorem ones_eq : ones = ones'.
Abort.

Section stream_eq.
  Variable A : Type.
  CoInductive stream_eq : stream A -> stream A -> Prop :=
  | Stream_eq : forall h t1 t2,
      stream_eq t1 t2 -> stream_eq (Cons h t1) (Cons h t2).
End stream_eq.

Theorem oneS_eq : stream_eq ones ones'.
                    cofix.
Abort.

Definition frob A (s : stream A) : stream A :=
  match s with
  | Cons h t => Cons h t
  end.

Theorem frob_eq : forall A (s : stream A) , s = frob s.
                                              destruct s; reflexivity.
Qed.

Theorem ones_eq : stream_eq ones ones'.
                    cofix.
                    rewrite (frob_eq ones).
                    rewrite (frob_eq ones').
                    simpl.
                    constructor.
                    assumption.
Qed.

Theorem ones_eq' : stream_eq ones ones'.
                     cofix; crush.
                     (* Guarded ** TODO: Figure out guarded. *)
Abort.

Definition hd A (s : stream A) : A :=
  match s with
  | Cons x _ => x
  end.

Section stream_eq_coind.
  Variable A : Type.
  Variable R : stream A -> stream A -> Prop.
  Hypothesis Cons_case_hd : forall s1 s2, R s1 s2 -> hd s1 = hd s2.
  Hypothesis Cons_case_tl : forall s1 s2, R s1 s2 -> R (tl s1) (tl s2).

  Theorem stream_eq_coind : forall s1 s2 , R s1 s2 -> stream_eq s1 s2.
                                             cofix; destruct s1; destruct s2; intro.
                                             generalize (Cons_case_hd H); intro Heq; simpl in Heq; rewrite Heq.
                                             constructor.
                                             apply stream_eq_coind.
                                             apply (Cons_case_tl H).
  Qed.
End stream_eq_coind.

Print stream_eq_coind.

Theorem ones_eq'' : stream_eq ones ones'.
                      apply (stream_eq_coind (fun s1 s2 => s1 = ones /\ s2 = ones')); crush.
Qed.

Section stream_eq_loop.
  Variable A : Type.
  Variable s1 s2 : stream A.
  Hypothesis Cons_case_hd : hd s1 = hd s2.
  Hypothesis loop1 : tl s1 = s1.
  Hypothesis loop2 : tl s2 = s2.
  Theorem stream_eq_loop : stream_eq s1 s2.
                             apply (stream_eq_coind (fun s1' s2' => s1 = s1' /\ s2 = s2')); crush.
  Qed.
End stream_eq_loop.

Theorem ones_eq''' : stream_eq ones ones'.
                       apply stream_eq_loop; crush.
Qed.

Print fact.

CoFixpoint fact_slow' (n : nat) := Cons (fact n) (fact_slow' (S n)).
Definition fact_slow := fact_slow' 1.

CoFixpoint fact_iter' (cur acc : nat) := Cons acc (fact_iter' (S cur) (acc * cur)).
Definition fact_iter := fact_iter' 2 1.

Eval simpl in approx fact_iter 5.
Eval simpl in approx fact_slow 5.

Lemma fact_def : forall x n,
    fact_iter' x (fact n * S n) = fact_iter' x (fact (S n)).
      simpl; intros; f_equal; ring.
Qed.

Hint Resolve fact_def.

Lemma fact_eq' : forall n , stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).
      intro; apply (stream_eq_coind (fun s1 s2 => exists n, s1 = fact_iter' (S n) (fact n) /\ s2 = fact_slow' n)); crush; eauto.
Qed.

Theorem fact_eq : stream_eq fact_iter fact_slow.
                    apply fact_eq'.
Qed.

Section stream_eq_onequant.
  Variables A B : Type.
  Variables f g : A -> stream B.

  Hypothesis Cons_case_hd : forall x , hd (f x) = hd (g x).
  Hypothesis Cons_case_tl : forall x , exists y , tl (f x) = f y /\ tl (g x) = g y.
  Theorem stream_eq_onequant : forall x , stream_eq (f x) (g x).
        intro; apply (stream_eq_coind (fun s1 s2 => exists x , s1 = f x /\ s2 = g x)); crush; eauto.
  Qed.
End stream_eq_onequant.

Lemma fact_eq'' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).
      apply stream_eq_onequant; crush; eauto.
Qed.

(* 5.3 Simple Modeling of Non-Terminating Programs *)

Definition var := nat.

Definition vars := var -> nat.
Definition set (vs : vars) (v : var) (n : nat) : vars :=
  fun v' => if beq_nat v v' then n else vs v'.

Inductive exp : Set :=
| Const : nat -> exp
| Var : var -> exp
| Plus : exp -> exp -> exp
.

Fixpoint evalExp (vs : vars) (e : exp) : nat :=
  match e with
  | Const n => n
  | Var v => vs v
  | Plus e1 e2 => evalExp vs e1 + evalExp vs e2
  end
.

Inductive cmd : Set :=
| Assign : var -> exp -> cmd
| Seq : cmd -> cmd -> cmd
| While : exp -> cmd -> cmd
.

CoInductive evalCmd : vars -> cmd -> vars -> Prop :=
| EvalAssign : forall vs v e , evalCmd vs (Assign v e) (set vs v (evalExp vs e))
| EvalSeq : forall vs1 vs2 vs3 c1 c2 ,
    evalCmd vs1 c1 vs2
    -> evalCmd vs2 c2 vs3
    -> evalCmd vs1 (Seq c1 c2) vs3
| EvalWhileFalse : forall vs e c ,
    evalExp vs e = 0
    -> evalCmd vs (While e c) vs
| EvalWhileTrue : forall vs1 vs2 vs3 e c ,
    evalExp vs1 e <> 0
    -> evalCmd vs1 c vs2
    -> evalCmd vs2 (While e c) vs3
    -> evalCmd vs1 (While e c) vs3
.

(*

----------------------------------------- (EvalAssign)
{vs} Assign v e {set vs v (evalExp vs e)}

{vs1} c1 {vs2}           {vs2} c2 {vs3}
--------------------------------------- (EvalSeq)
         {vs1} Seq c1 c2 {vs3}

 evalExp vs e = 0
------------------- (EvalWhileFalse)
{vs} While e c {vs}

evalExp vs1 e <> 0     {vs1} c {vs2}      {vs2} While e c {vs3}
--------------------------------------------------------------- (EvalWhileTrue)
                   {vs1} While e c {vs3}

*)

Section evalCmd_coind.
  Variable R : vars -> cmd -> vars -> Prop.

  Hypothesis AssignCase : forall vs1 vs2 v e, R vs1 (Assign v e) vs2
    -> vs2 = set vs1 v (evalExp vs1 e).

  Hypothesis SeqCase : forall vs1 vs3 c1 c2, R vs1 (Seq c1 c2) vs3
    -> exists vs2, R vs1 c1 vs2 /\ R vs2 c2 vs3.

  Hypothesis WhileCase : forall vs1 vs3 e c, R vs1 (While e c) vs3
    -> (evalExp vs1 e = 0 /\ vs3 = vs1)
    \/ exists vs2, evalExp vs1 e <> 0 /\ R vs1 c vs2 /\ R vs2 (While e c) vs3.

  Theorem evalCmd_coind : forall vs1 c vs2, R vs1 c vs2 -> evalCmd vs1 c vs2.
    cofix; intros; destruct c.
    rewrite (AssignCase H); constructor.
    destruct (SeqCase H) as [? [? ?]]; econstructor; eauto.
    destruct (WhileCase H) as [[? ?] | [? [? [? ?]]]]; subst; econstructor; eauto.
  Qed.
End evalCmd_coind.

Fixpoint optExp (e : exp) : exp :=
  match e with
  | Plus (Const 0) e => optExp e
  | Plus e1 e2 => Plus (optExp e1) (optExp e2)
  | _ => e
  end
.

Fixpoint optCmd (c : cmd) : cmd :=
  match c with
  | Assign v e => Assign v (optExp e)
  | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)
  | While e c => While (optExp e) (optCmd c)
  end
.

Lemma optExp_correct : forall vs e ,
    evalExp vs (optExp e) = evalExp vs e.
      induction e; crush;
      repeat (match goal with
              | [ |- context[match ?E with Const _ => _ | _ => _ end]] => destruct E
              | [ |- context [match ?E with O => _ | S _ => _ end ]] => destruct E
              end; crush).
Qed.

Hint Rewrite optExp_correct.

Ltac finisher :=
  match goal with
  | [ H : evalCmd _ _ _ |- _ ] => ((inversion H; [])
                                   || (inversion H; [|])); subst
  end; crush; eauto 10.

Lemma optCmd_correct1 : forall vs1 c vs2 ,
    evalCmd vs1 c vs2 -> evalCmd vs1 (optCmd c) vs2.
      intros; apply (evalCmd_coind (fun vs1 c' vs2 => exists c , evalCmd vs1 c vs2 /\ c' = optCmd c)); eauto; crush; match goal with
  | [ H : _ = optCmd ?E |- _ ] => destruct E; simpl in *; discriminate || injection H; intros; subst
                                                                                end; finisher.
Qed.

Lemma optCmd_correct2 : forall vs1 c vs2 ,
    evalCmd vs1 (optCmd c) vs2 -> evalCmd vs1 c vs2.
      intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));
      crush; finisher.
Qed.

Theorem optCmd_correct : forall vs1 c vs2 ,
    evalCmd vs1 (optCmd c) vs2 <-> evalCmd vs1 c vs2.
      intuition; apply optCmd_correct1
                 || apply optCmd_correct2; assumption.
Qed.


(** ** Some useful instances of Monoid classes

File %\href{../Powers/SRC/Monoid_instances.v}{Powers/SRC/Monoid\_instances}
defines various instances of [Monoid] and [EMonoid].
*)

Require Export Monoid_def.
Require Import RelationClasses Morphisms.

Require Import ZArith PArith.
Require Import Arith.
Require Import NArith.
Require Import Ring31.

Open Scope Z_scope.

(** *** Multiplicative monoid on [Z] *)

(* begin snippet ZMultDef *)
#[ global ] Instance Z_mult_op : Mult_op Z := Z.mul.

#[ global ] Instance ZMult : Monoid  Z_mult_op 1. (* .no-out *)
Proof. (* .no-out *)
  split.
    all: unfold Z_mult_op, mult_op;intros;ring.
Qed.
(* end snippet ZMultDef *)

#[ global ] Instance ZMult_Abelian : Abelian_Monoid ZMult.
Proof.
  split; exact Zmult_comm.
Qed.

(** *** Multiplicative monoid on [nat] *)

(* begin snippet natMult:: no-out *)

#[ global ] Instance nat_mult_op : Mult_op nat | 5 := Nat.mul.

#[ global ] Instance  Natmult : Monoid nat_mult_op  1%nat | 5.
Proof.
   split;unfold nat_mult_op, mult_op; intros; ring.
Qed.
(* end snippet natMult *)

(** *** Additive monoid on [nat]

The following monoid is useful for proving the correctness of complex
exponentiation algorithms. In effect, the $n$-th "power" of $1$ is
equal to $n$. See Sect.%~\ref{chains-exponent}.
*)

(* begin snippet natPlus:: no-out *)
#[ global ] Instance nat_plus_op : Mult_op nat | 12 := Nat.add.

#[ global ] Instance Natplus : Monoid nat_plus_op  0%nat | 12.
Proof.
   split;unfold nat_plus_op, mult_op; intros; ring.
Qed.

(* end snippet natPlus *)

Open Scope N_scope.

#[ global ] Instance N_mult_op  : Mult_op N | 5 := N.mul.

#[ global ] Instance NMult : Monoid N_mult_op 1 | 5.
Proof.
  split;unfold N_mult_op, mult_op; intros; ring.
Qed.

(* begin snippet CheckCoercion *)
Check NMult : EMonoid  N.mul 1%N eq.
(* end snippet CheckCoercion *)

#[ global ] Instance N_plus_op  : Mult_op N | 12 := N.add.

#[ global ] Instance NPlus : Monoid N_plus_op 0 | 12.
Proof.
  split;unfold N_plus_op, mult_op; intros; ring.
Qed.

(** Multiplicative Monoid on [positive]
*)

#[ global ] Instance P_mult_op : Mult_op positive | 5  := Pos.mul .

#[ global ] Instance PMult : Monoid P_mult_op xH | 5.
Proof.
 split;unfold P_mult_op, Mult_op;intros.
 -  now rewrite Pos.mul_assoc.
 - reflexivity.
 - now rewrite Pos.mul_1_r.
Qed.

Import Int31.
Open Scope int31_scope.

(** ***  Multiplicative monoid on 31-bits integers

Cyclic numeric types are  good candidates for testing exponentiations
with big exponents, since the size of data is bounded.

The type [int31] is defined in Standard Library in Module
[Coq.Numbers.Cyclic.Int31.Int31].
*)

(* begin snippet int31:: no-out *)
#[ global ] Instance int31_mult_op : Mult_op int31 := mul31.

#[ global ] Instance  Int31mult : Monoid int31_mult_op  1.
Proof.
   split;unfold int31_mult_op, mult_op; intros; ring.
Qed.
(* end snippet int31 *)

  (* begin snippet BadFact *)
Module Bad.

  Fixpoint int31_from_nat (n:nat) :=
    match n with
    | O => 1
    | S p => 1 + int31_from_nat p
    end.

  Coercion int31_from_nat : nat >-> int31.

  Fixpoint fact (n:nat) := match n with
                             O => 1
                           | S p => n * fact p
                           end.
  Compute fact 40.

End Bad.
(* end snippet BadFact *)

Close Scope int31_scope.

(** *** Monoid of 2x2 matrices

Let $A$ be some type, provided with a ring structure. We define the multiplication
of $2\times 2$-matrices, the coefficients of which have type $A$.

*)

(* begin snippet M2Defsa *)

Section M2_def.
Variables (A:Type)
           (zero one : A)
           (plus mult  : A -> A -> A).

 Notation "0" := zero.
 Notation "1" := one.
 Notation "x + y" := (plus x y).
 Notation "x * y " := (mult x y).

 Variable rt : semi_ring_theory  zero one plus mult (@eq A).
 Add  Ring Aring : rt.

Structure M2 : Type := {c00 : A;  c01 : A;
                        c10 : A;  c11 : A}.

Definition Id2 : M2 := Build_M2 1 0 0 1.

Definition M2_mult (m m':M2) : M2 :=
 Build_M2 (c00 m * c00 m' + c01 m * c10 m')
          (c00 m * c01 m' + c01 m * c11 m')
          (c10 m * c00 m' + c11 m * c10 m')
          (c10 m * c01 m' + c11 m * c11 m').

(* end snippet M2Defsa *)

Lemma M2_eq_intros : forall a b c d a' b' c' d',
  a=a' -> b=b' -> c=c' -> d=d' ->
   Build_M2 a b c d = Build_M2 a' b' c' d'.
Proof.
 intros; now f_equal.
Qed.

(* begin snippet M2Defsb:: no-out *)

#[global] Instance M2_op : Mult_op M2 := M2_mult.

#[global] Instance M2_Monoid : Monoid   M2_op Id2.
(* ... *)
(* end snippet M2Defsb *)
Proof.
 unfold M2_op, mult_op; split.
 - destruct x;destruct y;destruct z;simpl.
   unfold M2_mult; apply M2_eq_intros; simpl; ring.
 - destruct x;simpl;
   unfold M2_mult; apply M2_eq_intros; simpl; ring.
 - destruct x;simpl;
   unfold M2_mult;apply M2_eq_intros;simpl;ring.
Qed.

End M2_def.

Arguments M2_Monoid {A zero one plus mult} rt.
Arguments Build_M2 {A} _ _ _ _.

(** Matrices over N *)
Definition M2N := M2_Monoid Nth.

(** *** Integers modulo m

The following instance of [EMonoid] describes the set of integers modulo
$m$, where $m$ is some integer greater or equal than $2$.
For simplicity's sake, we represent such values using the type [N],
and consider "equivalence modulo $m$" instead of equality.
*)

(* begin snippet Nmoduloa:: no-out *)
Section Nmodulo.
  Variable m : N.
  Hypothesis m_gt_1 : 1 < m.
  (* end snippet Nmoduloa *)

  Remark m_neq_0 : m <> 0.
    intro H;subst m. discriminate.
  Qed.

  #[local] Hint Resolve m_neq_0 : chains.

  (* begin snippet Nmodulob:: no-out *)
  Definition mult_mod (x y : N) := (x * y) mod m.
  Definition mod_eq (x y: N) := x mod m = y mod m.

  Instance mod_equiv : Equiv N := mod_eq.

  Instance mod_op : Mult_op N := mult_mod.

  Instance mod_Equiv : Equivalence mod_equiv.
  (* end snippet Nmodulob *)
  Proof.
    split.
    - intros x; reflexivity.
    - intros x y H; now symmetry.
    - intros x y z Hxy Hyz; transitivity (y mod m) ; auto.
  Qed.

  (* begin snippet Nmoduloc:: no-out *)
  #[global] Instance mult_mod_proper :
    Proper (mod_equiv ==> mod_equiv ==> mod_equiv) mod_op.
  (* end snippet Nmoduloc *)
  Proof.
    unfold mod_equiv, mod_op, mult_mod, mod_eq.
    intros x y Hxy z t Hzt.
    repeat rewrite N.mod_mod; auto with chains.
    rewrite (N.mul_mod x z);auto with chains.
    rewrite (N.mul_mod y t);auto with chains.
    rewrite Hxy, Hzt; reflexivity.
  Qed.

  (* begin snippet Nmodulod:: no-out *)
  #[local]  Open Scope M_scope.

  Lemma mult_mod_associative :  forall x y z,
      x * (y * z) = x * y * z.
  (* end snippet Nmodulod *)
  Proof.
    intros  x y z.
    unfold mod_op, mult_op, mult_mod.
    rewrite N.mul_mod_idemp_r;auto with chains.
    rewrite N.mul_mod_idemp_l;auto with chains.
    now rewrite  N.mul_assoc.
  Qed.

  (* begin snippet Nmoduloe:: no-out *)
  Lemma one_mod_neutral_l  : forall x, 1 * x == x.
  (* end snippet Nmoduloe *)
  Proof.
    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.
    intro x; rewrite N.mul_1_l, N.mod_mod; auto with chains.
  Qed.
  (* begin snippet Nmodulof:: no-out *)
  Lemma one_mod_neutral_r  : forall x, x * 1 == x.
  (* end snippet Nmodulof *)
  Proof.
    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.
    intro x; rewrite N.mul_1_r, N.mod_mod; auto with chains.
  Qed.

  (* begin snippet Nmodulog:: no-out *)
  #[global] Instance Nmod_Monoid : EMonoid  mod_op 1 mod_equiv.
  (* end snippet Nmodulog *)
  Proof.
    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.
    split.
    - exact mod_Equiv.
    - exact mult_mod_proper.
    - intros; rewrite mult_mod_associative; reflexivity.
    - exact one_mod_neutral_l.
    - exact one_mod_neutral_r.
  Defined.

  (* begin snippet Nmodulog *)
End Nmodulo.

Section S256.

  Let mod256 :=  mod_op 256.

  #[local] Existing Instance mod256 | 1.

  Compute (211 * 67)%M.

  (* end snippet Nmodulog *)

  (* begin snippet Nmoduloh *)

End S256.

Compute (211 * 67)%M.

(* end snippet Nmoduloh *)

Close Scope N_scope.
Close Scope positive_scope.


(** * MoreCoq: More About Coq *)

Require Export Poly.

(** This chapter introduces several more Coq tactics that,
    together, allow us to prove many more theorems about the
    functional programs we are writing. *)

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

  intros eq2.

  rewrite eq2 with (r := m).
  reflexivity.
  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.
    intros H.
    apply H.
Qed.
(** [] *)

(** 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.
  intros l l'.
  symmetry.
  rewrite -> H.
  apply rev_involutive.
Qed.
(** [] *)

(** **** 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 m n o p.
    intros eq1 eq2.
    apply trans_eq with (m:=n).
    apply eq2. apply eq1.
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.
    intros X x y z l j.
    intros eq1. intros eq2.
    inversion eq1.
    inversion eq2.
    symmetry.
    apply H0.
Qed.
(** [] *)

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.
  intros X x y z l j.
  intros eq. inversion eq.
Qed.
(** [] *)

(** 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.
    intros n.
    intros eq.
    inversion eq.
    destruct n. reflexivity.
    inversion H0.
Qed.

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  intros n.
  intros eq.
  destruct n. reflexivity.
  inversion eq.
Qed.
(** [] *)

(* ###################################################### *)
(** * 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 *)
    intros m. simpl. destruct m. reflexivity. intros. inversion H.
    simpl.

    rewrite <- plus_n_Sm.
    intros m.
    intros H.
    destruct m. inversion H.
    inversion H.
    rewrite <- plus_n_Sm in H1.
    inversion H1.
    apply IHn' in H2.
    rewrite -> H2.
    reflexivity.
Qed.

(** [] *)

(* ###################################################### *)
(** * 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'].
  Case "n = O". simpl. intros eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'". intros eq. destruct m as [| m'].
    SCase "m = O". inversion eq.
    SCase "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 _this 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'].
  Case "n = O". simpl. intros m eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "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'].
    SCase "m = O".
      (* The 0 case is trivial *)
      inversion eq.
    SCase "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.
    intros n. induction n.
    simpl. intros m. destruct m. reflexivity. intros H. inversion H.

    simpl. intros m. destruct m. intros H. inversion H.
    intros H. apply IHn in H. apply f_equal. apply H.
Qed.
(** [] *)

(** **** 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'].
  Case "m = O". simpl. intros eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "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'].
  Case "m = O". simpl. intros n eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros n eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "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'].

  Case "l = []".
    intros n eq. rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    intros n eq. simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "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'].

  Case "l = []".
    rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "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.
    intros n.
    intros X.
    intros l.
    generalize dependent n.
    induction l.

    destruct n. reflexivity. intros H. inversion H.

    intros n.
    destruct n. intros H. inversion H.

    simpl. intros H.
    apply IHl.
    inversion H.
    reflexivity.
Qed.

(** [] *)

(** **** 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.
    intros n X v l.
    generalize dependent n.
    induction l.
    intros n. simpl. intros H. rewrite -> H. reflexivity.

    intros n.
    simpl.
    intros H.
    apply f_equal.
    rewrite <- H.
    apply IHl.
    reflexivity.
Qed.
(** [] *)

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

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.
    intros X l1 l2 x n.
    generalize dependent n.
    induction l1.
    intros n. simpl. intros. rewrite H. reflexivity.

    intros n.
    simpl. intros H. rewrite <- H.
    apply f_equal.
    apply IHl1.
    reflexivity.
Qed.

(** [] *)

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

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
    intros X n l.
    generalize dependent n.
    induction l. intros n. intros H. rewrite <- H. reflexivity.

    intros n. simpl.
    replace (length (l ++ x :: l)) with (S(length (l ++ l))).
    intros H.
    destruct n.

        inversion H.

        rewrite <- plus_n_Sm.
        apply f_equal.
        simpl.
        apply f_equal.
        apply IHl.
        inversion H. reflexivity.

    apply app_length_cons with (x:=x).
    reflexivity.
Qed.
(** [] *)

(** **** 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.
    intros H.
    intros Hm.
    intros Hn.
    intros Hmn.

    intros m n.
    generalize dependent m.
    induction n.
    Case "n = 0".
        induction m.
        apply H. apply Hm. apply IHm.

    Case "n > 0".
        induction m.
        apply Hn.
        apply IHn.

        apply Hmn.
        apply IHn.
Qed.
(** [] *)

(* ###################################################### *)
(** * 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).
    Case "beq_nat n 3 = true". reflexivity.
    Case "beq_nat n 3 = false". destruct (beq_nat n 5).
      SCase "beq_nat n 5 = true". reflexivity.
      SCase "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.
  intros X.
  intros x1 x2 k1 k2.
  intros f.
  unfold override.
  destruct (beq_nat k1 k2).
  reflexivity. reflexivity.
Qed.
(** [] *)

(** **** 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.
  intros X Y l l1 l2.
  generalize dependent l2.
  generalize dependent l1.
  induction l.
  intros l1 l2.
  intros H.
  inversion H.
  reflexivity.

  intros l1 l2.
  simpl.
  destruct x.
  destruct (split l).
  intros H.
  destruct l1.
  inversion H.
  destruct l2.
  inversion H.
  simpl.
  inversion H.
  apply f_equal.
  apply IHl.
  rewrite H2.
  rewrite H4.
  reflexivity.
Qed.
(** [] *)

(** 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. *)
    Case "e3 = true". apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    Case "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.
        SCase "e5 = true".
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        SCase "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.
  intros f b.
  destruct (f b) eqn:fb.
  destruct b.
  rewrite -> fb. apply fb.
  destruct (f true) eqn:ft.
  apply ft.
  apply fb.
  destruct b.
  destruct (f false) eqn:ff.
  apply fb.
  apply ff.
  rewrite -> fb. apply fb.
Qed.

(** [] *)

(** **** 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.
  intros X x1 k1 k2 f.
  intros h.
  unfold override.
  destruct (beq_nat k1 k2) eqn:beq.
  apply beq_nat_true in beq.
  rewrite <- beq.
  symmetry.
  apply h.
  reflexivity.
Qed.
(** [] *)

(* ################################################################## *)
(** * 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.
    intros n m.
    generalize dependent m.
    induction n.
    simpl.
    destruct m. reflexivity. reflexivity.

    simpl. destruct m.
    reflexivity.
    simpl.
    apply IHn.
Qed.

(** [] *)

(** **** 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.
  intros m n p.
  intros H. apply beq_nat_true in H.
  intros H1. apply beq_nat_true in H1.
  rewrite -> H. rewrite -> H1.
  symmetry.
  apply beq_nat_refl.
Qed.
(** [] *)

(** **** 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]?

    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 :=
    forall X Y: Type, forall l1: list X, forall l2: list Y,
    length l1 = length l2 -> split (combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
    unfold split_combine_statement.
    intros X Y.
    intros l1.
    induction l1.
    simpl.
    intros l2.
    intros H.
    destruct l2. reflexivity. inversion H.

    intros l2.
    simpl.
    intros H.
    destruct l2.
    inversion H.

    simpl.
    rewrite -> IHl1.
    reflexivity.
    simpl in H.
    inversion H.
    reflexivity.
Qed.
(** [] *)

(** **** 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.
    intros X x1 x2 k1 k2 k3 f.
    intros H.
    unfold override.
    destruct (beq_nat k1 k3) eqn:k13.
    destruct (beq_nat k2 k3) eqn:k23.
    apply beq_nat_true in k13.
    apply beq_nat_true in k23.
    rewrite k13 in H.
    rewrite k23 in H.
    rewrite <- beq_nat_refl in H.
    inversion H.
    reflexivity.
    destruct (beq_nat k2 k3) eqn:k23.
    reflexivity.
    reflexivity.
Qed.
(** [] *)

(** **** 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.
    intros test.
    intros x.
    induction l.
    intros lf.
    intros H.
    inversion H.
    intros lf.
    simpl.
    destruct (test x0) eqn:tx0.
    intros H.
    inversion H.
    rewrite <- H1.
    apply tx0.

    apply IHl.
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 that [existsb'] and [existsb] have the same behavior.
*)
Fixpoint forallb  {X: Type} (f: X -> bool) (l: list X) :=
    match l with
    | nil => true
    | h :: t => (andb (f h) (forallb f t))
    end.

Fixpoint existsb  {X: Type} (f: X -> bool) (l: list X) :=
    match l with
    | nil => false
    | h :: t => (orb (f h) (existsb f t))
    end.

Example foo0 : forallb oddb [1;3;5;7;9] = true.
Proof. reflexivity. Qed.
Example foo1 : forallb negb [false;false] = true.
Proof. reflexivity. Qed.
Example foo2 : forallb evenb [0;2;4;5] = false.
Proof. reflexivity. Qed.
Example foo3 : forallb (beq_nat 5) [] = true.
Proof. reflexivity. Qed.
Example foo4 : existsb (beq_nat 5) [0;2;3;6] = false.
Proof. reflexivity. Qed.
Example foo5 : existsb (andb true) [true;true;false] = true.
Proof. reflexivity. Qed.
Example foo6 : existsb oddb [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.
Example foo7 : existsb evenb [] = false.
Proof. reflexivity. Qed.

Definition existsb' {X: Type} (f: X -> bool) (l: list X) :=
    negb (forallb (fun x => negb (f x)) l).
Example foo8 : existsb' (beq_nat 5) [0;2;3;6] = false.
Proof. reflexivity. Qed.
Example foo9 : existsb' (andb true) [true;true;false] = true.
Proof. reflexivity. Qed.
Example fox0 : existsb' oddb [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.
Example fox1 : existsb' evenb [] = false.
Proof. reflexivity. Qed.

Theorem same_existsb_existsb' :
    forall (X: Type) (f: X -> bool) (l: list X),
        existsb f l = existsb' f l.
Proof.
    intros X. intros f.
    intros l.
    induction l.
    reflexivity.

    simpl.
    destruct (f x) eqn:fx.
    simpl.
    unfold existsb'. simpl. rewrite fx. simpl. reflexivity.

    simpl. unfold existsb'. simpl. rewrite fx. simpl. rewrite -> IHl.
    unfold existsb'. reflexivity.
Qed.
(* FILL IN HERE *)
(** [] *)

(* $Date: 2014-02-04 07:15:43 -0500 (Tue, 04 Feb 2014) $ *)