(*************************************************************)
(*      This file is distributed under the terms of the      *)
(*      GNU Lesser General Public License Version 2.1        *)
(*************************************************************)
(*   Assia.Mahboubi@inria.fr, Laurence.Rideau@inria.fr       *)
(*  Laurent.Thery@inria.fr Yves.Bertot Frederique.Guilhot    *)
(*  &all    Inria, 2006                                      *)
(*************************************************************)

Require Export Reals.
Require Export Field.
Require Export Fourier.
Open Scope R_scope.
Hint Resolve fact_neq_0 prod_neq_R0 :real.

Ltac RReplace a b := replace a with b; [idtac | ring || auto with real].

Ltac NReplace a b := replace a with b; [idtac | omega || auto with arith].

Lemma C_nn: forall (n : nat),  C n n = 1.
intros; unfold C; simpl.
NReplace (n - n)%nat 0%nat.
simpl; field.
RReplace (INR (fact n) * 1) (INR (fact n)).
auto with real.
Qed.

Lemma C_n0: forall (n : nat),  C n O = 1.
intros.
rewrite <- (C_nn n).
rewrite pascal_step1.
NReplace (n - 0)%nat n; auto.
omega.
Qed.

Lemma util_C:
 forall (n i j : nat),
 (i <= j)%nat -> (j <= n)%nat ->  C n i * C (n - i) (j - i) = C j i * C n j.
intros.
assert (i <= n)%nat.
omega.
unfold C.
replace  ((n - i) - (j - i))%nat with (n - j)%nat;[ | omega].
field.
repeat split; auto with real.
Qed.

Lemma pow_Rmult: forall (x y : R) (n : nat),  (x * y) ^ n = x ^ n * y ^ n.
intros; (induction n; simpl).
auto with real.
RReplace ((x * x ^ n) * (y * y ^ n)) ((x * y) * (x ^ n * y ^ n)).
rewrite <- IHn.
ring.
Qed.

Lemma sum_f_permute:
 forall (f : nat -> nat ->  R) (n p : nat),
  sum_f_R0 (fun (i : nat) => sum_f_R0 (fun (j : nat) => f i j) p) n =
  sum_f_R0 (fun (j : nat) => sum_f_R0 (fun (i : nat) => f i j) n) p.
intros f; induction n; simpl; intros.
apply sum_eq; intros; auto.
rewrite IHn.
rewrite <- sum_plus.
apply sum_eq; intros; auto.
Qed.

Definition reverse (p : nat) (b : nat ->  R) := fun (i : nat) => b (p - i)%nat.

Lemma sigma_reverse:
 forall (p : nat) (b : nat ->  R),  sum_f_R0 b p = sum_f_R0 (reverse p b) p.
induction p; intros.
simpl; unfold reverse.
NReplace (0 - 0)%nat 0%nat; auto.
rewrite tech5; auto.
rewrite (tech2 (reverse (S p) b) 0 (S p)); auto.
simpl; unfold reverse.
NReplace (S p - 0)%nat (S p)%nat.
NReplace (p - 0)%nat p.
assert (sum_f_R0 b p = sum_f_R0 (fun (i : nat) => b (S p - S i)%nat) p).
rewrite IHp.
apply sum_eq; intros; unfold reverse.
NReplace (S p - S i)%nat (p - i)%nat; auto.
rewrite H; ring.
omega.
Qed.
(* Formalisation de l'algorithme qui permet de calculer a partir de la liste b des coefficients de P
   dans la base RBern (l r) ses coefficients dans la base RBern (l m)*)

Fixpoint coef_algo (b : nat ->  R) (A B : R) (n : nat) {struct n} : nat ->  R :=
 match n with
   0 => b
  | S i =>
      fun (j : nat) => A * coef_algo b A B i j + B * coef_algo b A B i (j + 1)
 end.
(* l'input de l'algorithme correspond a la premiere ligne
  l'output de l'algorithme correspond a la premiere colonne*)

