Module PNPEX.

From mathcomp.ssreflect
Require Import ssreflect ssrfun eqtype ssrnat ssrbool seq.

Section Chapter2.

(* Exercise 2.1 *)

Fixpoint alternate (s1 : seq nat) (s2 : seq nat) : seq nat :=
  match s1, s2 with
    | nil, nil => nil
    | nil, _   => s2
    | _  , nil => s1
    | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2
  end.

Compute alternate [:: 1;2;3] [:: 4;5;6] = [:: 1;4;2;5;3;6].
Compute alternate [:: 1] [:: 4;5;6] = [:: 1;4;5;6].
Compute alternate [:: 1;2;3] [:: 4] = [:: 1;4;2;3].

End Chapter2.

Section Chapter3.

(* Exercise 3.1 *)

Theorem all_imp_ist A (P Q: A -> Prop):
  (forall x: A, P x -> Q x) -> (forall y, P y) -> forall z, Q z.
Proof.
  move=> H1 H2 z.
  by apply H1.
Qed.

Inductive my_ex A (S: A -> Prop) : Prop := my_ex_intro x of S x.

Theorem ex_imp_ex A (S T: A -> Prop):
  (exists a: A, S a) -> (forall x: A, S x -> T x) -> exists b: A, T b.
Proof.
  case=> a Hs Hst.
  exists a.
  apply Hst.
  apply Hs.
Qed.

(* Exercise 3.2 *)

Goal forall A (S: A -> Prop), my_ex A S <-> exists y: A, S y.
Proof.
  firstorder.
Qed.

(* Exercise 3.3 *)

Require Import Classical_Prop.

Definition peirce_law := forall P Q: Prop, ((P -> Q) -> P) -> P.
Definition peirce := peirce_law.
Definition double_neg := forall P: Prop, ~ ~ P -> P.
Definition excluded_middle := forall P: Prop, P \/ ~P.
Definition de_morgan_not_and_not := forall P Q: Prop, ~ ( ~P /\ ~Q) -> P \/ Q.
Definition implies_to_or := forall P Q: Prop, (P -> Q) -> (~P \/ Q).

Lemma peirce_dn: peirce -> double_neg.
Proof.
  rewrite /peirce /double_neg /peirce_law.
  firstorder.
  apply H with (Q := P).
  move=> H1.
  suff: P.
  exact H1.
  apply NNPP.
  exact H0.
Qed.

Lemma dn_em : double_neg -> excluded_middle.
Proof.
  rewrite /double_neg /excluded_middle.
  (* firstorder. *)
  (* apply classic. *)
  compute.
  intros.
  apply H.
  intuition.
Qed.

Lemma em_dmnan: excluded_middle -> de_morgan_not_and_not.
Proof.
  rewrite /excluded_middle /de_morgan_not_and_not.
  compute.
  intros.
  specialize (H (P \/ Q)).
  inversion H.
  done.
  intuition.
Qed.

Lemma dmnan_ito : de_morgan_not_and_not -> implies_to_or.
Proof.
  rewrite /de_morgan_not_and_not /implies_to_or.
  compute.
  intros.
  specialize (H (P -> False) Q).
  intuition.
Qed.

Lemma ito_peirce : implies_to_or -> peirce.
Proof.
  rewrite /implies_to_or /peirce.
  compute.
  intros.
  specialize (H P P).
  intuition.
Qed.

End Chapter3.

Section Chapter4.

(* Exercise 4.1 *)

Set Implicit Arguments.
Inductive my_eq (A : Type) (x : A) : A -> Prop :=  my_eq_refl : my_eq x x.
Notation "x === y" := (my_eq x y) (at level 70).

Lemma disaster2: 1 === 2 -> False.
Proof.
  move=> H.
  pose D x := if x is 1 then False else True.
  have D2: D 2.
  by [].
  case: H D2.
  move=> /=.
  done.
Qed.

(* Exercise 4.2 *)

(** the best refernce is the source code https://github.com/math-comp/math-comp/blob/master/mathcomp/ssreflect/ssrnat.v *)

Definition maxn m n := if m < n then n else m.

Lemma max_l m n: n <= m -> maxn m n = m.
Proof.
  rewrite /maxn.
  case: leqP=>//.
Qed.

Lemma max_is_max m n: n <= maxn m n /\ m <= maxn m n.
Proof.
  rewrite /maxn.
  case leqP=>//.
  move=>H.
  split.
  by apply leqnn.
  rewrite ltn_neqAle in H.
  by case /andP: H.
Qed.

Lemma maxnE m n : maxn m n = m + (n - m).
Proof. by rewrite /maxn addnC; case: leqP => [/eqnP-> | /ltnW/subnK]. Qed.

Lemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).
Proof.
  rewrite !maxnE.
  rewrite addSn.
  done.
Qed.

Lemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.
Proof.
  rewrite !maxnE.
  rewrite subnDl.
  rewrite addnA.
  done.
Qed.

(* Exercice 4.3 *)

Inductive nat_rels m n : bool -> bool -> bool -> Set :=
  | CompareNatLt of m < n : nat_rels m n true false false
  | CompareNatGt of m > n : nat_rels m n false true false
  | CompareNatEq of m = n : nat_rels m n false false true.

Lemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).
Proof.
  rewrite ltn_neqAle eqn_leq.
  case: ltnP; first by constructor.
  by rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.
Qed.

(* Exercise 4.4 *)

Definition minn m n := if m < n then m else n.

Lemma addn_min_max m n : minn m n + maxn m n = m + n.
Proof.
  rewrite /minn /maxn.
  case: ltngtP => // [_|->] //.
  apply: addnC.
Qed.

End Chapter4.

End PNPEX.


From Undecidability.Shared.Libs.PSL Require Import BasicDefinitions.
From Undecidability.Shared.Libs.PSL Require Import FiniteTypes.FinTypes.
From Undecidability.Shared.Libs.PSL Require Import Vectors.Vectors.
From Undecidability.Shared.Libs.PSL Require Import Vectors.VectorDupfree.
Import VectorNotations2.
From Undecidability.Shared.Libs.PSL Require Import FiniteTypes.Cardinality.

Definition Fin_initVect (n : nat) : Vector.t (Fin.t n) n :=
  tabulate (fun i : Fin.t n => i).

Lemma Fin_initVect_dupfree n :
  dupfree (Fin_initVect n).
Proof.
  unfold Fin_initVect.
  eapply dupfree_tabulate_injective.
  firstorder.
Qed.

Lemma Fin_initVect_full n k :
  Vector.In k (Fin_initVect n).
Proof.
  unfold Fin_initVect.
  apply in_tabulate. eauto.
Qed.

Definition Fin_initVect_nth (n : nat) (k : Fin.t n) :
  Vector.nth (Fin_initVect n) k = k.
Proof. unfold Fin_initVect. apply nth_tabulate. Qed.

Import VecToListCoercion.

#[global]
Instance Fin_finTypeC n : finTypeC (EqType (Fin.t n)).
Proof.
  constructor 1 with (enum := Fin_initVect n).
  intros x. cbn in x.
  eapply dupfreeCount.
  - eapply tolist_dupfree. apply Fin_initVect_dupfree.
  - eapply tolist_In. apply Fin_initVect_full.
Defined.

#[export] Hint Extern 4 (finTypeC (EqType (Fin.t _))) => eapply Fin_finTypeC : typeclass_instances.

Lemma Fin_cardinality n : Cardinality (finType_CS (Fin.t n)) = n.
Proof.
  unfold Cardinality, elem, enum. cbn. unfold Fin_initVect. now rewrite vector_to_list_length.
Qed.

(* Function that produces a list of all Vectors of length n over A *)
Fixpoint Vector_pow {X: Type} (A: list X) n {struct n} : list (Vector.t X n) :=
  match n with
  | 0 => [Vector.nil _]
  | S n => concat (map (fun a => map (fun v => a:::v) (Vector_pow A n) ) A)
  end.

#[global]
Instance Vector_finTypeC (A:finType) n: finTypeC (EqType (Vector.t A n)).
Proof.
  exists (undup ((Vector_pow (elem A) n))). cbn in *.
  intros v. eapply dupfreeCount.
  - eapply dupfree_undup.
  - rewrite undup_id_equi. induction v; cbn.
    + eauto.
    + eapply in_concat_iff. eexists; split.
      2:eapply in_map_iff. 2:eexists.
      2:split. 2:reflexivity.
      eapply in_map_iff. eauto.
      eapply elem_spec.
Defined.

#[export] Hint Extern 4 (finTypeC (EqType (Vector.t _ _))) => eapply Vector_finTypeC : typeclass_instances.

Lemma ProdCount (T1 T2: eqType) (A: list T1) (B: list T2) (a:T1) (b:T2)  :
  FinTypesDef.count (prodLists A B) (a,b) =  FinTypesDef.count A a * FinTypesDef.count B b .
Proof.
  induction A.
  - reflexivity.
  - cbn. rewrite <- countSplit. decide (a = a0) as [E | E].
    + cbn. f_equal. subst a0. apply countMap. eauto.
    + rewrite <- plus_O_n. f_equal. now apply countMapZero. eauto.
Qed.

Lemma prod_enum_ok (T1 T2: finType) (x: T1 * T2):
  FinTypesDef.count (prodLists (elem T1) (elem T2)) x = 1.
Proof.
  destruct x as [x y]. rewrite ProdCount. unfold elem.
  now repeat rewrite enum_ok.
Qed.

Global
Instance finTypeC_Prod (F1 F2: finType) : finTypeC (EqType (F1 * F2)).
Proof.
  econstructor.  apply prod_enum_ok.
Defined.


(** * H4: Nierówność i różność [TODO] *)

Set Universe Polymorphism.

Require Import Arith.
Require Import Bool.
Require Import Equality.
Require Import FunctionalExtensionality.

Require Import List.
Import ListNotations.

From Typonomikon Require Import H1.
From Typonomikon Require Import D5.

(** * Różność *)

(** ** Nierówność liczb naturalnych - rekurencyjnie *)

Module nat_neq_rec.

(** A co to znaczy, że liczby naturalne nie są równe? *)

(** Powinien być tylko jeden dowód na nierówność. *)

Fixpoint code (n m : nat) : Type :=
match n, m with
| 0, 0 => False
| 0, S _ => True
| S _, 0 => True
| S n', S m' => code n' m'
end.

Lemma isProp_code :
  forall {n m : nat} (c1 c2 : code n m), c1 = c2.
(* begin hide *)
Proof.
  induction n as [| n'], m as [| m']; cbn.
    1-3: destruct c1, c2; reflexivity.
    apply IHn'.
Qed.
(* end hide *)

