(* Práctica 4 *)

(* Ejercicio 1 *)
Section Ejercicio1.

(* 1.1 *)
Inductive list (A: Set) :  Set :=
    nil
  | cons : A -> list A -> list A. (* se puede hacer: forall A:Set...? solo si se definio como list: Set -> Set *)

Check nil.
Check cons.

Inductive bintree(A:Set):Set :=
    btree_nil
  | node: bintree A -> A -> bintree A -> bintree A.

Check bintree_ind.

(* 1.2 *)
Inductive Array (A:Set): nat -> Set :=
    array_nil : Array A 0
  | array_cons : forall n:nat, A -> Array A n -> Array A (S n).

Inductive Matrix (A:Set): nat -> nat -> Set :=
    matrix_nil : Matrix A 0 0
  | ins_fila : forall n m:nat, Array A m -> Matrix A n m -> Matrix A (S n) m.

(* 1.3 *)
Inductive leq : nat -> nat -> Prop :=
    leq0 : forall n:nat, leq 0 n
  | leqS : forall n m:nat, leq n m -> leq (S n) (S m).

(* 1.4 *)
Inductive eq_list (A:Set):list A -> list A -> Prop :=
    eq0 : eq_list A (nil A) (nil A)
  | eqS : forall (a b:A) (l1 l2:list A), eq_list A l1 l2 -> a = b -> eq_list A (cons A a l1) (cons A b l2).
(* Alternativamente podría hacer forall (a:A) (l1 l2:list A), eq_list A l1 l2 -> eq_list A (cons A a l1) (cons A a l2),
pero deja "implicita" la igual, hay casos donde NO podría aplicarse, dado que la igualdad no es obvia *)

(* 1.5 *)
Inductive sorted (A:Set):(A->A->Prop) -> list A -> Prop :=
  | sortedBNil : forall R:A->A->Prop, sorted A R (nil A)
  | sortedBUnit : forall (R:A->A->Prop) (a:A) (l:list A), sorted A R (cons A a (nil A))
  | sortedI : forall (R:A->A->Prop) (a b : A) (l:list A),
      sorted A R (cons A b l) -> R a b -> sorted A R (cons A a (cons A b l)).

(* 1.6 *)
Inductive mirror(A:Set):bintree A -> bintree A -> Prop :=
    mirror0 : mirror A (btree_nil A) (btree_nil A)
  | mirrorS : forall (t1 t2 t1' t2':bintree A) (a b : A), a = b -> mirror A t1 t2' -> mirror A t2 t1' -> mirror A (node A t1 a t2) (node A t1' b t2').

(* 1.7 *)
(* isomorfismo entre arboles binarios *)
Inductive isomorfismo(A:Set):bintree A -> bintree A -> Prop :=
    isomorfismo0 : isomorfismo A (btree_nil A) (btree_nil A)
  | isomorfismoS : forall (t1 t2 t1' t2':bintree A) (a b : A), isomorfismo A t1 t1' -> isomorfismo A t2 t2' -> isomorfismo A (node A t1 a t2) (node A t1' b t2').

(* 1.8 *)
(* está bien? *)
Inductive
 Gtree(A:Set):Set :=
     empty_gtree : Gtree A
   | node_gtree : A -> Forest A -> Gtree A
with
 Forest(A:Set):Set :=
    empty_forest : Forest A
  | branch_forest : Gtree A -> Forest A -> Forest A.

End Ejercicio1.

(* Ejercicio 2 *)
Section Ejercicio2.

(* 2.1 *)
Definition Or (a:bool) (b:bool):bool :=
  match a with
  | false => b
  | _ => true
  end.

Definition And (a:bool) (b:bool):bool :=
  match a with
  | true => b
  | _ => false
  end.

Definition Not (a:bool):bool :=
  match a with
  | true => false
  | _ => true
  end.

Definition Xor (a:bool) (b:bool):bool :=
  match b with
  | false => a
  | _ => Not a
  end.

(* 2.2 *)
Definition is_nil (A:Set)(a:list A):bool :=
  match a with
  | nil => true
  | _ => false
  end.
End Ejercicio2.

(* Ejercicio 3 *)
Section Ejercicio3.
(* 3.1 *)
(* El "struc" indica el argumento que será estructuralmente menor
en la llamada recursiva, en general no es necesario. *)
Fixpoint sum (n m:nat) {struct n}: nat :=
  match n with
  | 0 => m
  | S k => S (sum k m)
  end.

(* 3.2 *)
Fixpoint prod (n m:nat) {struct n}: nat :=
  match n with
  | 0 => 0
  | S k => sum m (prod k m)
  end.

(* 3.3 *)
Fixpoint pot (n m:nat) {struct m}: nat :=
  match m with
  | 0 => 1
  | S k => prod n (pot n k)
  end.

(* 3.4 *)
Fixpoint leBool (n m:nat): bool :=
  match n , m with
  | 0 , _ => true
  | S k , 0 => false
  | S k, S j => leBool k j
  end.
End Ejercicio3.

(* Ejercicio 4 *)
Section Ejercicio4.

(* 4.1 *)
Fixpoint length (A:Set) (l:list A):nat :=
  match l with
  | nil => 0
  | cons _ l => 1 + length A l
  end.

(* 4.2 *)
Fixpoint append (A:Set) (l1:list A) (l2:list A):list A :=
  match l1, l2 with
  | nil, ll => ll
  | ll, nil => ll
  | cons a ll, lll => cons A a (append A ll lll)
  end.

(* 4.3 *)
Fixpoint reverse (A:Set) (l:list A):list A :=
  match l with
  | nil => nil A
  | cons a ll => append A (reverse A ll) (cons A a (nil A))
  end.

(* 4.4 *)
Fixpoint filter (A:Set) (f:A -> bool) (l:list A):list A :=
  match l with
  | nil => nil A
  | cons a l' => if f a then cons A a (filter A f l') else filter A f l'
  end.

(* 4.5 *)
Fixpoint map (A B:Set) (f:A -> B) (l:list A):list B :=
  match l with
  | nil => nil B
  | cons a l' => cons B (f a) (map A B f l')
  end.

(* 4.6 *)
Fixpoint exists_ (A: Set) (f:A -> bool) (l:list A):bool :=
  match l with
  | nil => false
  | cons a l' => if f a then true else exists_ A f l'
  end.
End Ejercicio4.

(* Ejercicio 5 *)
Section Ejercicio5.

(* 5.1 *)
Fixpoint inverse (A:Set) (t:bintree A):bintree A :=
  match t with
  | btree_nil => btree_nil A
  | node t1 a t2 => node A (inverse A t2) a (inverse A t1)
  end.