Definition output b A B := fun (i : nat) => coef_algo b A B i 0%nat.
(* l'output2 de l'algorithme correspond a l'hypotenuse du triangle*)

Definition output2 p b A B := fun (i : nat) => coef_algo b A B (p - i) i.
(* linearite de l'algorithme *)

Lemma add_coef_algo:
 forall k b c A B n,
  coef_algo (fun (j : nat) => b j + c j) A B k n =
  coef_algo b A B k n + coef_algo c A B k n.
induction k; intros; simpl; auto.
rewrite IHk.
rewrite IHk.
ring.
Qed.

Lemma scal_coef_algo:
 forall k b A B x n,
  coef_algo (fun (j : nat) => x * b j) A B k n = x * coef_algo b A B k n.
induction k; intros; simpl; auto.
rewrite IHk.
rewrite IHk.
ring.
Qed.

Lemma output_add:
 forall k b c A B,
  output (fun (j : nat) => b j + c j) A B k = output b A B k + output c A B k.
intros; unfold output.
rewrite add_coef_algo; auto.
Qed.

Lemma output_scal:
 forall k b A B x,  output (fun (j : nat) => x * b j) A B k = x * output b A B k.
intros; unfold output.
rewrite scal_coef_algo; auto.
Qed.
(* (fi) avec i<=n est une famille de suites, formalisation de la suite k ->(f0 + .....+fn) (k)*)

Definition sum_suite (f : nat -> nat ->  R) (n : nat) :=
   fun (k : nat) => sum_f_R0 (fun (i : nat) => f i k) n.
(* l'output d'une somme finie de listes correspond a la somme finie des outputs de chacune des listes*)

Lemma output_sumsuite:
 forall n f A B k,
  output (sum_suite f n) A B k =
  sum_f_R0 (fun (i : nat) => output (fun (j : nat) => f i j) A B k) n.
unfold sum_suite.
induction n; intros; simpl; auto.
rewrite (output_add
          k (fun (k0 : nat) => sum_f_R0 (fun (i : nat) => f i k0) n)
          (fun (j : nat) => f (S n) j)).
rewrite IHn; auto.
Qed.
(* formalisation des suites delta i*)

Definition delta (n p : nat) :=
   match eq_nat_dec n p with left _ => 1 | right _ => 0 end.

Lemma delta_ii: forall (i : nat),  delta i i = 1.
intros; unfold delta.
elim (eq_nat_dec i i); auto.
intuition.
Qed.

Lemma delta_ij: forall (i j : nat), i <> j ->  delta i j = 0.
intros; unfold delta.
elim (eq_nat_dec i j); auto.
intuition.
Qed.

Lemma decompose_sum_3:
 forall (f : nat ->  R) (n p : nat),
 (p < n)%nat ->
 (0 < p)%nat ->
  sum_f_R0 f n =
  (sum_f_R0 f (pred p) +
   (f p + sum_f_R0 (fun (i : nat) => f (S p + i)%nat) (n - S p)))%R.
intros.
rewrite (tech2 f p n); auto.
rewrite (sum_N_predN f p); auto.
ring.
Qed.

Definition ps_delta (f : nat ->  R) :=
   fun (k : nat) => fun (i : nat) => f k * delta k i.
(* f0, f1 ,....,fn une liste peut s'ecrire comme somme des fi * delta i*)

Theorem decompose_delta:
 forall (f : nat ->  R) (n k : nat),
 (k <= n)%nat ->  sum_suite (ps_delta f) n k = f k.
intros; unfold sum_suite, ps_delta.
case (zerop n); intros.
rewrite e; simpl.
NReplace k 0%nat.
rewrite delta_ii; ring.
case (le_lt_eq_dec k n); auto; intros H1.
case (zerop k); intros H2.
rewrite decomp_sum; auto.
rewrite H2.
rewrite delta_ii.
assert (sum_f_R0 (fun (i : nat) => f (S i) * delta (S i) 0) (pred n) = 0).
apply sum_eq_R0; intros.
rewrite delta_ij; auto with arith.
ring.
rewrite H0; ring.
rewrite (decompose_sum_3 (fun (i : nat) => f i * delta i k) n k); auto.
assert (sum_f_R0 (fun (i : nat) => f i * delta i k) (pred k) = 0).
apply sum_eq_R0; intros.
rewrite delta_ij; (try omega).
ring.
assert
 (sum_f_R0 (fun (i : nat) => f (S k + i)%nat * delta (S k + i) k) (n - S k) = 0).
apply sum_eq_R0; intros.
rewrite delta_ij; (try omega).
ring.
rewrite H3; rewrite H0; rewrite delta_ii; ring.
rewrite sum_N_predN; auto.
rewrite H1.
assert (sum_f_R0 (fun (i : nat) => f i * delta i n) (pred n) = 0).
apply sum_eq_R0; intros.
rewrite delta_ij; (try omega).
ring.
rewrite H0; rewrite delta_ii; ring.
Qed.
(* application de l'algorithme a delta (i+1)*)

Lemma translation_delta:
 forall k A B i j,
  coef_algo (delta (S i)) A B k (S j) = coef_algo (delta i) A B k j.
induction k; intros; simpl.
elim (eq_nat_dec i j); intros.
rewrite a.
(repeat rewrite delta_ii); auto.
repeat (rewrite delta_ij; intuition).
rewrite IHk.
rewrite IHk; auto.
Qed.
(* algorithme applique a delta_i (colonne j > i)*)

Lemma coef_algo_delta_col_supi:
 forall k A B i j, (j > i)%nat ->  coef_algo (delta i%nat) A B k j = 0.
induction k; intros; simpl.
rewrite delta_ij; intuition.
rewrite IHk; intuition.
rewrite IHk; intuition.
ring.
Qed.
(* algorithme applique a delta_i (ligne n ,colonne  i)*)

Lemma coef_algo_delta_col_i:
 forall n i A B,  coef_algo (delta i%nat) A B n i = A ^ n.
induction n; intros; simpl.
rewrite delta_ii; auto.
rewrite IHn.
rewrite coef_algo_delta_col_supi; intuition.
ring.
Qed.
(* algorithme applique a delta_i (colonne k avec k < i - j, ligne j avec j < i)*)

Lemma coef_algo_delta_ligne_infi_k:
 forall j i A B,
 (j < i)%nat ->
 forall k, (k < i - j)%nat ->  coef_algo (delta i%nat) A B j k = 0.
induction j; intros; simpl.
rewrite delta_ij; intuition.
rewrite IHj; intuition.
rewrite IHj; intuition.
ring.
Qed.
(* algorithme applique a delta_i (colonne 0, ligne j avec j < i)*)

Lemma coef_algo_delta_ligne_infi:
 forall j i A B, (j < i)%nat ->  coef_algo (delta i) A B j 0%nat = 0.
induction j; intros; simpl.
rewrite delta_ij; intuition.
rewrite IHj; intuition.
rewrite coef_algo_delta_ligne_infi_k; intuition.
ring.
Qed.
(* algorithme applique a delta_i (colonne 0, ligne i + k )*)

Lemma coef_algo_delta_ligne_sup_i:
 forall i k A B,
  coef_algo (delta i) A B (i + k) 0%nat = (C (k + i) i * A ^ k) * B ^ i.
induction i; intros; simpl.
rewrite coef_algo_delta_col_i.
rewrite C_n0.
ring.
rewrite translation_delta.
rewrite IHi.
elim k; simpl.
NReplace (i + 0)%nat i.
rewrite coef_algo_delta_ligne_infi_k; (try omega).
repeat rewrite C_nn.
ring.
intros.
NReplace (i + S n)%nat (S (i + n))%nat.
simpl.
rewrite translation_delta.
rewrite IHi.
rewrite H.
rewrite <- (pascal (n + S i) i); auto.
NReplace (S (n + i))%nat (n + S i)%nat.
ring.
omega.
Qed.
(*ouput de delta i*)

Theorem output_delta_infi:
 forall i j A B, (j < i)%nat ->  output (delta i) A B j = 0.
intros; unfold output.
rewrite coef_algo_delta_ligne_infi; auto.
Qed.

Theorem output_delta_supi:
 forall i j A B,
 (j >= i)%nat ->  output (delta i) A B j = (C j i * A ^ (j - i)) * B ^ i.
intros; unfold output.
pattern j at 1.
NReplace j (i + (j - i))%nat.
rewrite (coef_algo_delta_ligne_sup_i i (j - i)).
NReplace ((j - i) + i)%nat j; auto.
Qed.
(*avec une liste f0,....,fn, on peut calculer un "triangle" de coefficients du tableau *)

Lemma coef_algo_comp_eq:
 forall f g A B n,
 (forall k, (k <= n)%nat ->  f k = g k) ->
 forall i j,
 (i <= n)%nat -> (j <= n - i)%nat ->  coef_algo f A B i j = coef_algo g A B i j.
induction i; intros; simpl; auto.
rewrite H; auto.
omega.
rewrite IHi; auto.
rewrite IHi; auto.
omega.
omega.
omega.
omega.
Qed.

Lemma output_comp_eq:
 forall f g A B n,
 (forall k, (k <= n)%nat ->  f k = g k) ->
 forall i, (i <= n)%nat ->  output f A B i = output g A B i.
intros; unfold output.
rewrite (coef_algo_comp_eq _ _ A B _ H); auto.
omega.
Qed.
(* output b comme somme des output delta i *)

Lemma sum_output_delta:
 forall b A B n k,
 (k <= n)%nat ->
  output b A B k = sum_f_R0 (fun (i : nat) => b i * output (delta i) A B k) n.
intros.
assert (output b A B k = output (sum_suite (ps_delta b) n) A B k).
apply (output_comp_eq b (sum_suite (ps_delta b) n) A B n); auto.
intros; rewrite decompose_delta; auto.
rewrite H0.
rewrite output_sumsuite; auto.
unfold ps_delta.
apply sum_eq; intros.
rewrite (output_scal k (delta i) A B (b i)); auto.
Qed.
(* algorithme applique a la suite inversee*)

Lemma algo_reverse:
 forall b A B p i k,
 (i <= p)%nat ->
 (k <= p - i)%nat ->
  coef_algo (reverse p b) B A i k = coef_algo b A B i (p - (i + k)).
induction i; intros.
unfold reverse; simpl; auto.
simpl.
rewrite IHi; (try omega).
rewrite IHi; (try omega).
NReplace (p - (i + k))%nat ((p - S (i + k)) + 1)%nat.
NReplace (p - (i + (k + 1)))%nat (p - S (i + k))%nat.
ring.
Qed.
(* output2 en fonction de output de la suite inversee*)

Lemma ouput_reverse:
 forall b A B p i,
 (i <= p)%nat ->  output2 p b A B i = reverse p (output (reverse p b) B A) i.
intros.
change (output2 p b A B i = output (reverse p b) B A (p - i)).
unfold output, output2.
rewrite algo_reverse; (try omega).
NReplace (p - ((p - i) + 0))%nat i; auto.
Qed.
(*Polynomes de Bernstein (l,r)*)
Definition RBern p i l r X :=
  C p i *  (Rdiv (X - l) (r - l) ^ i * Rdiv (r - X) (r - l) ^ (p - i)).

Lemma
   RBern_def :
   forall p i l r X,
   (i <= p)%nat ->
   r - l <> 0 ->
    RBern p i l r X =
    C p i * (Rdiv (X - l) (r - l) ^ i * Rdiv (r - X) (r - l) ^ (p - i)).
intros; reflexivity.
Qed.

Lemma RBern_rl:
 forall p i l r X,
 (i <= p)%nat -> r - l <> 0 ->  RBern p i r l X = RBern p (p - i) l r X.
intros.
repeat (rewrite RBern_def; auto).
NReplace (p - (p - i))%nat i.
rewrite pascal_step1; auto.
RReplace ((X - l) / (r - l)) ((l - X) / (l - r)).
RReplace ((r - X) / (r - l)) ((X - r) / (l - r)).
ring.
field.
auto with real.
field.
auto with real.
omega.
auto with real.
Qed.

Lemma reverse_RBern:
 forall b p l r X P,
 r - l <> 0 ->
 P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->
  P = sum_f_R0 (fun (i : nat) => reverse p b i * RBern p i r l X) p.
intros.
rewrite H0.
rewrite sigma_reverse.
apply sum_eq; intros; unfold reverse.
rewrite <- RBern_rl; auto.
Qed.

Section RBernstein.
Variables X l r m : R.
Hypothesis neq_rl : r - l <> 0.
Hypothesis neq_ml : m - l <> 0.
Hypothesis neq_rm : r - m <> 0.

Definition A := Rdiv (r - m) (r - l).

Definition B := Rdiv (m - l) (r - l).
Hint Unfold A B :real.

Lemma pow_Xl_k:
 forall k,  Rdiv (X - l) (r - l) ^ k = B ^ k * Rdiv (X - l) (m - l) ^ k.
intros; unfold B.
rewrite <- pow_Rmult.
replace ((X - l) / (r - l)) with (((m - l) / (r - l)) * ((X - l) / (m - l)));
 auto.
field.
auto.
Qed.

Lemma dev_rX:
 Rdiv (r - X) (r - l) = A * Rdiv (X - l) (m - l) + Rdiv (m - X) (m - l).
unfold A.
field.
auto.
Qed.

Lemma pow_rX_n:
 forall n,
  Rdiv (r - X) (r - l) ^ n =
  sum_f_R0
   (fun (i : nat) =>
    (C n i * (A ^ i * Rdiv (X - l) (m - l) ^ i)) *
    Rdiv (m - X) (m - l) ^ (n - i)) n.
intros.
rewrite dev_rX.
rewrite binomial.
apply sum_eq; intros.
rewrite pow_Rmult; auto.
Qed.

Lemma RBern_sum:
 forall p k,
 (k <= p)%nat ->
  RBern p k l r X =
  C p k *
  sum_f_R0
   (fun (i : nat) =>
    (C (p - k) i * (A ^ i * (B ^ k * Rdiv (X - l) (m - l) ^ (i + k)))) *
    Rdiv (m - X) (m - l) ^ ((p - k) - i)) (p - k).
intros.
rewrite RBern_def; auto.
rewrite pow_Xl_k.
rewrite pow_rX_n.
rewrite scal_sum.
apply Rmult_eq_compat_l.
apply sum_eq; intros.
rewrite pow_add.
ring.
Qed.

Lemma RBern_lr_sum_RBern_lm:
 forall p k,
 (k <= p)%nat ->
  RBern p k l r X =
  sum_f_R0
   (fun (i : nat) => (C (i + k) k * (A ^ i * B ^ k)) * RBern p (i + k) l m X)
   (p - k).
intros.
rewrite RBern_sum; auto.
rewrite scal_sum.
apply sum_eq; intros.
rewrite RBern_def; auto.
NReplace (p - (i + k))%nat ((p - k) - i)%nat.
RReplace (((C (p - k) i * (A ^ i * (B ^ k * ((X - l) / (m - l)) ^ (i + k)))) *
           ((m - X) / (m - l)) ^ ((p - k) - i)) * C p k)
         (((B ^ k * (A ^ i * (C p k * C (p - k) i))) *
           ((m - X) / (m - l)) ^ ((p - k) - i)) * ((X - l) / (m - l)) ^ (i + k)).
replace (C (p - k) i) with (C (p - k) ((i + k) - k)).
rewrite (util_C p k (i + k)); (try omega).
ring.
NReplace ((i + k) - k)%nat i; auto.
omega.
Qed.
(* Ce theoreme exprime les RBern(l r) comme somme finie des Rbern (l m)*)

Theorem RBern_lr_sum_k_n_RBern_lm:
 forall p i,
 (i <= p)%nat ->
  RBern p i l r X =
  sum_f i p (fun (j : nat) => (C j i * (A ^ (j - i) * B ^ i)) * RBern p j l m X).
intros; unfold sum_f.
rewrite RBern_lr_sum_RBern_lm; auto.
apply sum_eq; intros j; intros.
NReplace ((j + i) - i)%nat j; auto.
Qed.

Lemma RBern_sigma_coef_algo:
 forall (p k : nat),
 (k <= p)%nat ->
  RBern p k l r X =
  sum_f_R0
   (fun (i : nat) => output (delta k) A B (i + k) * RBern p (i + k) l m X)
   (p - k).
intros; unfold output.
rewrite RBern_lr_sum_RBern_lm; auto.
apply sum_eq; intros.
pattern (i + k)%nat at 3.
NReplace (i + k)%nat (k + i)%nat.
rewrite coef_algo_delta_ligne_sup_i; ring.
Qed.

Lemma RBern_sigma_p:
 forall (p k : nat),
 (k <= p)%nat ->
  RBern p k l r X =
  sum_f_R0 (fun (i : nat) => output (delta k) A B i * RBern p i l m X) p.
intros.
rewrite RBern_sigma_coef_algo; auto.
case (zerop k); intros.
rewrite e.
NReplace (p - 0)%nat p.
apply sum_eq; intros.
NReplace (i + 0)%nat i; auto.
rewrite (tech2
          (fun (i : nat) => output (delta k) A B i * RBern p i l m X) (k - 1) p);
 auto.
assert
 (sum_f_R0 (fun (i : nat) => output (delta k) A B i * RBern p i l m X) (k - 1) =
  0).
apply sum_eq_R0; intros.
rewrite output_delta_infi; (try omega).
ring.
rewrite H0.
NReplace (S (k - 1))%nat k.
ring_simplify.
apply sum_eq; intros.
NReplace (k + i)%nat (i + k)%nat; auto.
omega.
Qed.
(*input : b0,....,bp : calul explicite de l'output*)

Lemma output_sum_C:
 forall (b : nat ->  R) (p k : nat),
 (k <= p)%nat ->
  output b A B k =
  sum_f_R0 (fun (i : nat) => b i * ((C k i * A ^ (k - i)) * B ^ i)) k.
intros.
rewrite (sum_output_delta b A B p); auto.
elim (eq_nat_dec k p); intros.
rewrite a.
apply sum_eq; intros.
rewrite output_delta_supi; auto.
rewrite (tech2 (fun (i : nat) => b i * output (delta i) A B k) k p).
assert
 (sum_f_R0
   (fun (i : nat) => b (S k + i)%nat * output (delta (S k + i)) A B k) (p - S k)
  = 0).
apply sum_eq_R0; intros.
rewrite output_delta_infi; (try omega).
ring.
rewrite H0.
ring_simplify.
apply sum_eq; intros.
rewrite output_delta_supi; auto.
omega.
Qed.
(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)
   alors (output b)0,....,(output b)p sont les coefficients de P dans la base Bern(l,m)*)

Theorem algo_correct:
 forall (b : nat ->  R) (p : nat) (P : R),
 P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->
  P = sum_f_R0 (fun (i : nat) => (output b A B) i * RBern p i l m X) p.
intros.
pose (f:=
 fun (j : nat) =>
 fun (i : nat) => b i * (output (delta i) A B j * RBern p j l m X)).
assert
 (sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p =
  sum_f_R0 (fun (i : nat) => sum_f_R0 (fun (j : nat) => f i j) p) p).
rewrite sum_f_permute.
apply sum_eq; intros k; intros.
rewrite RBern_sigma_p; auto.
rewrite scal_sum.
apply sum_eq; intros i; intros.
unfold f; ring.
rewrite H; rewrite H0.
apply sum_eq; intros i; intros.
rewrite (sum_output_delta b A B p i); auto.
rewrite Rmult_comm.
rewrite scal_sum.
apply sum_eq; intros j; intros.
unfold f; ring.
Qed.

End RBernstein.

Lemma A_rl: forall l r m, l - r <> 0 ->  A r l m = B l r m.
unfold A, B; intros.
field.
auto with real.
Qed.

Lemma B_rl: forall l r m, l - r <> 0 ->  B r l m = A l r m.
unfold A, B; intros.
field.
auto with real.
Qed.
(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)
   alors (output2 b)0,....,(output2 b)p sont les coefficients de P dans la base Bern(m,r)*)

Theorem algo_correct2:
 forall (X l r m P : R) (b : nat ->  R) (p : nat),
 l - r <> 0 ->
 m - r <> 0 ->
 P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->
  P =
  sum_f_R0
   (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p i m r X) p.
intros.
assert
 (P =
  sum_f_R0
   (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p (p - i) r m X)
   p).
assert (P = sum_f_R0 (fun (i : nat) => reverse p b i * RBern p i r l X) p).
rewrite (reverse_RBern b p l r X P); auto with real.
rewrite (algo_correct X r l m H H0 (reverse p b) p P); auto.
rewrite sigma_reverse; auto.
apply sum_eq; intros.
change
 (output (reverse p b) (A r l m) (B r l m) (p - i) * RBern p (p - i) r m X =
  output2 p b (A l r m) (B l r m) i * RBern p (p - i) r m X).
rewrite ouput_reverse; auto.
rewrite B_rl; auto with real.
rewrite A_rl; auto with real.
rewrite H2; auto.
apply sum_eq; intros.
rewrite <- RBern_rl; auto with real.
Qed.
(* si b0,....,bp sont les coefficients du polynome P dans la base Bern(l,r)
   alors l'algorithme donnent les coefficients de P dans la base Bern(l,m) et dans la base Bern(m,r)*)

Theorem conclusion:
 forall (X l r m P : R) (b : nat ->  R) (p : nat),
 l - r <> 0 ->
 m - l <> 0 ->
 m - r <> 0 ->
 P = sum_f_R0 (fun (i : nat) => b i * RBern p i l r X) p ->
  and
   (P =
    sum_f_R0
     (fun (i : nat) => output b (A l r m) (B l r m) i * RBern p i l m X) p)
   (P =
    sum_f_R0
     (fun (i : nat) => output2 p b (A l r m) (B l r m) i * RBern p i m r X) p).
intros.
split.
apply algo_correct; auto with real.
apply algo_correct2; auto with real.
Qed.


From mathcomp Require Import ssreflect.

Require Import relation.

(* Axiom Of Extentionality in setontypetheory *)

Axiom AxiomOfEmpty: forall U:Type, exists z':Collection U, (forall x:U, x ∉ z').

Inductive EmptyCollection (U:Type) : Collection U := .
Inductive FullCollection (U:Type) : Collection U :=
| intro_full_collection: forall x:U, x ∈ FullCollection U.

Notation "`Ø`" :=  (EmptyCollection _) (at level 10).

Definition ComplementOfCollection (U:Type) (X:Collection U) : Collection U :=
  fun x:U => x ∉ X.

Notation "A ^c" := (ComplementOfCollection _ A) (at level 15).

Theorem noone_in_empty:
  forall U:Type, forall x:U, x ∉ `Ø`.
Proof.
  move => U x.
  case.
Qed.

Theorem same_empty_collection_is_exsitance:
  forall U:Type, exists a':Collection U, (forall x:U, x ∉ a') <-> (a' = `Ø`).
Proof.
  move => U.
  case: (AxiomOfEmpty U) => e' HAE.
  exists e'.
  rewrite /iff. split => H.
  apply: AxiomOfExtentionality => x0.
  rewrite /iff. split => H0.
  case: (HAE x0). by [].
  case: (noone_in_empty U x0). by [].
  by [].
Qed.

Theorem noone_in_collection_to_empty_collection:
  forall U:Type, forall {a':Collection U}, (forall x:U, x ∉ a') -> a' = `Ø`.
Proof.
  move => U a' HE.
  apply AxiomOfExtentionality.
  rewrite /iff. split => H.
  case: (HE x). by[].
  case: (noone_in_empty U x). by [].
Qed.

Theorem empty_collection_to_noone_in_collection:
  forall U:Type, forall a':Collection U, a' = `Ø` -> (forall x:U, x ∉ a').
Proof.
  move => U a' H.
  rewrite H.
  apply noone_in_empty.
Qed.

Theorem empty_collection_is_noone_in_collection:
  forall U:Type, forall a':Collection U, a' = `Ø` <-> (forall x:U, x ∉ a').
Proof.
  move => U a'.
  rewrite /iff. split.
  apply empty_collection_to_noone_in_collection.
  apply noone_in_collection_to_empty_collection.
Qed.

Theorem not_empty_collection_to_exists_element_in_collection:
  forall U:Type, forall a':Collection U, a' <> `Ø` -> (exists x:U, x ∈ a').
Proof.
  move => U a' HaNE.
  apply DoubleNegativeElimination => H.
  have L1: forall x:U, x ∉ a'.
  apply DeMorganNotExists.
  trivial.
  apply empty_collection_is_noone_in_collection in L1.
  apply HaNE.
  trivial.
Qed.

Theorem exists_element_in_collection_to_not_empty_collection:
  forall U:Type, forall a':Collection U, (exists x:U, x ∈ a') -> a' <> `Ø`.
Proof.
  move => U a' HexA HxA.
  move: HexA.
  apply DeMorganNotExists.
  apply empty_collection_is_noone_in_collection.
  trivial.
Qed.

Theorem not_empty_collection_has_least_a_element:
  forall U:Type, forall a':Collection U, a' <> `Ø` <-> (exists x:U, x ∈ a').
Proof.
  move => U a'.
  rewrite /iff. split.
  apply not_empty_collection_to_exists_element_in_collection.
  apply exists_element_in_collection_to_not_empty_collection.
Qed.

Theorem empty_collection_is_unique:
  forall U:Type, forall {a' b':Collection U}, (forall x: U, x ∉ a') -> (forall x: U, x ∉ b') -> a' = b'.
Proof.
  move => U a' b' HNa HNb.
  apply (noone_in_collection_to_empty_collection U) in HNa.
  apply (noone_in_collection_to_empty_collection U) in HNb.
  rewrite HNa HNb.
  reflexivity.
Qed.

Theorem all_collection_included_empty:
  forall U:Type, forall A:(Collection U), `Ø` ⊂ A.
Proof.
  move => U A x H.
  case: (noone_in_empty U x). by[].
Qed.

Theorem collection_is_subcollect_of_fullcollection:
  forall U:Type, forall A:(Collection U), A ⊂ FullCollection U.
Proof.
  move => U A x H.
  split.
Qed.

Theorem element_in_empty_collection_to_empty_collection_eq:
  forall (U:Type) (A:Collection U),
    (forall x:U, x ∈ A -> x ∈ `Ø`) -> A = `Ø`.
Proof.
  move => U A H.
  apply mutally_included_to_eq.
  split;[trivial|apply all_collection_included_empty].
Qed.

Theorem complement_of_complement_collect_is_self:
  forall U:Type, forall A:Collection U, A = (A^c)^c.
Proof.
  move => U A.
  apply mutally_included_to_eq.
  split => x H.
  case. by [].
  apply DoubleNegativeElimination in H. by [].
Qed.

Theorem LawOfExcludedMiddleAtComplementCollection:
  forall U:Type, forall A:Collection U, forall x:U, x ∈ A \/ x ∈ A^c.
Proof.
  move => U A x.
  apply LawOfExcludedMiddle.
Qed.

Theorem notin_collect_iff_in_complement:
  forall U:Type, forall A:Collection U, forall x:U, x ∉ A <-> x ∈ A^c.
Proof.
  move => U A x.
  rewrite /iff. split; apply.
Qed.


Definition FizzBuzzInteger := {n : N | n mod 5 <> 0 /\ n mod 3 <> 0}.

Inductive FizzBuzzEntry : Set :=
| Shadow : FizzBuzzShadow -> FizzBuzzEntry
| Num : FizzBuzzInteger -> FizzBuzzEntry
.

Inductive FizzBuzzShadow : Set :=
| Fizz : {n : N | n mod 3 = 0 /\ n mod 5 <> 0} -> FizzBuzzShadow
| Buzz : {n : N | n mod 3 <> 0 /\ n mod 5 = 0} -> FizzBuzzShadow
| FizzBuzz : {n : N | n mod 3 = 0 /\ n mod 5 = 0} -> FizzBuzzShadow
.

Definition initial : FizzBuzzEntry.
  refine (Num (exist _ 1 _)).
  split.
  * assert (1 mod 3 = 1).
    ** auto.
    ** rewrite H.
       zify. omega.
  *  assert (1 mod 5 = 1).
    ** auto.
    ** rewrite H.
       zify. omega.
Qed.

Definition toNat (previousEntry : FizzBuzzEntry): N :=
  match previousEntry with
  | Shadow (Fizz (exist _ shadowed _))     => shadowed
  | Shadow (Buzz (exist _ shadowed _))     => shadowed
  | Shadow (FizzBuzz (exist _ shadowed _)) => shadowed
  | Num (exist _ n _)                      => n
  end.

Definition next (previousEntry : FizzBuzzEntry): FizzBuzzEntry :=
  fromNat (toNat previousEntry + 1).

Definition fromNat (n : N): FizzBuzzEntry.
  refine (match (n mod 3 ?= 0, n mod 5 ?= 0)
                as cmp
                return (n mod 3 ?= 0, n mod 5 ?= 0) = cmp -> FizzBuzzEntry with
          | (Eq, Eq) => fun pf => _
          | (Eq, Gt) => fun pf => _
          | (Gt, Eq) => fun pf => _
          | (Gt, Gt) => fun pf => _
          | _ => _
          end eq_refl).
  * apply pair_equal_spec in pf.
    destruct pf.
    apply N.compare_eq_iff in H.
    apply N.compare_eq_iff in H0.
    assert (n mod 3 = 0 /\ n mod 5 = 0); auto.
    apply (Shadow (FizzBuzz (exist _ n H1))).
  * intros.
    apply pair_equal_spec in H.
    destruct H.
    destruct H.
    exfalso.
    apply N.compare_lt_iff in H0.
    assert (0 <= (n mod 5)).
    ** apply N.mod_bound_pos.
       *** destruct n.
           **** zify. omega.
           **** apply N.lt_succ_r. apply N.compare_gt_iff. auto.
       *** zify. omega.
    ** assert (n mod 5 < 0).
       *** auto.
       *** assert ((n mod 5 ?= 0) <> Lt).
           **** apply N.compare_0_r.
           **** contradiction.
  * apply pair_equal_spec in pf.
    destruct pf.
    apply N.compare_eq_iff in H.
    apply N.compare_gt_iff in H0.
    assert (n mod 3 = 0 /\ n mod 5 <> 0).
    ** intuition.
    ** apply (Shadow (Fizz (exist _ n H1))).
  * intros.
    apply pair_equal_spec in H.
    destruct H.
    exfalso.
    *** assert ((n mod 3 ?= 0) <> Lt).
        **** apply N.compare_0_r.
        **** contradiction.
  * apply pair_equal_spec in pf.
    destruct pf.
    apply N.compare_eq_iff in H0.
    apply N.compare_gt_iff in H.
    assert (n mod 3 <> 0 /\ n mod 5 = 0).
    ** intuition.
    ** apply (Shadow (Buzz (exist _ n H1))).
  * intros.
    apply pair_equal_spec in H.
    destruct H.
    exfalso.
    *** assert ((n mod 5 ?= 0) <> Lt).
        **** apply N.compare_0_r.
        **** contradiction.
  * apply pair_equal_spec in pf.
    destruct pf.
    apply N.compare_gt_iff in H0.
    apply N.compare_gt_iff in H.
    assert (n mod 3 <> 0 /\ n mod 5 <> 0).
    ** intuition.
    ** apply (Num (exist _ n H1)).
Defined.


Definition T := nat.

Definition le := le.

Hint Unfold le.

Lemma le_refl : forall n : nat, le n n.
  auto.
Qed.

Require Import Le.

Lemma le_trans : forall n m k : nat, le n m -> le m k -> le n k.
   eauto with arith.
Qed.

Lemma le_antis : forall n m : nat, le n m -> le m n -> n = m.
   eauto with arith.
Qed.


Require Import String.
Require Import ZArith.
Require Import List.
Import ListNotations.
Definition Identifier := string.
Definition id_eq_dec := string_dec.
Inductive Term : Set :=
  | Var : Identifier -> Term
  | Bool : bool -> Term
  | Eq : Term -> Term -> Term
  | And : Term -> Term -> Term
  | Or : Term -> Term -> Term
  | Not : Term -> Term
  | If : Term -> Term -> Term -> Term
  | Int : Z -> Term
  | Plus : Term -> Term -> Term
  | Times : Term -> Term -> Term
  | Minus : Term -> Term -> Term
  | Choose : Identifier -> Term -> Term.
Definition extendEnv {Value} (env : Identifier -> Value)
  (var : Identifier) (newValue : Value) : Identifier -> Value :=
  fun id => if id_eq_dec id var then newValue else env id.
Record EpsilonLogic :=
 mkLogic {Value : Type;
          value_eq_dec : forall v1 v2 : Value, {v1 = v2} + {v1 <> v2};
          eval : (Identifier -> Value) -> Term -> Value;
          evalVar : forall env id, eval env (Var id) = env id;
          evalIntConst :
           forall env1 env2 i, eval env1 (Int i) = eval env2 (Int i);
          evalIntInj :
           forall env i j, i <> j -> eval env (Int i) <> eval env (Int j);
          evalBoolConst :
           forall env1 env2 b, eval env1 (Bool b) = eval env2 (Bool b);
          evalBoolInj :
           forall env, eval env (Bool true) <> eval env (Bool false);
          evalEqTrue :
           forall env a b,
           eval env a = eval env b <->
           eval env (Eq a b) = eval env (Bool true);
          evalEqFalse :
           forall env a b,
           eval env a <> eval env b <->
           eval env (Eq a b) = eval env (Bool false);
          evalIfTrue :
           forall env cond a b,
           eval env cond = eval env (Bool true) ->
           eval env (If cond a b) = eval env a;
          evalIfFalse :
           forall env cond a b,
           eval env cond = eval env (Bool false) ->
           eval env (If cond a b) = eval env b;
          evalAnd :
           forall env a b,
           eval env (And a b) = eval env (If a b (Bool false));
          evalOr :
           forall env a b, eval env (Or a b) = eval env (If a (Bool true) b);
          evalNot :
           forall env a,
           eval env (Not a) = eval env (If a (Bool false) (Bool true));
          evalPlus :
           forall env iE jE i j,
           eval env iE = eval env (Int i) ->
           eval env jE = eval env (Int j) ->
           eval env (Plus iE jE) = eval env (Int (i + j));
          evalMinus :
           forall env iE jE i j,
           eval env iE = eval env (Int i) ->
           eval env jE = eval env (Int j) ->
           eval env (Minus iE jE) = eval env (Int (i - j));
          evalTimes :
           forall env iE jE i j,
           eval env iE = eval env (Int i) ->
           eval env jE = eval env (Int j) ->
           eval env (Times iE jE) = eval env (Int (i * j));
          evalChoose :
           forall env x P,
           (exists value,
              eval (extendEnv env x value) P = eval env (Bool true)) ->
           eval (extendEnv env x (eval env (Choose x P))) P =
           eval env (Bool true);
          evalChooseDet :
           forall env x P Q,
           eval env P = eval env (Bool true) <->
           eval env Q = eval env (Bool true) ->
           eval env (Choose x P) = eval env (Choose x Q)}.
Definition isTheorem (L : EpsilonLogic) (t : Term) :=
  forall env, L.(eval) env t = L.(eval) env (Bool true).
Fixpoint identity (t : Term) : Term :=
  match t with
  | Var x => Var x
  | Bool b => Bool b
  | Eq a b => Eq (identity a) (identity b)
  | And a b => And (identity a) (identity b)
  | Or a b => Or (identity a) (identity b)
  | Not a => Not (identity a)
  | If a b c => If (identity a) (identity b) (identity c)
  | Int i => Int i
  | Plus a b => Plus (identity a) (identity b)
  | Times a b => Times (identity a) (identity b)
  | Minus a b => Minus (identity a) (identity b)
  | Choose x P => Choose x (identity P)
  end.
Theorem eval_eq_true_or_false :
  forall (L : EpsilonLogic) env (t1 t2 : Term),
  L.(eval) env (Eq t1 t2) = L.(eval) env (Bool true) \/
  L.(eval) env (Eq t1 t2) = L.(eval) env (Bool false).
Proof.
(intros).
(destruct (L.(value_eq_dec) (L.(eval) env t1) (L.(eval) env t2))).
-
left.
apply -> L.(evalEqTrue).
assumption.
-
right.
apply -> L.(evalEqFalse).
assumption.
Qed.
Theorem identity_correct :
  forall (L : EpsilonLogic) (t : Term), isTheorem L (Eq t (identity t)).
Proof.
(unfold isTheorem).
(induction t; intros; simpl in *).
-
apply -> evalEqTrue.
reflexivity.
-
apply -> evalEqTrue.
reflexivity.
-
apply -> evalEqTrue.
specialize IHt1 with env.
specialize IHt2 with env.
apply <- evalEqTrue in IHt1.
apply <- evalEqTrue in IHt2.
(destruct (eval_eq_true_or_false L env t1 t2)).
+
(rewrite H).
(apply evalEqTrue in H).
(rewrite H in IHt1).
(rewrite IHt1 in IHt2).
symmetry.
apply -> evalEqTrue.
assumption.
+
(rewrite H).
(apply evalEqFalse in H).
(assert (eval L env (identity t1) <> eval L env (identity t2)) by congruence).
symmetry.
apply -> evalEqFalse.
assumption.
Admitted.
Fixpoint free_vars (t : Term) : list Identifier :=
  match t with
  | Var x => [x]
  | Int _ => []
  | Bool _ => []
  | Eq a b => free_vars a ++ free_vars b
  | And a b => free_vars a ++ free_vars b
  | Or a b => free_vars a ++ free_vars b
  | Not a => free_vars a
  | If a b c => free_vars a ++ free_vars b ++ free_vars c
  | Plus a b => free_vars a ++ free_vars b
  | Times a b => free_vars a ++ free_vars b
  | Minus a b => free_vars a ++ free_vars b
  | Choose x P =>
      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)
  end.
Axiom (fresh_var : list Identifier -> Identifier).
Axiom (fresh_var_unique : forall exclude, ~ In (fresh_var exclude) exclude).
Definition Divide (t1 : Term) (t2 : Term) :=
  let x := fresh_var (free_vars t1 ++ free_vars t2) in
  Choose x (Eq t1 (Times (Var x) t2)).
Lemma extendEnv_eq :
  forall Value env x (val : Value), (extendEnv env x val) x = val.
Proof.
(intros).
(unfold extendEnv).
(destruct (id_eq_dec x x); congruence).
(* Auto-generated comment: Succeeded. *)


(** * Poly: Polymorphism and Higher-Order Functions *)

(* Final reminder: Please do not put solutions to the exercises in
   publicly accessible places.  Thank you!! *)

Require Export Lists.

(* ################################################################# *)
(** * Polymorphism *)

(** In this chapter we continue our development of basic
    concepts of functional programming.  The critical new ideas are
    _polymorphism_ (abstracting functions over the types of the data
    they manipulate) and _higher-order functions_ (treating functions
    as data).  We begin with polymorphism. *)

(* ================================================================= *)
(** ** Polymorphic Lists *)

(** For the last couple of chapters, we've been working just
    with lists of numbers.  Obviously, interesting programs also need
    to be able to manipulate lists with elements from other types --
    lists of strings, lists of booleans, lists of lists, etc.  We
    _could_ just define a new inductive datatype for each of these,
    for example... *)

Inductive boollist : Type :=
  | bool_nil : boollist
  | bool_cons : bool -> boollist -> boollist.

(** ... but this would quickly become tedious, partly because we
    have to make up different constructor names for each datatype, but
    mostly because we would also need to define new versions of all
    our list manipulating functions ([length], [rev], etc.) for each
    new datatype definition. *)

(** To avoid all this repetition, Coq supports _polymorphic_
    inductive type definitions.  For example, here is a _polymorphic
    list_ datatype. *)

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

(** This is exactly like the definition of [natlist] from the
    previous chapter, except that the [nat] argument to the [cons]
    constructor has been replaced by an arbitrary type [X], a binding
    for [X] has been added to the header, and the occurrences of
    [natlist] in the types of the constructors have been replaced by
    [list X].  (We can re-use the constructor names [nil] and [cons]
    because the earlier definition of [natlist] was inside of a
    [Module] definition that is now out of scope.)

    What sort of thing is [list] itself?  One good way to think
    about it is that [list] is a _function_ from [Type]s to
    [Inductive] definitions; or, to put it another way, [list] is a
    function from [Type]s to [Type]s.  For any particular type [X],
    the type [list X] is an [Inductive]ly defined set of lists whose
    elements are of type [X]. *)

(** With this definition, when we use the constructors [nil] and
    [cons] to build lists, we need to tell Coq the type of the
    elements in the lists we are building -- that is, [nil] and [cons]
    are now _polymorphic constructors_.  Observe the types of these
    constructors: *)

Check nil.
(* ===> nil : forall X : Type, list X *)
Check cons.
(* ===> cons : forall X : Type, X -> list X -> list X *)

(** (Side note on notation: In .v files, the "forall" quantifier
    is spelled out in letters.  In the generated HTML files and in the
    way various IDEs show .v files (with certain settings of their
    display controls), [forall] is usually typeset as the usual
    mathematical "upside down A," but you'll still see the spelled-out
    "forall" in a few places.  This is just a quirk of typesetting:
    there is no difference in meaning.) *)

(** The "[forall X]" in these types can be read as an additional
    argument to the constructors that determines the expected types of
    the arguments that follow.  When [nil] and [cons] are used, these
    arguments are supplied in the same way as the others.  For
    example, the list containing [2] and [1] is written like this: *)

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

(** (We've written [nil] and [cons] explicitly here because we haven't
    yet defined the [ [] ] and [::] notations for the new version of
    lists.  We'll do that in a bit.) *)

(** We can now go back and make polymorphic versions of all the
    list-processing functions that we wrote before.  Here is [repeat],
    for example: *)

Fixpoint repeat (X : Type) (x : X) (count : nat) : list X :=
  match count with
  | 0 => nil X
  | S count' => cons X x (repeat X x count')
  end.

(** As with [nil] and [cons], we can use [repeat] by applying it
    first to a type and then to its list argument: *)

Example test_repeat1 :
  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).
Proof. reflexivity.  Qed.

(** To use [repeat] to build other kinds of lists, we simply
    instantiate it with an appropriate type parameter: *)

Example test_repeat2 :
  repeat bool false 1 = cons bool false (nil bool).
Proof. reflexivity.  Qed.

Module MumbleGrumble.

(** **** Exercise: 2 stars (mumble_grumble)  *)
(** Consider the following two inductively defined types. *)

Inductive mumble : Type :=
  | a : mumble
  | b : mumble -> nat -> mumble
  | c : mumble.

Inductive grumble (X:Type) : Type :=
  | d : mumble -> grumble X
  | e : X -> grumble X.

(** Which of the following are well-typed elements of [grumble X] for
    some type [X]?
      - [d (b a 5)]
      - [d mumble (b a 5)]
      - [d bool (b a 5)]
      - [e bool true]
      - [e mumble (b c 0)]
      - [e bool (b c 0)]
      - [c]
(* FILL IN HERE *)
*)
(** [] *)

End MumbleGrumble.

(* ----------------------------------------------------------------- *)
(** *** Type Annotation Inference *)

(** Let's write the definition of [repeat] again, but this time we
    won't specify the types of any of the arguments.  Will Coq still
    accept it? *)

Fixpoint repeat' X x count : list X :=
  match count with
  | 0        => nil X
  | S count' => cons X x (repeat' X x count')
  end.

(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)

Check repeat'.
(* ===> forall X : Type, X -> nat -> list X *)
Check repeat.
(* ===> forall X : Type, X -> nat -> list X *)

(** It has exactly the same type type as [repeat].  Coq was able
    to use _type inference_ to deduce what the types of [X], [x], and
    [count] must be, based on how they are used.  For example, since
    [X] is used as an argument to [cons], it must be a [Type], since
    [cons] expects a [Type] as its first argument; matching [count]
    with [0] and [S] means it must be a [nat]; and so on.

    This powerful facility means we don't always have to write
    explicit type annotations everywhere, although explicit type
    annotations are still quite useful as documentation and sanity
    checks, so we will continue to use them most of the time.  You
    should try to find a balance in your own code between too many
    type annotations (which can clutter and distract) and too
    few (which forces readers to perform type inference in their heads
    in order to understand your code). *)

(* ----------------------------------------------------------------- *)
(** *** Type Argument Synthesis *)

(** To use a polymorphic function, we need to pass it one or
    more types in addition to its other arguments.  For example, the
    recursive call in the body of the [repeat] function above must
    pass along the type [X].  But since the second argument to
    [repeat] is an element of [X], it seems entirely obvious that the
    first argument can only be [X] -- why should we have to write it
    explicitly?

    Fortunately, Coq permits us to avoid this kind of redundancy.  In
    place of any type argument we can write the "implicit argument"
    [_], which can be read as "Please try to figure out for yourself
    what belongs here."  More precisely, when Coq encounters a [_], it
    will attempt to _unify_ all locally available information -- the
    type of the function being applied, the types of the other
    arguments, and the type expected by the context in which the
    application appears -- to determine what concrete type should
    replace the [_].

    This may sound similar to type annotation inference -- indeed, the
    two procedures rely on the same underlying mechanisms.  Instead of
    simply omitting the types of some arguments to a function, like

      repeat' X x count : list X :=

    we can also replace the types with [_]

      repeat' (X : _) (x : _) (count : _) : list X :=

    to tell Coq to attempt to infer the missing information.

    Using implicit arguments, the [count] function can be written like
    this: *)

Fixpoint repeat'' X x count : list X :=
  match count with
  | 0        => nil _
  | S count' => cons _ x (repeat'' _ x count')
  end.

(** In this instance, we don't save much by writing [_] instead of
    [X].  But in many cases the difference in both keystrokes and
    readability is nontrivial.  For example, suppose we want to write
    down a list containing the numbers [1], [2], and [3].  Instead of
    writing this... *)

Definition list123 :=
  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).

(** ...we can use argument synthesis to write this: *)

Definition list123' :=
  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).

(* ----------------------------------------------------------------- *)
(** *** Implicit Arguments *)

(** We can go further and even avoid writing [_]'s in most cases by
    telling Coq _always_ to infer the type argument(s) of a given
    function.  The [Arguments] directive specifies the name of the
    function (or constructor) and then lists its argument names, with
    curly braces around any arguments to be treated as implicit.  (If
    some arguments of a definition don't have a name, as is often the
    case for constructors, they can be marked with a wildcard pattern
    [_].) *)

Arguments nil {X}.
Arguments cons {X} _ _.
Arguments repeat {X} x count.

(** Now, we don't have to supply type arguments at all: *)

Definition list123'' := cons 1 (cons 2 (cons 3 nil)).

(** Alternatively, we can declare an argument to be implicit
    when defining the function itself, by surrounding it in curly
    braces instead of parens.  For example: *)

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

(** (Note that we didn't even have to provide a type argument to the
    recursive call to [repeat''']; indeed, it would be invalid to
    provide one!)

    We will use the latter style whenever possible, but we will
    continue to use use explicit [Argument] declarations for
    [Inductive] constructors.  The reason for this is that marking the
    parameter of an inductive type as implicit causes it to become
    implicit for the type itself, not just for its constructors.  For
    instance, consider the following alternative definition of the
    [list] type: *)

Inductive list' {X:Type} : Type :=
  | nil' : list'
  | cons' : X -> list' -> list'.

(** Because [X] is declared as implicit for the _entire_ inductive
    definition including [list'] itself, we now have to write just
    [list'] whether we are talking about lists of numbers or booleans
    or anything else, rather than [list' nat] or [list' bool] or
    whatever; this is a step too far. *)

(** Let's finish by re-implementing a few other standard list
    functions on our new polymorphic lists... *)

Fixpoint app {X : Type} (l1 l2 : list X)
             : (list X) :=
  match l1 with
  | nil      => l2
  | cons h t => cons h (app t l2)
  end.

Fixpoint rev {X:Type} (l:list X) : list X :=
  match l with
  | nil      => nil
  | cons h t => app (rev t) (cons h nil)
  end.

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

Example test_rev1 :
  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).
Proof. reflexivity.  Qed.

Example test_rev2:
  rev (cons true nil) = cons true nil.
Proof. reflexivity.  Qed.

Example test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.
Proof. reflexivity.  Qed.

(* ----------------------------------------------------------------- *)
(** *** Supplying Type Arguments Explicitly *)

(** One small problem with declaring arguments [Implicit] is
    that, occasionally, Coq does not have enough local information to
    determine a type argument; in such cases, we need to tell Coq that
    we want to give the argument explicitly just this time.  For
    example, suppose we write this: *)

Fail Definition mynil := nil.

(** (The [Fail] qualifier that appears before [Definition] can be
    used with _any_ command, and is used to ensure that that command
    indeed fails when executed. If the command does fail, Coq prints
    the corresponding error message, but continues processing the rest
    of the file.)

    Here, Coq gives us an error because it doesn't know what type
    argument to supply to [nil].  We can help it by providing an
    explicit type declaration (so that Coq has more information
    available when it gets to the "application" of [nil]): *)

Definition mynil : list nat := nil.

(** Alternatively, we can force the implicit arguments to be explicit by
   prefixing the function name with [@]. *)

Check @nil.

Definition mynil' := @nil nat.

(** Using argument synthesis and implicit arguments, we can
    define convenient notation for lists, as before.  Since we have
    made the constructor type arguments implicit, Coq will know to
    automatically infer these when we use the notations. *)

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

(** Now lists can be written just the way we'd hope: *)

Definition list123''' := [1; 2; 3].

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

(** **** Exercise: 2 stars, optional (poly_exercises)  *)
(** Here are a few simple exercises, just like ones in the [Lists]
    chapter, for practice with polymorphism.  Complete the proofs below. *)

Theorem app_nil_r : forall (X:Type), forall l:list X,
  l ++ [] = l.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  (* FILL IN HERE *) Admitted.

Lemma app_length : forall (X:Type) (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)
(** Here are some slightly more interesting ones... *)

Theorem rev_app_distr: forall X (l1 l2 : list X),
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Polymorphic Pairs *)

(** Following the same pattern, the type definition we gave in
    the last chapter for pairs of numbers can be generalized to
    _polymorphic pairs_, often called _products_: *)

Inductive prod (X Y : Type) : Type :=
| pair : X -> Y -> prod X Y.

Arguments pair {X} {Y} _ _.

(** As with lists, we make the type arguments implicit and define the
    familiar concrete notation. *)

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

(** We can also use the [Notation] mechanism to define the standard
    notation for product _types_: *)

Notation "X * Y" := (prod X Y) : type_scope.

(** (The annotation [: type_scope] tells Coq that this abbreviation
    should only be used when parsing types.  This avoids a clash with
    the multiplication symbol.) *)

(** It is easy at first to get [(x,y)] and [X*Y] confused.
    Remember that [(x,y)] is a _value_ built from two other values,
    while [X*Y] is a _type_ built from two other types.  If [x] has
    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)

(** The first and second projection functions now look pretty
    much as they would in any functional programming language. *)

Definition fst {X Y : Type} (p : X * Y) : X :=
  match p with
  | (x, y) => x
  end.

Definition snd {X Y : Type} (p : X * Y) : Y :=
  match p with
  | (x, y) => y
  end.

(** The following function takes two lists and combines them
    into a list of pairs.  In other functional languages, it is often
    called [zip]; we call it [combine] for consistency with Coq's
    standard library. *)

Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)
           : list (X*Y) :=
  match lx, ly with
  | [], _ => []
  | _, [] => []
  | x :: tx, y :: ty => (x, y) :: (combine tx ty)
  end.

(** **** Exercise: 1 star, optional (combine_checks)  *)
(** Try answering the following questions on paper and
    checking your answers in coq:
    - What is the type of [combine] (i.e., what does [Check
      @combine] print?)
    - What does

        Compute (combine [1;2] [false;false;true;true]).

      print? *)
(** [] *)

(** **** Exercise: 2 stars, recommended (split)  *)
(** The function [split] is the right inverse of [combine]: it takes a
    list of pairs and returns a pair of lists.  In many functional
    languages, it is called [unzip].

    Fill in the definition of [split] below.  Make sure it passes the
    given unit test. *)

Fixpoint split {X Y : Type} (l : list (X*Y))
               : (list X) * (list Y)
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example test_split:
  split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Polymorphic Options *)

(** One last polymorphic type for now: _polymorphic options_,
    which generalize [natoption] from the previous chapter: *)

Inductive option (X:Type) : Type :=
  | Some : X -> option X
  | None : option X.

Arguments Some {X} _.
Arguments None {X}.

(** We can now rewrite the [nth_error] function so that it works
    with any type of lists. *)

Fixpoint nth_error {X : Type} (l : list X) (n : nat)
                   : option X :=
  match l with
  | [] => None
  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)
  end.

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

(** **** Exercise: 1 star, optional (hd_error_poly)  *)
(** Complete the definition of a polymorphic version of the
    [hd_error] function from the last chapter. Be sure that it
    passes the unit tests below. *)

Definition hd_error {X : Type} (l : list X) : option X
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

(** Once again, to force the implicit arguments to be explicit,
    we can use [@] before the name of the function. *)

Check @hd_error.

Example test_hd_error1 : hd_error [1;2] = Some 1.
 (* FILL IN HERE *) Admitted.
Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].
 (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * Functions as Data *)

(** Like many other modern programming languages -- including
    all functional languages (ML, Haskell, Scheme, Scala, Clojure,
    etc.) -- Coq treats functions as first-class citizens, allowing
    them to be passed as arguments to other functions, returned as
    results, stored in data structures, etc.*)

(* ================================================================= *)
(** ** Higher-Order Functions *)

(** Functions that manipulate other functions are often called
    _higher-order_ functions.  Here's a simple one: *)

Definition doit3times {X:Type} (f:X->X) (n:X) : X :=
  f (f (f n)).

(** The argument [f] here is itself a function (from [X] to
    [X]); the body of [doit3times] applies [f] three times to some
    value [n]. *)

Check @doit3times.
(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)

Example test_doit3times: doit3times minustwo 9 = 3.
Proof. reflexivity.  Qed.

Example test_doit3times': doit3times negb true = false.
Proof. reflexivity.  Qed.

(* ================================================================= *)
(** ** Filter *)

(** Here is a more useful higher-order function, taking a list
    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])
    and "filtering" the list, returning a new list containing just
    those elements for which the predicate returns [true]. *)

Fixpoint filter {X:Type} (test: X->bool) (l:list X)
                : (list X) :=
  match l with
  | []     => []
  | h :: t => if test h then h :: (filter test t)
                        else       filter test t
  end.

(** For example, if we apply [filter] to the predicate [evenb]
    and a list of numbers [l], it returns a list containing just the
    even members of [l]. *)

Example test_filter1: filter evenb [1;2;3;4] = [2;4].
Proof. reflexivity.  Qed.

Definition length_is_1 {X : Type} (l : list X) : bool :=
  beq_nat (length l) 1.

Example test_filter2:
    filter length_is_1
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity.  Qed.

(** We can use [filter] to give a concise version of the
    [countoddmembers] function from the [Lists] chapter. *)

Definition countoddmembers' (l:list nat) : nat :=
  length (filter oddb l).

Example test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.
Proof. reflexivity.  Qed.
Example test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.
Proof. reflexivity.  Qed.
Example test_countoddmembers'3:   countoddmembers' nil = 0.
Proof. reflexivity.  Qed.

(* ================================================================= *)
(** ** Anonymous Functions *)

(** It is arguably a little sad, in the example just above, to
    be forced to define the function [length_is_1] and give it a name
    just to be able to pass it as an argument to [filter], since we
    will probably never use it again.  Moreover, this is not an
    isolated example: when using higher-order functions, we often want
    to pass as arguments "one-off" functions that we will never use
    again; having to give each of these functions a name would be
    tedious.

    Fortunately, there is a better way.  We can construct a function
    "on the fly" without declaring it at the top level or giving it a
    name. *)

Example test_anon_fun':
  doit3times (fun n => n * n) 2 = 256.
Proof. reflexivity.  Qed.

(** The expression [(fun n => n * n)] can be read as "the function
    that, given a number [n], yields [n * n]." *)

(** Here is the [filter] example, rewritten to use an anonymous
    function. *)

Example test_filter2':
    filter (fun l => beq_nat (length l) 1)
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (filter_even_gt7)  *)
(** Use [filter] (instead of [Fixpoint]) to write a Coq function
    [filter_even_gt7] that takes a list of natural numbers as input
    and returns a list of just those that are even and greater than
    7. *)

Definition filter_even_gt7 (l : list nat) : list nat
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example test_filter_even_gt7_1 :
  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
 (* FILL IN HERE *) Admitted.

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
 (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (partition)  *)
(** Use [filter] to write a Coq function [partition]:

      partition : forall X : Type,
                  (X -> bool) -> list X -> list X * list X

   Given a set [X], a test function of type [X -> bool] and a [list
   X], [partition] should return a pair of lists.  The first member of
   the pair is the sublist of the original list containing the
   elements that satisfy the test, and the second is the sublist
   containing those that fail the test.  The order of elements in the
   two sublists should be the same as their order in the original
   list. *)

Definition partition {X : Type}
                     (test : X -> bool)
                     (l : list X)
                   : list X * list X
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).
(* FILL IN HERE *) Admitted.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
(* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Map *)