Fixpoint encode {n m : nat} {struct n} : n <> m -> code n m.
(* begin hide *)
Proof.
  destruct n as [| n'], m as [| m']; cbn; intro p.
    apply p. reflexivity.
    exact I.
    exact I.
    apply encode. intro q. apply p. f_equal. exact q.
Defined.
(* end hide *)

Fixpoint decode {n m : nat} : code n m -> n <> m.
(* begin hide *)
Proof.
  destruct n as [| n'], m as [| m']; cbn; intro p.
    contradiction.
    inversion 1.
    inversion 1.
    intro q. apply (decode _ _ p). inversion q. reflexivity.
Defined.
(* end hide *)

Lemma encode_decode :
  forall {n m : nat} (p : n <> m),
    decode (encode p) = p.
Proof.
  intros.
  apply functional_extensionality.
  destruct x.
  contradiction.
Qed.

Lemma decode_encode :
  forall {n m : nat} (c : code n m),
    encode (decode c) = c.
Proof.
  intros.
  apply isProp_code.
Qed.

End nat_neq_rec.

(** ** Nierówność liczb naturalnych - induktywnie *)

Module nat_neq_ind.

Inductive nat_neq : nat -> nat -> Prop :=
| ZS : forall n : nat, nat_neq 0 (S n)
| SZ : forall n : nat, nat_neq (S n) 0
| SS : forall n m : nat, nat_neq n m -> nat_neq (S n) (S m).

Arguments ZS {n}.
Arguments SZ {n}.
Arguments SS {n m} _.

Scheme nat_neq_ind' := Induction for nat_neq Sort Prop.

Lemma isProp_nat_neq :
  forall {n m : nat} (p q : nat_neq n m), p = q.
(* begin hide *)
Proof.
  induction p using nat_neq_ind';
  dependent destruction q.
    reflexivity.
    reflexivity.
    apply f_equal, IHp.
Qed.
(* end hide *)

Fixpoint encode {n m : nat} : n <> m -> nat_neq n m :=
match n, m with
| 0, 0       => fun p => match p eq_refl with end
| 0, S m'    => fun _ => @ZS m'
| S n', 0    => fun _ => @SZ n'
| S n', S m' => fun p => SS (@encode n' m' (fun p' => p (f_equal S p')))
end.

Fixpoint decode {n m : nat} (c : nat_neq n m) : n <> m.
Proof.
  destruct c.
    inversion 1.
    inversion 1.
    inversion 1. apply (decode _ _ c). assumption.
Defined.

Lemma encode_decode :
  forall {n m : nat} (p : n <> m),
    decode (encode p) = p.
(* begin hide *)
Proof.
  induction n as [| n'];
  destruct  m as [| m'];
  cbn; intros.
    contradiction.
    apply functional_extensionality. inversion x.
    apply functional_extensionality. inversion x.
    apply functional_extensionality. intro. contradiction.
Qed.
(* end hide *)

Lemma decode_encode :
  forall {n m : nat} (c : nat_neq n m),
    encode (decode c) = c.
(* begin hide *)
Proof.
  induction c using nat_neq_ind'; cbn.
    1-2: reflexivity.
    f_equal. rewrite <- IHc. f_equal.
      apply functional_extensionality.
      destruct x. cbn. rewrite IHc. reflexivity.
Qed.
(* end hide *)

End nat_neq_ind.

Module nat_eq_neq.

Import nat_eq_ind nat_neq_ind.

Lemma nat_eq_dec :
  forall n m : nat, nat_eq n m + nat_neq n m.
(* begin hide *)
Proof.
  induction n as [| n']; destruct m as [| m'].
  - left. constructor.
  - right. constructor.
  - right. constructor.
  - destruct (IHn' m').
    + left. constructor. assumption.
    + right. constructor. assumption.
Qed.
(* end hide *)

End nat_eq_neq.

(** ** Nierówność list - rekursywnie *)

Fixpoint list_neq_rec {A : Type} (l1 l2 : list A) : Prop :=
match l1, l2 with
| [], [] => False
| [], _ => True
| _, [] => True
| h1 :: t1, h2 :: t2 => h1 <> h2 \/ list_neq_rec t1 t2
end.

Lemma list_neq_rec_spec :
  forall (A : Type) (l1 l2 : list A),
    list_neq_rec l1 l2 -> l1 <> l2.
(* begin hide *)
Proof.
  induction l1 as [| h1 t1];
  destruct l2 as [| h2 t2];
  cbn; intros.
    contradiction.
    congruence.
    congruence.
    inversion 1; subst. destruct H.
      contradiction.
      apply (IHt1 _ H). reflexivity.
Qed.
(* end hide *)

(** ** Nierówność list - induktywnie *)

Inductive list_neq_ind {A : Type} : list A -> list A -> Prop :=
| nil_cons : forall h t, list_neq_ind nil (cons h t)
| cons_nil : forall h t, list_neq_ind (cons h t) nil
| cons_cons1 :
    forall h1 h2 t1 t2,
      h1 <> h2 -> list_neq_ind (cons h1 t1) (cons h2 t2)
| cons_cons2 :
    forall h1 h2 t1 t2,
      list_neq_ind t1 t2 -> list_neq_ind (cons h1 t1) (cons h2 t2).

Lemma list_neq_ind_spec :
  forall {A : Type} (l1 l2 : list A),
    list_neq_ind l1 l2 -> l1 <> l2.
Proof.
  induction 1; cbn; congruence.
Qed.

Lemma list_neq_ind_list_neq_rec :
  forall {A : Type} (l1 l2 : list A),
    list_neq_ind l1 l2 -> list_neq_rec l1 l2.
Proof.
  induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; inversion_clear 1.
  1-2: trivial.
  - left. assumption.
  - right. apply IHt1. assumption.
Qed.

(** ** Różność (słaby apartheid) list - rekursywnie *)

Fixpoint list_apart_rec
  {A : Type} (R : A -> A -> Prop) (l1 l2 : list A) : Prop :=
match l1, l2 with
| [], [] => False
| h1 :: t1, h2 :: t2 => R h1 h2 \/ list_apart_rec R t1 t2
| _, _ => True
end.

Lemma list_apart_list_neq_rec :
  forall {A : Type} (R : A -> A -> Prop) (l1 l2 : list A),
    (forall x y : A, R x y -> x <> y) ->
      list_apart_rec R l1 l2 -> list_neq_rec l1 l2.
Proof.
  induction l1 as [| h1 t1 IH]; destruct l2 as [| h2 t2]; cbn; firstorder.
Qed.

(** ** Różność (silny apartheid) list - rekursywnie *)

Fixpoint list_strong_apart_rec
  {A : Type} (R : A -> A -> Type) (l1 l2 : list A) : Type :=
match l1, l2 with
| [], [] => False
| h1 :: t1, h2 :: t2 => R h1 h2 + list_strong_apart_rec R t1 t2
| _, _ => True
end.

Lemma list_strong_apart_rec_list_apart :
  forall {A : Type} (R : A -> A -> Prop) (l1 l2 : list A),
    (forall x y : A, R x y -> x <> y) ->
      list_strong_apart_rec R l1 l2 -> list_apart_rec R l1 l2.
Proof.
  induction l1 as [| h1 t1 IH]; destruct l2 as [| h2 t2]; cbn; firstorder.
Qed.

(** ** Różność list - induktywnie *)

Module list_neq_ind.

Inductive list_neq
  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=
| nc  : forall (h : A) (t : list A), list_neq R [] (h :: t)
| cn  : forall (h : A) (t : list A), list_neq R (h :: t) []
| cc1 : forall (h1 h2 : A) (t1 t2 : list A),
          R h1 h2 -> list_neq R (h1 :: t1) (h2 :: t2)
| cc2 : forall (h1 h2 : A) (t1 t2 : list A),
          list_neq R t1 t2 -> list_neq R (h1 :: t1) (h2 :: t2).

#[global] Hint Constructors list_neq : core.

Lemma list_neq_irrefl_aux :
  forall {A : Type} {R : A -> A -> Prop} (l1 l2 : list A),
    (forall x : A, R x x -> False) ->
      list_neq R l1 l2 -> l1 <> l2.
(* begin hide *)
Proof.
  induction 2; inversion 1; subst.
    apply (H _ r).
    apply IHX. reflexivity.
Defined.
(* end hide *)

Lemma list_neq_irrefl_sym :
  forall {A : Type} {R : A -> A -> Prop} (l1 l2 : list A),
    (forall x y : A, R x y -> R y x) ->
      list_neq R l1 l2 -> list_neq R l2 l1.
(* begin hide *)
Proof.
  induction 2.
    1-3: constructor. apply H. assumption.
    constructor 4. assumption.
Defined.
(* end hide *)

Lemma list_neq_cotrans :
  forall {A : Type} {R : A -> A -> Prop} (l1 l3 : list A),
    (forall x y z : A, R x z -> R x y + R y z) ->
      list_neq R l1 l3 -> forall l2 : list A,
        list_neq R l1 l2 + list_neq R l2 l3.
(* begin hide *)
Proof.
  induction 2; intros.
    destruct l2; [right | left]; constructor.
    destruct l2; [left | right]; constructor.
    destruct l2 as [| h t].
      left. constructor.
      destruct (X _ h _ r).
        left. constructor. assumption.
        right. constructor. assumption.
    destruct l2 as [| h t].
      left. constructor.
      destruct (IHX0 t).
        left. constructor 4. assumption.
        right. constructor 4. assumption.
Defined.
(* end hide *)

Inductive Exists2
  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=
| E2_here :
    forall {h1 h2 : A} (t1 t2 : list A),
      R h1 h2 -> Exists2 R (h1 :: t1) (h2 :: t2)
| E2_there :
    forall {h1 h2 : A} {t1 t2 : list A},
      Exists2 R t1 t2 -> Exists2 R (h1 :: t1) (h2 :: t2).

Lemma Exists2_list_neq :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    Exists2 R l1 l2 -> list_neq R l1 l2.
(* begin hide *)
Proof.
  induction 1.
    constructor. assumption.
    constructor 4. assumption.
Qed.
(* end hide *)

Inductive DifferentStructure
  {A : Type} : list A -> list A -> Type :=
| DS_nc :
    forall (h : A) (t : list A),
      DifferentStructure [] (h :: t)
| DS_cn :
    forall (h : A) (t : list A),
      DifferentStructure (h :: t) []
| DS_cc :
    forall (h1 h2 : A) {t1 t2 : list A},
      DifferentStructure t1 t2 ->
        DifferentStructure (h1 :: t1) (h2 :: t2).

(** Insajt, że o ja pierdole: [list_neq] to w sumie [Exists2] lub
    [DifferentStructure], czyli listy różnią się, gdy różnią się
    na którymś elemencie lub mają różną długość. *)

Lemma lnE2 :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    list_neq R l1 l2 -> Exists2 R l1 l2 + DifferentStructure l1 l2.
(* begin hide *)
Proof.
  induction 1.
    right. constructor.
    right. constructor.
    left. constructor. assumption.
    destruct IHX.
      left. constructor 2. assumption.
      right. constructor. assumption.
Defined.
(* end hide *)

Lemma lnE2_conv :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    Exists2 R l1 l2 + DifferentStructure l1 l2 -> list_neq R l1 l2.
(* begin hide *)
Proof.
  destruct 1.
    induction e.
      constructor. assumption.
      constructor 4. assumption.
    induction d.
      constructor.
      constructor.
      constructor 4. assumption.
Defined.
(* end hide *)

Lemma okurwa :
  forall
    (A : Type) (R : A -> A -> Type) (h1 h2 : A) (t1 t2 : list A)
    (r1 : R h1 h2) (r2 : R h1 h2),
      @inl _
        (DifferentStructure (h1 :: t1) (h2 :: t2))
        (E2_here R t1 t2 r1)
      =
      inl (E2_here R t1 t2 r2) ->
        r1 = r2.
(* begin hide *)
Proof.
  assert (forall (A B : Type) (x y : A), @inl A B x = inl y -> x = y).
    inversion 1. reflexivity.
  intros. apply H in H0.
  apply (f_equal
    (fun x : Exists2 R (h1 :: t1) (h2 :: t2) =>
      match x with
      | E2_here _ _ _ r => Some r
      | _             => None
      end))
  in H0.
  inversion H0. reflexivity.
Qed.
(* end hide *)

Lemma lnE2_lnE2_conv :
  forall
    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}
    (c : list_neq R l1 l2),
      lnE2_conv (lnE2 c) = c.
(* begin hide *)
Proof.
  induction c; cbn.
    1-3: reflexivity.
    destruct (list_neq_rect A R _) eqn: Heq.
      cbn. f_equal. induction e; cbn in *.
        dependent destruction c; cbn in *.
          f_equal. symmetry. apply okurwa in Heq. assumption.
          cbn in *. rewrite Heq in IHc. cbn in IHc. inversion IHc.
        dependent destruction c.
          cbn in *. inversion Heq.
          cbn in *. rewrite Heq in IHc. cbn in IHc. assumption.
      cbn. f_equal. dependent destruction c; cbn in *.
        inversion Heq; subst; cbn. reflexivity.
        inversion Heq; subst; cbn. reflexivity.
        inversion Heq.
        rewrite Heq in IHc. cbn in IHc. assumption.
Qed.
(* end hide *)

Lemma lnE2_conv_lnE2 :
  forall
    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}
    (x : Exists2 R l1 l2 + DifferentStructure l1 l2),
      lnE2 (lnE2_conv x) = x.