(* 5.2 *)
Fixpoint nodos_internos (A:Set) (t:Gtree A) :nat :=
  match t with
    empty_gtree => 0
  | node_gtree a f => S (nodos_internos' A f)
  end
with nodos_internos' (A:Set) (f:Forest A):nat :=
  match f with
   empty_forest => 0
  | branch_forest t f' => plus (nodos_internos A t) (nodos_internos' A f')
  end.

Fixpoint nodos_externos (A:Set) (t:Gtree A) :nat :=
  match t with
    empty_gtree => 0
  | node_gtree a f => nodos_externos' A f
  end
with nodos_externos' (A:Set) (f:Forest A):nat :=
  match f with
   empty_forest => 1
  | branch_forest t f' => plus (nodos_externos A t) (nodos_externos' A f')
  end.

(* Está bien? *)
Definition hayMas_nodos_internos (A:Set) (t:Gtree A):bool :=
  Not (leBool (nodos_internos A t) (nodos_externos A t)).

End Ejercicio5.

(* Ejercicio 6 *)
Section Ejercicio6.

(* 6.1 *)
Require Import Coq.Arith.EqNat.
Definition listN := list nat.

Print listN.

(* Puedo importar librerias? Sí *)
Fixpoint member (n:nat) (l:listN):bool :=
  match l with
  | nil => false
  | cons a l' => if beq_nat a n then true else member n l'
  end.

(* 6.2 *)
Fixpoint delete (l:listN) (n:nat):listN :=
  match l with
  | nil => nil nat
  | cons a l' => if beq_nat a n then delete l' n else cons nat a (delete l' n)
  end.

(* 6.3 *)
Require Import Coq.Arith.Compare_dec.

Function insert' (n:nat) (l:listN):listN :=
  match l with
  | nil => cons nat n (nil nat)
  | cons a l' => if leb a n then cons nat a (insert' n l') else cons nat n (cons nat a l')
  end.

Function insert_sort (l:listN):listN :=
  match l with
  | nil => nil nat
  | cons a l' => insert' a (insert_sort l')
  end.

(* Generalización *)
Fixpoint memberG (A:Set) (eqA:A->A->bool) (x:A) (l:list A):bool :=
  match l with
  | nil => false
  | cons a l' => if eqA a x then true else memberG A eqA x l'
  end.

Fixpoint deleteG (A:Set) (eqA:A->A->bool) (l:list A) (x:A):list A :=
  match l with
  | nil => nil A
  | cons y l' => if (eqA x y) then deleteG A eqA l' x else cons A y (deleteG A eqA l' x)
  end.

Fixpoint insertG' (A:Set) (leA:A->A->bool) (x:A) (l:list A):list A :=
  match l with
  | nil => nil A
  | cons a l' => if leA a x then insertG' A leA a l' else cons A x (cons A a l')
  end.

Fixpoint insert_sortG (A:Set) (leA:A->A->bool) (l:list A):list A :=
  match l with
  | nil => nil A
  | cons a l' => insertG' A leA a (insert_sortG A leA l')
  end.

End Ejercicio6.

(* Ejercicio 7 *)
Section Ejercicio7.

(* 7.1 *)
Inductive Exp (A:Set):Set :=
    mas: A -> A -> Exp A
  | producto: A -> A -> Exp A
  | menos_unario: A -> Exp A.

(* 7.2 *)
Definition expNat (e:Exp nat):nat :=
  match e with
  | mas x y => plus x y
  | producto x y => prod x y
  | menos_unario x => x
  end.

(* 7.3 *)
Definition expBool (e:Exp bool):bool :=
  match e with
  | mas x y =>
    match x with
    | true => true
    | _ => x
    end
  | producto x y =>
    match x with
    | false => false
    | _ => y
    end
  | menos_unario x =>
    match x with
    | true => false
    | false => true
    end
  end.

End Ejercicio7.

(* Ejercicio 8 *)
Section Ejercicio8.

(* 8.1 *)
(* Uso induction o case? En este caso son lo mismo *)
Lemma conmutatividadAnd : forall a b:bool, And a b = And b a.
Proof.
  intros x y.
  unfold And.
  case x; case y; reflexivity.
Qed.

Lemma conmutatividadOr : forall a b:bool, Or a b = Or b a.
Proof.
  intros x y.
  unfold Or.
  case x; case y; reflexivity.
Qed.

Lemma asociatidadAnd : forall a b c:bool, And (And a b) c = And a (And b c).
Proof.
  intros x y c.
  unfold And.
  case x; reflexivity.
Qed.

Lemma asociatividadOr : forall a b c:bool, Or (Or a b) c = Or a (Or b c).
Proof.
  intros x y c.
  unfold Or.
  case x; reflexivity.
Qed.

(* 8.2 *)
Lemma LAnd : forall a b : bool, And a b = true <-> a = true /\ b = true.
Proof.
  intros x y.
  unfold iff, And.
  split.
    intro H; split.
      destruct x.
        reflexivity.

        assumption.
      destruct x.
        assumption.

        discriminate H.
    intro H; elim H.
    intros H' H''; clear H.
    induction x; assumption.
Qed.

(* 8.3 *)
Lemma LOr1 : forall a b : bool, Or a b = false <-> a = false /\ b = false.
Proof.
  intros x y; unfold iff, Or; split; intro H.
    split; destruct x.
      discriminate H.

      reflexivity.

      discriminate H.

      assumption.
    elim H; intros H' H''; clear H.
    destruct x.
      discriminate H'.

      assumption.
Qed.

(* 8.4 *)
(* Por qué cuando aplico "induction x", tambien modifica las hipotesis que tiene a x?
Por que cuando cambia las expresiones que tienen x en el gol, tambien debería modificar
las expresiones que están en las hipótesis.
 Por qué "case x" NO modifica las hipótesis, pero "destruct x" si lo hace? *)
Lemma LOr2 : forall a b : bool, Or a b = true <-> a = true \/ b = true.
Proof.
  intros x y; unfold iff, Or.
  split; intro H.
    destruct x.
      left; reflexivity.

      right; assumption.
    elim H; intro H'; clear H; destruct x.
      reflexivity.

      discriminate H'.

      reflexivity.

      assumption.
Qed.

(* 8.5 *)
Lemma LXor : forall a b : bool, Xor a b = true <-> a <> b.
Proof.
  intros x y; unfold iff, Xor, Not, not; split.
    intros H H'.
    destruct y, x.
        discriminate H.
        discriminate H'.
        discriminate H'.
        discriminate H.
    intro H.
    destruct y, x.
        elim (H (eq_refl true)).
        reflexivity.
        reflexivity.
        elim (H (eq_refl false)).
Qed.

(* 8.6 *)
Lemma LNot : forall b : bool, Not (Not b) = b.
Proof.
  intro x; unfold Not.
  case x; reflexivity.
Qed.

End Ejercicio8.

(* Ejercicio 9 *)
Section Ejercicio9.

(* 9.1 *)
(* Está bien usar "induction" para probar sobre Fixpoint? Si*)
Lemma SumO : forall n : nat, sum n 0 = n.
Proof.
  intro x.
  induction x.
    simpl.
    reflexivity.

    simpl.
    rewrite -> IHx.
    reflexivity.
Qed.

(* 9.2 *)
Lemma SumS : forall n m : nat, sum n (S m) = sum (S n) m.
Proof.
  intros x y.
  induction x.
    simpl; reflexivity.

    simpl.
    rewrite -> IHx.
    reflexivity.
Qed.

(* 9.3 *)
(* Hay una táctica que sirva como éste lema? Si, apply f_equal. O sino, usar "rewrite". *)
(* No lo uso, se puede BORRAR *)
Lemma aux:forall n m:nat, n=m -> S n = S m.
Proof.
  intros x y H.
  induction x; induction y.
  reflexivity.
  rewrite <- H.
  reflexivity.
  rewrite -> H.
  reflexivity.
  rewrite <- H.
  reflexivity.
Qed.

(* Está bien hacer induction sobre una variable de un para todo? Sí*)
(* Por qué si primero hago intros, y luego doble induccion, el último caso tiene
una hipotesis inductiva con un implica? *)
Lemma SumConm : forall n m : nat, sum n m = sum m n.
Proof.
  induction n.
    induction m.
      simpl; reflexivity.
      simpl; rewrite <- IHm; reflexivity.
    induction m.
      simpl.
      rewrite (IHn 0).
      simpl; reflexivity.

      rename m into m'.
      simpl.
      rewrite <- IHm.
      rewrite (IHn (S m')).
      simpl.
      rewrite (IHn m').
      reflexivity.
Qed.

(* 9.4 *)
Lemma SumAsoc : forall n m p : nat, sum n (sum m p) = sum (sum n m) p.
Proof.
  intros x y z.
  induction x.
    simpl.
    reflexivity.

    simpl.
    rewrite -> IHx.
    reflexivity.
Qed.

(* 9.5 *)
Lemma ProdConm : forall n m : nat, prod n m = prod m n.
Proof.
  induction n; induction m.
    reflexivity.

    simpl.
    rewrite <- IHm; simpl; reflexivity.

    simpl.
    rewrite (IHn 0).
    simpl; reflexivity.  (* Cuando hago doble inducción, en el último caso tengo "dos m", hace falta que renombre? No. *)

    simpl; rewrite <- IHm.
    rewrite (IHn (S m)).
    simpl.
    rewrite (IHn m).
    rewrite -> (SumAsoc m n (prod m n)).
    rewrite -> (SumAsoc n m (prod m n)).
    rewrite (SumConm n m).
    reflexivity.
Qed.

(* 9.7 *)
(* Puedo hacer éste ejercicio antes del 9.6? Sí *)
Lemma ProdDistr : forall n m p : nat, prod n (sum m p) = sum (prod n m) (prod n p).
Proof.
  induction n.
    intros; simpl; reflexivity.

    intros m' p'; simpl.
    rewrite <- (SumAsoc m' (prod n m') (sum p' (prod n p'))).
    rewrite (SumAsoc (prod n m') p' (prod n p')).
    rewrite (SumConm (prod n m') p').
    rewrite <- (SumAsoc p' (prod n m') (prod n p')).
    rewrite (SumAsoc m' p' (sum (prod n m') (prod n p'))).
    rewrite (IHn m' p').
    reflexivity.
Qed.

(* 9.6 *)
Lemma ProdAsoc : forall n m p : nat, prod n (prod m p) = prod (prod n m) p.
Proof.
  induction n.
    intros; simpl; reflexivity.

    simpl.
    intros m' p'.
    rewrite (IHn m' p').
    rewrite (ProdConm m' p').
    rewrite (ProdConm (prod n m') p').
    rewrite (ProdConm (sum m' (prod n m')) p').
    symmetry; exact(ProdDistr p' m' (prod n m')).
Qed.

End Ejercicio9.

(* Ejercicio 10 *)
Section Ejercicio10.

(* 10.1 *)
Lemma L1 : forall (A : Set) (l : list A), append A l (nil A) = l.
Proof.
  intros; destruct l; simpl; reflexivity.
Qed.

(* 10.2 *)
(* Está bien usar "discriminate"? Sí *)
Lemma L2 : forall (A : Set) (l : list A) (a : A), ~(cons A a l) = nil A.
Proof.
  intros; unfold not; intro H.
  discriminate H.
Qed.

(* 10.3 *)
Lemma L3 : forall (A : Set) (l m : list A) (a : A), cons A a (append A l m) = append A (cons A a l) m.
Proof.
  destruct l; intros; destruct m; simpl; reflexivity.
Qed.

(* 10.4 *)
Lemma L4 : forall (A : Set) (l m : list A),
length A (append A l m) = sum (length A l) (length A m).
Proof.
  induction l; intro m'.
    simpl; reflexivity.

    destruct m'.
      simpl.
      rewrite (SumConm (length A l) 0).
      simpl; reflexivity.

      simpl.
      rewrite (IHl (cons A a0 m')).
      simpl; reflexivity.
Qed.

(* 10.5 *)
Lemma L5:forall (A : Set) (l : list A), length A (reverse A l) = length A l.
Proof.
  induction l.
    simpl; reflexivity.

    simpl.
    rewrite <- IHl.
    rewrite (L4 A (reverse A l) (cons A a (nil A))).
    simpl.
    rewrite (SumConm (length A (reverse A l)) 1).
    simpl; reflexivity.
Qed.

(* 11.3 *)
(* Puedo usar éste lema antes? Sí *)
Lemma L9 : forall (A : Set) (l m n : list A),
append A l (append A m n) = append A (append A l m) n.
Proof.
  induction l.
    intros; simpl; reflexivity.

    intros m' n'.
    rewrite <- (L3 A l m' a).
    rewrite <- (L3 A (append A l m') n' a).
    rewrite <- (IHl m' n').
    rewrite -> (L3 A l (append A m' n') a).
    reflexivity.
Qed.

(* 10.6 *)
Lemma L6 : forall (A : Set) (l m : list A),
reverse A (append A l m) = append A (reverse A m) (reverse A l).
Proof.
  induction l.
    intro m'.
    simpl.
    rewrite (L1 A (reverse A m')); reflexivity.

    intro m'; rewrite <- (L3 A l m').
    simpl.
    rewrite (L9 A (reverse A m') (reverse A l) (cons A a (nil A))).
    rewrite (IHl m'); reflexivity.
Qed.

End Ejercicio10.

(* Ejercicio 11  *)
Section Ejercicio11.

(* 11.1 *)
Lemma L7 : forall (A B : Set) (l m : list A) (f : A -> B), map A B f (append A l m) = append B (map A B f l) (map A B f m).
Proof.
  induction l.
    simpl; reflexivity.

    intros m' f'.
    destruct m'.
      simpl; reflexivity.

      simpl.
      assert(map A B f' (append A l (cons A a0 m')) = append B (map A B f' l) (map A B f' (cons A a0 m'))); [exact(IHl (cons A a0 m') f') | idtac].
      rewrite H.
      simpl; reflexivity.
Qed.

(* 11.2 *)
Lemma L8 : forall (A : Set) (l m : list A) (P : A -> bool),
filter A P (append A l m) = append A (filter A P l) (filter A P m).
Proof.
  induction l.
    intros; simpl; reflexivity.

    intros m' P'.
    rewrite <- (L3 A l m' a).
    simpl.
    destruct (P' a).
      rewrite <- (L3 A (filter A P' l) (filter A P' m')).
      rewrite (IHl m' P'); reflexivity.

      rewrite (IHl m' P'); reflexivity.
Qed.

(* 11.3, está echo en la sección Ejercicio10 *)

(* 11.4 *)
Lemma L10 : forall (A : Set) (l : list A), reverse A (reverse A l) = l.
Proof.
  induction l.
    simpl; reflexivity.

    simpl.
    rewrite (L6 A (reverse A l) (cons A a (nil A))).
    rewrite IHl.
    simpl reverse.
    rewrite <- (L3 A (nil A) l a).
    simpl; reflexivity.
Qed.

End Ejercicio11.

(* Ejercicio 12 *)
Section Ejercicio12.

Fixpoint filterMap (A B : Set) (P : B -> bool) (f : A -> B) (l : list A) {struct l} : list B :=
  match l with
  | nil => nil B
  | cons a l1 =>
    match P (f a) with
    | true => cons B (f a) (filterMap A B P f l1)
    | false => filterMap A B P f l1
    end
  end.

Lemma FusionFilterMap : forall (A B : Set) (P : B -> bool) (f : A -> B) (l : list A),
  filter B P (map A B f l) = filterMap A B P f l.
Proof.
  induction l.
    simpl; reflexivity.

    simpl.
    destruct (P (f a)); rewrite IHl; reflexivity.
Qed.

End Ejercicio12.

(* Ejercicio 13 *)
Section Ejercicio13.

(* Puedo interpretar a éste lema como: inverse cumple su especificación? Si *)
Lemma arbol_espejo : forall (A:Set) (b:bintree A), mirror A (inverse A b) b.
Proof.
  induction b.
    simpl.
    exact (mirror0 A).

    simpl.
    exact(mirrorS A (inverse A b2) (inverse A b1) b1 b2 a a (eq_refl a) IHb2 IHb1).
Qed.

End Ejercicio13.

(* Ejercicio 14 *)
Section Ejercicio14.

(* 14.1 *)
Definition arbol_id (A:Set) (b:bintree A):bintree A := b.

Lemma arbol_id_isomorfo : forall (A:Set) (b:bintree A), isomorfismo A (arbol_id A b) b.
Proof.
  induction b.
    unfold arbol_id.
    exact (isomorfismo0 A).

    unfold arbol_id.
    exact (isomorfismoS A b1 b2 b1 b2 a a IHb1 IHb2).
Qed.

(* 14.2 *)
Lemma isomorfismo_reflexividad : forall (A:Set) (b:bintree A), isomorfismo A b b.
Proof.
  induction b.
    exact (isomorfismo0 A).

    exact(isomorfismoS A b1 b2 b1 b2 a a IHb1 IHb2).
Qed.

Lemma ismorfismo_simetria : forall (A:Set) (b b':bintree A), isomorfismo A b b' -> isomorfismo A b' b.
Proof.
  intros.
  induction H.
  (* Si tuviese (node ..) en lugar de b', está bien aplicar induction H, y que (node ..) se pise?
     Si no lo necesito esta bien. Para preservar el (node ..), hago una nueva hipotesis: b'' = node .., y
     hago induccion sobre " isomorfismo A b b'' ", dejando el isomorfismo lo mas generico posible.*)
    exact (isomorfismo0 A).

    exact (isomorfismoS A t1' t2' t1 t2 b a IHisomorfismo1 IHisomorfismo2).
Qed.

End Ejercicio14.

(* Ejercicio 15 *)
Section Ejercicio15.

Inductive Tree (A:Set):Set :=
    leaf : A -> Tree A
  | tnode : Tree A -> Tree A -> Tree A.

(* 15.1 *)
Fixpoint mapTree (A B:Set) (t:Tree A) (f:A->B) {struct t}:Tree B :=
  match t with
  | leaf x => leaf B (f x)
  | tnode t1 t2 => tnode B (mapTree A B t1 f) (mapTree A B t2 f)
  end.

(* 15.2 *)
Fixpoint num_hojas (A:Set) (t:Tree A) {struct t}:nat :=
  match t with
  | leaf x => 1
  | tnode t1 t2 => sum (num_hojas A t1) (num_hojas A t2)
  end.

(* 15.3 *)
Lemma ej15_3 : forall (A B:Set) (f:A->B) (t:Tree A), num_hojas A t = num_hojas B (mapTree A B t f).
Proof.
  induction t.
    simpl; reflexivity.

    simpl.
    rewrite <- IHt1, IHt2; reflexivity.
Qed.

(* 15.4 *)
Fixpoint hojas (A:Set) (t:Tree A):list A :=
  match t with
  | leaf x => cons A x (nil A)
  | tnode t1 t2 => append A (hojas A t1) (hojas A t2)
  end.

Lemma ej15_4 : forall (A:Set) (t:Tree A), num_hojas A t = length A (hojas A t).
Proof.
  induction t.
    simpl; reflexivity.

    simpl.
    rewrite (L4 A (hojas A t1) (hojas A t2)).
    rewrite <- IHt1, IHt2; reflexivity.
Qed.

End Ejercicio15.

Section Ejercicio16.

(* 16.1 *)
(* posfijo l1 l2 <-> l1 es un posfijo de l2 *)
Inductive posfijo (A:Set):list A -> list A -> Prop :=
    posfijoB : forall (l :list A), posfijo A l l
  | posfijoC : forall (l1 l2:list A) (a:A), posfijo A l1 l2 -> posfijo A l1 (cons A a l2).

(* 16.2 *)
Lemma ej16_2a : forall (A:Set) (l1 l2 l3:list A), l2 = append A l3 l1 -> posfijo A l1 l2.
Proof.
  induction l2.
    intros; simpl.
    destruct l1.
      exact (posfijoB A (nil A)).
      destruct l3.
        simpl in H; discriminate H.
        rewrite <- (L3 A l3 (cons A a l1) a0) in H; discriminate H.

   intros l3' H.
   destruct l3'.
     simpl in H; rewrite H; exact (posfijoB A l1).
     rewrite <- (L3 A l3' l1 a0) in H.
     injection H; intros; clear H.
     exact (posfijoC A l1 l2 a ((IHl2 l3') H0)).
Qed.

(* En ésta forma se hace induccion sobre l3, pero antes de hacer induccion se reescribe l2 y se borra la igualdad *)
Lemma ej16_2a' : forall (A:Set) (l1 l2 l3:list A), l2 = append A l3 l1 -> posfijo A l1 l2.
Proof.
  intros.
  rewrite H; clear H.
  induction l3.
    simpl; exact (posfijoB A l1).

    rewrite <- (L3 A l3 l1 a).
    apply (posfijoC A l1 (append A l3 l1)).
    assumption.
Qed.

Lemma ej16_2b : forall (A:Set) (l1 l2:list A), posfijo A l1 l2 -> exists (l3:list A), l2 = append A l3 l1.
Proof.
  intros.
  induction H.
    exists (nil A).
    simpl; reflexivity.

    elim IHposfijo; intros; clear IHposfijo.
    exists (cons A a x).
    rewrite <- (L3 A x l1).
    (* otra forma seria hacer: rewrite H0 *)
    apply f_equal. (* puedo usar f_equal? Si*)
    assumption.
Qed.

(* 16.3 *)
Fixpoint ultimo (A:Set) (l:list A):list A :=
  match l with
  | nil => nil A
  | cons x nil => cons A x (nil A)
  | cons x l'' => ultimo A l''  (* está bien? Si *)
  end.

(* 16.4 *)
Lemma ej16_4aux : forall (A:Set) (l:list A) (a a':A), ultimo A (cons A a (cons A a' l)) = ultimo A (cons A a' l).
Proof.
  intros; simpl; reflexivity.
Qed.

Lemma ej16_4 : forall (A:Set) (l:list A), posfijo A (ultimo A l) l.
Proof.
  induction l.
    simpl.
    exact (posfijoB A (nil A)).

    destruct l.
      simpl.
      exact (posfijoB A (cons A a (nil A))).
      rewrite (ej16_4aux A l a a0).
      exact ((posfijoC A (ultimo A (cons A a0 l)) (cons A a0 l) a) IHl).
Qed.

End Ejercicio16.

(* Ejercicio 17 *)
Section Ejercicio17.

(* 17.1 *)
(* Es un arbol completo, pues las hojas siempre tienen un elemento *)
Inductive ABin (A B:Set):Set :=
  | ABLeaf : B -> ABin A B
  | ABCons : forall (_:A) (ab1 ab2:ABin A B), ABin A B.

(* 17.2 *)
Fixpoint ABhojas (A B:Set) (ab:ABin A B) {struct ab}:nat :=
  match ab with
  | ABLeaf _ => 1
  | ABCons _ ab1 ab2 => sum (ABhojas A B ab1) (ABhojas A B ab2)
  end.

(* 17.3 *)
Fixpoint ABnodos (A B:Set) (ab:ABin A B) {struct ab}:nat :=
  match ab with
  | ABLeaf _ => 0
  | ABCons _ ab1 ab2 => S (sum (ABnodos A B ab1) (ABnodos A B ab2))
  end.

(* 17.4 *)
Lemma ej17_4 : forall (A B:Set) (ab:ABin A B), ABhojas A B ab = S (ABnodos A B ab).
Proof.
  induction ab.
    simpl; reflexivity.

    simpl.
    rewrite IHab1, IHab2; simpl.
    rewrite -> (SumConm (ABnodos A B ab1) (S (ABnodos A B ab2))); simpl.
    rewrite -> (SumConm (ABnodos A B ab2) (ABnodos A B ab1)); reflexivity.
Qed.

End Ejercicio17.

(* Ejercicio 18 *)
Section Ej_18.

Variable A : Set.

Inductive Tree_ : Set :=
  | nullT : Tree_
  | consT : A -> Tree_ -> Tree_ -> Tree_.

(* 18.1 *)
(* Por que si uso un \/, el principio de inducción sale mal?
Es conveniente NO hacer definiciones inductivas que tengan \/. *)
Inductive isSubTree : Tree_ -> Tree_ -> Prop :=
  | sb_iguales : forall (t:Tree_), isSubTree t t
  | sb_izq : forall (t t1 t2:Tree_ ) (a:A), isSubTree t t1 -> isSubTree t (consT a t1 t2)
  | sb_der : forall (t t1 t2:Tree_ ) (a:A), isSubTree t t2 -> isSubTree t (consT a t1 t2).

(* 18.2 *)
Lemma isSubTree_ref : forall (t:Tree_), isSubTree t t.
Proof.
  exact (sb_iguales).
Qed.

(* 18.3 *)
Lemma isSubTree_tran : forall (t1 t2 t3:Tree_), isSubTree t1 t2 /\ isSubTree t2 t3 -> isSubTree t1 t3.
Proof.
  intros.
  elim H; intros; clear H.
  Print isSubTree_ind.
  induction H1.
    assumption.
    apply (sb_izq t1 t0 t2 a); exact (IHisSubTree H0).
    apply (sb_der t1 t0 t2 a); exact (IHisSubTree H0).
Qed.

End Ej_18.

(* Ejercicio 19 *)
Section Ejercicio19.

(* 19.1 *)
Inductive ACom (A:Set): nat -> Set :=
  | AComB : A -> ACom A 0
  | AComI : forall (n :nat) (_:A) (ac1 ac2:ACom A n), ACom A (S n).

(* 19.2 *)
Fixpoint h (A:Set) (n:nat) (ac:ACom A n) {struct ac}:nat :=
  match ac with
  | AComB _ => 1
  | AComI n _ _ _ => sum (pot 2 n) (pot 2 n)  (* está bien el match? si *)
  end.

(* 19.3 *)
(* Parameter pot: nat -> nat -> nat. *)
Axiom potO : forall n : nat, pot (S n) 0 = 1.
Axiom potS : forall m: nat, pot 2 (S m) = sum (pot 2 m) (pot 2 m).

Lemma ej19_3 : forall (A:Set) (n:nat) (ac:ACom A n), h A n ac = pot 2 n.
Proof.
  intros.
  induction ac.
    simpl h; rewrite (potO 1); reflexivity.
    Check ACom_ind.
    simpl h; rewrite (potS n).
    reflexivity.
Qed.

End Ejercicio19.

(* Ejercicio 20 *)
Section Ejercicio20.

(* 20.1 *)
Inductive AB (A:Set):nat->Set :=
    ABNil : AB A 0
  | ABC : forall (n m:nat) (_:A) (t1:AB A n) (t2:AB A m), AB A (S (max n m)).

(* 20.2 *)
(* Por qué tengo que usar gt_dec, en el if then else? *)
Require Import Coq.Arith.Compare_dec.

Fixpoint camino (A:Set) (n:nat) (ab:AB A n):list A :=
  match ab with
  | ABNil => nil A
  | ABC n m x t1 t2 => if gt_dec m n then cons A x (camino A m t2) else cons A x (camino A n t1)
  end.

(* 20.3 *)
Require Import Coq.Arith.Lt.

Lemma ej20_3 : forall (A:Set) (n:nat) (ab:AB A n), length A (camino A n ab) = n.
Proof.
  induction ab.
    simpl; reflexivity.

    simpl.
      destruct (gt_dec m n).
        simpl.
        rewrite IHab2.
        rewrite (max_r n m (lt_le_weak n m g)).
        reflexivity.

        simpl.
        rewrite IHab1.
        rewrite (max_l n m (not_gt m n n0)).
        reflexivity.
Qed.

End Ejercicio20.


(** * Prop: Propositions and Evidence *)

Require Export Logic.

(* ####################################################### *)
(** ** From Boolean Functions to Propositions *)

(** In chapter [Basics] we defined a _function_ [evenb] that tests a
    number for evenness, yielding [true] if so.  We can use this
    function to define the _proposition_ that some number [n] is
    even: *)

Definition even (n:nat) : Prop :=
  evenb n = true.

(** That is, we can define "[n] is even" to mean "the function [evenb]
    returns [true] when applied to [n]."

    Note that here we have given a name
    to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. This isn't a fundamentally
    new kind of proposition;  it is still just an equality. *)

(** Another alternative is to define the concept of evenness
    directly.  Instead of going via the [evenb] function ("a number is
    even if a certain computation yields [true]"), we can say what the
    concept of evenness means by giving two different ways of
    presenting _evidence_ that a number is even. *)

(** ** Inductively Defined Propositions *)

Inductive ev : nat -> Prop :=
  | ev_0 : ev O
  | ev_SS : forall n:nat, ev n -> ev (S (S n)).

(** This definition says that there are two ways to give
    evidence that a number [m] is even.  First, [0] is even, and
    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some
    [n] and we can give evidence [e] that [n] is even, then [m] is
    also even, and [ev_SS n e] is the evidence. *)

(** **** Exercise: 1 star (double_even) *)

Theorem double_even : forall n,
  ev (double n).
Proof.
  intros.
  induction n.
  Case "n=0". simpl. apply ev_0.
  Case "n=Sn". simpl. apply ev_SS. apply IHn.
Qed.
(** [] *)

(** *** Discussion: Computational vs. Inductive Definitions *)

(** We have seen that the proposition "[n] is even" can be
    phrased in two different ways -- indirectly, via a boolean testing
    function [evenb], or directly, by inductively describing what
    constitutes evidence for evenness.  These two ways of defining
    evenness are about equally easy to state and work with.  Which we
    choose is basically a question of taste.

    However, for many other properties of interest, the direct
    inductive definition is preferable, since writing a testing
    function may be awkward or even impossible.

    One such property is [beautiful].  This is a perfectly sensible
    definition of a set of numbers, but we cannot translate its
    definition directly into a Coq Fixpoint (or into a recursive
    function in any other common programming language).  We might be
    able to find a clever way of testing this property using a
    [Fixpoint] (indeed, it is not too hard to find one in this case),
    but in general this could require arbitrarily deep thinking.  In
    fact, if the property we are interested in is uncomputable, then
    we cannot define it as a [Fixpoint] no matter how hard we try,
    because Coq requires that all [Fixpoint]s correspond to
    terminating computations.

    On the other hand, writing an inductive definition of what it
    means to give evidence for the property [beautiful] is
    straightforward. *)

(** **** Exercise: 1 star (ev__even) *)
(** Here is a proof that the inductive definition of evenness implies
    the computational one. *)

Theorem ev__even : forall n,
  ev n -> even n.
Proof.
  intros n E. induction E as [| n' E'].
  Case "E = ev_0".
    unfold even. reflexivity.
  Case "E = ev_SS n' E'".
    unfold even. apply IHE'.
Qed.

(** Could this proof also be carried out by induction on [n] instead
    of [E]?  If not, why not? *)
(** Unable to prove the case (S n') by induction -- no rule for this case *)
(** [] *)

(** The induction principle for inductively defined propositions does
    not follow quite the same form as that of inductively defined
    sets.  For now, you can take the intuitive view that induction on
    evidence [ev n] is similar to induction on [n], but restricts our
    attention to only those numbers for which evidence [ev n] could be
    generated.  We'll look at the induction principle of [ev] in more
    depth below, to explain what's really going on. *)

(** **** Exercise: 1 star (l_fails) *)
(** The following proof attempt will not succeed.
     Theorem l : forall n,
       ev n.
     Proof.
       intros n. induction n.
         Case "O". simpl. apply ev_0.
         Case "S".
           ...
   Intuitively, we expect the proof to fail because not every
   number is even. However, what exactly causes the proof to fail?

There's no rule of ev to match the case ev (S n), attempts to apply won't unify.
*)
(** [] *)

(** **** Exercise: 2 stars (ev_sum) *)
(** Here's another exercise requiring induction. *)

Theorem ev_sum : forall n m,
   ev n -> ev m -> ev (n+m).
Proof.
  intros n m E F. induction E.
  Case "E = ev_0". simpl. apply F.
  Case "E = ev_SS". simpl. apply ev_SS. apply IHE.
Qed.
(** [] *)

(* ##################################################### *)
(** * Inductively Defined Propositions *)

(**  As a running example, let's
    define a simple property of natural numbers -- we'll call it
    "[beautiful]." *)

(** Informally, a number is [beautiful] if it is [0], [3], [5], or the
    sum of two [beautiful] numbers.

    More pedantically, we can define [beautiful] numbers by giving four
    rules:

       - Rule [b_0]: The number [0] is [beautiful].
       - Rule [b_3]: The number [3] is [beautiful].
       - Rule [b_5]: The number [5] is [beautiful].
       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is
         their sum. *)
(** ** Inference Rules *)
(** We will see many definitions like this one during the rest
    of the course, and for purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**
                              -----------                               (b_0)
                              beautiful 0

                              ------------                              (b_3)
                              beautiful 3

                              ------------                              (b_5)
                              beautiful 5

                       beautiful n     beautiful m
                       ---------------------------                      (b_sum)
                              beautiful (n+m)
*)

(** *** *)
(** Each of the textual rules above is reformatted here as an
    inference rule; the intended reading is that, if the _premises_
    above the line all hold, then the _conclusion_ below the line
    follows.  For example, the rule [b_sum] says that, if [n] and [m]
    are both [beautiful] numbers, then it follows that [n+m] is
    [beautiful] too.  If a rule has no premises above the line, then
    its conclusion holds unconditionally.

    These rules _define_ the property [beautiful].  That is, if we
    want to convince someone that some particular number is [beautiful],
    our argument must be based on these rules.  For a simple example,
    suppose we claim that the number [5] is [beautiful].  To support
    this claim, we just need to point out that rule [b_5] says so.
    Or, if we want to claim that [8] is [beautiful], we can support our
    claim by first observing that [3] and [5] are both [beautiful] (by
    rules [b_3] and [b_5]) and then pointing out that their sum, [8],
    is therefore [beautiful] by rule [b_sum].  This argument can be
    expressed graphically with the following _proof tree_: *)
(**
         ----------- (b_3)   ----------- (b_5)
         beautiful 3         beautiful 5
         ------------------------------- (b_sum)
                   beautiful 8
*)
(** *** *)
(**
    Of course, there are other ways of using these rules to argue that
    [8] is [beautiful], for instance:
         ----------- (b_5)   ----------- (b_3)
         beautiful 5         beautiful 3
         ------------------------------- (b_sum)
                   beautiful 8
*)

(** **** Exercise: 1 star (varieties_of_beauty) *)
(** How many different ways are there to show that [8] is [beautiful]? *)

(** Many more than the 2 presented, consider that 0+8 = 8 -- we could have an infinite proof tree. *)
(** [] *)

(** *** *)
(** In Coq, we can express the definition of [beautiful] as
    follows: *)

Inductive beautiful : nat -> Prop :=
  b_0   : beautiful 0
| b_3   : beautiful 3
| b_5   : beautiful 5
| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).

(** The first line declares that [beautiful] is a proposition -- or,
    more formally, a family of propositions "indexed by" natural
    numbers.  (That is, for each number [n], the claim that "[n] is
    [beautiful]" is a proposition.)  Such a family of propositions is
    often called a _property_ of numbers.  Each of the remaining lines
    embodies one of the rules for [beautiful] numbers.
*)
(** *** *)
(**
    The rules introduced this way have the same status as proven
    theorems; that is, they are true axiomatically.
    So we can use Coq's [apply] tactic with the rule names to prove
    that particular numbers are [beautiful].  *)

Theorem three_is_beautiful: beautiful 3.
Proof.
   (* This simply follows from the rule [b_3]. *)
   apply b_3.
Qed.

Theorem eight_is_beautiful: beautiful 8.
Proof.
   (* First we use the rule [b_sum], telling Coq how to
      instantiate [n] and [m]. *)
   apply b_sum with (n:=3) (m:=5).
   (* To solve the subgoals generated by [b_sum], we must provide
      evidence of [beautiful 3] and [beautiful 5]. Fortunately we
      have rules for both. *)
   apply b_3.
   apply b_5.
Qed.

(** *** *)
(** As you would expect, we can also prove theorems that have
hypotheses about [beautiful]. *)

Theorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).
Proof.
  intros n B.
  apply b_sum with (n:=8) (m:=n).
  apply eight_is_beautiful.
  apply B.
Qed.

(** **** Exercise: 2 stars (b_times2) *)
Theorem b_times2: forall n, beautiful n -> beautiful (2*n).
Proof.
    intros n H. simpl. apply b_sum. apply H. apply b_sum. apply H. apply b_0.
Qed.
(** [] *)

(** **** Exercise: 3 stars (b_timesm) *)
Theorem b_timesm: forall n m, beautiful n -> beautiful (m*n).
Proof.
   intros n m B. induction m as [|m'].
   Case "m = 0". simpl. apply b_0.
   Case "m = S m'". simpl. apply b_sum. apply B. apply IHm'.
Qed.
(** [] *)

(* ####################################################### *)
(** ** Induction Over Evidence *)

(** Besides _constructing_ evidence that numbers are beautiful, we can
    also _reason about_ such evidence. *)

(** The fact that we introduced [beautiful] with an [Inductive]
    declaration tells Coq not only that the constructors [b_0], [b_3],
    [b_5] and [b_sum] are ways to build evidence, but also that these
    four constructors are the _only_ ways to build evidence that
    numbers are beautiful. *)

(** In other words, if someone gives us evidence [E] for the assertion
    [beautiful n], then we know that [E] must have one of four shapes:

      - [E] is [b_0] (and [n] is [O]),
      - [E] is [b_3] (and [n] is [3]),
      - [E] is [b_5] (and [n] is [5]), or
      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is
        evidence that [n1] is beautiful and [E2] is evidence that [n2]
        is beautiful). *)

(** *** *)
(** This permits us to _analyze_ any hypothesis of the form [beautiful
    n] to see how it was constructed, using the tactics we already
    know.  In particular, we can use the [induction] tactic that we
    have already seen for reasoning about inductively defined _data_
    to reason about inductively defined _evidence_.

    To illustrate this, let's define another property of numbers: *)

Inductive gorgeous : nat -> Prop :=
  g_0 : gorgeous 0
| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)
| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).

(** **** Exercise: 1 star (gorgeous_tree) *)
(** Write out the definition of [gorgeous] numbers using inference rule
    notation.

   ---------- (g_0)
   gorgeous 0

   gorgeous n
   ---------------- (g_plus3)
   gorgeous (3 + n)

   gorgeous n
   ---------------- (g_plus5)
   goregous (5 + n)
[]
*)

(** **** Exercise: 1 star (gorgeous_plus13) *)
Theorem gorgeous_plus13: forall n,
  gorgeous n -> gorgeous (13+n).
Proof.
  intros n H. apply g_plus5. apply g_plus5. apply g_plus3. apply H.
Qed.
(** [] *)

(** *** *)
(** It seems intuitively obvious that, although [gorgeous] and
    [beautiful] are presented using slightly different rules, they are
    actually the same property in the sense that they are true of the
    same numbers.  Indeed, we can prove this. *)

Theorem gorgeous__beautiful : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros n H.
   induction H as [|n'|n'].
   Case "g_0".
       apply b_0.
   Case "g_plus3".
       apply b_sum. apply b_3.
       apply IHgorgeous.
   Case "g_plus5".
       apply b_sum. apply b_5. apply IHgorgeous.
Qed.

(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)

(** Let's see what happens if we try to prove this by induction on [n]
   instead of induction on the evidence [H]. *)

Theorem gorgeous__beautiful_FAILED : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros. induction n as [| n'].
   Case "n = 0". apply b_0.
   Case "n = S n'". (* We are stuck! *)
Abort.

(** The problem here is that doing induction on [n] doesn't yield a
    useful induction hypothesis. Knowing how the property we are
    interested in behaves on the predecessor of [n] doesn't help us
    prove that it holds for [n]. Instead, we would like to be able to
    have induction hypotheses that mention other numbers, such as [n -
    3] and [n - 5]. This is given precisely by the shape of the
    constructors for [gorgeous]. *)

(** **** Exercise: 2 stars (gorgeous_sum) *)
Theorem gorgeous_sum : forall n m,
  gorgeous n -> gorgeous m -> gorgeous (n + m).
Proof.
  intros. induction H as [|n'|n'].
  Case "g_0". simpl. apply H0.
  Case "g_3". apply g_plus3. apply IHgorgeous.
  Case "g_5". apply g_plus5. apply IHgorgeous.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)
Theorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.
Proof.
  intros. induction H.
  Case "b_0". apply g_0.
  Case "b_3". apply g_plus3. apply g_0.
  Case "b_5". apply g_plus5. apply g_0.
  Case "b_sum". apply gorgeous_sum. apply IHbeautiful1. apply IHbeautiful2.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (g_times2) *)
(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].
    You might find the following helper lemma useful. *)

Lemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.
Proof.
  intros. rewrite plus_comm. rewrite <- plus_assoc. assert (y+x=x+y). apply plus_comm. rewrite H. apply plus_assoc.
Qed.

Theorem g_times2: forall n, gorgeous n -> gorgeous (2*n).
Proof.
   intros n H. simpl.
   induction H.
   Case "g_0". simpl. apply g_0.
   Case "g_plus3". apply g_plus3. fold plus.
                   rewrite helper_g_times2.
                   apply g_plus3. fold plus.
                   rewrite <- plus_assoc.
                   apply IHgorgeous.
   Case "g_plus5". apply g_plus5. fold plus.
                   rewrite helper_g_times2.
                   apply g_plus5. fold plus.
                   rewrite <- plus_assoc.
                   apply IHgorgeous.
Qed.
(** [] *)

(* ####################################################### *)
(** ** [Inversion] on Evidence *)

(** Another situation where we want to analyze evidence for evenness
    is when proving that, if [n] is even, then [pred (pred n)] is
    too.  In this case, we don't need to do an inductive proof.  The
    right tactic turns out to be [inversion].  *)

Theorem ev_minus2: forall n,
  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  inversion E as [| n' E'].
  Case "E = ev_0". simpl. apply ev_0.
  Case "E = ev_SS n' E'". simpl. apply E'.  Qed.

(** **** Exercise: 1 star, optional (ev_minus2_n) *)
(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)

(** Destruct on n would be stupid, and fail, but
The proof is identical if we destruct on E...
  destruct E as [| n' E'].
  Case "E = ev_0". simpl. apply ev_0.
  Case "E = ev_SS". simpl. apply E'. Qed. *)
(** [] *)

(** *** *)
(** Another example, in which [inversion] helps narrow down to
the relevant cases. *)

Theorem SSev__even : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  apply E'. Qed.

(** ** [inversion] revisited *)

(** These uses of [inversion] may seem a bit mysterious at first.
    Until now, we've only used [inversion] on equality
    propositions, to utilize injectivity of constructors or to
    discriminate between different constructors.  But we see here
    that [inversion] can also be applied to analyzing evidence
    for inductively defined propositions.

    (You might also expect that [destruct] would be a more suitable
    tactic to use here. Indeed, it is possible to use [destruct], but
    it often throws away useful information, and the [eqn:] qualifier
    doesn't help much in this case.)

    Here's how [inversion] works in general.  Suppose the name
    [I] refers to an assumption [P] in the current context, where
    [P] has been defined by an [Inductive] declaration.  Then,
    for each of the constructors of [P], [inversion I] generates
    a subgoal in which [I] has been replaced by the exact,
    specific conditions under which this constructor could have
    been used to prove [P].  Some of these subgoals will be
    self-contradictory; [inversion] throws these away.  The ones
    that are left represent the cases that must be proved to
    establish the original goal.

    In this particular case, the [inversion] analyzed the construction
    [ev (S (S n))], determined that this could only have been
    constructed using [ev_SS], and generated a new subgoal with the
    arguments of that constructor as new hypotheses.  (It also
    produced an auxiliary equality, which happens to be useless here.)
    We'll begin exploring this more general behavior of inversion in
    what follows. *)

(** **** Exercise: 1 star (inversion_practice) *)
Theorem SSSSev__even : forall n,
  ev (S (S (S (S n)))) -> ev n.
Proof.
  intros n H. inversion H. inversion H1. apply H3. Qed.

(** The [inversion] tactic can also be used to derive goals by showing
    the absurdity of a hypothesis. *)

Theorem even5_nonsense :
  ev 5 -> 2 + 2 = 9.
Proof.
  intros H. inversion H. inversion H1. inversion H3. Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)
(** Finding the appropriate thing to do induction on is a
    bit tricky here: *)

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
  intros n m E F. induction F.
  Case "F = ev_0". simpl in E. apply E.
  Case "F = ev_SS". inversion E. apply IHF. apply H0.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus) *)
(** Here's an exercise that just requires applying existing lemmas.  No
    induction or even case analysis is needed, but some of the rewriting
    may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
  intros n m p E.
  apply ev_ev__ev.
  rewrite plus_swap. rewrite <- plus_assoc. rewrite plus_assoc.
  apply ev_sum. rewrite plus_comm. apply E.
  rewrite <- double_plus. apply double_even.
Qed.
(** [] *)

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

(** **** Exercise: 4 stars (palindromes) *)
(** A palindrome is a sequence that reads the same backwards as
    forwards.

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor
    c : forall l, l = rev l -> pal l
      may seem obvious, but will not work very well.)

    - Prove that
       forall l, pal (l ++ rev l).
    - Prove that
       forall l, pal l -> l = rev l.
*)

Inductive pal {X:Type} : list X -> Prop :=
  pal_nil  : pal [ ]
| pal_sing : forall x, pal [x]
| pal_rec  : forall l x, pal l -> pal (x :: l ++ [x]).

Theorem pal_app_rev : forall (X:Type) (l : list X),
  pal (l ++ rev l).
Proof.
  intros. induction l as [|x l'].
  Case "l=[]". simpl. apply pal_nil.
  Case "l=x::l'". simpl.
    rewrite <- snoc_with_append.
    rewrite snoc_append.
    apply pal_rec.
    apply IHl'.
Qed.

Theorem pal_rev : forall X (l:list X),
  pal l -> l = rev l.
Proof.
  intros X l H.
  induction H.
  Case "pal []". reflexivity.
  Case "pal [x]". reflexivity.
  Case "pal_rec".
    rewrite <- cons_app_assoc.
    rewrite <- rev_app. simpl.
    rewrite <- IHpal.
    rewrite snoc_append.
    reflexivity.
Qed.
(** [] *)

(** **** Exercise: 5 stars, optional (palindrome_converse) *)
(** Using your definition of [pal] from the previous exercise, prove
    that
     forall l, l = rev l -> pal l.
*)

Theorem app_assoc : forall X (l1 l2 l3:list X),
  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
Proof.
  intros. induction l1.
  Case "[]". reflexivity.
  Case "l1=x::l1'". simpl. rewrite IHl1. reflexivity.
Qed.

Theorem app_singletons : forall X (x y : X),
  [x;y] = [x] ++ [y].
Proof. reflexivity. Qed.

Theorem nil_app_after : forall X (l : list X),
  l ++ [] = l.
Proof. induction l. reflexivity. simpl. rewrite IHl. reflexivity. Qed.

Lemma cons_app_head : forall X (l : list X) x,
  x :: l = [x] ++ l.
Proof. reflexivity. Qed.

Theorem length_app_dist : forall X (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof. intros. induction l1. reflexivity. simpl. rewrite IHl1. reflexivity. Qed.

Theorem plus_injective : forall (n m o : nat),
  n + m = n + o -> m = o.
Proof. induction n. simpl. intros.  apply H. simpl. intros. inversion H. apply IHn. apply H1. Qed.

Lemma list_append_length_contra : forall X x (l1 l2 : list X),
  l1 = (x::l2) ++ l1 -> 1 = 0.
Proof.
  intros. apply f_equal with (f:=length) in H.
  simpl in H. rewrite length_app_dist in H.
  rewrite <- plus_1_l in H. rewrite plus_comm in H. rewrite <- plus_assoc in H. rewrite plus_comm in H.
  symmetry in H. rewrite <- plus_0_r in H. rewrite <- plus_assoc in H.
  apply plus_injective with (n:=length l1) (m:=1 + length l2) (o:=0) in H.
  inversion H.
Qed.

Theorem app_injective : forall X (l1 l2 l : list X),
  l1 ++ l = l2 ++ l -> l1 = l2.
Proof.
  induction l1. induction l2.
  Case "l1=[]".
    SCase "l2=[]". reflexivity.
    SCase "l2=::". intros. simpl in H. apply list_append_length_contra in H. inversion H.
  Case "l1=::". induction l2.
    SCase "l2=[]". simpl. intros. symmetry in H. apply list_append_length_contra in H. inversion H.
    SCase "l2=::".
      intros. inversion H. apply IHl1 in H2. rewrite H2. reflexivity.
Qed.

Lemma length_0 : forall X (l : list X),
  length l = 0 -> l = [].
Proof. intros. destruct l. reflexivity. inversion H. Qed.

Theorem palindrome_converse : forall X (l:list X),
  l = rev l -> pal l.
Proof.
(*
  intros X l E.
  induction l as [|x l'].
  Case "l=[]". apply pal_nil.
  Case "l=x::l'". destruct l' as [|y l''].
  SCase "l=[x]". apply pal_sing.
  SCase "l=x::y::l''".
    simpl in H. rewrite snoc_append in H. rewrite snoc_append in H.
    rewrite app_assoc in H. simpl in H.
    destruct (rev l'') as [|z l3] eqn:L2.
    SSCase "[]".
      simpl in H. inversion H. assert ([y] = [] ++ [y]) as A. reflexivity. rewrite A. apply pal_rec. apply pal_nil.
    SSCase "rev l''=x0::l".
      inversion H. rewrite H2.
      apply f_equal with (f:=rev) in L2. rewrite rev_involutive in L2. rewrite L2 in H2. simpl in H2. rewrite snoc_append in H2.
      rewrite app_singletons in H2.
      rewrite <- app_assoc in H2. rewrite <- cons_app_assoc in H2.
      apply app_injective with (l2:=l3 ++ [y]) (l:=[z]) in H2.
      destruct l3 as [|z' l4] eqn:L3.
      SSSCase  "l3=[]".
        simpl. rewrite app_singletons. apply pal_rec. apply pal_sing.
      SSSCase "l3=::".
        simpl. inversion H2. rewrite snoc_append in H4. apply app_injective in H4.
        rewrite app_singletons. rewrite <- app_assoc. rewrite <- cons_app_assoc. apply pal_rec.
        apply pal_rec.
        (* consistent names please *)
        symmetry in H3. rewrite H3 in H2. rewrite H3 in H. rewrite H3 in L2.
        (* tidy up the ind hyp *)
        rewrite L2 in IHl'. simpl in IHl'. rewrite ?snoc_append in IHl'. rewrite ?app_assoc in IHl'.
        rewrite <- ?app_singletons in IHl'.
*)
(** Bad induction hypothesis, requires y :: rev l4 ++ [y;z] = z :: y :: l4 ++ [y]
    Note z is flipped from one end to the other.
    This is because the inductive step fails to require that the list has the form x :: l' ++ [x]
    If I could use pal as the inductive step, then things would be great...
*)
(* GIVE UP *) Admitted.

(** [] *)

(** **** Exercise: 4 stars, advanced (subsequence) *)
(** A list is a _subsequence_ of another list if all of the elements
    in the first list occur in the same order in the second list,
    possibly with some extra elements in between. For example,
    [1,2,3]
    is a subsequence of each of the lists
    [1,2,3]
    [1,1,1,2,2,3]
    [1,2,7,3]
    [5,6,1,9,9,2,7,3,8]
    but it is _not_ a subsequence of any of the lists
    [1,2]
    [1,3]
    [5,6,2,1,7,3,8]

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)
*)
Inductive subseq : list nat -> list nat -> Prop :=
  subseq_nil   : forall l, subseq [] l
| subseq_match : forall n l l', subseq l l' -> subseq (n :: l) (n :: l')
| subseq_else  : forall m n l l', subseq (n::l) l' -> subseq (n :: l) (m :: l').

Example subseq_test1 : subseq [1;2;3] [1;2;3].
Proof. apply subseq_match. apply subseq_match. apply subseq_match. apply subseq_nil. Qed.

Example subseq_test2 : subseq [1;2;3] [1;1;2;2;3].
Proof. apply subseq_else. apply subseq_match. apply subseq_match. apply subseq_else. apply subseq_match. apply subseq_nil. Qed.

(** - Prove that subsequence is reflexive, that is, any list is a
      subsequence of itself.
*)

Theorem subseq_refl : forall (l : list nat), subseq l l.
Proof.
  induction l.
  apply subseq_nil.
  apply subseq_match. apply IHl.
Qed.

(** - Prove that for any lists [l1], [l2], and [l3], if [l1] is a
      subsequence of [l2], then [l1] is also a subsequence of [l2 ++
      l3].
*)

Theorem subseq_extends : forall (l1 l2 l3 : list nat),
  subseq l1 l2 -> subseq l1 (l2 ++ l3).
Proof.
  intros l1 l2 l3 H. induction H.
  apply subseq_nil.
  simpl. apply subseq_match. apply IHsubseq.
  simpl. apply subseq_else. apply IHsubseq.
Qed.

(** - (Optional, harder) Prove that subsequence is transitive -- that
      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence
      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your
      induction carefully!
*)

Theorem subseq_trans : forall l1 l2 l3,
  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.
Proof.
  intros l1 l2 l3. generalize dependent l1.  generalize dependent l2.
  induction l3.
  Case "l3=[]". intros. inversion H0; inversion H; subst.
    apply subseq_nil.
    inversion H5. (* contra *)
    inversion H5. (* contra *)
  Case "l3=x::l3".  intros. inversion H0.
    SCase "l2=[]". subst. inversion H. apply H0.
    subst. inversion H.
      apply subseq_nil.
      apply subseq_match. apply IHl3 with (l2:=l). apply H4. apply H3.
      apply subseq_else. apply IHl3 with (l2:=l). apply H4. apply H3.
    subst. inversion H.
      apply subseq_nil.
      subst. apply subseq_else. apply IHl3 with (l2:=(n::l)). apply H. apply H3.
      subst. apply subseq_else. apply IHl3 with (l2:=(n::l)). apply H. apply H3.
Qed.
(* Phew! *)

(** [] *)

(** **** Exercise: 2 stars, optional (R_provability) *)
(** Suppose we give Coq the following definition:
*)
Inductive R : nat -> list nat -> Prop :=
| c1 : R 0 []
| c2 : forall n l, R n l -> R (S n) (n :: l)
| c3 : forall n l, R (S n) l -> R n l.
(*
    Which of the following propositions are provable?

    - [R 2 [1,0]]
      yes
    - [R 1 [1,2,1,0]]
      yes
    - [R 6 [3,2,1,0]]
      no
*)
Theorem r_1 : R 2 [1;0]. repeat constructor. Qed.
Theorem r_2 : R 1 [1;2;1;0]. repeat constructor. Qed.
Theorem r_3 : R 6 [3;2;1;0]. Abort.
(** [] *)

(* ####################################################### *)
(** * Relations *)

(** A proposition parameterized by a number (such as [ev] or
    [beautiful]) can be thought of as a _property_ -- i.e., it defines
    a subset of [nat], namely those numbers for which the proposition
    is provable.  In the same way, a two-argument proposition can be
    thought of as a _relation_ -- i.e., it defines a set of pairs for
    which the proposition is provable. *)

Module LeModule.

(** One useful example is the "less than or equal to"
    relation on numbers. *)

(** The following definition should be fairly intuitive.  It
    says that there are two ways to give evidence that one number is
    less than or equal to another: either observe that they are the
    same number, or give evidence that the first is less than or equal
    to the predecessor of the second. *)

Inductive le : nat -> nat -> Prop :=
  | le_n : forall n, le n n
  | le_S : forall n m, (le n m) -> (le n (S m)).

Notation "m <= n" := (le m n).

(** Proofs of facts about [<=] using the constructors [le_n] and
    [le_S] follow the same patterns as proofs about properties, like
    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]
    goals (e.g., to show that [3<=3] or [3<=6]), and we can use
    tactics like [inversion] to extract information from [<=]
    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)

(** *** *)
(** Here are some sanity checks on the definition.  (Notice that,
    although these are the same kind of simple "unit tests" as we gave
    for the testing functions we wrote in the first few lectures, we
    must construct their proofs explicitly -- [simpl] and
    [reflexivity] don't do the job, because the proofs aren't just a
    matter of simplifying computations.) *)

Theorem test_le1 :
  3 <= 3.
Proof.
  (* WORKED IN CLASS *)
  apply le_n.  Qed.

Theorem test_le2 :
  3 <= 6.
Proof.
  (* WORKED IN CLASS *)
  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.

Theorem test_le3 :
  (2 <= 1) -> 2 + 2 = 5.
Proof.
  (* WORKED IN CLASS *)
  intros H. inversion H. inversion H2.  Qed.

(** *** *)
(** The "strictly less than" relation [n < m] can now be defined
    in terms of [le]. *)

End LeModule.

Definition lt (n m:nat) := le (S n) m.

Notation "m < n" := (lt m n).

(** Here are a few more simple relations on numbers: *)

Inductive square_of : nat -> nat -> Prop :=
  sq : forall n:nat, square_of n (n * n).

Inductive next_nat (n:nat) : nat -> Prop :=
  | nn : next_nat n (S n).

Inductive next_even (n:nat) : nat -> Prop :=
  | ne_1 : ev (S n) -> next_even n (S n)
  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).

(** **** Exercise: 2 stars (total_relation) *)
(** Define an inductive binary relation [total_relation] that holds
    between every pair of natural numbers. *)

Inductive total_relation : nat -> nat -> Prop :=
  | tr : forall n m:nat, total_relation n m.
(** [] *)

(** **** Exercise: 2 stars (empty_relation) *)
(** Define an inductive binary relation [empty_relation] (on numbers)
    that never holds. *)

Inductive empty_relation : nat -> Prop := .
(** [] *)

(** **** Exercise: 2 stars, optional (le_exercises) *)
(** Here are a number of facts about the [<=] and [<] relations that
    we are going to need later in the course.  The proofs make good
    practice exercises. *)

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
  intros. induction H0.
  Case "m=n". apply H.
  Case "Sm0=n". apply le_S. apply IHle.
Qed.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
  intros. induction n. apply le_n. apply le_S. apply IHn. Qed.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
  intros. induction H.
  Case "n=m". apply le_n.
  Case "Sm0=m". apply le_S. apply IHle.
Qed.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  induction m,n; intros.
  apply O_le_n.
  inversion H. inversion H1.
  apply O_le_n.
  inversion H. apply le_n.
  subst. apply le_S. apply IHm. apply H1.
Qed.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
  induction b.
  rewrite plus_0_r. apply le_n.
  rewrite plus_S_assoc. apply le_S. apply IHb.
Qed.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
  unfold lt. intros. split; induction H.
  rewrite <- plus_comm. rewrite <- plus_S_assoc. rewrite plus_comm. apply le_plus_l.
  apply le_S. apply IHle.
  rewrite <- plus_S_assoc. rewrite plus_comm. apply le_plus_l.
  apply le_S. apply IHle.
Qed.

Theorem lt_S : forall n m,
  n < m ->
  n < S m.
Proof.
  unfold lt. intros. apply le_S. apply H.
Qed.

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
  induction n; intros.
  Case "n=0". apply O_le_n.
  Case "n=Sn". destruct m.
    SCase "m=0". inversion H. (* absurd *)
    SCase "m=Sm". apply n_le_m__Sn_le_Sm. apply IHn. simpl in H. apply H.
Qed.

Lemma ble_nat_Sl : forall n m,
  ble_nat m n = true -> ble_nat m (S n) = true.
Proof.
  induction n; intros.
  Case "n=0". destruct m.
    SCase "m=0". reflexivity.
    SCase "m=Sm". simpl in H. inversion H. (* contra *)
  Case "n=Sn". destruct m.
    SCase "m=0". reflexivity.
    SCase "m=Sm". simpl. apply IHn. simpl in H. apply H.
 Qed.

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
  intros n m. generalize dependent n. induction m; intros.
  Case "m=0". destruct n.
    SCase "n=0". reflexivity.
    SCase "n=Sn". inversion H. (* absurd *)
  Case "m=Sm". inversion H.
    SCase "n=Sm". symmetry. apply ble_nat_refl.
    SCase "n<=m". apply IHm in H1. apply ble_nat_Sl. apply H1.
Qed.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
  intros.
  apply le_ble_nat. apply ble_nat_true in H. apply ble_nat_true in H0.
  apply le_trans with (m:=n) (n:=m). apply H. apply H0.
Qed.

(** **** Exercise: 2 stars, optional (ble_nat_false) *)
Theorem ble_nat_false : forall n m,
  ble_nat n m = false -> ~(n <= m).
Proof.
  unfold not. intros. apply le_ble_nat in H0. rewrite H0 in H. inversion H.
Qed.
(** [] *)

(** **** Exercise: 3 stars (R_provability) *)
Module R.
(** We can define three-place relations, four-place relations,
    etc., in just the same way as binary relations.  For example,
    consider the following three-place relation on numbers: *)

Inductive R : nat -> nat -> nat -> Prop :=
   | c1 : R 0 0 0
   | c2 : forall m n o, R m n o -> R (S m) n (S o)
   | c3 : forall m n o, R m n o -> R m (S n) (S o)
   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o
   | c5 : forall m n o, R m n o -> R n m o.

(** - Which of the following propositions are provable?
      - [R 1 1 2]
        Yes, c1 c3 c2.
      - [R 2 2 6]
        No?

    - If we dropped constructor [c5] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

      No, c2 and c3 permit adjustment of one of the first two params
      respectively, c4 operates same on both. All acions can be performed by all.

    - If we dropped constructor [c4] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

      I don't think so. c2.c3 and c3.c2 equiv to opposite of c4.
[]
*)

(** **** Exercise: 3 stars, optional (R_fact) *)
(** Relation [R] actually encodes a familiar function.  State and prove two
    theorems that formally connects the relation and the function.
    That is, if [R m n o] is true, what can we say about [m],
    [n], and [o], and vice versa?

    Addition
*)

Theorem R_plus : forall m n o,
  R m n o -> m + n = o.
Proof.
  intros. induction H.
  Case "c1". reflexivity.
  Case "c2". simpl. rewrite IHR. reflexivity.
  Case "c3". rewrite plus_S_assoc. rewrite IHR. reflexivity.
  Case "c4". rewrite plus_S_assoc in IHR. simpl in IHR. inversion IHR. reflexivity.
  Case "c5". rewrite plus_comm. apply IHR.
Qed.

Theorem plus_R : forall o m n,
  m + n = o -> R m n o.
Proof.
  induction o; intros; destruct m; simpl in H.
  Case "o=0".
    SCase "m=0". rewrite H. apply c1.
    SCase "m=Sm". inversion H. (* contra *)
  Case "o=So".
    SCase "m=0". rewrite H. apply c3. apply IHo. reflexivity.
    SCase "m=Sm". apply c2. apply IHo. simpl in H. inversion H. reflexivity.
Qed.
(** [] *)

End R.

(* ##################################################### *)
(** * Programming with Propositions Revisited *)

(** As we have seen, a _proposition_ is a statement expressing a factual claim,
    like "two plus two equals four."  In Coq, propositions are written
    as expressions of type [Prop]. . *)

Check (2 + 2 = 4).
(* ===> 2 + 2 = 4 : Prop *)

Check (ble_nat 3 2 = false).
(* ===> ble_nat 3 2 = false : Prop *)

Check (beautiful 8).
(* ===> beautiful 8 : Prop *)

(** *** *)
(** Both provable and unprovable claims are perfectly good
    propositions.  Simply _being_ a proposition is one thing; being
    _provable_ is something else! *)

Check (2 + 2 = 5).
(* ===> 2 + 2 = 5 : Prop *)

Check (beautiful 4).
(* ===> beautiful 4 : Prop *)

(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions
    of type [Prop]. *)

(** *** *)
(** We've mainly seen one place that propositions can appear in Coq: in
    [Theorem] (and [Lemma] and [Example]) declarations. *)

Theorem plus_2_2_is_4 :
  2 + 2 = 4.
Proof. reflexivity.  Qed.

(** But they can be used in many other ways.  For example, we have also seen that
    we can give a name to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. *)

Definition plus_fact : Prop  :=  2 + 2 = 4.
Check plus_fact.
(* ===> plus_fact : Prop *)

(** We can later use this name in any situation where a proposition is
    expected -- for example, as the claim in a [Theorem] declaration. *)

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

(** *** *)
(** We've seen several ways of constructing propositions.

       - We can define a new proposition primitively using [Inductive].

       - Given two expressions [e1] and [e2] of the same type, we can
         form the proposition [e1 = e2], which states that their
         values are equal.

       - We can combine propositions using implication and
         quantification. *)
(** *** *)
(** We have also seen _parameterized propositions_, such as [even] and
    [beautiful]. *)

Check (even 4).
(* ===> even 4 : Prop *)
Check (even 3).
(* ===> even 3 : Prop *)
Check even.
(* ===> even : nat -> Prop *)

(** *** *)
(** The type of [even], i.e., [nat->Prop], can be pronounced in
    three equivalent ways: (1) "[even] is a _function_ from numbers to
    propositions," (2) "[even] is a _family_ of propositions, indexed
    by a number [n]," or (3) "[even] is a _property_ of numbers."  *)

(** Propositions -- including parameterized propositions -- are
    first-class citizens in Coq.  For example, we can define functions
    from numbers to propositions... *)

Definition between (n m o: nat) : Prop :=
  andb (ble_nat n o) (ble_nat o m) = true.

(** ... and then partially apply them: *)

Definition teen : nat->Prop := between 13 19.

(** We can even pass propositions -- including parameterized
    propositions -- as arguments to functions: *)

Definition true_for_zero (P:nat->Prop) : Prop :=
  P 0.

(** *** *)
(** Here are two more examples of passing parameterized propositions
    as arguments to a function.

    The first function, [true_for_all_numbers], takes a proposition
    [P] as argument and builds the proposition that [P] is true for
    all natural numbers. *)

Definition true_for_all_numbers (P:nat->Prop) : Prop :=
  forall n, P n.

(** The second, [preserved_by_S], takes [P] and builds the proposition
    that, if [P] is true for some natural number [n'], then it is also
    true by the successor of [n'] -- i.e. that [P] is _preserved by
    successor_: *)

Definition preserved_by_S (P:nat->Prop) : Prop :=
  forall n', P n' -> P (S n').

(** *** *)
(** Finally, we can put these ingredients together to define
a proposition stating that induction is valid for natural numbers: *)

Definition natural_number_induction_valid : Prop :=
  forall (P:nat->Prop),
    true_for_zero P ->
    preserved_by_S P ->
    true_for_all_numbers P.

(** **** Exercise: 3 stars (combine_odd_even) *)
(** Complete the definition of the [combine_odd_even] function
    below. It takes as arguments two properties of numbers [Podd] and
    [Peven]. As its result, it should return a new property [P] such
    that [P n] is equivalent to [Podd n] when [n] is odd, and
    equivalent to [Peven n] otherwise. *)

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  fun n => if (oddb n) then Podd n else Peven n.

(** To test your definition, see whether you can prove the following
    facts: *)

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  intros. unfold combine_odd_even. destruct (oddb n).
  Case "true". apply H. reflexivity.
  Case "false". apply H0. reflexivity.
Qed.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  unfold combine_odd_even. intros. rewrite H0 in H. apply H.
Qed.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  unfold combine_odd_even. intros. rewrite H0 in H. apply H.
Qed.

(** [] *)

(* ##################################################### *)
(** One more quick digression, for adventurous souls: if we can define
    parameterized propositions using [Definition], then can we also
    define them using [Fixpoint]?  Of course we can!  However, this
    kind of "recursive parameterization" doesn't correspond to
    anything very familiar from everyday mathematics.  The following
    exercise gives a slightly contrived example. *)

(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)
(** Define a recursive function
    [true_upto_n__true_everywhere] that makes
    [true_upto_n_example] work. *)

Fixpoint true_upto_n__true_everywhere (n : nat) (f : nat->Prop) : Prop :=
  match n with
  | O    => forall m : nat, f m
  | S n' => f n -> true_upto_n__true_everywhere n' f
  end.

Example true_upto_n_example :
    (true_upto_n__true_everywhere 3 (fun n => even n))
  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).
Proof. reflexivity.  Qed.
(** [] *)

(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)


Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(* Rework your last proof using the full syntax of ssreflect. *)

(* Solve the following equations. Search is your best friend. *)
Lemma ex5_arit1 n m : n + (m * n + 0) = n * m.+1.
Proof.
  by rewrite addn0 -add1n mulnDr muln1 mulnC.
Qed.

Lemma ex5_arit2 n m : n %/ 2 + m = (2 * m + n) %/ 2.
Proof.
  by rewrite mulnC divnMDl // addnC.
Qed.

Lemma ex5_arit3 n m p : 0 < p ->  p %| n -> n %/ p + m = (p * m + n) %/ p.
Proof.
  move=> Hp Hpn.
  rewrite divnDr //=.
  rewrite mulKn //=.
  by rewrite addnC.
Qed.

(* Prove this by induction. *)
Lemma size_iota_sumn l : sumn (map (addn 1) l) = size l + sumn l.
Proof.
  elim l => //= x xs IH.
  by rewrite !addSn [x + _]addnC addnA IH add0n addnC.
Qed.

(* Prove the following Theorem by induction. *)
Theorem ex5_gauss n : (n * n.-1) %/ 2 = sumn (iota 0 n).
Proof.
  elim n => //= n' IH.
    rewrite (iota_addl 1 0) add0n size_iota_sumn -IH{IH} size_iota.
    rewrite -{3}[n'](@mulnK _ 2) // -divnDl ?dvdn_mull //.
    by rewrite [_ * _.-1]mulnC !mulnS muln0 addn0 -addnA; case: n'.
Qed.

(* Advanced part *)

(* Read the documentation of the wlog tactic *)

(* Prove the following lemma without using dvdn_pexp2r following one the two informal
   proofs. The first one is more detailed, the second one is more challenging.
   If you want to try the second one, just skip ahead without reading the
   following informal proof. *)
Lemma ex5_dvdn : forall m n k, k > 0 -> (m ^ k %| n ^ k) -> (m %| n).
Proof.

(* Without loss of generality n is positive, since any number divides 0 *)

(* Given d := gcdn m n, n can be written as n' * d and m as m' * d *)

(* We also have d > 0 *)

(* We can now refine our assumption to m' ^ k %| n' ^ k
   since for b positive, a * b %| c * b -> a %| c     *)

(* We can also prove that (m' ^ k) and (n' ^ k) are coprime since
   the gcdn of m' and n' is 1, or equivalently (gcdn m' n') * d = d *)

(* From this coprimality and the refiner hypothesis follows that
   m' ^ k = 1 = gcdn (m' ^ k) (n' ^ k). Hint: gcdn a (a %% b) = gcdn a b *)

(* Since m'^k = 1 also m' = 1. Thus m = d and d %| n *)

Qed.

Lemma ex5_dvdn_advanced : forall m n k, k > 0 -> (m ^ k %| n ^ k) -> (m %| n).
Proof.
(* Without loss of generality we can assume (m ^ k) and (n ^ k) are coprime
   (i.e. dividing n and m by their gcdn).
   Since (m ^ k) also divides (n ^ k), (m ^ k) is 1, thus m is 1,
   thus it trivially divides n. *)

Qed.


Require Import Arith.

Search (_ =? _).

Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  intros n.
  destruct n.
  - (* zero *) intros m. intros eq1. destruct m.
    + (* zero *) reflexivity.
    + (* S m *) apply beq_nat_true. exact eq1.
  - (* S n *) intros m. intros eq1. destruct m.
    + (* zero *) inversion eq1.
    + (* S m *) apply beq_nat_true. exact eq1.
Qed.


Inductive List :=
|nil : List
|cons : nat -> List -> List.

Print List_ind.

Fixpoint append (l1 l2 : List) : List :=
  match l1 with
  | nil => l2
  | cons n l => cons n (append l l2)
end.

Definition list1 := (cons 3 (cons 2 nil)).
Definition list2 := (cons 4 (cons 7 nil)).

Compute (append list1 list2).
Compute (append list2 list1).

Lemma append_nil_left:
  forall l, append nil l = l.
Proof.
  trivial.
Qed.

Lemma append_nil_right:
  forall l, append l nil = l.
Proof.
  induction l.
  - trivial.
  - simpl.
    rewrite IHl.
    reflexivity.
Qed.

Lemma append_assoc :
  forall l1 l2 l3,
    append l1 (append l2 l3) = append (append l1 l2) l3.
Proof.
  induction l1.
  - trivial.
  - intros l2 l3.
    simpl.
    rewrite IHl1.
    reflexivity.
Qed.

Fixpoint reverse(l : List) : List :=
  match l with
  |nil => nil
  |(cons n l1) => append (reverse l1) (cons n nil)
end.

Lemma helper:
  forall l l2,
     reverse ( append l l2) =
     append (reverse l2) (reverse l).
Proof.
  induction l.
  - intros. simpl.
    rewrite append_nil_right.
    reflexivity.
  - intros.
    simpl.
    rewrite IHl.
    rewrite append_assoc.
    reflexivity.
Qed.

Lemma involutive_reverse:
  forall l, reverse (reverse l) = l.
Proof.
  induction l.
  - trivial.
  - simpl.
    rewrite helper.
    rewrite IHl.
    simpl.
    reflexivity.
Qed.


(* This code is copyrighted by its authors; it is distributed under  *)
(* the terms of the LGPL license (see LICENSE and description files) *)

(* Contribution to the Coq Library   V6.3 (July 1999)                    *)
(****************************************************************************)
(*                                                                          *)
(*                                                                          *)
(*                   Solange Coupet-Grimal & Line Jakubiec                  *)
(*                                                                          *)
(*                                                                          *)
(*              Laboratoire d'Informatique de Marseille                     *)
(*               CMI-Technopole de Chateau-Gombert                          *)
(*                   39, Rue F. Joliot Curie                                *)
(*                   13453 MARSEILLE Cedex 13                               *)
(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lim.univ-mrs.fr          *)
(*                                                                          *)
(*                                                                          *)
(*                                Coq V5.10                                 *)
(*                              May 30th 1996                               *)
(*                                                                          *)
(****************************************************************************)
(*                               Lib_Minus.v                                *)
(****************************************************************************)

Require Export Lib_Pred.

Lemma minus_SS_n : forall n : nat, S (S n) - n = 2.
intros n.
elim minus_Sn_m.
apply eq_S.
elim minus_Sn_m.
apply eq_S.
elim minus_n_n; auto with arith.
auto with arith.
auto with arith.
Qed.
Hint Resolve minus_SS_n.

Lemma minus_S : forall n m : nat, n - m = S n - S m.
intros; simpl in |- *; auto with arith.
Qed.
Hint Resolve minus_S.

Lemma pred_minus_minus : forall n m : nat, pred (n - m) = n - S m.
simple induction n; simple induction m; auto with arith.
intros; elim minus_S.
elim minus_S; auto with arith.
Qed.
Hint Resolve pred_minus_minus.

Lemma minus_pred_S : forall n m p : nat, n = m - p -> pred n = m - S p.
intros n m p H.
rewrite H; auto with arith.
Qed.
Hint Resolve minus_pred_S.

Lemma pred_minus : forall n : nat, pred n = n - 1.
simple induction n; auto with arith.
Qed.
Hint Resolve pred_minus.

Lemma O_minus_S : forall n m : nat, 0 = n - m -> 0 = n - S m.
intros n m H.
elim pred_minus_minus.
elim H; auto with arith.
Qed.
Hint Resolve O_minus_S.

Lemma minus_minus_plus : forall n m p : nat, n - m - p = n - (m + p).
simple induction n; simple induction m; auto with arith.
intros; elim minus_S.
change (n0 - n1 - p = S n0 - S (n1 + p)) in |- *.
elim minus_S; apply H.
Qed.
Hint Resolve minus_minus_plus.

Lemma lt_O_minus : forall n m : nat, n < m -> 0 < m - n.
simple induction n; simple induction m; simpl in |- *; auto with arith.
intro.
apply lt_trans with (S n0); auto with arith.
Qed.
Hint Resolve lt_O_minus.

Lemma le_minus : forall n m : nat, n - m <= n.
simple induction n; auto with arith.
  intros.
  case m; simpl in |- *; auto with arith.
Qed.
Hint Resolve le_minus.

Lemma le_minus_n_Sn : forall n m : nat, n - m <= S n - m.
simple induction n; simple induction m; auto with arith.
intros.
elim minus_S.
elim minus_S; apply H.
Qed.
Hint Resolve le_minus_n_Sn.

Lemma le_reg_minus : forall n m p : nat, n <= m -> n - p <= m - p.
intros.
elim H; auto with arith.
intros.
apply le_trans with (m0 - p).
assumption.
apply le_minus_n_Sn.
Qed.
Hint Resolve le_reg_minus.

Lemma lt_transp_r : forall n m p : nat, 0 < n -> p < n + m -> p - m < n.
simple induction m; simple induction p.
elim plus_n_O; auto with arith.
elim plus_n_O; auto with arith.
auto with arith.
intros.
simpl in |- *.
apply H.
auto with arith.
apply lt_S_n.
replace (S (n + n0)) with (n + S n0).
auto with arith.
elim plus_comm; simpl in |- *; auto with arith.
Qed.

Lemma lt_neq_O_pred : forall n m : nat, S n < m -> pred (m - n) <> 0.
intros.
elim H.
rewrite minus_SS_n; auto with arith.
intros.
elim minus_Sn_m.
simpl in |- *.
auto with arith.
apply le_trans with (S (S n)); auto with arith.
Qed.
Hint Resolve lt_neq_O_pred.

Lemma minus_Sn_n : forall n : nat, S n - n = 1.
simple induction n; auto with arith.
Qed.
Hint Resolve minus_Sn_n.

Lemma eq_minus_plus : forall n m : nat, m <= n -> n - m + m = n.
intros n m.
generalize n.
elim m.
clear n.
intro n.
intro lenO.
elim plus_n_O.
auto with arith.
clear n m.
intros m H_rec n leSmn.
elim plus_n_Sm.
replace (S (n - S m + m)) with (S (n - S m) + m); auto with arith.
rewrite minus_Sn_m; auto with arith.
apply (H_rec n).
auto with arith.
Qed.
Hint Immediate eq_minus_plus.

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


Require Import Arith.

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

Theorem fact : forall n, 2 * sum_up_to n = n * (n + 1).
Proof.
  intros.
  induction n.
  {
    (* Prove the base case. *)
    reflexivity.
  }
  {
    (* Prove the inductive case. *)
    (* Unfold the definition of sum_up_to and refold it once,
       to effectively pull the +1 out of its argument. *)
    unfold sum_up_to.
    fold sum_up_to.
    (* Distribute multiplication once, so our inductive
       hypothesis exactly fits a subterm. *)
    rewrite mult_plus_distr_l.
    (* Rewrite using our inductive hypothesis. *)
    rewrite IHn.
    (* Now that sum_up_to is eliminated, simple
       semi-ring properties suffice. *)
    ring.
  }
Qed.

Print fact.


Inductive natlist : Type :=
  | nil
  | cons (n : nat) (l : natlist).

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

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

Fixpoint count (v : nat) (s : bag) : nat :=
    match s with
    | nil => O
    | h :: t => match eqb v h with
        | true => 1 + count v t
        | false => count v t
        end
    end.

Fixpoint remove_one (v : nat) (s: bag) : bag :=
    match s with
    | nil => nil
    | h :: t => match eqb v h with
        | true => t
        | false => h :: remove_one v t
        end
    end.

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

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

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

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

Fixpoint remove_all (v:nat) (s:bag) : bag :=
    match s with
    | nil => nil
    | h :: t => match eqb v h with
        | true => remove_all v t
        | false => h :: remove_all v t
        end
    end.

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

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

Fixpoint member (v : nat) (s : bag) : bool :=
  match s with
  | nil => false
  | h :: t => match eqb h v with
    | true => true
    | false => member v t
    end
  end.

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

(* Question: is there a more precise syntax than
  match true|false with
  | true => ...
  | false => ...

*)

Example test_included1: included [1;2] [2;1;4;1] = true.
Proof. simpl. reflexivity. Qed.

Example test_included2: included [1;2;2] [2;1;4;1] = false.
Proof. simpl. reflexivity. Qed.


Require Import Arith Lia.

Definition inj {X Y} (f : X -> Y) :=
  forall x x', f x = f x' -> x = x'.
Definition inv {X Y} (g : Y -> X) (f : X -> Y) :=
  forall x, g (f x) = x.
Definition bijection X Y :=
  { f : X -> Y & { g & inv g f /\ inv f g }}.

Lemma size_rect {X} σ f :
  (forall x, (forall y : X, σ y < σ x -> f y) -> f x) -> forall x, f x.
Proof.
  intros H x. apply H.
  induction (σ x).
  - now intros ??%PeanoNat.Nat.nlt_0_r.
  - intros. apply H.
    intros. apply IHn. lia.
Defined.

Section Cantor.

  Definition next '(x,y) :=
    match x with
    | O => (S y, O)
    | S x' => (x', S y)
    end.

  Fact n00_next : forall p, (0,0) <> next p.
  Proof. intros [[] ]; intuition discriminate. Qed.

  Fact inj_next : inj next.
  Proof. intros [[] ][[] ]; cbn; congruence. Qed.

  Fixpoint decode n :=
    match n with
    | 0 => (0,0)
    | S x => next (decode x)
    end.

  Lemma inj_decode : inj decode.
  Proof.
    intros n. induction n; intros []; auto.
    - now intros ?%n00_next.
    - now intros ?%eq_sym%n00_next.
    - intros [=?%inj_next%IHn]. congruence.
  Qed.

  (* Shows that the function "next" is almost surjective *)
  Fact zero_or_next : forall p, {a | p = next a} + {p = (0,0)}.
  Proof.
    intros [x []].
    - destruct x. now right. left; now exists (0, x).
    - left; now exists (S x, n).
  Defined.

  Fixpoint Σ n := match n with 0 => 0 | S x => n + Σ x end.

  Definition code '(x,y) := Σ(x+y)+y.

  Lemma code_next p : code(next p) = S(code p).
  Proof.
    destruct p as [[|x] y]; cbn.
    - rewrite <-!plus_n_O, Nat.add_comm. reflexivity.
    - rewrite !Nat.add_succ_r. reflexivity.
  Qed.

  Lemma inv_dc : inv decode code.
  Proof.
    unfold inv.
    apply (size_rect code). intros p rec.
    destruct (zero_or_next p) as [[? ->] | ->].
    - rewrite code_next. cbn. f_equal. apply rec.
      rewrite code_next; auto.
    - reflexivity.
  Qed.

  Fact inv_cd : inv code decode.
  Proof.
    intros ?. apply inj_decode. now rewrite inv_dc.
  Qed.

  Corollary Bij_Nat_NatNat : bijection nat (nat * nat).
  Proof.
    exists decode, code. split. apply inv_cd. apply inv_dc.
  Qed.

  Fact CantorBound x y n : code (x, y) = n -> y < S n.
  Proof. cbn; lia. Qed.

End Cantor.


Add LoadPath "$COQ_PROOFS" as Path.
Load unit_1_006_numbers.

Theorem plus_O_n :
  forall n : nat, 0 + n = n. (* Proposition *)
(* We manipulate the goal and context with tactics (intros, simpl and reflexivity)) *)
Proof. intros n. simpl. reflexivity. Qed.

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

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


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

(* Comments and source code are derived from the book Certified Programming with Dependent Types by Professor Adam Chlipala available for free at http://adam.chlipala.net/cpdt/. *)

(* We define an inductive datatype binop to stand for the binary operators of our source language *)
Inductive binop : Set := Plus | Times.

(* We write that a constant may be built from one argument, a natural number; and a binary operation may be built from a choice of operator and two operand expressions. *)
Inductive exp : Set :=
    | Const : nat -> exp
    | Binop : binop -> exp -> exp -> exp.

(* The meaning of a binary operator is a binary function over nat referring to the
functions plus and mult from the Coq standard library. *)
Definition binopDenote (b : binop) : nat -> nat -> nat :=
    match b with
        | Plus => plus
        | Times => mult
    end.

(* A simple recursive definition of the meaning of an expression. *)
Fixpoint expDenote (e : exp) : nat :=
    match e with
    | Const n => n
    | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
    end.

(* An instruction either pushes a constant onto the stack or pops two arguments, applies a binary operator to them, and pushes the result onto the stack.*)
Inductive instr : Set :=
    | iConst : nat -> instr
    | iBinop : binop -> instr.

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

(* We can give instructions meanings as functions from stacks to optional stacks, where running an instruction results in None in case of a stack underflow and results in Some s’ when the result of execution is the new stack s’ *)
Definition instrDenote (i : instr) (s : stack) : option stack :=
    match i with
        | iConst n => Some (n :: s)
        | iBinop b => match s with
            | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')
            | _ => None
        end
    end.

(* Iterates application of instrDenote through a whole program. *)
Fixpoint progDenote (p : prog) (s : stack) : option stack :=
    match p with
        | nil => Some s
        | i :: p' => match instrDenote i s with
            | None => None
            | Some s' => progDenote p' s'
            end
        end.

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

(* How can we be sure the compiler operates correctly for all input
programs? *)
Theorem compile_correct : forall e, progDenote (compile e) nil
    = Some (expDenote e :: nil).

Abort.

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

induction e.

intros.

unfold compile.

unfold expDenote.

unfold progDenote at 1.

simpl.

fold progDenote.

reflexivity.

intros.

unfold compile.

fold compile.

unfold expDenote.

fold expDenote.

Check app_assoc_reverse.

rewrite app_assoc_reverse.

rewrite IHe2.

rewrite app_assoc_reverse.

rewrite IHe1.

unfold progDenote at 1.

simpl.

fold progDenote.

reflexivity.

Qed.


(* "especially useful" *)

Inductive natlist : Type :=
  | nil
  | cons (n : nat) (l : natlist).

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

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

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

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

Definition odd (n:nat) : bool :=
    negb (even n).

Fixpoint oddmembers (l:natlist) : natlist :=
    match l with
    | nil => nil
    | O :: t => oddmembers t
    | S n :: t => match odd(S n) with
        | true => S n :: oddmembers t
        | false => oddmembers t
        end
    end.

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

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

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

Example test_countoddmembers2:
  countoddmembers [0;2;4] = 0.
Proof. reflexivity. Qed.

Example test_countoddmembers3:
  countoddmembers nil = 0.
Proof. reflexivity. Qed.