(** Another handy higher-order function is called [map]. *)

Fixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=
  match l with
  | []     => []
  | h :: t => (f h) :: (map f t)
  end.

(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]
    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has
    been applied to each element of [l] in turn.  For example: *)

Example test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

(** The element types of the input and output lists need not be
    the same, since [map] takes _two_ type arguments, [X] and [Y]; it
    can thus be applied to a list of numbers and a function from
    numbers to booleans to yield a list of booleans: *)

Example test_map2:
  map oddb [2;1;2;5] = [false;true;false;true].
Proof. reflexivity.  Qed.

(** It can even be applied to a list of numbers and
    a function from numbers to _lists_ of booleans to
    yield a _list of lists_ of booleans: *)

Example test_map3:
    map (fun n => [evenb n;oddb n]) [2;1;2;5]
  = [[true;false];[false;true];[true;false];[false;true]].
Proof. reflexivity.  Qed.

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

(** **** Exercise: 3 stars (map_rev)  *)
(** Show that [map] and [rev] commute.  You may need to define an
    auxiliary lemma. *)

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, recommended (flat_map)  *)
(** The function [map] maps a [list X] to a [list Y] using a function
    of type [X -> Y].  We can define a similar function, [flat_map],
    which maps a [list X] to a [list Y] using a function [f] of type
    [X -> list Y].  Your definition should work by 'flattening' the
    results of [f], like so:

        flat_map (fun n => [n;n+1;n+2]) [1;5;10]
      = [1; 2; 3; 5; 6; 7; 10; 11; 12].
*)

Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)
                   : (list Y)
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example test_flat_map1:
  flat_map (fun n => [n;n;n]) [1;5;4]
  = [1; 1; 1; 5; 5; 5; 4; 4; 4].
 (* FILL IN HERE *) Admitted.