(* begin hide *)
Proof.
  destruct x.
    induction e; cbn in *.
      reflexivity.
      destruct (list_neq_rect A R _); inversion IHe. reflexivity.
    induction d; cbn in *.
      reflexivity.
      reflexivity.
      destruct (list_neq_rect A R _); inversion IHd. reflexivity.
Qed.
(* end hide *)

Inductive DifferentStructure'
  {A : Type} : list A -> list A -> SProp :=
| DS'_nc :
    forall (h : A) (t : list A),
      DifferentStructure' [] (h :: t)
| DS'_cn :
    forall (h : A) (t : list A),
      DifferentStructure' (h :: t) []
| DS'_cc :
    forall (h1 h2 : A) {t1 t2 : list A},
      DifferentStructure' t1 t2 ->
        DifferentStructure' (h1 :: t1) (h2 :: t2).

Lemma DS_DS' :
  forall {A : Type} {l1 l2 : list A},
    DifferentStructure l1 l2 -> DifferentStructure' l1 l2.
(* begin hide *)
Proof.
  induction 1; constructor; assumption.
Qed.
(* end hide *)

Inductive sEmpty : SProp := .

Lemma sEmpty_rec' :
  forall A : Type, sEmpty -> A.
(* begin hide *)
Proof.
  destruct 1.
Qed.
(* end hide *)

Lemma DS'_spec :
  forall {A : Type} {l1 l2 : list A},
    DifferentStructure' l1 l2 -> l1 <> l2.
(* begin hide *)
Proof.
  induction l1 as [| h1 t1];
  destruct l2 as [| h2 t2];
  cbn; intros H Heq; inv Heq.
    apply sEmpty_rec'. inv H.
    apply (IHt1 t2).
      inv H. assumption.
      reflexivity.
Defined.
(* end hide *)

Lemma DS'_DS :
  forall {A : Type} {l1 l2 : list A},
    DifferentStructure' l1 l2 -> DifferentStructure l1 l2.
(* begin hide *)
Proof.
  induction l1 as [| h1 t1];
  destruct l2 as [| h2 t2];
  cbn; intros; try constructor.
    apply sEmpty_rec'. inv H.
    apply IHt1. inv H. assumption.
Defined.
(* end hide *)

Lemma isProp_DS :
  forall
    {A : Type} {l1 l2 : list A}
    (p q : DifferentStructure l1 l2),
      p = q.
(* begin hide *)
Proof.
  induction p; intro q.
    refine (match q with DS_nc _ _   => _ end). reflexivity.
    refine (match q with DS_cn _ _   => _ end). reflexivity.
    dependent destruction q. f_equal. apply IHp.
Qed.
(* end hide *)

Lemma DS_DS'_DS :
  forall {A : Type} {l1 l2 : list A} (p : DifferentStructure l1 l2),
    DS'_DS (DS_DS' p) = p.
(* begin hide *)
Proof.
  intros. apply isProp_DS.
Qed.
(* end hide *)

Lemma DS'_DS_DS' :
  forall {A : Type} {l1 l2 : list A} (p : DifferentStructure' l1 l2),
    DS_DS' (DS'_DS p) = p.
Proof.
  reflexivity.
Abort.

Inductive sor (A : Type) (B : SProp) : Type :=
| sinl : A -> sor A B
| sinr : B -> sor A B.

Arguments sinl {A B} _.
Arguments sinr {A B} _.

Lemma lnE2' :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    list_neq R l1 l2 -> sor (Exists2 R l1 l2) (DifferentStructure' l1 l2).
(* begin hide *)
Proof.
  induction 1.
    right. constructor.
    right. constructor.
    left. constructor. assumption.
    destruct IHX.
      left. constructor 2. assumption.
      right. constructor. assumption.
Defined.
(* end hide *)

Lemma lnE2'_conv :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    sor (Exists2 R l1 l2) (DifferentStructure' l1 l2) -> list_neq R l1 l2.
(* begin hide *)
Proof.
  destruct 1.
    induction e.
      constructor. assumption.
      constructor 4. assumption.
    revert l2 d.
    induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; intro.
      apply sEmpty_rec'. inv d.
      constructor.
      constructor.
      constructor 4. apply IHt1. inv d. assumption.
Defined.
(* end hide *)

Lemma okurwa' :
  forall
    (A : Type) (R : A -> A -> Type) (h1 h2 : A) (t1 t2 : list A)
    (r1 : R h1 h2) (r2 : R h1 h2),
      @sinl _
        (DifferentStructure' (h1 :: t1) (h2 :: t2))
        (E2_here R t1 t2 r1)
      =
      sinl (E2_here R t1 t2 r2) ->
        r1 = r2.
(* begin hide *)
Proof.
  assert (forall A B (x y : A), @sinl A B x = sinl y -> x = y).
    inversion 1. reflexivity.
  intros. apply H in H0.
  apply (f_equal
    (fun x : Exists2 R (h1 :: t1) (h2 :: t2) =>
      match x with
      | E2_here _ _ _ r => Some r
      | _             => None
      end))
  in H0.
  inversion H0. reflexivity.
Qed.
(* end hide *)

Lemma lnE2'_lnE2'_conv :
  forall
    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}
    (c : list_neq R l1 l2),
      lnE2'_conv (lnE2' c) = c.
(* begin hide *)
Proof.
  induction c; cbn.
    1-3: reflexivity.
    destruct (list_neq_rect A R _) eqn: Heq.
      cbn. f_equal. induction e; cbn in *.
        dependent destruction c; cbn in *.
          f_equal. symmetry. apply okurwa' in Heq. assumption.
          cbn in *. rewrite Heq in IHc. cbn in IHc. inversion IHc.
        dependent destruction c.
          cbn in *. inversion Heq.
          cbn in *. rewrite Heq in IHc. cbn in IHc. assumption.
      cbn. f_equal. dependent destruction c; cbn in *.
        inversion Heq; subst; cbn. reflexivity.
        inversion Heq; subst; cbn. reflexivity.
        inversion Heq.
        rewrite Heq in IHc. cbn in IHc. assumption.
Qed.
(* end hide *)

