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

- Frederic Blanqui, 2009-03-19 (setoid)
- Adam Koprowski, 2007-04-02

Arithmetic over vectors on some semiring.
*)

Set Implicit Arguments.

From Coq Require Import Setoid Morphisms.
From CoLoR Require Import VecUtil RelUtil SemiRing OrdSemiRing NatUtil
  LogicUtil.

Module VectorArith (SRT : SemiRingType).

  Module Export SR := SemiRing SRT.

  Notation vec := (vector A).

  Definition zero_vec := Vconst A0.

  Definition id_vec n i (ip : i < n) := Vreplace (zero_vec n) ip A1.

  Notation "v1 =v v2" := (Vforall2 eqA v1 v2) (at level 70).

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

  Definition vector_plus n (v1 v2 : vec n) := Vmap2 Aplus v1 v2.

  Infix "[+]" := vector_plus (at level 50).

  Global Instance vector_plus_mor n :
    Proper (Vforall2 eqA ==> Vforall2 eqA ==> Vforall2 eqA) (@vector_plus n).

  Proof.
    intros u u' uu' v v' vv'. apply Vforall2_intro_nth. intros.
    unfold vector_plus. rewrite !Vnth_map2.
    (*COQ: rewrite H does not work even if Vnth is declared as morphism *)
    apply Aplus_mor; apply Vforall2_elim_nth; hyp.
  Qed.

  Lemma vector_plus_nth n (vl vr : vec n) i (ip : i < n) :
    Vnth (vl [+] vr) ip =A= Vnth vl ip + Vnth vr ip.

  Proof. unfold vector_plus. rewrite Vnth_map2. refl. Qed.

  Lemma vector_plus_comm n (v1 v2 : vec n) : v1 [+] v2 =v v2 [+] v1.

  Proof. apply Vforall2_intro_nth. intros. rewrite !vector_plus_nth. ring. Qed.

  Lemma vector_plus_assoc n (v1 v2 v3 : vec n) :
    v1 [+] (v2 [+] v3) =v v1 [+] v2 [+] v3.

  Proof. apply Vforall2_intro_nth. intros. rewrite !vector_plus_nth. ring. Qed.

  Lemma vector_plus_zero_r n (v : vec n) : v [+] zero_vec n =v v.

  Proof.
    apply Vforall2_intro_nth. intros. rewrite vector_plus_nth.
    set (w := Vnth_const A0 ip). fold zero_vec in w. rewrite w. ring.
  Qed.

  Lemma vector_plus_zero_l n (v : vec n) : zero_vec n [+] v =v v.

  Proof. rewrite vector_plus_comm. apply vector_plus_zero_r. Qed.

  (***********************************************************************)
  (** sum of a vector of vectors *)

  Definition add_vectors n k (v : vector (vec n) k) :=
    Vfold_left_rev (@vector_plus n) (zero_vec n) v.

  Global Instance add_vectors_mor n k :
    Proper (Vforall2 (Vforall2 eqA) ==> Vforall2 eqA) (@add_vectors n k).

  Proof.
    intro x; revert x.
    induction x; simpl; intros. VOtac. refl. revert H. VSntac y.
    unfold add_vectors. simpl. rewrite Vforall2_cons_eq. intuition.
    rewrite H1. apply vector_plus_mor. 2: refl.
    eapply Vfold_left_rev_Vforall2. apply vector_plus_mor. refl. hyp.
  Qed.

  Lemma add_vectors_cons n i (a : vec n) (v : vector (vec n) i) :
    add_vectors (Vcons a v) =v a [+] add_vectors v.

  Proof. unfold add_vectors. simpl. rewrite vector_plus_comm. refl. Qed.

  Lemma add_vectors_zero n k : forall v : vector (vec n) k,
    Vforall (fun v => v =v zero_vec n) v -> add_vectors v =v zero_vec n.

  Proof.
    induction v. refl. rewrite add_vectors_cons. simpl. intuition.
    rewrite H0, vector_plus_zero_l. hyp.
  Qed.

  Lemma add_vectors_perm n i v v' (vs : vector (vec n) i) :
    add_vectors (Vcons v (Vcons v' vs)) =v add_vectors (Vcons v' (Vcons v vs)).

  Proof.
    rewrite !add_vectors_cons, !vector_plus_assoc, (vector_plus_comm v v').
    refl.
  Qed.

  Lemma add_vectors_nth n k : forall (vs : vector (vec n) k) i (ip : i < n),
    Vnth (add_vectors vs) ip
    =A= Vfold_left_rev Aplus A0 (Vmap (fun v => Vnth v ip) vs).

  Proof.
    induction vs; simpl; intros.
    unfold add_vectors, zero_vec; simpl. rewrite Vnth_const. refl.
    rewrite (Vforall2_elim_nth (R:=eqA)). 2: rewrite add_vectors_cons; refl.
    rewrite vector_plus_nth, IHvs, Aplus_comm. refl.
  Qed.

  Lemma add_vectors_split n : forall k (v vl vr : vector (vec n) k),
    (forall i (ip : i < k), Vnth v ip =v Vnth vl ip [+] Vnth vr ip) ->
    add_vectors v =v add_vectors vl [+] add_vectors vr.

  Proof.
    induction k; intros.
    VOtac. unfold add_vectors. simpl. rewrite vector_plus_zero_r. refl.
    VSntac v. VSntac vl. VSntac vr.
    rewrite !add_vectors_cons, (IHk (Vtail v) (Vtail vl) (Vtail vr)),
      !Vhead_nth, (H 0 (lt_O_Sn k)).
    match goal with
      |- (?A [+] ?B) [+] (?C [+] ?D) =v (?A [+] ?C) [+] (?B [+] ?D) =>
        set (X := A); set (Y := B); set (W := C); set (V := D) end.
    rewrite <- !vector_plus_assoc, (vector_plus_assoc W Y V),
      (vector_plus_comm W Y), !vector_plus_assoc. refl.
    intros. rewrite !Vnth_tail. apply H.
  Qed.

  (***********************************************************************)
  (** point-wise product *)

  Definition dot_product n (l r : vec n) :=
    Vfold_left_rev Aplus A0 (Vmap2 Amult l r).

  Global Instance dot_product_mor n :
    Proper (Vforall2 eqA ==> Vforall2 eqA ==> eqA) (@dot_product n).

  Proof.
    intros u u' uu' v v' vv'; revert u u' uu' v v' vv'.
    induction n; intros. VOtac. refl.
    revert uu' vv'. VSntac u. VSntac v. VSntac u'. VSntac v'. intros H3 H4.
    rewrite Vforall2_cons_eq in H3. rewrite Vforall2_cons_eq in H4. intuition.
    unfold dot_product. simpl. unfold dot_product in IHn.
    rewrite (IHn _ _ H6 _ _ H7), H5, H3. refl.
  Qed.

  Lemma dot_product_zero : forall n (v v' : vec n),
    Vforall (fun el => el =A= A0) v -> dot_product v v' =A= A0.

  Proof.
    induction n; intros.
    VOtac. refl.
    VSntac v. VSntac v'. unfold dot_product. simpl.
    fold (dot_product (Vtail v) (Vtail v')). rewrite IHn.
    assert (Vhead v =A= A0). rewrite Vhead_nth. apply Vforall_nth. hyp.
    rewrite H2. ring.
    apply Vforall_incl with (S n) v. intros.
    apply Vin_tail. hyp. hyp.
  Qed.

  Lemma dot_product_id : forall i n (ip : i < n) v,
    dot_product (id_vec ip) v =A= Vnth v ip.

  Proof.
    induction i. intros.
    destruct n. lia.

    (* induction base *)
    VSntac v. unfold id_vec, dot_product. simpl.
    change (dot_product (Vconst A0 n) (Vtail v) + A1 * Vhead v =A= Vhead v).
    rewrite dot_product_zero. ring.
    apply Vforall_nth_intro. intros.
    rewrite Vnth_const. refl.

    (* induction step *)
    intros. destruct n. lia.
    VSntac v. unfold dot_product. simpl.
    rewrite <- (IHi n (lt_S_n ip) (Vtail v)).
    ring_simplify. unfold dot_product. refl.
  Qed.

  Lemma dot_product_comm : forall n (u v : vec n),
    dot_product u v =A= dot_product v u.

  Proof.
    induction n. refl. intros. VSntac u. VSntac v. unfold dot_product. simpl.
    unfold dot_product in IHn. rewrite IHn. ring.
  Qed.

  Lemma dot_product_distr_r : forall n (v vl vr : vec n),
    dot_product v (vl [+] vr) =A= dot_product v vl + dot_product v vr.

  Proof.
    induction n; intros.
    VOtac. unfold dot_product. simpl. ring.
    VSntac v. VSntac vl. VSntac vr. unfold dot_product. simpl.
    fold (Vtail vl [+] Vtail vr).
    fold (dot_product (Vtail v) (Vtail vl [+] Vtail vr)).
    rewrite IHn. unfold dot_product. ring.
  Qed.

  Lemma dot_product_distr_l n (v vl vr : vec n) :
    dot_product (vl [+] vr) v =A= dot_product vl v + dot_product vr v.

  Proof.
    rewrite dot_product_comm, dot_product_distr_r, (dot_product_comm v vl),
      (dot_product_comm v vr). refl.
  Qed.

  Lemma dot_product_cons : forall n al ar (vl vr : vec n),
    dot_product (Vcons al vl) (Vcons ar vr) =A= al * ar + dot_product vl vr.

  Proof. intros. unfold dot_product. simpl. ring. Qed.

  Lemma dot_product_distr_mult : forall n a (v v' : vec n),
    a * dot_product v v'
    =A= dot_product (Vbuild (fun i ip => a * Vnth v ip)) v'.

  Proof.
    induction n; intros.
    VOtac. unfold dot_product. simpl. ring.
    rewrite (VSn_eq (Vbuild (fun i (ip : i < S n) => a * Vnth v ip))).
    VSntac v. VSntac v'. rewrite !dot_product_cons. ring_simplify.
    rewrite IHn, Vbuild_tail, Vbuild_head. simpl. ring_simplify.
    match goal with
      |- _ + dot_product ?X _ =A= _ + dot_product ?Y _ => replace X with Y end.
    refl. apply Veq_nth. intros.
    rewrite !Vbuild_nth, lt_Sn_nS. refl.
  Qed.

  (***********************************************************************)
  (** hints *)

  Global Hint Rewrite vector_plus_zero_l vector_plus_zero_r add_vectors_cons : arith.

End VectorArith.

(***********************************************************************)
(** product ordering on vectors *)

Module OrdVectorArith (OSRT : OrdSemiRingType).

  Module Export VA := VectorArith OSRT.SR.
  Module Export OSR := OrdSemiRing OSRT.

(***********************************************************************)
(** [ge] on vectors *)

  Infix ">=v" := (Vforall2 ge) (at level 70).

  Global Instance vec_ge_mor n :
    Proper (Vforall2 eqA ==> Vforall2 eqA ==> iff) (Vforall2 ge (n:=n)).

  Proof. apply Vforall2_aux_Proper. class. Qed.

  Arguments vec_ge_mor [n x y] _ [x0 y0] _ : rename.

  Lemma vec_plus_ge_compat : forall n (vl vl' vr vr' : vec n),
    vl >=v vl' -> vr >=v vr' -> vl [+] vr >=v vl' [+] vr'.

  Proof.
    unfold vector_plus. intros. apply Vforall2_intro_nth.
    intros. simpl. rewrite !Vnth_map2.
    apply plus_ge_compat.
    apply Vforall2_elim_nth. hyp.
    apply Vforall2_elim_nth. hyp.
  Qed.

  Lemma vec_plus_ge_compat_r : forall n (vl vl' vr : vec n),
    vl >=v vl' -> vl [+] vr >=v vl' [+] vr.

  Proof. intros. apply vec_plus_ge_compat. hyp. refl. Qed.

  Lemma vec_plus_ge_compat_l : forall n (vl vr vr' : vec n),
    vr >=v vr' -> vl [+] vr >=v vl [+] vr'.

  Proof. intros. apply vec_plus_ge_compat. refl. hyp. Qed.

End OrdVectorArith.


(******************************************************************************)
(** * Lemmas about sorted lists *)
(******************************************************************************)

Require Import HahnBase HahnSets HahnList HahnRelationsBasic HahnEquational.
Require Export Sorted Setoid.

Set Implicit Arguments.

Add Parametric Morphism A : (@StronglySorted A) with signature
  inclusion ==> eq ==> Basics.impl as StronglySorted_mori.
Proof.
  unfold inclusion; red; ins; desf.
  induction H0; econs; ins.
  rewrite Forall_forall in *; ins; desf; eauto.
Qed.

Add Parametric Morphism A : (@StronglySorted A) with signature
  same_relation ==> eq ==> iff as StronglySorted_more.
Proof.
  by split; [rewrite (proj1 H)|rewrite (proj2 H)].
Qed.

Lemma StronglySorted_cons_iff A (r : relation A) (a : A) (l : list A) :
  StronglySorted r (a :: l) <-> StronglySorted r l /\ Forall (r a) l.
Proof.
  split; ins; desf; auto using SSorted_cons, StronglySorted_inv.
Qed.

Lemma StronglySorted_app_iff A (r: relation A) l1 l2 :
  StronglySorted r (l1 ++ l2) <->
  StronglySorted r l1 /\ StronglySorted r l2 /\
  (forall x1 (IN1: In x1 l1) x2 (IN2: In x2 l2), r x1 x2).
Proof.
  induction l1; ins; [by intuition; vauto|].
  rewrite !StronglySorted_cons_iff, IHl1, Forall_app.
  clear; intuition; desf; eauto.
  all: rewrite Forall_forall in *; eauto.
Qed.

Lemma StronglySorted_app A (r: relation A) l1 l2
    (S1: StronglySorted r l1) (S2: StronglySorted r l2)
    (L: forall x1 (IN1: In x1 l1) x2 (IN2: In x2 l2), r x1 x2):
  StronglySorted r (l1 ++ l2).
Proof.
  by apply StronglySorted_app_iff.
Qed.

Lemma StronglySorted_app_l A r (l l': list A):
  StronglySorted r (l ++ l') -> StronglySorted r l.
Proof.
  rewrite StronglySorted_app_iff; tauto.
Qed.

Lemma StronglySorted_app_r A r (l l': list A):
  StronglySorted r (l ++ l') -> StronglySorted r l'.
Proof.
  rewrite StronglySorted_app_iff; tauto.
Qed.

Lemma StronglySorted_filter A r f (l : list A):
  StronglySorted r l -> StronglySorted r (filter f l).
Proof.
  induction l; ins; eauto; desf; rewrite StronglySorted_cons_iff in *; desf.
  all: splits; desf; eauto using Forall_filter.
Qed.

Lemma StronglySorted_filterP A r f (l : list A):
  StronglySorted r l -> StronglySorted r (filterP f l).
Proof.
  induction l; ins; eauto; desf; rewrite StronglySorted_cons_iff in *; desf.
  all: splits; desf; eauto using Forall_filterP.
Qed.

Lemma NoDup_StronglySorted A (r: relation A) (IRR: irreflexive r)
      l (SS: StronglySorted r l):
  NoDup l.
Proof.
  induction l; ins.
  apply StronglySorted_inv in SS; desc.
  rewrite Forall_forall in *.
  constructor; eauto.
Qed.

Global Hint Resolve NoDup_StronglySorted : hahn.
Global Hint Resolve SSorted_nil : hahn.
Global Hint Resolve StronglySorted_filterP : hahn.
Global Hint Resolve StronglySorted_filter : hahn.

Lemma sorted_perm_eq : forall A (cmp: A -> A -> Prop)
  (TRANS: transitive cmp)
  (ANTIS: antisymmetric cmp)
  l l' (P: Permutation l l')
  (S : StronglySorted cmp l) (S' : StronglySorted cmp l'), l = l'.
Proof.
  induction l; ins.
    by apply Permutation_nil in P; desf.
  assert (X: In a l') by eauto using Permutation_in, Permutation_sym, in_eq.
  apply In_split2 in X; desf; apply Permutation_cons_app_inv in P.
  destruct l1; ins; [by inv S; inv S'; eauto using f_equal|].
  assert (X: In a0 l) by eauto using Permutation_in, Permutation_sym, in_eq.
  inv S; inv S'; rewrite Forall_forall in *; ins.
  destruct X0; left; apply ANTIS; eauto with hahn.
Qed.

Lemma StronglySorted_eq A (r: relation A) (ORD: strict_partial_order r) l l'
   (SS: StronglySorted r l) (SS': StronglySorted r l')
   (EQ: forall x, In x l <-> In x l'): l = l'.
Proof.
  red in ORD; desc.
  eapply sorted_perm_eq; eauto using NoDup_Permutation with hahn.
Qed.

Lemma StronglySorted_restr A cond (r: relation A) l:
  StronglySorted (restr_rel cond r) l -> StronglySorted r l.
Proof.
  induction l; ins; vauto.
  rewrite StronglySorted_cons_iff, ForallE in *.
  firstorder.
Qed.

Fixpoint isort A (r : relation A) l :=
  match l with
  | nil => nil
  | x :: l =>
    let l' := isort r l in
    filterP (fun y => r y x) l' ++ x :: filterP (fun y => ~ r y x) l'
  end.

Global Hint Resolve SSorted_nil : hahn.
Global Hint Resolve StronglySorted_filterP : hahn.

Lemma in_isort_iff A x (r : relation A) l : In x (isort r l) <-> In x l.
Proof.
  induction l; ins; rewrite in_app_iff; ins; in_simp; rewrite IHl.
  tauto.
Qed.

Lemma StronglySorted_isort A (r : relation A)
      (TOT: strict_total_order (fun _ : A => True) r)
      l (ND: NoDup l) :
  StronglySorted r (isort r l).
Proof.
  destruct TOT as [[IRR T] TOT].
  induction l; ins; vauto.
  rewrite nodup_cons in *; desc.
  apply StronglySorted_app; ins; in_simp; eauto with hahn.
    econs; eauto with hahn.
    apply Forall_forall; ins; in_simp.
  all: rewrite in_isort_iff in *; desf.
    forward eapply TOT with (a:=x) (b:=a); try red; ins; desf; eauto.
    forward eapply TOT with (a:=x1) (b:=x2); try red; ins; desf; eauto.
  exfalso; eauto.
Qed.


Inductive bool : Set :=
| true
| false.

Definition notb (b : bool) : bool :=
  match b with
  | true => false
  | false => true
  end.

Definition andb (b1 b2 : bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Lemma andb_comm :
  forall b1 b2,
    andb b1 b2 = andb b2 b1.
Proof.
  intro b1.
  intro b2.
  destruct b1.
    - destruct b2.
      + reflexivity.
      + simpl. reflexivity.
    - destruct b2.
      + simpl. reflexivity.
      + reflexivity.
Qed.

Print andb_comm.


(************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

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

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

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

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

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

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

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

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

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

(** Exemple of use: *)

Section Examples.

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

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

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

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

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

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

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

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

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

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

End Examples.

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

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


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

Inductive nat : Set :=
| O : nat
| S : nat -> nat.

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Definition synth (y : natural) (x : natural) : natural := Succ (plus y x).


From Hammer Require Import Hammer.

Require Import BinNat.
Local Open Scope N_scope.

Definition Pdiv_eucl a b := N.pos_div_eucl a (Npos b).

Definition Pdiv_eucl_correct a b :
let (q,r) := Pdiv_eucl a b in Npos a = q * Npos b + r
:= N.pos_div_eucl_spec a (Npos b).

Lemma Pdiv_eucl_remainder a b :
snd (Pdiv_eucl a b) < Npos b.
Proof. hammer_hook "Ndiv_def" "Ndiv_def.Pdiv_eucl_remainder".   now apply (N.pos_div_eucl_remainder a (Npos b)). Qed.

Notation Ndiv_eucl := N.div_eucl (compat "8.3").
Notation Ndiv := N.div (compat "8.3").
Notation Nmod := N.modulo (compat "8.3").

Notation Ndiv_eucl_correct := N.div_eucl_spec (compat "8.3").
Notation Ndiv_mod_eq := N.div_mod' (compat "8.3").
Notation Nmod_lt := N.mod_lt (compat "8.3").


(** printing ==>  $⟹$  #⟹#  *)
(** printing ==>* $⟹*$ #⟹*# *)
(** printing |-   $⊢$  #⊢#  *)
(** printing \in  $∈$  #∈#  *)

(** * Types: Type Systems *)

(** Our next major topic is _type systems_ -- static program
    analyses that classify expressions according to the "shapes" of
    their results.  We'll begin with a typed version of the simplest
    imaginable language, to introduce the basic ideas of types and
    typing rules and the fundamental theorems about type systems:
    _type preservation_ and _progress_.  In chapter [Stlc] we'll move
    on to the _simply typed lambda-calculus_, which lives at the core
    of every modern functional programming language (including
    Coq!). *)

Require Import Coq.Arith.Arith.

Load Relation.
Load Maps.

Hint Constructors multi.

(* ################################################################# *)
(** * Typed Arithmetic Expressions *)

(** To motivate the discussion of type systems, let's begin as
    usual with a tiny toy language.  We want it to have the potential
    for programs to go wrong because of runtime type errors, so we
    need something a tiny bit more complex than the language of
    constants and addition that we used in chapter [Smallstep]: a
    single kind of data (e.g., numbers) is too simple, but just two
    kinds (numbers and booleans) gives us enough material to tell an
    interesting story.

    The language definition is completely routine. *)

(* ================================================================= *)
(** ** Syntax *)

(** Here is the syntax, informally:
<<
    t ::= true
        | false
        | if t then t else t
        | 0
        | succ t
        | pred t
        | iszero t
>>
    And here it is formally: *)

Inductive tm : Type :=
  | ttrue : tm
  | tfalse : tm
  | tif : tm -> tm -> tm -> tm
  | tzero : tm
  | tsucc : tm -> tm
  | tpred : tm -> tm
  | tiszero : tm -> tm.

(** _Values_ are [true], [false], and numeric values... *)

Inductive bvalue : tm -> Prop :=
  | bv_true : bvalue ttrue
  | bv_false : bvalue tfalse.

Inductive nvalue : tm -> Prop :=
  | nv_zero : nvalue tzero
  | nv_succ : forall t, nvalue t -> nvalue (tsucc t).

Definition value (t:tm) := bvalue t \/ nvalue t.

Hint Constructors bvalue nvalue.
Hint Unfold value.
Hint Unfold update.

(* ================================================================= *)
(** ** Operational Semantics *)

(** Here is the single-step relation, first informally... *)
(**
<<
                    ------------------------------                  (ST_IfTrue)
                    if true then t1 else t2 ==> t1

                   -------------------------------                 (ST_IfFalse)
                   if false then t1 else t2 ==> t2

                              t1 ==> t1'
            ------------------------------------------------            (ST_If)
            if t1 then t2 else t3 ==> if t1' then t2 else t3

                              t1 ==> t1'
                         --------------------                         (ST_Succ)
                         succ t1 ==> succ t1'

                             ------------                         (ST_PredZero)
                             pred 0 ==> 0

                           numeric value v1
                        ---------------------                     (ST_PredSucc)
                        pred (succ v1) ==> v1

                              t1 ==> t1'
                         --------------------                         (ST_Pred)
                         pred t1 ==> pred t1'

                          -----------------                     (ST_IszeroZero)
                          iszero 0 ==> true

                           numeric value v1
                      --------------------------                (ST_IszeroSucc)
                      iszero (succ v1) ==> false

                              t1 ==> t1'
                       ------------------------                     (ST_Iszero)
                       iszero t1 ==> iszero t1'
>>
*)

(** ... and then formally: *)

Reserved Notation "t1 '==>' t2" (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_IfTrue : forall t1 t2,
      (tif ttrue t1 t2) ==> t1
  | ST_IfFalse : forall t1 t2,
      (tif tfalse t1 t2) ==> t2
  | ST_If : forall t1 t1' t2 t3,
      t1 ==> t1' ->
      (tif t1 t2 t3) ==> (tif t1' t2 t3)
  | ST_Succ : forall t1 t1',
      t1 ==> t1' ->
      (tsucc t1) ==> (tsucc t1')
  | ST_PredZero :
      (tpred tzero) ==> tzero
  | ST_PredSucc : forall t1,
      nvalue t1 ->
      (tpred (tsucc t1)) ==> t1
  | ST_Pred : forall t1 t1',
      t1 ==> t1' ->
      (tpred t1) ==> (tpred t1')
  | ST_IszeroZero :
      (tiszero tzero) ==> ttrue
  | ST_IszeroSucc : forall t1,
       nvalue t1 ->
      (tiszero (tsucc t1)) ==> tfalse
  | ST_Iszero : forall t1 t1',
      t1 ==> t1' ->
      (tiszero t1) ==> (tiszero t1')

where "t1 '==>' t2" := (step t1 t2).

Hint Constructors step.

(** Notice that the [step] relation doesn't care about whether
    expressions make global sense -- it just checks that the operation
    in the _next_ reduction step is being applied to the right kinds
    of operands.  For example, the term [succ true] (i.e.,
    [tsucc ttrue] in the formal syntax) cannot take a step, but the
    almost as obviously nonsensical term
<<
       succ (if true then true else true)
>>
    can take a step (once, before becoming stuck). *)

(* ================================================================= *)
(** ** Normal Forms and Values *)

(** The first interesting thing to notice about this [step] relation
    is that the strong progress theorem from the [Smallstep] chapter
    fails here.  That is, there are terms that are normal forms (they
    can't take a step) but not values (because we have not included
    them in our definition of possible "results of reduction").  Such
    terms are _stuck_. *)

Notation step_normal_form := (normal_form step).

Definition stuck (t:tm) : Prop :=
  step_normal_form t /\ ~ value t.

Hint Unfold stuck.

(** **** Exercise: 2 stars (some_term_is_stuck)  *)
Example some_term_is_stuck :
  exists t, stuck t.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** However, although values and normal forms are _not_ the same in this
    language, the set of values is included in the set of normal
    forms.  This is important because it shows we did not accidentally
    define things so that some value could still take a step. *)

(** **** Exercise: 3 stars (value_is_nf)  *)
Lemma value_is_nf : forall t,
  value t -> step_normal_form t.
Proof.
  (* FILL IN HERE *) Admitted.

(** (Hint: You will reach a point in this proof where you need to
    use an induction to reason about a term that is known to be a
    numeric value.  This induction can be performed either over the
    term itself or over the evidence that it is a numeric value.  The
    proof goes through in either case, but you will find that one way
    is quite a bit shorter than the other.  For the sake of the
    exercise, try to complete the proof both ways.) *)
(** [] *)

(** **** Exercise: 3 stars, optional (step_deterministic)  *)
(** Use [value_is_nf] to show that the [step] relation is also
    deterministic. *)

Theorem step_deterministic:
  deterministic step.
Proof with eauto.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Typing *)

(** The next critical observation is that, although this
    language has stuck terms, they are always nonsensical, mixing
    booleans and numbers in a way that we don't even _want_ to have a
    meaning.  We can easily exclude such ill-typed terms by defining a
    _typing relation_ that relates terms to the types (either numeric
    or boolean) of their final results.  *)

Inductive ty : Type :=
  | TBool : ty
  | TNat : ty.

(** In informal notation, the typing relation is often written
    [|- t \in T] and pronounced "[t] has type [T]."  The [|-] symbol
    is called a "turnstile."  Below, we're going to see richer typing
    relations where one or more additional "context" arguments are
    written to the left of the turnstile.  For the moment, the context
    is always empty. *)
(**
<<
                           ----------------                            (T_True)
                           |- true \in Bool

                          -----------------                           (T_False)
                          |- false \in Bool

             |- t1 \in Bool    |- t2 \in T    |- t3 \in T
             --------------------------------------------                (T_If)
                    |- if t1 then t2 else t3 \in T

                             ------------                              (T_Zero)
                             |- 0 \in Nat

                            |- t1 \in Nat
                          ------------------                           (T_Succ)
                          |- succ t1 \in Nat

                            |- t1 \in Nat
                          ------------------                           (T_Pred)
                          |- pred t1 \in Nat

                            |- t1 \in Nat
                        ---------------------                        (T_IsZero)
                        |- iszero t1 \in Bool
>>
*)

Reserved Notation "'|-' t '\in' T" (at level 40).

Inductive has_type : tm -> ty -> Prop :=
  | T_True :
       |- ttrue \in TBool
  | T_False :
       |- tfalse \in TBool
  | T_If : forall t1 t2 t3 T,
       |- t1 \in TBool ->
       |- t2 \in T ->
       |- t3 \in T ->
       |- tif t1 t2 t3 \in T
  | T_Zero :
       |- tzero \in TNat
  | T_Succ : forall t1,
       |- t1 \in TNat ->
       |- tsucc t1 \in TNat
  | T_Pred : forall t1,
       |- t1 \in TNat ->
       |- tpred t1 \in TNat
  | T_Iszero : forall t1,
       |- t1 \in TNat ->
       |- tiszero t1 \in TBool

where "'|-' t '\in' T" := (has_type t T).

Hint Constructors has_type.

Example has_type_1 :
  |- tif tfalse tzero (tsucc tzero) \in TNat.
Proof.
  apply T_If.
    - apply T_False.
    - apply T_Zero.
    - apply T_Succ.
       + apply T_Zero.
Qed.

(** (Since we've included all the constructors of the typing relation
    in the hint database, the [auto] tactic can actually find this
    proof automatically.) *)

(** It's important to realize that the typing relation is a
    _conservative_ (or _static_) approximation: it does not consider
    what happens when the term is reduced -- in particular, it does
    not calculate the type of its normal form. *)

Example has_type_not :
  ~ (|- tif tfalse tzero ttrue \in TBool).
Proof.
  intros Contra. solve_by_inverts 2.  Qed.

(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat)  *)
Example succ_hastype_nat__hastype_nat : forall t,
  |- tsucc t \in TNat ->
  |- t \in TNat.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ----------------------------------------------------------------- *)
(** *** Canonical forms *)

(** The following two lemmas capture the fundamental property that the
    definitions of boolean and numeric values agree with the typing
    relation. *)

Lemma bool_canonical : forall t,
  |- t \in TBool -> value t -> bvalue t.
Proof.
  intros t HT HV.
  inversion HV; auto.
  induction H; inversion HT; auto.
Qed.

Lemma nat_canonical : forall t,
  |- t \in TNat -> value t -> nvalue t.
Proof.
  intros t HT HV.
  inversion HV.
  inversion H; subst; inversion HT.
  auto.
Qed.

(* ================================================================= *)
(** ** Progress *)

(** The typing relation enjoys two critical properties.  The first is
    that well-typed normal forms are not stuck -- or conversely, if a
    term is well typed, then either it is a value or it can take at
    least one step.  We call this _progress_. *)

(** **** Exercise: 3 stars (finish_progress)  *)
Theorem progress : forall t T,
  |- t \in T ->
  value t \/ exists t', t ==> t'.

(** Complete the formal proof of the [progress] property.  (Make sure
    you understand the parts we've given of the informal proof in the
    following exercise before starting -- this will save you a lot of
    time.) *)
Proof with auto.
  intros t T HT.
  induction HT...
  (* The cases that were obviously values, like T_True and
     T_False, were eliminated immediately by auto *)
  - (* T_If *)
    right. inversion IHHT1; clear IHHT1.
    + (* t1 is a value *)
    apply (bool_canonical t1 HT1) in H.
    inversion H; subst; clear H.
      exists t2...
      exists t3...
    + (* t1 can take a step *)
      inversion H as [t1' H1].
      exists (tif t1' t2 t3)...
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advancedM (finish_progress_informal)  *)
(** Complete the corresponding informal proof: *)

(** _Theorem_: If [|- t \in T], then either [t] is a value or else
    [t ==> t'] for some [t']. *)

(** _Proof_: By induction on a derivation of [|- t \in T].

      - If the last rule in the derivation is [T_If], then [t = if t1
        then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
        \in T].  By the IH, either [t1] is a value or else [t1] can step
        to some [t1'].

            - If [t1] is a value, then by the canonical forms lemmas
              and the fact that [|- t1 \in Bool] we have that [t1]
              is a [bvalue] -- i.e., it is either [true] or [false].
              If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],
              while if [t1 = false], then [t] steps to [t3] by
              [ST_IfFalse].  Either way, [t] can step, which is what
              we wanted to show.

            - If [t1] itself can take a step, then, by [ST_If], so can
              [t].

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

(** This theorem is more interesting than the strong progress theorem
    that we saw in the [Smallstep] chapter, where _all_ normal forms
    were values.  Here a term can be stuck, but only if it is ill
    typed. *)

(* ================================================================= *)
(** ** Type Preservation *)

(** The second critical property of typing is that, when a well-typed
    term takes a step, the result is also a well-typed term. *)

(** **** Exercise: 2 stars (finish_preservation)  *)
Theorem preservation : forall t t' T,
  |- t \in T ->
  t ==> t' ->
  |- t' \in T.

(** Complete the formal proof of the [preservation] property.  (Again,
    make sure you understand the informal proof fragment in the
    following exercise first.) *)

Proof with auto.
  intros t t' T HT HE.
  generalize dependent t'.
  induction HT;
         (* every case needs to introduce a couple of things *)
         intros t' HE;
         (* and we can deal with several impossible
            cases all at once *)
         try solve_by_invert.
    - (* T_If *) inversion HE; subst; clear HE.
      + (* ST_IFTrue *) assumption.
      + (* ST_IfFalse *) assumption.
      + (* ST_If *) apply T_If; try assumption.
        apply IHHT1; assumption.
    (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advancedM (finish_preservation_informal)  *)
(** Complete the following informal proof: *)

(** _Theorem_: If [|- t \in T] and [t ==> t'], then [|- t' \in T]. *)

(** _Proof_: By induction on a derivation of [|- t \in T].

      - If the last rule in the derivation is [T_If], then [t = if t1
        then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
        \in T].

        Inspecting the rules for the small-step reduction relation and
        remembering that [t] has the form [if ...], we see that the
        only ones that could have been used to prove [t ==> t'] are
        [ST_IfTrue], [ST_IfFalse], or [ST_If].

           - If the last rule was [ST_IfTrue], then [t' = t2].  But we
             know that [|- t2 \in T], so we are done.

           - If the last rule was [ST_IfFalse], then [t' = t3].  But we
             know that [|- t3 \in T], so we are done.

           - If the last rule was [ST_If], then [t' = if t1' then t2
             else t3], where [t1 ==> t1'].  We know [|- t1 \in Bool] so,
             by the IH, [|- t1' \in Bool].  The [T_If] rule then gives us
             [|- if t1' then t2 else t3 \in T], as required.

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

(** **** Exercise: 3 stars (preservation_alternate_proof)  *)
(** Now prove the same property again by induction on the
    _evaluation_ derivation instead of on the typing derivation.
    Begin by carefully reading and thinking about the first few
    lines of the above proofs to make sure you understand what
    each one is doing.  The set-up for this proof is similar, but
    not exactly the same. *)

Theorem preservation' : forall t t' T,
  |- t \in T ->
  t ==> t' ->
  |- t' \in T.
Proof with eauto.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** The preservation theorem is often called _subject reduction_,
    because it tells us what happens when the "subject" of the typing
    relation is reduced.  This terminology comes from thinking of
    typing statements as sentences, where the term is the subject and
    the type is the predicate. *)

(* ================================================================= *)
(** ** Type Soundness *)

(** Putting progress and preservation together, we see that a
    well-typed term can never reach a stuck state.  *)

Definition multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).

Corollary soundness : forall t t' T,
  |- t \in T ->
  t ==>* t' ->
  ~(stuck t').
Proof.
  intros t t' T HT P. induction P; intros [R S].
  destruct (progress x T HT); auto.
  apply IHP.  apply (preservation x y T HT H).
  unfold stuck. split; auto.   Qed.

(* ################################################################# *)
(** * Aside: the [normalize] Tactic *)

(** When experimenting with definitions of programming languages
    in Coq, we often want to see what a particular concrete term steps
    to -- i.e., we want to find proofs for goals of the form [t ==>*
    t'], where [t] is a completely concrete term and [t'] is unknown.
    These proofs are quite tedious to do by hand.  Consider, for
    example, reducing an arithmetic expression using the small-step
    relation [astep]. *)

Tactic Notation "print_goal" :=
  match goal with |- ?x => idtac x end.
Tactic Notation "normalize" :=
  repeat (print_goal; eapply multi_step ;
            [ (eauto 10; fail) | (instantiate; simpl)]);
  apply multi_refl.

Example step_example1'' :
  tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc (tzero)))
  ==>* tzero.
Proof.
  normalize.
  (* The [print_goal] in the [normalize] tactic shows
     a trace of how the expression reduced...

     (tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc tzero)) ==>* tzero)
     (multi step (tif tfalse (tsucc tzero) (tpred (tsucc tzero))) tzero)
     (multi step (tpred (tsucc tzero)) tzero)
     (multi step tzero tzero)
  *)
Qed.

(** The [normalize] tactic also provides a simple way to calculate the
    normal form of a term, by starting with a goal with an existentially
    bound variable. *)

Example step_example1''' : exists e',
  tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc (tzero)))
  ==>* e'.
Proof.
  eapply ex_intro. normalize.
(* This time, the trace is:

  (tif (tiszero (tsucc tzero)) (tsucc tzero) (tpred (tsucc tzero)) ==>* ?e')
  (multi step (tif tfalse (tsucc tzero) (tpred (tsucc tzero))) ?e')
  (multi step (tpred (tsucc tzero)) ?e')
  (multi step tzero ?e')

   where ?e' is the variable ``guessed'' by eapply. *)
Qed.

(** **** Exercise: 1 star (normalize_ex)  *)
Theorem normalize_ex : exists e',
  (tsucc (tpred (tpred tzero)))
  ==>* e'.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optional (normalize_ex')  *)
(** For comparison, prove it using [apply] instead of [eapply]. *)

Theorem normalize_ex' : exists e',
  (tsucc (tpred (tpred tzero)))
  ==>* e'.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Additional Exercises *)

(** **** Exercise: 2 stars, recommendedM (subject_expansion)  *)
(** Having seen the subject reduction property, one might
    wonder whether the opposity property -- subject _expansion_ --
    also holds.  That is, is it always the case that, if [t ==> t']
    and [|- t' \in T], then [|- t \in T]?  If so, prove it.  If
    not, give a counter-example.  (You do not need to prove your
    counter-example in Coq, but feel free to do so.)

    (* FILL IN HERE *)
[] *)

(** **** Exercise: 2 starsM (variation1)  *)
(** Suppose, that we add this new rule to the typing relation:
<<
      | T_SuccBool : forall t,
           |- t \in TBool ->
           |- tsucc t \in TBool
>>
   Which of the following properties remain true in the presence of
   this rule?  For each one, write either "remains true" or
   else "becomes false." If a property becomes false, give a
   counterexample.
      - Determinism of [step]

      - Progress

      - Preservation

[] *)

(** **** Exercise: 2 starsM (variation2)  *)
(** Suppose, instead, that we add this new rule to the [step] relation:
<<
      | ST_Funny1 : forall t2 t3,
           (tif ttrue t2 t3) ==> t3
>>
   Which of the above properties become false in the presence of
   this rule?  For each one that does, give a counter-example.

[] *)

(** **** Exercise: 2 stars, optional (variation3)  *)
(** Suppose instead that we add this rule:
<<
      | ST_Funny2 : forall t1 t2 t2' t3,
           t2 ==> t2' ->
           (tif t1 t2 t3) ==> (tif t1 t2' t3)
>>
   Which of the above properties become false in the presence of
   this rule?  For each one that does, give a counter-example.

[] *)

(** **** Exercise: 2 stars, optional (variation4)  *)
(** Suppose instead that we add this rule:
<<
      | ST_Funny3 :
          (tpred tfalse) ==> (tpred (tpred tfalse))
>>
   Which of the above properties become false in the presence of
   this rule?  For each one that does, give a counter-example.

[] *)

(** **** Exercise: 2 stars, optional (variation5)  *)
(** Suppose instead that we add this rule:
<<
      | T_Funny4 :
            |- tzero \in TBool
>>
   Which of the above properties become false in the presence of
   this rule?  For each one that does, give a counter-example.

[] *)

(** **** Exercise: 2 stars, optional (variation6)  *)
(** Suppose instead that we add this rule:
<<
      | T_Funny5 :
            |- tpred tzero \in TBool
>>
   Which of the above properties become false in the presence of
   this rule?  For each one that does, give a counter-example.

[] *)

(** **** Exercise: 3 stars, optional (more_variations)  *)
(** Make up some exercises of your own along the same lines as
    the ones above.  Try to find ways of selectively breaking
    properties -- i.e., ways of changing the definitions that
    break just one of the properties and leave the others alone.
[] *)

(** **** Exercise: 1 starM (remove_predzero)  *)
(** The reduction rule [ST_PredZero] is a bit counter-intuitive: we
    might feel that it makes more sense for the predecessor of zero to
    be undefined, rather than being defined to be zero.  Can we
    achieve this simply by removing the rule from the definition of
    [step]?  Would doing so create any problems elsewhere?

(* FILL IN HERE *)
[] *)

(** **** Exercise: 4 stars, advancedM (prog_pres_bigstep)  *)
(** Suppose our evaluation relation is defined in the big-step style.
    What are the appropriate analogs of the progress and preservation
    properties?  (You do not need to prove them.)

(* FILL IN HERE *)
[] *)

(** $Date: 2016-12-20 11:35:30 -0500 (Tue, 20 Dec 2016) $ *)


 (************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

(** Properties of addition. [add] is defined in [Init/Peano.v] as:
<<
Fixpoint plus (n m:nat) : nat :=
  match n with
  | O => m
  | S p => S (p + m)
  end
where "n + m" := (plus n m) : nat_scope.
>>
 *)

Require Import Le.
Require Import Lt.

Open Local Scope nat_scope.

Implicit Types m n p q : nat.

(** * Zero is neutral
Deprecated : Already in Init/Peano.v *)
Notation plus_0_l := plus_O_n (only parsing).
Definition plus_0_r n := eq_sym (plus_n_O n).

(** * Commutativity *)

Lemma plus_comm : forall n m, n + m = m + n.
Proof.
  intros n m; elim n; simpl in |- *; auto with arith.
  intros y H; elim (plus_n_Sm m y); auto with arith.
Qed.
Hint Immediate plus_comm: arith v62.

(** * Associativity *)

Definition plus_Snm_nSm : forall n m, S n + m = n + S m:=
 plus_n_Sm.

Lemma plus_assoc : forall n m p, n + (m + p) = n + m + p.
Proof.
  intros n m p; elim n; simpl in |- *; auto with arith.
Qed.
Hint Resolve plus_assoc: arith v62.

Lemma plus_permute : forall n m p, n + (m + p) = m + (n + p).
Proof.
  intros; rewrite (plus_assoc m n p); rewrite (plus_comm m n); auto with arith.
Qed.

Lemma plus_assoc_reverse : forall n m p, n + m + p = n + (m + p).
Proof.
  auto with arith.
Qed.
Hint Resolve plus_assoc_reverse: arith v62.

(** * Simplification *)

Lemma plus_reg_l : forall n m p, p + n = p + m -> n = m.
Proof.
  intros m p n; induction n; simpl in |- *; auto with arith.
Qed.

Lemma plus_le_reg_l : forall n m p, p + n <= p + m -> n <= m.
Proof.
  induction p; simpl in |- *; auto with arith.
Qed.

Lemma plus_lt_reg_l : forall n m p, p + n < p + m -> n < m.
Proof.
  induction p; simpl in |- *; auto with arith.
Qed.

(** * Compatibility with order *)

Lemma plus_le_compat_l : forall n m p, n <= m -> p + n <= p + m.
Proof.
  induction p; simpl in |- *; auto with arith.
Qed.
Hint Resolve plus_le_compat_l: arith v62.

Lemma plus_le_compat_r : forall n m p, n <= m -> n + p <= m + p.
Proof.
  induction 1; simpl in |- *; auto with arith.
Qed.
Hint Resolve plus_le_compat_r: arith v62.

Lemma le_plus_l : forall n m, n <= n + m.
Proof.
  induction n; simpl in |- *; auto with arith.
Qed.
Hint Resolve le_plus_l: arith v62.

Lemma le_plus_r : forall n m, m <= n + m.
Proof.
  intros n m; elim n; simpl in |- *; auto with arith.
Qed.
Hint Resolve le_plus_r: arith v62.

Theorem le_plus_trans : forall n m p, n <= m -> n <= m + p.
Proof.
  intros; apply le_trans with (m := m); auto with arith.
Qed.
Hint Resolve le_plus_trans: arith v62.

Theorem lt_plus_trans : forall n m p, n < m -> n < m + p.
Proof.
  intros; apply lt_le_trans with (m := m); auto with arith.
Qed.
Hint Immediate lt_plus_trans: arith v62.

Lemma plus_lt_compat_l : forall n m p, n < m -> p + n < p + m.
Proof.
  induction p; simpl in |- *; auto with arith.
Qed.
Hint Resolve plus_lt_compat_l: arith v62.

Lemma plus_lt_compat_r : forall n m p, n < m -> n + p < m + p.
Proof.
  intros n m p H; rewrite (plus_comm n p); rewrite (plus_comm m p).
  elim p; auto with arith.
Qed.
Hint Resolve plus_lt_compat_r: arith v62.

Lemma plus_le_compat : forall n m p q, n <= m -> p <= q -> n + p <= m + q.
Proof.
  intros n m p q H H0.
  elim H; simpl in |- *; auto with arith.
Qed.

Lemma plus_le_lt_compat : forall n m p q, n <= m -> p < q -> n + p < m + q.
Proof.
  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. rewrite plus_Snm_nSm.
  apply plus_le_compat; assumption.
Qed.

Lemma plus_lt_le_compat : forall n m p q, n < m -> p <= q -> n + p < m + q.
Proof.
  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. apply plus_le_compat; assumption.
Qed.

Lemma plus_lt_compat : forall n m p q, n < m -> p < q -> n + p < m + q.
Proof.
  intros. apply plus_lt_le_compat. assumption.
  apply lt_le_weak. assumption.
Qed.

(** * Inversion lemmas *)

Lemma plus_is_O : forall n m, n + m = 0 -> n = 0 /\ m = 0.
Proof.
  intro m; destruct m as [| n]; auto.
  intros. discriminate H.
Qed.

Definition plus_is_one :
  forall m n, m + n = 1 -> {m = 0 /\ n = 1} + {m = 1 /\ n = 0}.
Proof.
  intro m; destruct m as [| n]; auto.
  destruct n; auto.
  intros.
  simpl in H. discriminate H.
Defined.

(** * Derived properties *)

Lemma plus_permute_2_in_4 : forall n m p q, n + m + (p + q) = n + p + (m + q).
Proof.
  intros m n p q.
  rewrite <- (plus_assoc m n (p + q)). rewrite (plus_assoc n p q).
  rewrite (plus_comm n p). rewrite <- (plus_assoc p n q). apply plus_assoc.
Qed.

(** * Tail-recursive plus *)

(** [tail_plus] is an alternative definition for [plus] which is
    tail-recursive, whereas [plus] is not. This can be useful
    when extracting programs. *)

Fixpoint tail_plus n m : nat :=
  match n with
    | O => m
    | S n => tail_plus n (S m)
  end.

Lemma plus_tail_plus : forall n m, n + m = tail_plus n m.
induction n as [| n IHn]; simpl in |- *; auto.
intro m; rewrite <- IHn; simpl in |- *; auto.
Qed.

(** * Discrimination *)

Lemma succ_plus_discr : forall n m, n <> S (plus m n).
Proof.
  intros n m; induction n as [|n IHn].
  discriminate.
  intro H; apply IHn; apply eq_add_S; rewrite H; rewrite <- plus_n_Sm;
    reflexivity.
Qed.

Lemma n_SSn : forall n, n <> S (S n).
Proof.
  intro n; exact (succ_plus_discr n 1).
Qed.

Lemma n_SSSn : forall n, n <> S (S (S n)).
Proof.
  intro n; exact (succ_plus_discr n 2).
Qed.

Lemma n_SSSSn : forall n, n <> S (S (S (S n))).
Proof.
  intro n; exact (succ_plus_discr n 3).
Qed.


(** Coq coding by choukh, Oct 2021 **)

Require Import BBST.Axiom.Meta.
Require Import BBST.Axiom.Extensionality.
Require Import BBST.Axiom.Separation.
Require Import BBST.Axiom.Union.
Require Import BBST.Definition.Include.
Require Import BBST.Definition.Emptyset.
Require Import BBST.Definition.Intersect.
Require Import BBST.Definition.BinaryUnion.
Require Import BBST.Definition.BinaryIntersect.
Require Import BBST.Definition.Complement.

Lemma 并交吸收律 : ∀ A B, A ∪ (A ∩ B) = A.
Proof with auto.
  intros. 外延... apply 二元并除去 in H as []...
  apply 二元交除去 in H as []...
Qed.

Lemma 交并吸收律 : ∀ A B, A ∩ (A ∪ B) = A.
Proof with auto.
  intros. 外延... apply 二元交除去 in H as []...
Qed.

Lemma 交并分配律 : ∀ A B C, (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C).
Proof with auto.
  intros. 外延.
  - apply 二元并除去 in H as []...
    apply 二元交除去 in H as []...
  - apply 二元交除去 in H as [];
    apply 二元并除去 in H as [];
    apply 二元并除去 in H0 as []...
Qed.

Lemma 并交分配律 : ∀ A B C, (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C).
Proof with auto.
  intros. 外延.
  - apply 二元交除去 in H as [].
    apply 二元并除去 in H as []...
  - apply 二元并除去 in H as [];
    apply 二元交除去 in H as []...
Qed.

Lemma 并补分配律 : ∀ A B C, (A ∪ B) - C = (A - C) ∪ (B - C).
Proof.
  intros. 外延.
  - apply 分离除去 in H as [Hx Hx'].
    apply 二元并除去 in Hx as [].
    + apply 左并介入. now apply 分离介入.
    + apply 右并介入. now apply 分离介入.
  - apply 二元并除去 in H as [];
    apply 分离除去 in H as [Hx Hx']; apply 分离介入; auto.
Qed.

Lemma 交补分配律 : ∀ A B C, (A ∩ B) - C = (A - C) ∩ (B - C).
Proof.
  intros. 外延.
  - apply 分离除去 in H as [Hx Hx'].
    apply 二元交除去 in Hx as [].
    apply 二元交介入; now apply 分离介入.
  - apply 二元交除去 in H as [].
    apply 分离除去 in H as [HxA HxC].
    apply 分离之父集 in H0. apply 分离介入; auto.
Qed.

Corollary 交补分配律_简化 : ∀ A B C, (A ∩ B) - C = A ∩ (B - C).
Proof.
  intros. rewrite 交补分配律. 外延.
  - apply 二元交除去 in H as []. apply 分离之父集 in H.
    apply 二元交介入; auto.
  - apply 二元交除去 in H as [H1 H2].
    apply 分离除去 in H2 as [Hx Hx'].
    apply 二元交介入; apply 分离介入; auto.
Qed.

Lemma 补并德摩根律 : ∀ A B C, C - (A ∪ B) = (C - A) ∩ (C - B).
Proof.
  intros. 外延.
  - apply 分离除去 in H as [Hx Hx'].
    apply 二元交介入; apply 分离介入; auto.
  - apply 二元交除去 in H as [H1 H2].
    apply 分离除去 in H1 as [Hx Hx']. apply 分离之条件 in H2.
    apply 分离介入; auto. now apply 二元并外介入.
Qed.

Lemma 补交德摩根律 : ∀ A B C, C - (A ∩ B) = (C - A) ∪ (C - B).
Proof.
  intros. 外延.
  - apply 分离除去 in H as [Hx Hx'].
    apply 二元交外除去 in Hx' as [].
    + apply 左并介入. now apply 分离介入.
    + apply 右并介入. now apply 分离介入.
  - apply 二元并除去 in H as [];
    apply 分离除去 in H as [Hx Hx'];
    apply 分离介入; auto; apply 二元交外介入; auto.
Qed.

Lemma 先补再并等于没补 : ∀ A B, A ∪ (B - A) = A ∪ B.
Proof with auto.
  intros. 外延.
  - apply 二元并除去 in H as []... apply 分离之父集 in H...
  - apply 二元并除去 in H as []...
    排中 (x ∈ A)... apply 右并介入. apply 分离介入...
Qed.

Lemma 先并再补等于没并 : ∀ A B, (A ∪ B) - A = B - A.
Proof with auto.
  intros. 外延; apply 分离除去 in H as [].
  - apply 二元并除去 in H as []. exfalso... apply 分离介入...
  - apply 分离介入...
Qed.

Lemma 并自身之补得全集 : ∀ A S, A ⊆ S → A ∪ (S - A) = S.
Proof with auto.
  intros. rewrite 先补再并等于没补. 外延...
  apply 二元并除去 in H0 as []; auto.
Qed.

Lemma 交自身之补得空集 : ∀ A S, A ∩ (S - A) = ∅.
Proof.
  intros. apply 空集介入. intros x H.
  apply 二元交除去 in H as [H1 H2].
  now apply 分离之条件 in H2.
Qed.


(** * 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.
Search (evenb (S _)).
(* ################################################################# *)
(** * Polymorphism *)

(** In this chapter weopt 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 with lists
    containing just numbers.  Obviously, interesting programs also
    need to be able to manipulate lists with elements from other
    types -- 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 function header on the first line,
    and the occurrences of [natlist] in the types of the constructors
    have been replaced by [list X].

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

Check 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) : 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)) : 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 : 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 : forall X : Type, X -> list X -> list X.

(** (A side note on notations: 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, depending on the settings of their
    display controls, [forall] is usually typeset as the standard
    mathematical "upside down A," though 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 every single use of a
    list constructor would be rather burdensome; we will soon see ways
    of reducing this annotation burden. *)

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

(** 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)]  NO -> d doit prendre un type X en premier argument puis un second argument de type mumble
      - [d mumble (b a 5)] YES grumble mumble
      - [d bool (b a 5)]      YES grumble bool
      - [e bool true]         YES grumble bool
      - [e mumble (b c 0)] YES grumble mumble
      - [e bool (b c 0)]      NO mal typé
      - [c]  NO -> il est bien typé de type mumble est pas grumble X*)
(* FILL IN HERE *)
Check grumble.
Check d.
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 can still be quite useful as documentation and sanity
    checks, so we will continue to use them much of the time. *)

(* ----------------------------------------------------------------- *)
(** *** 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 -- and, 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 holes

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

(** In fact, 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, because Coq is not expecting it.)

    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, once in a while, 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 : 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.
  intros X l.
  induction l.
  - reflexivity.
  - simpl.
    rewrite IHl.
    reflexivity.
Qed.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  intros A l m n.
  induction l.
  - reflexivity.
  - simpl.
    rewrite IHl.
    reflexivity.
Qed.

Lemma app_length : forall (X:Type) (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  intros X l1 l2.
  induction l1.
  - reflexivity.
  - 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.
  intros X l1 l2.
  induction l1 as [| x l1' IHl1'].
  - simpl.
    Search (_ ++ []).
    rewrite -> app_nil_r.
    reflexivity.
  - simpl.
    rewrite IHl1'.
    Search ((_ ++ _ ) ++ _).
    rewrite app_assoc.
    reflexivity.
Qed.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  intros X l.
  induction l.
  - reflexivity.
  - simpl.
    rewrite rev_app_distr.
    rewrite IHl.
    reflexivity.
Qed.
(** [] *)

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

(** Following the same pattern, the definition for pairs of
    numbers that we gave in the last chapter 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, not when parsing
    expressions.  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, especially useful (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) :=
  match l with
  | [] => ([], [])
  | (x,y)::l' =>
    match split l' with
      (l1,l2) => (x::l1, y::l2)
    end
  end.

Fixpoint split' {X Y : Type} (l : list (X*Y))
  : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (x,y)::l' => (x::fst(split l'), y::snd(split l'))
  end.

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

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

(** Our last polymorphic type for now is _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
  | nil => None
  | a :: l' => match n with
               | O => Some a
               | S n' => nth_error l' n'
               end
  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 :=
  match l with
  | [] => None
  | x::_ => Some x
  end.

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

Check @hd_error : forall X : Type, list X -> option X.

Example test_hd_error1 : hd_error [1;2] = Some 1.
Proof. reflexivity. Qed.
Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].
Proof. reflexivity. Qed.
(** [] *)

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

(** Like most modern programming languages -- especially other
    "functional" languages, including OCaml, Haskell, Racket, 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 : 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 :=
    filter (fun n => andb (evenb n) (leb 7 n)) l.

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

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
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 predicate 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 :=
    (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]).
Proof. reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
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. *)

Lemma map_fct_comm : forall (X Y: Type) (f:X->Y)(l: list X) (x:X),
     map f (l ++ [x]) = map f l ++ [f x].
Proof.
 intros X Y f l x.
 induction l as [| n l'].
 - simpl. reflexivity.
 - simpl. rewrite -> IHl'.
   reflexivity. Qed.

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  intros X Y f l.
  induction l as [| x l1' IHl1'].
  - simpl. reflexivity.
  - simpl. rewrite <- IHl1'.
           rewrite -> map_fct_comm.
           reflexivity. Qed.
(** [] *)

(** **** Exercise: 2 stars, standard, especially useful (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) :=
 match l with
 | nil => nil
 | h :: t => app (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].
  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) : 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? *)

(* Oui, dans la situation ou on veut  faire une operation arithmetique sur les nombres
   avec differents type tel que  float et integer par exemple *)

(* 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 : nat -> nat.

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.
  intros X l.
  induction l as [| n l'].
  - reflexivity.
  - 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 :=
   fold (fun x tail=> f(x):: tail ) l [].

Example test_map1: fold_map ( fun x => x*x )[2;0;2] = [4;0;4].
Proof. reflexivity. Qed.

Example mytest2: fold_map (fun x => x * x )[] = [].
Proof. reflexivity. Qed.

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

Theorem fold_map_correct : forall X Y (l : list X) (f: X -> Y),
  fold_map f l = map f l.
  Proof.
  intros X Y l f.
  induction l as [| n l'].
  - simpl. reflexivity.
  - 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 :=  f (fst p) (snd p).

(** 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.
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.
  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
*)
(* THéorème : Pour tous listes de types X [l] et n de type nat, length l = n -> @nth_error X l n = None.

preuve  : Par induction sur [l].

  - premièrement, on suppose que [l = []]. Et on doit montre que

      length [] = n -> nth_error X [] n = None.

      Ce qui est vraie de la definition de [nth_error].
      Si 0 = n l'egalite None = None est toujours vraie.

  - Secondement, on suppose que [l = n::l'], avec

 *)

(* 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
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

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

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

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

(** [] *)

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

(** Addition of two natural numbers: *)
Definition plus (n m : cnat) : cnat
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

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

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

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

(** [] *)

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

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

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

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

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

(** [] *)

(** **** 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
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

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

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

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

(** [] *)

End Church.
End Exercises.

(* 2020-09-09 20:51 *)


(* Exercise 29 *)

Require Import BenB.

Variables A B C D : Prop.

Theorem exercise_029 : ~A -> (~(A \/ ~B) \/ (~A /\ ~B)).
Proof.
imp_i a1.
dis_e (B \/ ~B) a2 a2.
LEM.
dis_i1.
neg_i (1=1) a3.
dis_e (A \/ ~B) a4 a4.
hyp a3.
neg_e A.
hyp a1.
hyp a4.
neg_e B.
hyp a4.
hyp a2.
lin_solve.
dis_i2.
con_i.
hyp a1.
hyp a2.
Qed.


(* Exercise 25 *)

Require Import BenB.

Variables A B C D : Prop.

Theorem exercise_025 : A -> (~B \/ (A /\ B)).
Proof.
imp_i Sigma.
dis_e (B \/ ~B) G H.
LEM.
dis_i2.
con_i.
hyp Sigma.
hyp G.
dis_i1.
hyp H.
Qed.