(** [] *)

(** Lists are not the only inductive type that we can write a
    [map] function for.  Here is the definition of [map] for the
    [option] type: *)

Definition option_map {X Y : Type} (f : X -> Y) (xo : option X)
                      : option Y :=
  match xo with
    | None => None
    | Some x => Some (f x)
  end.

(** **** Exercise: 2 stars, optional (implicit_args)  *)
(** The definitions and uses of [filter] and [map] use implicit
    arguments in many places.  Replace the curly braces around the
    implicit arguments with parentheses, and then fill in explicit
    type parameters where necessary and use Coq to check that you've
    done so correctly.  (This exercise is not to be turned in; it is
    probably easiest to do it on a _copy_ of this file that you can
    throw away afterwards.)  [] *)

(* ================================================================= *)
(** ** Fold *)

(** An even more powerful higher-order function is called
    [fold].  This function is the inspiration for the "[reduce]"
    operation that lies at the heart of Google's map/reduce
    distributed programming framework. *)

Fixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)
                         : Y :=
  match l with
  | nil => b
  | h :: t => f h (fold f t b)
  end.

(** Intuitively, the behavior of the [fold] operation is to
    insert a given binary operator [f] between every pair of elements
    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively
    means [1+2+3+4].  To make this precise, we also need a "starting
    element" that serves as the initial second input to [f].  So, for
    example,

       fold plus [1;2;3;4] 0

    yields

       1 + (2 + (3 + (4 + 0))).

    Some more examples: *)