Lemma lnE2'_conv_lnE2' :
  forall
    {A : Type} {R : A -> A -> Prop} {l1 l2 : list A}
    (x : sor (Exists2 R l1 l2) (DifferentStructure' l1 l2)),
      lnE2' (lnE2'_conv x) = x.
Proof.
  destruct x.
    induction e; cbn in *.
      reflexivity.
      destruct (list_neq_rect A R _); inversion IHe. reflexivity.
    revert l2 d.
    induction l1 as [| h1 t1]; destruct l2 as [| h2 t2]; cbn; intro.
      apply sEmpty_rec. inv d.
      reflexivity.
      reflexivity.
Abort.

(** Wnioski: próba użycia tutaj [SProp] jest bardzo poroniona. *)

End list_neq_ind.

(** ** Nierówność liczb konaturalnych - induktywnie *)

From Typonomikon Require F2.

Module conat_neq.

Import F3.

Inductive conat_neq : conat -> conat -> Prop :=
| cnzs :
    forall c : conat, conat_neq zero (succ c)
| cnsz :
    forall c : conat, conat_neq (succ c) zero
| cnss :
    forall n m : conat, conat_neq n m -> conat_neq (succ n) (succ m).

Lemma conat_neq_spec :
  forall n m : conat,
    conat_neq n m -> n <> m.
(* begin hide *)
Proof.
  induction 1; intro Heq; inversion Heq; congruence.
Qed.
(* end hide *)

Lemma conat_neq_irrefl :
  forall n : conat, ~ conat_neq n n.
(* begin hide *)
Proof.
  intros n Hneq. eapply conat_neq_spec; eauto.
Qed.
(* end hide *)

End conat_neq.

(** ** Nierówność strumieni *)

From Typonomikon Require F3.

Module Stream_neq.

Import F2.

Inductive Stream_neq
  {A : Type} : Stream A -> Stream A -> Type :=
| Stream_apart_hd' :
    forall t1 t2 : Stream A,
      hd t1 <> hd t2 -> Stream_neq t1 t2
| Stream_apart_tl' :
    forall t1 t2 : Stream A,
      Stream_neq (tl t1) (tl t2) -> Stream_neq t1 t2.

Lemma Stream_neq_not_sim :
  forall {A : Type} {s1 s2 : Stream A},
    Stream_neq s1 s2 -> ~ sim s1 s2.
(* begin hide *)
Proof.
  induction 1; intros []; contradiction.
Qed.
(* end hide *)

Lemma Stream_neq_neq :
  forall {A : Type} {s1 s2 : Stream A},
    Stream_neq s1 s2 -> s1 <> s2.
(* begin hide *)
Proof.
  induction 1; intros ->; contradiction.
Qed.
(* end hide *)

End Stream_neq.

(** ** Różność (słaby apartheid) strumieni - induktywnie *)

From Typonomikon Require F3.

Module Stream_apart.

Import F2 Stream_neq.

Inductive Stream_apart
  {A : Type} (R : A -> A -> Prop) : Stream A -> Stream A -> Type :=
| Stream_apart_hd :
    forall (h1 h2 : A) (t1 t2 : Stream A),
      R h1 h2 -> Stream_apart R (scons h1 t1) (scons h2 t2)
| Stream_apart_tl :
    forall (h1 h2 : A) (t1 t2 : Stream A),
      Stream_apart R t1 t2 -> Stream_apart R (scons h1 t1) (scons h2 t2).

Lemma Stream_apart_not_sim :
  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},
    (forall x : A, ~ R x x) ->
      Stream_apart R s1 s2 -> ~ sim s1 s2.
(* begin hide *)
Proof.
  induction 2; intros Hsim; inversion Hsim; cbn in *; subst; clear Hsim.
  - apply (H h2). assumption.
  - contradiction.
Qed.
(* end hide *)

Lemma Stream_neq_Stream_apart :
  forall {A : Type} {s1 s2 : Stream A},
    Stream_neq s1 s2 ->
      Stream_apart (fun x y => x <> y) s1 s2.
(* begin hide *)
Proof.
  induction 1.
Admitted.
(*
  - destruct t1, t2. cbn in *. left. assumption.
  - destruct t1, t2. cbn in *. right. assumption.
Qed.
*)
(* end hide *)

Lemma Stream_apart_Stream_neq :
  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},
    (forall x : A, ~ R x x) ->
      Stream_apart R s1 s2 -> Stream_neq s1 s2.
(* begin hide *)
Proof.
  induction 2.
  - left. cbn. intro. subst. apply (H _ r).
  - right. cbn. assumption.
Qed.
(* end hide *)

End Stream_apart.

(** ** Różność (silny apartheid) strumieni - induktywnie *)

From Typonomikon Require F3.

Module Stream_strong_apart.

Import F2 Stream_apart.

Inductive Stream_strong_apart
  {A : Type} (R : A -> A -> Type) : Stream A -> Stream A -> Type :=
| Stream_strong_apart_hd :
    forall s1 s2 : Stream A,
      R (hd s1) (hd s2) -> Stream_strong_apart R s1 s2
| Stream_strong_apart_tl :
    forall s1 s2 : Stream A,
      Stream_strong_apart R (tl s1) (tl s2) -> Stream_strong_apart R s1 s2.

Lemma Stream_strong_apart_spec :
  forall {A : Type} {R : A -> A -> Prop} {s1 s2 : Stream A},
    (forall x : A, ~ R x x) ->
      Stream_strong_apart R s1 s2 -> Stream_apart R s1 s2.
(* begin hide *)
Proof.
  intros A R s1 s2 HR HSsa; induction HSsa.
Admitted.
(* end hide *)

End Stream_strong_apart.

(** ** Różność kolist *)

From Typonomikon Require F4.

Module CoList_apart.

Import F4.

Inductive CoList_apart {A : Type} (R : A -> A -> Type) (l1 l2 : CoList A) : Type :=
| CLa_nil_cons :
    uncons l1 = NilF -> uncons l2 <> NilF -> CoList_apart R l1 l2
| CLa_cons_nil :
    uncons l1 <> NilF -> uncons l2 = NilF -> CoList_apart R l1 l2
| CLa_head :
    forall
      {h1 : A} {t1 : CoList A} (Hu1 : uncons l1 = ConsF h1 t1)
      {h2 : A} {t2 : CoList A} (Hu2 : uncons l2 = ConsF h2 t2),
        R h1 h2 -> CoList_apart R l1 l2
| CLa_tail :
    forall
      {h1 : A} {t1 : CoList A} (Hu1 : uncons l1 = ConsF h1 t1)
      {h2 : A} {t2 : CoList A} (Hu2 : uncons l2 = ConsF h2 t2),
        CoList_apart R t1 t2 -> CoList_apart R l1 l2.

Lemma CoList_apart_spec :
  forall {A : Type} {R : A -> A -> Type} {l1 l2 : CoList A},
    (forall x : A, R x x -> False) ->
      CoList_apart R l1 l2 -> ~ lsim l1 l2.
(* begin hide *)
Proof.
  intros A R l1 l2 HR; induction 1; intros [Hlsim].
  - inversion Hlsim; subst; clear Hlsim; congruence.
  - inversion Hlsim; subst; clear Hlsim; congruence.
  - inversion Hlsim; subst; clear Hlsim.
    + congruence.
    + apply (HR h3). congruence.
  - inversion Hlsim; subst; clear Hlsim; congruence.
Qed.
(* end hide *)

End CoList_apart.

(** ** Różność funkcji *)

(** Funkcje są różne (w silnym sensie), gdy różnią się dla jakiegoś
    argumentu. *)

Inductive fun_apart
  {A B : Type} (R : B -> B -> Type) (f g : A -> B) : Type :=
| fun_apart' : forall {x : A}, R (f x) (g x) -> fun_apart R f g.

Lemma fun_apart_spec :
  forall {A B : Type} (R : B -> B -> Type) (f g : A -> B),
    (forall x : B, R x x -> False) ->
      fun_apart R f g -> f <> g.
(* begin hide *)
Proof.
  intros A B R f g HR [x r] ->.
  apply (HR (g x)). apply r.
Qed.
(* end hide *)

Lemma fun_apart_spec' :
  forall {A B : Type} (R : B -> B -> Type) (f g : A -> B),
    (forall x : B, R x x -> False) ->
      fun_apart R f g -> ~ (forall x : A, f x = g x).
(* begin hide *)
Proof.
  intros A B R f g HR [x r] Hext.
  apply (HR (g x)). rewrite <- Hext at 1. assumption.
Qed.
(* end hide *)

Inductive dep_fun_apart
  {A : Type} {B : A -> Type}
  (R : forall x : A, B x -> B x -> Type)
  (f g : forall x : A, B x) : Type :=
| dep_fun_apart' : forall {x : A}, R x (f x) (g x) -> dep_fun_apart R f g.

Lemma dep_fun_apart_spec :
  forall
    {A : Type} {B : A -> Type}
    (R : forall x : A, B x -> B x -> Type)
    (f g : forall x : A, B x)
    (HR : forall {x : A} (y : B x), R x y y -> False),
      dep_fun_apart R f g -> f <> g.
(* begin hide *)
Proof.
  intros A B R f g HR [x r] ->.
  apply (HR _ (g x)). apply r.
Qed.
(* end hide *)

Lemma dep_fun_apart_spec' :
  forall
    {A : Type} {B : A -> Type}
    (R : forall x : A, B x -> B x -> Type)
    (f g : forall x : A, B x)
    (HR : forall {x : A} (y : B x), R x y y -> False),
      dep_fun_apart R f g -> ~ (forall x : A, f x = g x).
(* begin hide *)
Proof.
  intros A B R f g HR [x r] Hext.
  apply (HR _ (g x)). rewrite <- Hext at 1. assumption.
Qed.
(* end hide *)

(** * Protokoły różnicowe *)

Module DiffProtocols.

(** [list_neq_ind.list_neq] to pokazanie na odpowiadające sobie miejsca w
    dwóch listach, które różnią się znajdującym się tam elementem. *)

Inductive ListDiffProtocol
  {A : Type} (R : A -> A -> Type) : list A -> list A -> Type :=
| nn'  : ListDiffProtocol R [] []
| nc'  : forall (h : A) (t : list A), ListDiffProtocol R [] (h :: t)
| cn'  : forall (h : A) (t : list A), ListDiffProtocol R (h :: t) []
| cc1' :
  forall (h1 h2 : A) (t1 t2 : list A),
    R h1 h2 -> ListDiffProtocol R t1 t2 ->
      ListDiffProtocol R (h1 :: t1) (h2 :: t2)
| cc2' :
  forall (h : A) (t1 t2 : list A),
    ListDiffProtocol R t1 t2 ->
      ListDiffProtocol R (h :: t1) (h :: t2).

(** [ListDiffProtocol] to sprawozdanie mówiące, w których miejscach listy
    się różnią, a w których są takie same (i od którego miejsca jedna jest
    dłuższa od drugiej).

    Spróbujmy udowodnić, że jeżeli elementy mogą się różnić tylko na
    jeden sposób, to protokół jest unikalny. *)

Lemma isProp_ListDiffProtocol :
  forall {A : Type} {R : A -> A -> Prop} {l1 l2 : list A},
    (forall (x y : A) (p q : R x y), p = q) ->
    (forall x : A, ~ R x x) ->
      forall p q : ListDiffProtocol R l1 l2, p = q.
Proof.
  induction p; dependent destruction q; try reflexivity; f_equal.
    apply H.
    apply IHp.
    destruct (H0 _ r).
    destruct (H0 _ r).
    apply IHp.
Qed.

(** Protokoły są zwrotne i symetryczne, ale niekoniecznie przechodnie. *)

Lemma proto_refl :
  forall {A : Type} {R : A -> A -> Type} (l : list A),
    ListDiffProtocol R l l.
(* begin hide *)
Proof.
  induction l as [| h t]; cbn.
    constructor.
    constructor 5. assumption.
Qed.
(* end hide *)

Lemma proto_sym :
  forall {A : Type} {R : A -> A -> Type} {l1 l2 : list A},
    (forall x y : A, R x y -> R y x) ->
      ListDiffProtocol R l1 l2 -> ListDiffProtocol R l2 l1.