Check (fold andb).
(* ===> fold andb : list bool -> bool -> bool *)

Example fold_example1 :
  fold mult [1;2;3;4] 1 = 24.
Proof. reflexivity. Qed.

Example fold_example2 :
  fold andb [true;true;false;true] true = false.
Proof. reflexivity. Qed.

Example fold_example3 :
  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].
Proof. reflexivity. Qed.

(** **** Exercise: 1 star, advanced (fold_types_different)  *)
(** Observe that the type of [fold] is parameterized by _two_ type
    variables, [X] and [Y], and the parameter [f] is a binary operator
    that takes an [X] and a [Y] and returns a [Y].  Can you think of a
    situation where it would be useful for [X] and [Y] to be
    different? *)

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

(* ================================================================= *)
(** ** Functions That Construct Functions *)

(** Most of the higher-order functions we have talked about so
    far take functions as arguments.  Let's look at some examples that
    involve _returning_ functions as the results of other functions.
    To begin, here is a function that takes a value [x] (drawn from
    some type [X]) and returns a function from [nat] to [X] that
    yields [x] whenever it is called, ignoring its [nat] argument. *)

Definition constfun {X: Type} (x: X) : nat->X :=
  fun (k:nat) => x.

Definition ftrue := constfun true.

Example constfun_example1 : ftrue 0 = true.
Proof. reflexivity. Qed.

Example constfun_example2 : (constfun 5) 99 = 5.
Proof. reflexivity. Qed.

(** In fact, the multiple-argument functions we have already
    seen are also examples of passing functions as data.  To see why,
    recall the type of [plus]. *)

Check plus.
(* ==> nat -> nat -> nat *)

(** Each [->] in this expression is actually a _binary_ operator
    on types.  This operator is _right-associative_, so the type of
    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it
    can be read as saying that "[plus] is a one-argument function that
    takes a [nat] and returns a one-argument function that takes
    another [nat] and returns a [nat]."  In the examples above, we
    have always applied [plus] to both of its arguments at once, but
    if we like we can supply just the first.  This is called _partial
    application_. *)

Definition plus3 := plus 3.
Check plus3.

Example test_plus3 :    plus3 4 = 7.
Proof. reflexivity.  Qed.
Example test_plus3' :   doit3times plus3 0 = 9.
Proof. reflexivity.  Qed.
Example test_plus3'' :  doit3times (plus 3) 0 = 9.
Proof. reflexivity.  Qed.

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

Module Exercises.

(** **** Exercise: 2 stars (fold_length)  *)
(** Many common functions on lists can be implemented in terms of
   [fold].  For example, here is an alternative definition of [length]: *)

Definition fold_length {X : Type} (l : list X) : nat :=
  fold (fun _ n => S n) l 0.