(* begin hide *)
Proof.
  induction 2.
    1-4: constructor.
      apply X. assumption.
      assumption.
    constructor 5. assumption.
Qed.
(* end hide *)

#[global] Hint Constructors ListDiffProtocol : core.

Lemma proto_trans :
  forall {A : Type} {R : A -> A -> Type} {l1 l2 l3 : list A},
    (forall x y z : A, R x y -> R y z -> R x z) ->
      ListDiffProtocol R l1 l2 -> ListDiffProtocol R l2 l3 ->
        ListDiffProtocol R l1 l3.
Proof.
  intros * H HLDP. revert l3.
  induction HLDP; inversion 1; subst; auto.
    admit.
Abort.

(** Protokół różnicowy dla funkcji mówi, dla których argumentów wyniki
    są takie same, a dla których są różne. *)

Definition FunDiffProtocol
  {A B : Type} (R : B -> B -> Prop) (f g : A -> B) : Type :=
    forall x : A, f x = g x \/ R (f x) (g x).

End DiffProtocols.


Require Import Arith Coq.Lists.List Setoid Coq.Lists.SetoidList Omega.
Require Export Infra.Option EqDec AutoIndTac Util Get Drop.

Set Implicit Arguments.

Fixpoint take n X (L:list X) :=
  match n, L with
    | S n, x::L => x::take n L
    | _, _ => nil
  end.

Lemma take_nil (X:Type) n
  : @take n X nil = nil.
Proof.
  destruct n; eauto.
Qed.

Lemma get_take_lt k X (L:list X) n x
: get (take k L) n x -> n < k.
Proof.
  intros. general induction k; destruct L; simpl in *; isabsurd.
  - inv H; eauto; try omega.
    + exploit IHk; eauto. omega.
Qed.

Lemma get_take_get k X (L:list X) n x
: get (take k L) n x -> get L n x.
Proof.
  intros. general induction k; destruct L; simpl in *; isabsurd.
  inv H; eauto using get.
Qed.

Lemma take_length_le X (L:list X) n
  : n <= length L -> length (take n L) = n.
Proof.
  intros. general induction L; destruct n; simpl in *; try omega; eauto.
  rewrite IHL; eauto; omega.
Qed.

Lemma take_length_ge X (L:list X) n
  : n >= length L -> length (take n L) = length L.
Proof.
  intros. general induction L; destruct n; simpl in *; try omega; eauto.
  rewrite IHL; eauto; omega.
Qed.

Lemma take_length X (L:list X) n
  : length (take n L) = min (length L) n.
Proof.
  decide (n < length L).
  - rewrite take_length_le; try omega.
    rewrite min_r; omega.
  - eapply not_lt in n0.
    rewrite min_l; try omega.
    eapply take_length_ge; eauto.
Qed.

Lemma take_get X (L:list X) n k x
  : get (take k L) n x -> get L n x /\ n < k.
Proof.
  intros.
  general induction H ; destruct k, L; simpl in *; inv Heql.
  - split; eauto using get; omega.
  - exploit IHget; eauto; dcr.
    split; eauto using get; omega.
Qed.

Lemma get_take X (L:list X) n k x
  : n < k
    -> get L n x
    -> get (take k L) n x.
Proof.
  intros LE GET.
  general induction GET; destruct k; simpl; eauto using get; try now (exfalso; omega).
  - econstructor.
    eapply IHGET. omega.
Qed.

 Lemma map_take X Y (f:X -> Y) (L:list X) n
  : f ⊝ take n L = take n (f ⊝ L).
Proof.
  general induction n; simpl; eauto.
  destruct L; simpl; eauto.
  f_equal; eauto.
Qed.