Example test_fold_length1 : fold_length [4;7;0] = 3.
Proof. reflexivity. Qed.

(** Prove the correctness of [fold_length]. *)

Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (fold_map)  *)
(** We can also define [map] in terms of [fold].  Finish [fold_map]
    below. *)

Definition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

(** Write down a theorem [fold_map_correct] in Coq stating that
   [fold_map] is correct, and prove it. *)

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

(** **** Exercise: 2 stars, advanced (currying)  *)
(** In Coq, a function [f : A -> B -> C] really has the type [A
    -> (B -> C)].  That is, if you give [f] a value of type [A], it
    will give you function [f' : B -> C].  If you then give [f'] a
    value of type [B], it will return a value of type [C].  This
    allows for partial application, as in [plus3].  Processing a list
    of arguments with functions that return functions is called
    _currying_, in honor of the logician Haskell Curry.

    Conversely, we can reinterpret the type [A -> B -> C] as [(A *
    B) -> C].  This is called _uncurrying_.  With an uncurried binary
    function, both arguments must be given at once as a pair; there is
    no partial application. *)

(** We can define currying as follows: *)

Definition prod_curry {X Y Z : Type}
  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).

(** As an exercise, define its inverse, [prod_uncurry].  Then prove
    the theorems below to show that the two are inverses. *)

Definition prod_uncurry {X Y Z : Type}
  (f : X -> Y -> Z) (p : X * Y) : Z
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

(** As a (trivial) example of the usefulness of currying, we can use it
    to shorten one of the examples that we saw above: *)

Example test_map2: map (fun x => plus 3 x) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

(** Thought exercise: before running the following commands, can you
    calculate the types of [prod_curry] and [prod_uncurry]? *)

Check @prod_curry.
Check @prod_uncurry.

Theorem uncurry_curry : forall (X Y Z : Type)
                        (f : X -> Y -> Z)
                        x y,
  prod_curry (prod_uncurry f) x y = f x y.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem curry_uncurry : forall (X Y Z : Type)
                        (f : (X * Y) -> Z) (p : X * Y),
  prod_uncurry (prod_curry f) p = f p.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)
(** Recall the definition of the [nth_error] function:

   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=
     match l with
     | [] => None
     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)
     end.

   Write an informal proof of the following theorem:

   forall X n l, length l = n -> @nth_error X l n = None

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

(** **** Exercise: 4 stars, advanced (church_numerals)  *)
(** This exercise explores an alternative way of defining natural
    numbers, using the so-called _Church numerals_, named after
    mathematician Alonzo Church.  We can represent a natural number
    [n] as a function that takes a function [f] as a parameter and
    returns [f] iterated [n] times. *)

Module Church.
Definition nat := forall X : Type, (X -> X) -> X -> X.

(** Let's see how to write some numbers with this notation. Iterating
    a function once should be the same as just applying it.  Thus: *)

Definition one : nat :=
  fun (X : Type) (f : X -> X) (x : X) => f x.

(** Similarly, [two] should apply [f] twice to its argument: *)

Definition two : nat :=
  fun (X : Type) (f : X -> X) (x : X) => f (f x).