Lemma take_app_le n X (L L':list X)
  : n <= length L
    -> take n (L ++ L') = take n L.
Proof.
  intros. general induction n; simpl; eauto.
  destruct L; isabsurd; simpl.
  rewrite IHn; eauto. simpl in *; omega.
Qed.

Lemma take_app_ge n X (L L':list X)
  : n >= length L
    -> take n (L ++ L') = L ++ take (n - length L) L'.
Proof.
  intros. general induction n; simpl; eauto.
  - destruct L; simpl in *; eauto. exfalso; omega.
  - destruct L; simpl in *; eauto.
    rewrite IHn; eauto. omega.
Qed.

Lemma take_eq_ge n X (L:list X)
  : n >= ❬L❭ -> take n L = L.
Proof.
  intros. general induction n; destruct L; simpl in *; eauto.
  - exfalso; omega.
  - rewrite IHn; eauto. omega.
Qed.

Lemma take_app_eq n X (L L':list X)
  : n = length L
    -> take n (L ++ L') = L.
Proof.
  intros. subst. general induction L; simpl; eauto.
  f_equal; eauto.
Qed.

Lemma drop_rev X (L:list X) k
  : drop k L = rev (take (❬L❭ - k) (rev L)).
Proof.
  general induction k.
  - simpl. rewrite take_eq_ge; eauto.
    rewrite rev_rev; eauto. rewrite rev_length; omega.
  - simpl. rewrite IHk.
    f_equal. destruct L. simpl; eauto.
    simpl.
    rewrite !take_app_le. reflexivity.
    rewrite rev_length. omega.
Qed.

Lemma take_take_lt X (L:list X) n m
  : n < m
    -> take n L = take n (take m L).
Proof.
  intros. general induction n; destruct L, m; simpl; eauto.
  - omega.
  - erewrite IHn; eauto. omega.
Qed.
Lemma take_take_app X (L:list X) n m
  : n < m
    -> take m L = take n L ++ take (m - n) (drop n L).
Proof.
  intros. general induction n; destruct L, m; simpl; eauto; try omega.
  - rewrite drop_nil, take_nil; eauto.
  - rewrite IHn; eauto. omega.
Qed.

Lemma take_one X (L:list X) x k
  : k > 0
    -> take k (x::L) = x :: take (k - 1) L.
Proof.
  intros; destruct k; simpl.
  - omega.
  - f_equal. f_equal. omega.
Qed.

Lemma take_InA A (R:A->A->Prop) L n x
  : InA R x (take n L)
    -> InA R x L.
Proof.
  general induction n; destruct L; simpl in *; isabsurd.
  invt InA; eauto using InA.
Qed.

Lemma nodup_take A (R:A->A->Prop) L n
  : NoDupA R L
    -> NoDupA R (take n L).
Proof.
  intros. general induction n; invt NoDupA; simpl; eauto using NoDupA.
  econstructor; eauto. intro. eapply take_InA in H2; eauto.
Qed.


Require Import Setoid.
Require Import Morphisms.
Require Import Coq.Program.Basics.

Unset Printing Records.

From Ordinal Require Import Defs.
From Ordinal Require Import Operators.
From Ordinal Require Import Arith.

Inductive countableOrd : Set :=
| czero  : countableOrd
| climit : (nat -> countableOrd) -> countableOrd.

Fixpoint countableToOrd (x:countableOrd) : Ord :=
  match x with
  | czero => zeroOrd
  | climit f => ord nat (fun i => countableToOrd (f i))
  end.

Canonical Structure Ω := ord countableOrd countableToOrd.

Definition Ωc := ord { o:countableOrd | complete (sz o) } (fun o => countableToOrd (proj1_sig o)).

Lemma countable_zero_dec (x:Ω) : x <= zeroOrd \/ zeroOrd < x.
Proof.
  destruct x; simpl; auto with ord.
  right.
  rewrite ord_lt_unfold. simpl. exists 0%nat.
  apply zero_least.
Qed.

Parameter nat_sum : nat -> nat + nat.
Parameter nat_unsum : nat + nat -> nat.

Hypothesis nat_sum_inv : forall n, nat_unsum (nat_sum n) = n.
Hypothesis nat_unsum_inv : forall xy, nat_sum (nat_unsum xy) = xy.

Parameter nat_prod : nat -> nat * nat.
Parameter nat_unprod : nat * nat -> nat.

Hypothesis nat_prodinv : forall n, nat_unprod (nat_prod n) = n.
Hypothesis nat_unprod_inv : forall xy, nat_prod (nat_unprod xy) = xy.

Definition club (x y : Ω) :=
  match x, y with
  | czero, _ => y
  | _, czero => x
  | climit fx, climit fy =>
    climit (fun i => match nat_sum i with
                     | inl a => fx a
                     | inr b => fy b
                     end)
  end.

Lemma club_eq : forall x y:Ω, club x y ≈ x ⊔ y.
Proof.
  split.
  - destruct x; destruct y; simpl.
    + apply zero_least.
    + rewrite ord_le_unfold; simpl; intro i.
      rewrite ord_lt_unfold; simpl. exists (inr i).
      reflexivity.
    + rewrite ord_le_unfold; simpl; intro i.
      rewrite ord_lt_unfold; simpl. exists (inl i).
      reflexivity.
    + rewrite ord_le_unfold; simpl; intro i.
      rewrite ord_lt_unfold; simpl.
      exists (nat_sum i).
      destruct (nat_sum i); simpl; reflexivity.
  - destruct x; destruct y; simpl.
    + rewrite ord_le_unfold; simpl; intro.
      destruct a; exfalso; auto.
    + rewrite ord_le_unfold; simpl; intro.
      destruct a. exfalso; auto.
      rewrite ord_lt_unfold; exists n; reflexivity.
    + rewrite ord_le_unfold; simpl; intro.
      destruct a.
      rewrite ord_lt_unfold; exists n; reflexivity.
      exfalso; auto.
    + rewrite ord_le_unfold; simpl; intro.
      rewrite ord_lt_unfold; simpl.
      exists (nat_unsum a).
      rewrite nat_unsum_inv.
      destruct a; simpl; reflexivity.
Qed.

Fixpoint club' (x y:countableOrd) : countableOrd :=
  match x, y with
  | czero, _ => y
  | _, czero => x
  | climit fx, climit fy =>
    climit (fun i => let (j,k) := nat_prod i in
                      club' (fx j) (fy k))
  end.

Lemma club'_le1 : forall (x y:countableOrd), countableToOrd x <= countableToOrd (club' x y).
Proof.
  simpl in *.
  induction x as [|f Hx].
  - intros. simpl. apply zero_least.
  - intros [|g].
    + simpl. reflexivity.
    + simpl. rewrite ord_le_unfold.
      intro i. simpl.
      rewrite ord_lt_unfold; simpl.
      exists (nat_unprod (i, 0%nat)).
      rewrite nat_unprod_inv.
      apply Hx.
Qed.

Lemma club'_le2 : forall (x y:countableOrd), countableToOrd y <= countableToOrd (club' x y).
Proof.
  simpl in *.
  intros x y; revert x.
  induction y as [|g Hy].
  - intros. simpl. apply zero_least.
  - intros [|f].
    + simpl. reflexivity.
    + simpl. rewrite ord_le_unfold.
      intro i. simpl.
      rewrite ord_lt_unfold; simpl.
      exists (nat_unprod (0%nat, i)).
      rewrite nat_unprod_inv.
      apply Hy.
Qed.

Lemma club'_least : forall (x y z:countableOrd),
  complete (sz z) ->
  sz x <= sz z ->
  sz y <= sz z ->
  sz (club' x y) <= sz z.
Proof.
  induction x as [|f Hx].
  { simpl; intros; auto. }
  intros [|g].
  { simpl; intros; auto. }
  simpl; intros.
  destruct z as [|h].
  { simpl in H0. destruct (ord_le_subord _ _ H0 0%nat) as [[] _]. }

  rewrite ord_le_unfold; simpl; intro i.
  set (j := fst (nat_prod i)).
  set (k := snd (nat_prod i)).
  destruct (ord_le_subord _ _ H0 j) as [j' Hj]. simpl in Hj.
  destruct (ord_le_subord _ _ H1 k) as [k' Hk]. simpl in Hk.
  destruct (complete_directed _ H j' k') as [l [Hj' Hk']].
  rewrite ord_lt_unfold. simpl. exists l.
  destruct (nat_prod i).
  apply Hx; auto.
  apply H.
  apply ord_le_trans with (sz (h j')); auto.
  apply ord_le_trans with (sz (h k')); auto.
Qed.

Lemma club'_complete : forall (x y:countableOrd),
  complete (sz x) -> complete (sz y) -> complete (sz (club' x y)).
Proof.
  induction x as [|f Hx].
  { simpl; intros; auto. }
  destruct y as [|g].
  { simpl; intros; auto. }
  intros. simpl.
  repeat split.
  - intros a b.
    set (xa := fst (nat_prod a)).
    set (ya := snd (nat_prod a)).
    set (xb := fst (nat_prod b)).
    set (yb := snd (nat_prod b)).
    destruct (complete_directed _ H xa xb) as [x' [??]].
    destruct (complete_directed _ H0 ya yb) as [y' [??]].
    exists (nat_unprod (x', y')).
    rewrite nat_unprod_inv.
    destruct (nat_prod a).
    destruct (nat_prod b).
    split.
    + apply club'_least. apply Hx.
      apply H. apply H0.
      unfold xa, ya, xb, yb in *. simpl in *.
      rewrite H1. apply club'_le1.
      unfold xa, ya, xb, yb in *. simpl in *.
      rewrite H3. apply club'_le2.
    + apply club'_least. apply Hx.
      apply H. apply H0.
      unfold xa, ya, xb, yb in *. simpl in *.
      rewrite H2. apply club'_le1.
      unfold xa, ya, xb, yb in *. simpl in *.
      rewrite H4. apply club'_le2.
  - left. exact (inhabits 0%nat).
  - intro i.
    destruct (nat_prod i).
    apply Hx. apply H. apply H0.
Qed.

Lemma Ωc_complete : complete Ωc.
Proof.
  simpl. repeat split.
  - intros [o1 Ho1] [o2 Ho2]. simpl.
    exists (exist _ (club' o1 o2) (club'_complete o1 o2 Ho1 Ho2)).
    simpl. split; [ apply club'_le1 | apply club'_le2 ].
  - left. exact (inhabits (exist _ czero zero_complete)).
  - intros [o H]. simpl. auto.
Qed.


Section ml.
Variables A B:Prop.
Theorem Dm_nore: not (or A B) <-> and (not A) (not B).
Proof.
    split.
    intro H0; split.
    intro Ha; elim H0.
    left; assumption.
    intro Hb; elim H0.
    right; assumption.
    intro H1.
    intro H2.
    elim H1; intros Na Nb.
    elim H2; assumption.
Qed.
End ml.

Check Dm_nore.


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

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

(* Suppress some annoying warnings from Coq: *)
Set Warnings "-notation-overridden,-parsing".
From LF 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 chapter, 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
  | bool_cons (b : bool) (l : 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.) and all
    their properties ([rev_length], [app_assoc], 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
  | cons (x : X) (l : 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]. *)

Check list.
(* ===> list : Type -> Type *)

(** The parameter [X] in the definition of [list] automatically
    becomes a parameter to the constructors [nil] and [cons] -- that
    is, [nil] and [cons] are now polymorphic constructors; when we use
    them, we must now provide a first argument that is the type of the
    list they are building. For example, [nil nat] constructs the
    empty list of type [nat]. *)

Check (nil nat).
(* ===> nil nat : list nat *)

(** Similarly, [cons nat] adds an element of type [nat] to a list of
    type [list nat]. Here is an example of forming a list containing
    just the natural number 3. *)

Check (cons nat 3 (nil nat)).
(* ===> cons nat 3 (nil nat) : list nat *)

(** What might the type of [nil] be? We can read off the type [list X]
    from the definition, but this omits the binding for [X] which is
    the parameter to [list]. [Type -> list X] does not explain the
    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's
    notation for this situation is [forall X : Type, list X]. *)

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

(** Similarly, the type of [cons] from the definition looks like
    [X -> list X -> list X], but using this convention to explain the
    meaning of [X] results in the type [forall X, X -> list X -> 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.) *)

(** Having to supply a type argument for each use of a list
    constructor may seem an awkward burden, but we will soon see
    ways of reducing that burden. *)

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 an element of this type (and a number): *)

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.

(** **** Exercise: 2 stars, standard (mumble_grumble)

    Consider the following two inductively defined types. *)

Module MumbleGrumble.

Inductive mumble : Type :=
  | a
  | b (x : mumble) (y : nat)
  | c.

Inductive grumble (X:Type) : Type :=
  | d (m : mumble)
  | e (x : X).

(** Which of the following are well-typed elements of [grumble X] for
    some type [X]?  (Add YES or NO to each line.)
      - [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]  *)
(* SOLUTION:

      - [d mumble (b a 5)]
      - [d bool (b a 5)]
      - [e bool true]
      - [e mumble (b c 0)]  *)
End MumbleGrumble.

(* Do not modify the following line: *)
Definition manual_grade_for_mumble_grumble : option (nat*string) := None.
(** [] *)

(* ----------------------------------------------------------------- *)
(** *** 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 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 a "hole" [_], 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 holes, the [repeat] 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 holes 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 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'
  | cons' (x : X) (l : 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.
(* ===> @nil : forall X : Type, list X *)

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, standard, 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.
  (* SOLUTION: *)
  intros X l. induction l as [|x l' IH].
  - reflexivity.
    - simpl. rewrite IH. reflexivity.
Qed.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  (* SOLUTION: *)
  intros A l m n.
  induction l as [|a l' IH].
  - reflexivity.
  - simpl. rewrite IH. reflexivity.
Qed.

Lemma app_length : forall (X:Type) (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  (* SOLUTION: *)
  intros X l1. induction l1 as [|x l1'].
  - (* l1 = nil *) reflexivity.
  - (* l1 = x::l1' *) intros l2.  simpl. rewrite -> IHl1'. reflexivity. Qed.
(** [] *)

(** **** Exercise: 2 stars, standard, 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.
  (* SOLUTION: *)
  intros X l1 l2. induction l1 as [|x1 l1' IH].
  - simpl. rewrite app_nil_r. reflexivity.
  - simpl. rewrite IH. rewrite app_assoc. reflexivity. Qed.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  (* SOLUTION: *)
  intros X l. induction l as [| n l'].
  - (* l = nil *)
    reflexivity.
  - (* l = cons *)
    simpl. rewrite -> rev_app_distr. rewrite -> IHl'. reflexivity.  Qed.
(** [] *)

(* ================================================================= *)
(** ** 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 : X) (y : 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, standard, 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, standard, 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)
  (* SOLUTION: *) :=
  match l with
  | [] => ([], [])
  | (x, y) :: t =>
      match split t with
      | (lx, ly) => (x :: lx, y :: ly)
      end
  end.

Example test_split:
  split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
(* SOLUTION: *)
  reflexivity.
Qed.
(** [] *)

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

(** One last polymorphic type for now: _polymorphic options_,
    which generalize [natoption] from the previous chapter.  (We put
    the definition inside a module because the standard library
    already defines [option] and it's this one that we want to use
    below.) *)

Module OptionPlayground.

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

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

End OptionPlayground.

(** 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 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, standard, 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
  (* SOLUTION: *) :=
  match l with
  | [] => None
  | a :: l' => Some a
  end.

(** 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.
 (* SOLUTION: *)
Proof. reflexivity.  Qed.
 Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].
 (* SOLUTION: *)
Proof. reflexivity.  Qed.
 (** [] *)

(* ################################################################# *)
(** * 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 :=
  (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 => (length l) =? 1)
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity. Qed.

(** **** Exercise: 2 stars, standard (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
  (* SOLUTION: *) :=
  filter (fun n => andb (evenb n) (ltb 7 n)) l.

Example test_filter_even_gt7_1 :
  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
 (* SOLUTION: *)
Proof. reflexivity. Qed.

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
 (* SOLUTION: *)
Proof. reflexivity. Qed.
 (** [] *)

(** **** Exercise: 3 stars, standard (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
  (* SOLUTION: *) :=
  (filter test l, filter (fun x => negb (test x)) l).

Example test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).
(* SOLUTION: *)
Proof. reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
(* SOLUTION: *)
Proof. reflexivity. Qed.
(** [] *)

(* ================================================================= *)
(** ** 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, standard (map_rev)

    Show that [map] and [rev] commute.  You may need to define an
    auxiliary lemma. *)

Theorem map_app : forall (A B : Type) (f : A -> B) (l l' : list A),
  map f (l ++ l') = map f l ++ map f l'.
Proof.
  intros A B f l l'. induction l as [|x l1 IH].
  - reflexivity.
  - simpl. rewrite IH. reflexivity.
Qed.

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  (* SOLUTION: *)
  intros X Y f l. induction l as [| v l' IHl'].
  - (* l = [] *)
    reflexivity.
  - (* l = v :: l' *)
    simpl. rewrite -> map_app. rewrite -> IHl'. reflexivity.  Qed.
(** [] *)

(** **** Exercise: 2 stars, standard, 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)
  (* SOLUTION: *) :=
  match l with
  | []     => []
  | h :: t => (f h) ++ (flat_map f t)
  end.

Example test_flat_map1:
  flat_map (fun n => [n;n;n]) [1;5;4]
  = [1; 1; 1; 5; 5; 5; 4; 4; 4].
 (* SOLUTION: *)
Proof. reflexivity.  Qed.
 (** [] *)

(** Lists are not the only inductive type for which [map] makes sense.
    Here is a [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, standard, 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? *)

(* SOLUTION:

    There are many.  For example, we could use [fold] to count the
    number of [true] elements in a list of booleans.  Here [X] would
    be [bool] and [Y] would be [nat]. *)

(* Do not modify the following line: *)
Definition manual_grade_for_fold_types_different : option (nat*string) := None.
(** [] *)

(* ================================================================= *)
(** ** 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, standard (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].  (Hint: It may help to
    know that [reflexivity] simplifies expressions a bit more
    aggressively than [simpl] does -- i.e., you may find yourself in a
    situation where [simpl] does nothing but [reflexivity] solves the
    goal.) *)

Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
Proof.
(* SOLUTION: *)
  induction l as [| x l' IHl'].
  - (* l = [] *) reflexivity.
  - (* l = x :: l' *) simpl.
    rewrite <- IHl'.
    reflexivity.  Qed.
(** [] *)

(** **** Exercise: 3 stars, standard (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
  (* SOLUTION: *) :=
  fold (fun x l' => f x :: l') l nil.

(** Write down a theorem [fold_map_correct] in Coq stating that
   [fold_map] is correct, and prove it.  (Hint: again, remember that
   [reflexivity] simplifies expressions a bit more aggressively than
   [simpl].) *)

(* SOLUTION: *)
Theorem fold_map_correct : forall X Y (f : X -> Y) (l : list X),
  fold_map f l = map f l.
Proof.
  induction l as [| x l' IHl'].
  - (* l = [] *) reflexivity.
  - (* l = x :: l' *) simpl.
    rewrite <- IHl'.
    reflexivity.  Qed.

(* Do not modify the following line: *)
Definition manual_grade_for_fold_map : option (nat*string) := None.
(** [] *)

(** **** 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
  (* SOLUTION: *) :=
    match p with
      | (x,y) => f x y
    end.

(** 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_map1': map (plus 3) [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.
  (* SOLUTION: *)
  intros X Y Z f x y.
  reflexivity.  Qed.

Theorem curry_uncurry : forall (X Y Z : Type)
                        (f : (X * Y) -> Z) (p : X * Y),
  prod_uncurry (prod_curry f) p = f p.
Proof.
  (* SOLUTION: *)
  intros X Y Z f p.
  destruct p as [x y].
  reflexivity.  Qed.
(** [] *)

(** **** 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 n =? O then Some a else nth_error l' (pred n)
     end.

   Write an informal proof of the following theorem:

   forall X l n, length l = n -> @nth_error X l n = None
*)
(* SOLUTION:

    Theorem: For all types [X], lists [l], and natural numbers [n],
    if [length l = n] then [nth_error X l n = None].

    Proof: By induction on [l]. There are two cases to consider:

      - If [l = nil], we must show [nth_error [] n = None].  This follows
        immediately from the definition of [nth_error].

      - Otherwise, [l = x :: l'] for some [x] and [l'], and the
        induction hypothesis tells us that [length l' = n' => nth_error l'
        n' = None] for any [n'].

        Let [n] be a number such that [length l = n].  We must show
        that [nth_error (x :: l') n = None].

        But we know that [n = length l = length (x :: l') = S (length l')].
        So it's enough to show [nth_error l' (length l') = None], which
        follows directly from the induction hypothesis, picking [length l']
        for [n']. *)

(* Do not modify the following line: *)
Definition manual_grade_for_informal_proof : option (nat*string) := None.
(** [] *)

(** The following exercises explore 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 cnat := 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 : cnat :=
  fun (X : Type) (f : X -> X) (x : X) => f x.

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

Definition two : cnat :=
  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 : cnat :=
  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 : cnat := @doit3times.

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

(** **** Exercise: 1 star, advanced (church_succ)  *)

(** Successor of a natural number: given a Church numeral [n],
    the successor [succ n] is a function that iterates its
    argument once more than [n]. *)
Definition succ (n : cnat) : cnat
  (* SOLUTION: *) :=
  fun X f x => f (n X f x).

Example succ_1 : succ zero = one.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example succ_2 : succ one = two.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example succ_3 : succ two = three.
Proof. (* SOLUTION: *) reflexivity. Qed.
(** [] *)

(** **** Exercise: 1 star, advanced (church_plus)  *)

(** Addition of two natural numbers: *)
Definition plus (n m : cnat) : cnat
  (* SOLUTION: *) :=
  fun X f x => n X f (m X f x).

Example plus_1 : plus zero one = one.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example plus_2 : plus two three = plus three two.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example plus_3 :
  plus (plus two two) three = plus one (plus three three).
Proof. (* SOLUTION: *) reflexivity. Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (church_mult)  *)

(** Multiplication: *)
Definition mult (n m : cnat) : cnat
  (* SOLUTION: *) :=
  fun X f x => n X (m X f) x.

Example mult_1 : mult one one = one.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example mult_2 : mult zero (plus three three) = zero.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example mult_3 : mult two three = plus three three.
Proof. (* SOLUTION: *) reflexivity. Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (church_exp)  *)

(** 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.  Iterating over [cnat] itself is usually problematic.) *)

Definition exp (n m : cnat) : cnat
  (* SOLUTION: *) :=
  fun X f x => m (X -> X) (n X) f x.

Example exp_1 : exp two two = plus two two.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example exp_2 : exp three zero = one.
Proof. (* SOLUTION: *) reflexivity. Qed.
Example exp_3 : exp three two = plus (mult two (mult two two)) one.
Proof. (* SOLUTION: *) reflexivity. Qed.
(** [] *)

End Church.

End Exercises.

(* Wed 28 Aug 2019 06:48:48 PM CEST *)


From mathcomp Require Import all_ssreflect.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(* Usage :

rewrite (ACl operator reordering)

- operator must be a (canonical) Monoid.com_law
- reordering is expressed using the syntax
  s := n | s + s' (where "+" is purely formal)
  where n is a nat
- we assume the lhs is associated to the left
  (use !opA before ACl if required)

Examples of syntax :
- (0 + 1) + 2 is the identity
- (0 + 2) + 1 correspond to opAC
- 0 + (1 + 2) is the same as chaining -opA and opCA
...
*)

Delimit Scope AC_scope with ac.

Section AC.

Inductive syntax := Leaf of nat | Op of syntax & syntax.
Definition seqtax :=
  (fix aux (acc : seq nat) (s : syntax) := match s with
               | Leaf n => n :: acc
               | Op s s' => (aux^~ s (aux^~ s' acc))
               end) [::].

Definition sfoldl R (d : R) f (s : seq R) :=
  if s is a::s then foldl f a s else d.
Definition sfoldr R (d : R) f (s : seq R) :=
  if s is a::s then foldr f a s else d.

Variables (T : Type) (default : T) (env : seq T) (op : Monoid.com_law default).

Local Notation "x + y" := (op x y).

Definition desyntax :=
  fix aux (s : syntax)  := match s with
               | Leaf n => nth default env n
               | Op s s' => aux s + aux s'
               end.

Lemma ACl_def s :
  let st := seqtax s in let sst := size st in let isst := iota 0 sst in
                                              perm_eq st isst ->
  sfoldl default op (map (nth default env) isst) = desyntax s.
Proof.
have seqtax_Op s1 s2 : seqtax (Op s1 s2) = seqtax s1 ++ seqtax s2.
  rewrite /seqtax; set aux := (X in X [::]); rewrite -/aux.
  elim: s1 (aux [::] s2) => [n|s11 IHs1 s12 IHs2] //= l.
  by rewrite IHs1 [in RHS]IHs1 IHs2 catA.
move=> st sst isst pst.
transitivity (\big[op/default]_(i <- isst) nth default env i).
  case: isst {pst} => [|x l /=]; rewrite (big_nil, big_cons) //=.
  elim: l (nth _ _ _) => [|y l IHl] x0.
    by rewrite big_nil ?Monoid.mulm1.
  by rewrite big_cons /= IHl Monoid.mulmA.
elim: s => [n|s IHs s' IHs'] //= in st sst (isst) pst *.
  have [/perm_eq_size {pst}] := (pst, pst).
  case: isst => // m [|//] _ /perm_eqP/(_ (pred1 m)) => /=.
  by rewrite eqxx; case: eqP => //= ->; rewrite big_cons big_nil Monoid.mulm1.
have /(eq_big_perm _) <- := pst.
by rewrite [st]seqtax_Op big_cat IHs ?IHs' //.
Qed.

End AC.

Coercion Leaf : nat >-> syntax.
Bind Scope AC_scope with syntax.
Notation "0" := 0%N : AC_scope.
Notation "1" := 1%N : AC_scope.
Notation "x * y" := (Op x%ac y%ac) : AC_scope.

Definition type_of T (x : T) := T.
Arguments type_of / T x.
Definition lhs T a b (e : a = b :> T) := a.
Arguments lhs / T a b e.
Definition rhs T a b (e : a = b :> T) := b.
Arguments rhs / T a b e.

Import Classes.Init.
Class envn T (n : nat) := Envn : seq T.
Instance envn0 T : envn T 0 := nil.
Definition consn T n x {s : envn T n} : envn T n.+1 := x :: s.
Hint Extern 0 (envn _ (S _)) =>
  match goal with |- envn ?T (S ?n) =>
                  let x := fresh "x" in
                  evar (x : T); apply (@consn _ _ x _)
  end : typeclass_instances.

Class compute T x y := Compute : x = y :> T.
Hint Extern 0 (@compute _ _ _) => compute; reflexivity : typeclass_instances.
Class simpl T x y := Simpl : x = y :> T.
Hint Extern 0 (@simpl _ _ _) => simpl; reflexivity : typeclass_instances.

Definition ACl_auto T default (law : Monoid.com_law default) (s : syntax)
   {peq : compute (perm_eq (seqtax s) (iota 0 (size (seqtax s)))) true}
   {sst} {_ : compute (size (seqtax s)) sst}
   {env : envn T sst}
   (use := @ACl_def T default env law s peq)
   {lhs'} {elhs : simpl (lhs use) lhs'}
   {rhs'} {erhs : simpl (rhs use) rhs'}
   : lhs' = rhs' :=
  (match elhs with erefl =>
    (match erhs with erefl => use end) end).

Notation ACl_of f s := (@ACl_auto _ _ [com_law of f] s%ac
                                isT _ _ _ _ _ _ _).
Notation ACl f s := (ACl_of f s%ac : f%function _ _ = _).

Section Tests.

Lemma test_orb (a b c d : bool) : (a || b) || (c || d) = (a || c) || (b || d).
Proof.
rewrite !orbA.
rewrite (ACl orb ((0 * 2) * (1 * 3))).
by rewrite !orbA.
Qed.

Lemma test_addn (a b c d : nat) : (a + b + c + d = a + c + b + d)%N.
Proof.
by rewrite (ACl addn (0 * 2 * 1 * 3)).
Qed.

End Tests.


Require Export Undecidability.Shared.Libs.PSL.FiniteTypes.
Require Import Undecidability.Shared.Libs.PSL.Vectors.Vectors.

Lemma dupfree_elements (X: finType) : NoDup (elem X).
Proof.
  apply (NoDup_count_occ' (@eqType_dec X)). intros x H.
  rewrite <- count_count_occ.
  apply enum_ok.
Qed.

(* From PSL/Lists/BaseLists.v *)
Lemma map_repeat (X Y : Type) (f : X -> Y) (n : nat) (a : X) :
  map f (repeat a n) = repeat (f a) n.
Proof.
  induction n as [|n IHn].
  - reflexivity.
  - cbn. now rewrite IHn.
Qed.

Definition equi X (A B : list X) : Prop := incl A B /\ incl B A.
Notation "A === B" := (equi A B) (at level 70).

#[global]
Instance equi_Equivalence X :
  Equivalence (@equi X).
Proof.
  constructor; hnf; firstorder.
Qed.

#[global]
Instance in_equi_proper X x :
  Proper (@equi X ==> iff) (@In X x).
Proof.
  intros ???. firstorder.
Qed.

(* from PSL/Vectors/Vectors.v *)
Lemma vector_to_list_inj (X : Type) (n : nat) (xs ys : Vector.t X n) :
  Vector.to_list xs = Vector.to_list ys -> xs = ys.
Proof.
  revert ys. induction xs as [ | x n xs IH]; intros; cbn in *.
  - destruct_vector. reflexivity.
  - destruct_vector. cbn in *. inv H. f_equal. auto.
Qed.

(* From TM/Util/VectorPrelim.v *)
Lemma nth_error_inj X (xs ys : list X) :
  (forall n, nth_error xs n = nth_error ys n) -> xs = ys.
Proof.
  induction xs in ys|-*;destruct ys;cbn;intros H. 1:easy. 1-2:now specialize (H 0).
  generalize (H 0).  intros [= ->]. erewrite IHxs. easy. intros n'. now specialize (H (S n')).
Qed.

Lemma vector_nth_error_nat X n' i (xs : Vector.t X n') :
  nth_error (Vector.to_list xs) i = match lt_dec i n' with
                                      Specif.left H => Some (Vector.nth xs (Fin.of_nat_lt H))
                                    | _ => None
                                    end.
Proof.
  clear. induction xs in i|-*. now destruct i.
  cbn in *. destruct i;cbn. easy. rewrite IHxs. do 2 destruct lt_dec. 4:easy. now symmetry;erewrite Fin.of_nat_ext. all:exfalso;Lia.nia.
Qed.

Lemma vector_to_list_cast (X : Type) (n1 n2 : nat) (H : n1 = n2) (v : Vector.t X n1) :
  Vector.to_list (Vector.cast v H) = Vector.to_list v.
Proof. subst. rename n2 into n. induction v as [ | x n v IH]; cbn; f_equal; auto. Qed.

(* From PSL/FiniteTypes/VectorFin.v *)
Lemma Fin_cardinality n : | elem (finType_CS (Fin.t n)) | = n.
Proof.
  apply VectorSpec.length_to_list.
Qed.

(* from PSL/FiniteTypes/FinTypes.v *)
Lemma index_leq (A:finType) (x:A): index x <= length (elem A).
Proof. apply Nat.lt_le_incl, index_le. Qed.


Require Import ProofCheckingEuclid.euclidean_axioms.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma lemma_s_ncol_n_col :
	forall A B C,
	nCol A B C ->
	~ Col A B C.
Proof.
	intros A B C.
	intros nCol_A_B_C.

	assert (~ Col A B C) as n_Col_a_b_c.
	{
		intros Col_A_B_C.

		unfold nCol in nCol_A_B_C.
		unfold Col in Col_A_B_C.
		destruct nCol_A_B_C as (
			neq_A_B & neq_A_C & neq_B_C & nBetS_A_B_C & nBetS_A_C_B & nBetS_B_A_C
		).
		destruct Col_A_B_C as [
			eq_A_B | [eq_A_C | [eq_B_C | [BetS_B_A_C | [BetS_A_B_C | BetS_A_C_B]]]]
		].

		contradict eq_A_B.
		exact neq_A_B.
		contradict eq_A_C .
		exact neq_A_C .
		contradict eq_B_C .
		exact neq_B_C .
		contradict BetS_B_A_C .
		exact nBetS_B_A_C .
		contradict BetS_A_B_C.
		exact nBetS_A_B_C.
		contradict BetS_A_C_B .
		exact nBetS_A_C_B .
	}
	exact n_Col_a_b_c.
Qed.

End Euclid.


(* Various definitions and lemmas involving binary trees *)

Require Import Arith List.
Require Import VerifiedNatIntf ArrayIntf CanonicalArrImpl.
Require Import Cpdt.CpdtTactics.

Import ListNotations.
Set Implicit Arguments.

Module TreeDefns (Natl : VerifiedNatInterface).

  Definition one := Natl.succ Natl.zero.

  Inductive tree (A : Type) : Type :=
    | Empty : tree A
    | Leaf : A -> tree A
    | Node : Natl.N -> Natl.N -> tree A -> tree A -> tree A.

  Definition T := tree.

  Fixpoint add A (x : A) (t : tree A) : tree A :=
    match t with
    | Empty => Leaf x
    | Leaf y => Node one one (Leaf x) (Leaf y)
    | Node nl nr l r =>
        match Natl.comp nl nr with
        | Lt => Node (Natl.succ nl) nr (add x l) r
        | Eq
        | Gt => Node nl (Natl.succ nr) l (add x r)
        end
    end.

  Fixpoint make A (m : nat) (x : A) : tree A :=
    match m with
    | O => Empty A
    | S m' => add x (make m' x)
    end.

  Definition len A (t : tree A) : Natl.N :=
    match t with
    | Empty => Natl.zero
    | Leaf _ => Natl.succ Natl.zero
    | Node nl nr _ _ => Natl.add nl nr
    end.

  Fixpoint get A (t : tree A) (index : Natl.N) : option A :=
    match t, index with
    | Empty, _ => None
    | Leaf x, _ =>
        match Natl.comp index Natl.zero with
        | Lt
        | Eq => Some x
        | Gt => None
        end
    | Node nl nr l r, i =>
        match Natl.comp i nl with
        | Lt => get l i
        | Eq
        | Gt => get r (Natl.sub i nl)
        end
    end.

  Fixpoint set A (t : tree A) (index : Natl.N) (x : A) : tree A :=
    match t, index with
    | Empty, _ => Empty A
    | Leaf y, _ =>
        match Natl.comp index Natl.zero with
        | Lt
        | Eq => Leaf x
        | Gt => Leaf y
        end
    | Node nl nr l r, i =>
        match Natl.comp i nl with
        | Lt => Node nl nr (set l i x) r
        | Eq
        | Gt => Node nl nr l (set r (Natl.sub i nl) x)
        end
    end.

  Definition concat A (t1 t2 : tree A) : tree A :=
    match t1, t2 with
    | Empty, _ => t2
    | _, Empty => t1
    | _, _ => Node (len t1) (len t2) t1 t2
    end.

  (** Properties and lemmas **)

  Fixpoint count A (t : tree A) : Natl.N :=
    match t with
    | Empty => Natl.zero
    | Leaf _ => Natl.succ (Natl.zero)
    | Node _ _ l r => Natl.add (count l) (count r)
    end.

  Fixpoint well_formed A (t : tree A) :=
    match t with
    | Empty => True
    | Leaf _ => True
    | Node nl nr l r => (count l = nl) /\ (count r = nr) /\ well_formed l /\ well_formed r
    end.

  Lemma add_inc : forall A (x:A) (t:tree A),
      count (add x t) = Natl.succ (count t).
    intros A x t.
    induction t as [| | nl nr l IHl r IHr ]; simpl; auto.
      (* Leaf *)
      rewrite Natl.add_succ; rewrite Natl.add_zero; reflexivity.
      (* Node *)
      remember (Natl.comp nl nr) as clr.
      Hint Resolve Natl.add_succ_right.
      destruct clr; simpl; rewrite <- Natl.add_succ; crush.
  Defined.

  Lemma add_preserves : forall A (x : A) (t : tree A),
      well_formed t -> well_formed (add x t).
    intros A x t.
    induction t as [| |nl nr l IHl r IHr]; simpl; auto.
      (* Node *)
      intros Hwf.
      Hint Resolve add_inc.
      destruct (Natl.comp nl nr); crush.
  Defined.

  Lemma make_wf : forall A n (x:A), well_formed (make n x).
    intros A m x.
    Hint Resolve add_preserves.
    induction m; crush.
  Defined.

  Lemma len_wf : forall A (t:tree A), well_formed t -> len t = count t.
    intros A t.
    destruct t; crush.
  Defined.

  Lemma set_count : forall A (t:tree A) i x,
      count (set t i x) = count t.
    intros A t.
    induction t as [| | nl nr l IHl r IHr ];
        intros i x; auto; simpl.
      (* Leaf _ *)
      destruct (Natl.comp i Natl.zero); auto.
      (* Node *)
      destruct (Natl.comp i nl); simpl.
        rewrite (IHr (Natl.sub i nl) x); reflexivity.
        rewrite (IHl i x); reflexivity.
        rewrite (IHr (Natl.sub i nl) x); reflexivity.
  Defined.

  Lemma set_wf : forall A (t:tree A) i x,
      well_formed t -> well_formed (set t i x).
    intros A t.
    induction t as [| | nl nr l IHl r IHr ];
        intros i x; simpl.
      (* Empty *)
      auto.
      (* Leaf *)
      destruct (Natl.comp i Natl.zero); auto.
      (* Node *)
      intros Hwf.
      destruct Hwf as (Hcr & Hcl & Hwfl & Hwfr).
      destruct (Natl.comp i nl);
          simpl;
          rewrite (set_count _ _ _).
        pose (IHr (Natl.sub i nl) x); auto.
        pose (IHl i x Hwfl); auto.
        pose (IHr (Natl.sub i nl) x); auto.
  Defined.

  Lemma concat_wf : forall A (t1 t2 : tree A),
      well_formed t1 -> well_formed t2 -> well_formed (concat t1 t2).
    intros A t1 t2.
    destruct t1; destruct t2; crush.
  Defined.

End TreeDefns.