(** Defining [zero] is somewhat trickier: how can we "apply a function
    zero times"?  The answer is actually simple: just return the
    argument untouched. *)

Definition zero : nat :=
  fun (X : Type) (f : X -> X) (x : X) => x.

(** More generally, a number [n] can be written as [fun X f x => f (f
    ... (f x) ...)], with [n] occurrences of [f].  Notice in
    particular how the [doit3times] function we've defined previously
    is actually just the Church representation of [3]. *)

Definition three : nat := @doit3times.

(** Complete the definitions of the following functions. Make sure
    that the corresponding unit tests pass by proving them with
    [reflexivity]. *)

(** Successor of a natural number: *)

Definition succ (n : nat) : nat
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example succ_1 : succ zero = one.
Proof. (* FILL IN HERE *) Admitted.

Example succ_2 : succ one = two.
Proof. (* FILL IN HERE *) Admitted.

Example succ_3 : succ two = three.
Proof. (* FILL IN HERE *) Admitted.

(** Addition of two natural numbers: *)

Definition plus (n m : nat) : nat
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example plus_1 : plus zero one = one.
Proof. (* FILL IN HERE *) Admitted.

Example plus_2 : plus two three = plus three two.
Proof. (* FILL IN HERE *) Admitted.

Example plus_3 :
  plus (plus two two) three = plus one (plus three three).
Proof. (* FILL IN HERE *) Admitted.

(** Multiplication: *)

Definition mult (n m : nat) : nat
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example mult_1 : mult one one = one.
Proof. (* FILL IN HERE *) Admitted.

Example mult_2 : mult zero (plus three three) = zero.
Proof. (* FILL IN HERE *) Admitted.

Example mult_3 : mult two three = plus three three.
Proof. (* FILL IN HERE *) Admitted.

(** Exponentiation: *)

(** (_Hint_: Polymorphism plays a crucial role here.  However,
    choosing the right type to iterate over can be tricky.  If you hit
    a "Universe inconsistency" error, try iterating over a different
    type: [nat] itself is usually problematic.) *)

Definition exp (n m : nat) : nat
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Example exp_1 : exp two two = plus two two.
Proof. (* FILL IN HERE *) Admitted.

Example exp_2 : exp three two = plus (mult two (mult two two)) one.
Proof. (* FILL IN HERE *) Admitted.

Example exp_3 : exp three zero = one.
Proof. (* FILL IN HERE *) Admitted.

End Church.
(** [] *)

End Exercises.

(** $Date: 2016-09-20 23:50:11 +0900 (2016年09月20日 (火)) $ *)


Require Import Setoid.
Require Import Coq.Lists.List.
Require Import Coq.Program.Equality.
Import ListNotations.
Require Import Lib.EqDec.

Class LinearOrder (A: Type) := {
  ord      : A -> A -> bool;
  refl     : forall x: A, ord x x = true;
  anti_sym : forall x y: A, ord x y = true -> ord y x = true -> x = y;
  trans    : forall x y z: A, ord x y = true -> ord y z = true -> ord x z = true;
  full     : forall x y, ord x y = true \/ ord y x = true;
}.

Global Instance LO_is_EqDec (A: Type) `{LinearOrder A}: EqDec A.
Proof.
  exists (fun x y => andb (ord x y) (ord y x)). intros x y.
  destruct (andb (ord x y) (ord y x)) eqn:e; constructor.
  - rewrite Bool.andb_true_iff in e. destruct e. apply anti_sym; auto.
  - intros E. subst. rewrite refl in e. cbn in *. inversion e.
Defined.

Inductive Sorted {A: Type} `{LinearOrder A} : list A -> Prop :=
  | SortedNil : Sorted []
  | SortedSing : forall h: A, Sorted [h]
  | SortedCons : forall h h' : A, forall t: list A,
      Sorted (h' :: t) -> ord h h' = true -> Sorted (h :: h' :: t).

Fixpoint count {A: Type} (p: A -> bool) (l: list A): nat :=
  match l with
  | nil => O
  | cons h t => if p h then S (count p t) else count p t
  end.

Definition permutation {A: Type} (a b : list A) :=
  forall p : A -> bool, count p a = count p b.

Lemma sorted_without_head {A: Type} `{LinearOrder A} : forall l: list A, forall a: A,
  Sorted (a::l) -> Sorted l.
Proof.
  intros l. induction l; intro h.
  - intros _. constructor.
  - intro s. dependent destruction s. assumption.
Qed.

Lemma sorted_with_head {A: Type} `{LinearOrder A} : forall l: list A, forall a h: A,
  Sorted (h::l) -> ord a h = true -> Sorted (a::h::l).
Proof.
  intros l a h sort o. constructor.
  - trivial.
  - assumption.
Qed.

Lemma sorted_head_relation {A: Type} `{L: LinearOrder A} :
  forall l: list A, forall h: A, Sorted (h::l) -> forall x: A, In x (h :: l) ->
  ord h x = true.
Proof.
  intros l. induction l; intros h sort x H.
  - cbn in H. destruct H.
    + subst. apply refl.
    + contradiction.
  - cbn in H. destruct H.
    + subst. apply refl.
    + assert (ord a x = true).
      { apply IHl.
        - apply (sorted_without_head _ h). assumption.
        - assumption.
      }
      dependent destruction sort; try discriminate.
      apply (trans h a x); assumption.
Qed.

Theorem perm_sym {A: Type} : forall l l': list A, permutation l l' <-> permutation l' l.
Proof.
  intros l l'. unfold permutation. split; intros H p; symmetry; apply (H p).
Qed.

Theorem perm_trans {A: Type} : forall x y z: list A,
  permutation x y -> permutation y z -> permutation x z.
Proof.
  intros x y z H H0. unfold permutation in *. intro p. specialize (H p). specialize (H0 p).
  transitivity (count p y); assumption.
Qed.

Lemma perm_without_head {A: Type} : forall l l': list A, forall a: A,
  permutation (cons a l) (cons a l') -> permutation l l'.
Proof.
  - intros l l' a H. unfold permutation in *. intro p. specialize (H p). cbn in H.
    destruct (p a).
    + inversion H. reflexivity.
    + assumption.
Qed.

Lemma perm_with_head {A: Type} : forall l l': list A, forall a: A,
  permutation l l' -> permutation (a::l) (a::l').
Proof.
  intros l l' a perm. unfold permutation in *. intro p. specialize (perm p).
  cbn. destruct (p a).
  - destruct perm. trivial.
  - assumption.
Qed.

Theorem perm_for_element {A: Type} : forall l l': list A, forall x: A,
  permutation l l' -> In x l' -> In x l.
Proof.
  unfold permutation. intros l. induction l; intros l' x perm H.
  - destruct l'.
    + cbn in H. destruct H.
    + specialize (perm (fun x => true)). cbn in perm. discriminate.
  - destruct l'.
    + cbn in H. destruct H.
    + cbn. cbn in H. destruct H.
      * subst. left.
Abort.

Lemma singleton_perm {A: Type} `{L: LinearOrder A} (x y: A) :
   x = y <-> permutation [x] [y].
Proof.
  split.
  - intros [] p. auto.
  - intros perm. specialize (perm (eqf x)). cbn [count] in *. rewrite eqf_refl in perm.
    destruct (eqf x y) eqn:e.
    + rewrite <- eqf_iff in e; auto.
    + inversion perm.
Qed.

Lemma week_eqf_in {A: Type} `{L: EqDec A} :
  forall x: A, forall l: list A, In x l <-> count (eqf x) l <> O.
Proof.
  intros x l. split.
  - intros H. induction l.
    + cbn in H. contradiction.
    + cbn. destruct (eqf x a) eqn:eq.
      * apply PeanoNat.Nat.neq_succ_0.
      * apply IHl. destruct H; auto. subst. rewrite eqf_refl in eq.
        inversion eq.
  - intro H. induction l.
    + cbn in H. contradiction.
    + cbn. destruct (eqf x a) eqn:eq.
      * left. apply eqf_iff. rewrite eqf_sym. assumption.
      * right. apply IHl. cbn in H. rewrite eq in H. assumption.
Qed.

Theorem weak_perm_in {A: Type} `{L: EqDec A} : forall l l': list A, forall x: A,
  permutation l l' -> In x l' -> In x l.
Proof.
  unfold permutation. intros l l' x perm H. specialize (perm (eqf x)). cut (count (eqf x) l' <> O).
  - intro H0. rewrite <- perm in H0. rewrite week_eqf_in. assumption.
  - apply week_eqf_in. assumption.
Qed.

Lemma sorted_head_eq {A: Type} `{L: LinearOrder A} : forall l l': list A, forall a a': A,
  permutation (a :: l) (a' :: l') -> Sorted (a :: l) -> Sorted (a' :: l') -> a = a'.
Proof.
  intros l l' h h' perm s1 s2.
  destruct (full h h').
  - assert (In h (h'::l')).
    + apply (weak_perm_in (h'::l') (h :: l) h); try apply perm_sym; auto.
      cbn. left. reflexivity.
    + assert (ord h' h = true) by (apply (sorted_head_relation l' h'); auto).
      apply anti_sym; auto.
  - assert (In h' (h::l)).
    + apply (weak_perm_in (h::l) (h' :: l') h'); auto.
      cbn. left. reflexivity.
    + assert (ord h h' = true) by (apply (sorted_head_relation l h); auto).
      apply anti_sym; auto.
Qed.

(* Unique *)

Theorem sorted_unique_representation {A: Type} `{L: LinearOrder A} :
  forall l l': list A, permutation l l' -> Sorted l -> Sorted l' -> l = l'.
Proof.
  intros l. induction l; intros l' perm sort sort'.
  - destruct l'; auto. specialize (perm (fun _ => true)). cbn in perm. discriminate.
  - destruct l'.
    + specialize (perm (fun _ => true)). cbn in perm. discriminate.
    + assert (a = a0) by (apply (sorted_head_eq l l'); auto). subst.
      f_equal. apply IHl.
      * apply (perm_without_head _ _ a0); auto.
      * apply (sorted_without_head _ a0). auto.
      * apply (sorted_without_head _ a0). auto.
Qed.