(** * Logic: Logic in Coq *)

Require Export MoreCoq.

(** Coq's built-in logic is very small: the only primitives are
    [Inductive] definitions, universal quantification ([forall]), and
    implication ([->]), while all the other familiar logical
    connectives -- conjunction, disjunction, negation, existential
    quantification, even equality -- can be encoded using just these.

    This chapter explains the encodings and shows how the tactics
    we've seen can be used to carry out standard forms of logical
    reasoning involving these connectives. *)

(* ########################################################### *)
(** * Propositions *)

(** In previous chapters, we have seen many examples of factual
    claims (_propositions_) and ways of presenting evidence of their
    truth (_proofs_).  In particular, we have worked extensively with
    _equality propositions_ of the form [e1 = e2], with
    implications ([P -> Q]), and with quantified propositions
    ([forall x, P]).
*)

(** In Coq, the type of things that can (potentially)
    be proven is [Prop]. *)

(** Here is an example of a provable proposition: *)

Check (3 = 3).
(* ===> Prop *)

(** Here is an example of an unprovable proposition: *)

Check (forall (n:nat), n = 2).
(* ===> Prop *)

(** Recall that [Check] asks Coq to tell us the type of the indicated
  expression. *)

(* ########################################################### *)
(** * Proofs and Evidence *)

(** In Coq, propositions have the same status as other types, such as
    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit
    the type [nat], a Coq proposition [P] is inhabited by its
    _proofs_.  We will refer to such inhabitants as _proof term_ or
    _proof object_ or _evidence_ for the truth of [P].

    In Coq, when we state and then prove a lemma such as:

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

    the tactics we use within the [Proof]...[Qed] keywords tell Coq
    how to construct a proof term that inhabits the proposition.  In
    this case, the proposition [0 * 3 = 0] is justified by a
    combination of the _definition_ of [mult], which says that [0 * 3]
    _simplifies_ to just [0], and the _reflexive_ principle of
    equality, which says that [0 = 0].

*)

(** *** *)

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

(** We can see which proof term Coq constructs for a given Lemma by
using the [Print] directive: *)

Print silly.
(* ===> silly = eq_refl : 0 * 3 = 0 *)

(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)

(** ** Implications _are_ functions *)

(** Just as we can implement natural number multiplication as a
function:

[
mult : nat -> nat -> nat
]

The _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.
*)

Lemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.
Proof. intros H. reflexivity. Qed.

(** We can see that the proof term for the above lemma is indeed a
function: *)

Print silly_implication.
(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl
     : 1 + 1 = 2 -> 0 * 3 = 0 *)

(** ** Defining Propositions *)

(** Just as we can create user-defined inductive types (like the
    lists, binary representations of natural numbers, etc., that we
    seen before), we can also create _user-defined_ propositions.

    Question: How do you define the meaning of a proposition?
*)

(** *** *)

(** The meaning of a proposition is given by _rules_ and _definitions_
    that say how to construct _evidence_ for the truth of the
    proposition from other evidence.

    - Typically, rules are defined _inductively_, just like any other datatype.

    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.

    In this, and subsequence chapters, we'll see more about how these
    proof terms work in more detail.
*)

(* ########################################################### *)
(** * Conjunction (Logical "and") *)

(** The logical conjunction of propositions [P] and [Q] can be
    represented using an [Inductive] definition with one
    constructor. *)

Inductive and (P Q : Prop) : Prop :=
  conj : P -> Q -> (and P Q).

(** The intuition behind this definition is simple: to
    construct evidence for [and P Q], we must provide evidence
    for [P] and evidence for [Q].  More precisely:

    - [conj p q] can be taken as evidence for [and P Q] if [p]
      is evidence for [P] and [q] is evidence for [Q]; and

    - this is the _only_ way to give evidence for [and P Q] --
      that is, if someone gives us evidence for [and P Q], we
      know it must have the form [conj p q], where [p] is
      evidence for [P] and [q] is evidence for [Q].

   Since we'll be using conjunction a lot, let's introduce a more
   familiar-looking infix notation for it. *)

Notation "P /\ Q" := (and P Q) : type_scope.

(** (The [type_scope] annotation tells Coq that this notation
    will be appearing in propositions, not values.) *)

(** Consider the "type" of the constructor [conj]: *)

Check conj.
(* ===>  forall P Q : Prop, P -> Q -> P /\ Q *)

(** Notice that it takes 4 inputs -- namely the propositions [P]
    and [Q] and evidence for [P] and [Q] -- and returns as output the
    evidence of [P /\ Q]. *)

(** ** "Introducing" Conjuctions *)
(** Besides the elegance of building everything up from a tiny
    foundation, what's nice about defining conjunction this way is
    that we can prove statements involving conjunction using the
    tactics that we already know.  For example, if the goal statement
    is a conjuction, we can prove it by applying the single
    constructor [conj], which (as can be seen from the type of [conj])
    solves the current goal and leaves the two parts of the
    conjunction as subgoals to be proved separately. *)

Theorem and_example :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  apply conj.
  Case "left". reflexivity.
  Case "right". reflexivity.  Qed.

(** Just for convenience, we can use the tactic [split] as a shorthand for
    [apply conj]. *)

Theorem and_example' :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  split.
    Case "left". reflexivity.
    Case "right". reflexivity.  Qed.

(** ** "Eliminating" conjunctions *)
(** Conversely, the [inversion] tactic can be used to take a
    conjunction hypothesis in the context, calculate what evidence
    must have been used to build it, and add variables representing
    this evidence to the proof context. *)

Theorem proj1 : forall P Q : Prop,
  P /\ Q -> P.
Proof.
  intros P Q H.
  inversion H as [HP HQ].
  apply HP.  Qed.

(** **** Exercise: 1 star, optional (proj2) *)
Theorem proj2 : forall P Q : Prop,
  P /\ Q -> Q.
Proof.
  intros P Q H.
  inversion H. apply H1. Qed.
(** [] *)

Theorem and_commut : forall P Q : Prop,
  P /\ Q -> Q /\ P.
Proof.
  intros P Q H.
  inversion H as [HP HQ].
  split.
    Case "left". apply HQ.
    Case "right". apply HP.  Qed.

(** **** Exercise: 2 stars (and_assoc) *)
(** In the following proof, notice how the _nested pattern_ in the
    [inversion] breaks the hypothesis [H : P /\ (Q /\ R)] down into
    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)

Theorem and_assoc : forall P Q R : Prop,
  P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R H.
  inversion H as [HP [HQ HR]].
  repeat (split; try (assumption)). Qed.
(** [] *)

(* ###################################################### *)
(** * Iff *)

(** The handy "if and only if" connective is just the conjunction of
    two implications. *)

Definition iff (P Q : Prop) := (P -> Q) /\ (Q -> P).

Notation "P <-> Q" := (iff P Q)
                      (at level 95, no associativity)
                      : type_scope.

Theorem iff_implies : forall P Q : Prop,
  (P <-> Q) -> P -> Q.
Proof.
  intros P Q H.
  inversion H as [HAB HBA]. apply HAB.  Qed.

Theorem iff_sym : forall P Q : Prop,
  (P <-> Q) -> (Q <-> P).
Proof.
  (* WORKED IN CLASS *)
  intros P Q H.
  inversion H as [HAB HBA].
  split.
    Case "->". apply HBA.
    Case "<-". apply HAB.  Qed.

(** **** Exercise: 1 star, optional (iff_properties) *)
(** Using the above proof that [<->] is symmetric ([iff_sym]) as
    a guide, prove that it is also reflexive and transitive. *)

Theorem iff_refl : forall P : Prop,
  P <-> P.
Proof.
  intros P.
  unfold iff.
  split; intros H; apply H. Qed.

Theorem iff_trans : forall P Q R : Prop,
  (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  unfold iff.
  intros P Q R H1 H2.
  inversion H1 as [PQ QP]. inversion H2 as [QR RQ].
  split; intros H.
  Case "left". apply QR. apply PQ. apply H.
  Case "right". apply QP. apply RQ. apply H.
Qed.

(** Hint: If you have an iff hypothesis in the context, you can use
    [inversion] to break it into two separate implications.  (Think
    about why this works.) *)
(** [] *)

(** Some of Coq's tactics treat [iff] statements specially, thus
    avoiding the need for some low-level manipulation when reasoning
    with them.  In particular, [rewrite] can be used with [iff]
    statements, not just equalities. *)

(* ############################################################ *)
(** * Disjunction (Logical "or") *)

(** ** Implementing Disjunction *)

(** Disjunction ("logical or") can also be defined as an
    inductive proposition. *)

Inductive or (P Q : Prop) : Prop :=
  | or_introl : P -> or P Q
  | or_intror : Q -> or P Q.

Notation "P \/ Q" := (or P Q) : type_scope.

(** Consider the "type" of the constructor [or_introl]: *)

Check or_introl.
(* ===>  forall P Q : Prop, P -> P \/ Q *)

(** It takes 3 inputs, namely the propositions [P], [Q] and
    evidence of [P], and returns, as output, the evidence of [P \/ Q].
    Next, look at the type of [or_intror]: *)

Check or_intror.
(* ===>  forall P Q : Prop, Q -> P \/ Q *)

(** It is like [or_introl] but it requires evidence of [Q]
    instead of evidence of [P]. *)

(** Intuitively, there are two ways of giving evidence for [P \/ Q]:

    - give evidence for [P] (and say that it is [P] you are giving
      evidence for -- this is the function of the [or_introl]
      constructor), or

    - give evidence for [Q], tagged with the [or_intror]
      constructor. *)

(** *** *)
(** Since [P \/ Q] has two constructors, doing [inversion] on a
    hypothesis of type [P \/ Q] yields two subgoals. *)

Theorem or_commut : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  inversion H as [HP | HQ].
    Case "left". apply or_intror. apply HP.
    Case "right". apply or_introl. apply HQ.  Qed.

(** From here on, we'll use the shorthand tactics [left] and [right]
    in place of [apply or_introl] and [apply or_intror]. *)

Theorem or_commut' : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  inversion H as [HP | HQ].
    Case "left". right. apply HP.
    Case "right". left. apply HQ.  Qed.

Theorem or_distributes_over_and_1 : forall P Q R : Prop,
  P \/ (Q /\ R) -> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R. intros H. inversion H as [HP | [HQ HR]].
    Case "left". split.
      SCase "left". left. apply HP.
      SCase "right". left. apply HP.
    Case "right". split.
      SCase "left". right. apply HQ.
      SCase "right". right. apply HR.  Qed.

(** **** Exercise: 2 stars (or_distributes_over_and_2) *)
Theorem or_distributes_over_and_2 : forall P Q R : Prop,
  (P \/ Q) /\ (P \/ R) -> P \/ (Q /\ R).
Proof.
  intros P Q R H.
  inversion H as [[HP | HQ] [HPP | HR]];
  repeat (try (left; assumption)).
  right. split; assumption.
Qed.
(** [] *)

(** **** Exercise: 1 star, optional (or_distributes_over_and) *)
Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R. unfold iff.
  split.
    Case "left". apply or_distributes_over_and_1.
    Case "right". apply or_distributes_over_and_2.
Qed.
(** [] *)

(* ################################################### *)
(** ** Relating [/\] and [\/] with [andb] and [orb] (advanced) *)

(** We've already seen several places where analogous structures
    can be found in Coq's computational ([Type]) and logical ([Prop])
    worlds.  Here is one more: the boolean operators [andb] and [orb]
    are clearly analogs of the logical connectives [/\] and [\/].
    This analogy can be made more precise by the following theorems,
    which show how to translate knowledge about [andb] and [orb]'s
    behaviors on certain inputs into propositional facts about those
    inputs. *)

Theorem andb_prop : forall b c,
  andb b c = true -> b = true /\ c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  destruct b.
    Case "b = true". destruct c.
      SCase "c = true". apply conj. reflexivity. reflexivity.
      SCase "c = false". inversion H.
    Case "b = false". inversion H.  Qed.

Theorem andb_true_intro : forall b c,
  b = true /\ c = true -> andb b c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  inversion H.
  rewrite H0. rewrite H1. reflexivity. Qed.

(** **** Exercise: 2 stars, optional (bool_prop) *)
Theorem andb_false : forall b c,
  andb b c = false -> b = false \/ c = false.
Proof.
  intros b c H.
  destruct b, c; try (left; reflexivity); try (right; reflexivity).
  Case "tt". inversion H. (* contra *)
Qed.

Theorem orb_prop : forall b c,
  orb b c = true -> b = true \/ c = true.
Proof.
  intros b c H.
  destruct b, c; try (left; reflexivity); try (right; reflexivity).
  Case "ff". inversion H.
Qed.

Theorem orb_false_elim : forall b c,
  orb b c = false -> b = false /\ c = false.
Proof.
  intros b c H.
  destruct b, c; inversion H.
  Case "ff". split; reflexivity.
Qed.
(** [] *)

(* ################################################### *)
(** * Falsehood *)

(** Logical falsehood can be represented in Coq as an inductively
    defined proposition with no constructors. *)

Inductive False : Prop := .

(** Intuition: [False] is a proposition for which there is no way
    to give evidence. *)

(** Since [False] has no constructors, inverting an assumption
    of type [False] always yields zero subgoals, allowing us to
    immediately prove any goal. *)

Theorem False_implies_nonsense :
  False -> 2 + 2 = 5.
Proof.
  intros contra.
  inversion contra.  Qed.

(** How does this work? The [inversion] tactic breaks [contra] into
    each of its possible cases, and yields a subgoal for each case.
    As [contra] is evidence for [False], it has _no_ possible cases,
    hence, there are no possible subgoals and the proof is done. *)

(** *** *)
(** Conversely, the only way to prove [False] is if there is already
    something nonsensical or contradictory in the context: *)

Theorem nonsense_implies_False :
  2 + 2 = 5 -> False.
Proof.
  intros contra.
  inversion contra.  Qed.

(** Actually, since the proof of [False_implies_nonsense]
    doesn't actually have anything to do with the specific nonsensical
    thing being proved; it can easily be generalized to work for an
    arbitrary [P]: *)

Theorem ex_falso_quodlibet : forall (P:Prop),
  False -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P contra.
  inversion contra.  Qed.

(** The Latin _ex falso quodlibet_ means, literally, "from
    falsehood follows whatever you please."  This theorem is also
    known as the _principle of explosion_. *)

(* #################################################### *)
(** ** Truth *)

(** Since we have defined falsehood in Coq, one might wonder whether
    it is possible to define truth in the same way.  We can. *)

(** **** Exercise: 2 stars, advanced (True) *)
(** Define [True] as another inductively defined proposition.  (The
    intution is that [True] should be a proposition for which it is
    trivial to give evidence.) *)

Inductive True : Prop := True_.
(** [] *)

(** However, unlike [False], which we'll use extensively, [True] is
    used fairly rarely. By itself, it is trivial (and therefore
    uninteresting) to prove as a goal, and it carries no useful
    information as a hypothesis. But it can be useful when defining
    complex [Prop]s using conditionals, or as a parameter to
    higher-order [Prop]s. *)

(* #################################################### *)
(** * Negation *)

(** The logical complement of a proposition [P] is written [not
    P] or, for shorthand, [~P]: *)

Definition not (P:Prop) := P -> False.

(** The intuition is that, if [P] is not true, then anything at
    all (even [False]) follows from assuming [P]. *)

Notation "~ x" := (not x) : type_scope.

Check not.
(* ===> Prop -> Prop *)

(** It takes a little practice to get used to working with
    negation in Coq.  Even though you can see perfectly well why
    something is true, it can be a little hard at first to get things
    into the right configuration so that Coq can see it!  Here are
    proofs of a few familiar facts about negation to get you warmed
    up. *)

Theorem not_False :
  ~ False.
Proof.
  unfold not. intros H. inversion H.  Qed.

(** *** *)
Theorem contradiction_implies_anything : forall P Q : Prop,
  (P /\ ~P) -> Q.
Proof.
  (* WORKED IN CLASS *)
  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.
  apply HNA in HP. inversion HP.  Qed.

Theorem double_neg : forall P : Prop,
  P -> ~~P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not. intros G. apply G. apply H.  Qed.

(** **** Exercise: 2 stars, advanced (double_neg_inf) *)
(** Write an informal proof of [double_neg]:

   _Theorem_: [P] implies [~~P], for any proposition [P].

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

(** **** Exercise: 2 stars (contrapositive) *)
Theorem contrapositive : forall P Q : Prop,
  (P -> Q) -> (~Q -> ~P).
Proof.
  intros P Q HPQ.
  unfold not. intros HQ HP.
  apply HQ. apply HPQ. apply HP.
Qed.
(** [] *)

(** **** Exercise: 1 star (not_both_true_and_false) *)
Theorem not_both_true_and_false : forall P : Prop,
  ~ (P /\ ~P).
Proof.
  intros P. unfold not. intros H. inversion H.
  apply H1. apply H0.
Qed.
(** [] *)

(** **** Exercise: 1 star, advanced (informal_not_PNP) *)
(** Write an informal proof (in English) of the proposition [forall P
    : Prop, ~(P /\ ~P)]. *)

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

(** *** Constructive logic *)
(** Note that some theorems that are true in classical logic are _not_
    provable in Coq's (constructive) logic.  E.g., let's look at how
    this proof gets stuck... *)

Theorem classic_double_neg : forall P : Prop,
  ~~P -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not in H.
  (* But now what? There is no way to "invent" evidence for [~P]
     from evidence for [P]. *)
  Abort.

(** **** Exercise: 5 stars, advanced, optional (classical_axioms) *)
(** For those who like a challenge, here is an exercise
    taken from the Coq'Art book (p. 123).  The following five
    statements are often considered as characterizations of
    classical logic (as opposed to constructive logic, which is
    what is "built in" to Coq).  We can't prove them in Coq, but
    we can consistently add any one of them as an unproven axiom
    if we wish to work in classical logic.  Prove that these five
    propositions are equivalent. *)

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

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

(** **** Exercise: 3 stars (excluded_middle_irrefutable) *)
(** This theorem implies that it is always safe to add a decidability
axiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].
Why? Because we cannot prove the negation of such an axiom; if we could,
we would have both [~ (P \/ ~P)] and [~ ~ (P \/ ~P)], a contradiction. *)

Theorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \/ ~ P).
Proof.
  intros P. unfold not. intros H. apply H. right. intros HP. apply H. left. apply HP.
Qed.

(* ########################################################## *)
(** ** Inequality *)

(** Saying [x <> y] is just the same as saying [~(x = y)]. *)

Notation "x <> y" := (~ (x = y)) : type_scope.

(** Since inequality involves a negation, it again requires
    a little practice to be able to work with it fluently.  Here
    is one very useful trick.  If you are trying to prove a goal
    that is nonsensical (e.g., the goal state is [false = true]),
    apply the lemma [ex_falso_quodlibet] to change the goal to
    [False].  This makes it easier to use assumptions of the form
    [~P] that are available in the context -- in particular,
    assumptions of the form [x<>y]. *)

Theorem not_false_then_true : forall b : bool,
  b <> false -> b = true.
Proof.
  intros b H. destruct b.
  Case "b = true". reflexivity.
  Case "b = false".
    unfold not in H.
    apply ex_falso_quodlibet.
    apply H. reflexivity.   Qed.

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** **** Exercise: 2 stars (false_beq_nat) *)
Theorem false_beq_nat : forall n m : nat,
     n <> m ->
     beq_nat n m = false.
Proof.
  induction n; intros m H; destruct m.
    Case "n = 0".
      SCase "m = 0". simpl. apply ex_falso_quodlibet. apply H. reflexivity.
      SCase "m = Sm". reflexivity.
    Case "n = Sn'".
      SCase "m = 0". reflexivity.
      SCase "m = Sm". simpl. apply IHn. unfold not. intros H1. apply H. rewrite H1. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, optional (beq_nat_false) *)
Theorem beq_nat_false : forall n m,
  beq_nat n m = false -> n <> m.
Proof.
  unfold not.
  induction n; destruct m; simpl; intros H0 H1; inversion H0; inversion H1.
  Case "n=Sn,m=Sm". rewrite H3 in H2. rewrite <- beq_nat_refl in H2.  inversion H2.
Qed.
(** [] *)

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


Require Export D.

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

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

    - Prove [pal_app_rev] that
       forall l, pal (l ++ rev l).
    - Prove [pal_rev] that
       forall l, pal l -> l = rev l.
*)

Inductive pal {X: Type} : list X -> Prop :=
| pal_nil: pal []
| pal_sgl: forall (x:X), pal [x]
| pal_rcs: forall (x:X) (l:list X), pal l -> pal (x::(snoc l x)).

Example test_pal_1: pal [0; 1; 0].
Proof. apply pal_rcs with (x:=0) (l:=[1]). apply pal_sgl. Qed.

Theorem pal_app_rev: forall (X: Type) (l: list X),
  pal (l ++ rev l).
Proof.
  intros. induction l.
  Case "[]". simpl. apply pal_nil.
  Case "x::l". simpl. replace (x :: l ++ snoc (rev l) x) with (x :: snoc (l ++ rev l) x). apply pal_rcs. apply IHl.
    Lemma snoc_app_lem : forall (X:Type) (x:X) l1 l2, snoc (l1 ++ l2) x = l1 ++ snoc l2 x.
    Proof. intros. induction l1. reflexivity.
    simpl. rewrite IHl1. reflexivity. Qed.
  rewrite snoc_app_lem with (l2:=(rev l)). reflexivity.
Qed.

Theorem pal_rev: forall (X: Type) (l: list X),
  pal l -> l = rev l.
 Proof. intros. induction H.
  Case "[]". reflexivity.
  Case "[x]". reflexivity.
  Case "x::l". simpl.
    Lemma x_snoc_lem : forall (X:Type) (x y:X) l,
      x :: snoc l y = snoc (x::l) y.
    Proof. intros. simpl. reflexivity. Qed.
    rewrite x_snoc_lem.
    Lemma snoc_rev_lem : forall (X:Type) (x:X) l,
       x :: (rev l)  = rev (snoc l x).
    Proof. intros.  induction l.
      Case "[]". simpl. reflexivity.
      Case "x0::l". simpl. rewrite<-IHl. simpl. reflexivity. Qed.
    assert (Hrev : x::l = x::(rev l)).
    Proof.  rewrite<-IHpal. reflexivity.
    rewrite -> Hrev. rewrite->snoc_rev_lem. reflexivity.
Qed.


Section PropositionalLogic.

Variables A B C : Prop.

Definition anb1 :
  A /\ B -> A
:= fun pAandB =>
    match pAandB with
    | conj pA pB => pA
    end.

Definition impl_trans :
  (A -> B) -> (B -> C) -> A -> C
:= fun pAB : A -> B => fun pBC : B -> C => fun a : A =>
    pBC (pAB a).

Definition HilbertS :
  (A -> B -> C) -> (A -> B) -> A -> C
:= fun pABC : A -> B -> C =>
    fun pAB : A -> B =>
        fun a : A =>
            pABC a (pAB a).

Definition double_negation_introduction :
    A -> ~ ~ A
:= fun pa : A => fun pna : ~ A => pna pa.

Definition DNE_triple_neg :
  ~ ~ ~ A -> ~ A
(* (((A -> False) -> False) -> False) -> (A -> False) *)
:= fun f : ~ ~ ~ A =>
    fun pA =>
        f (double_negation_introduction pA).

Definition or_comm :
  A \/ B -> B \/ A
:= fun AorB : A \/ B =>
    match AorB with
    | or_introl pA => or_intror pA
    | or_intror pB => or_introl pB
    end.

End PropositionalLogic.

Section Quantifiers.

Variable T : Type.
Variable A : Prop.
Variable P Q : T -> Prop.
Definition forall_conj_comm :
  (forall x, P x /\ Q x) <-> (forall x, Q x /\ P x)
:= conj
    (fun allx_PQ => fun x => match allx_PQ x with conj px qx => conj qx px end)
    (fun allx_QP => fun x => match allx_QP x with conj qx px => conj px qx end).

Definition forall_disj_comm :
  (forall x, P x \/ Q x) <-> (forall x, Q x \/ P x)
:= conj
    (fun allx_PQ =>
    fun x =>
        match allx_PQ x with
        | or_introl px => or_intror px
        | or_intror qx => or_introl qx
        end)
    (fun allx_QP =>
    fun x =>
        match allx_QP x with
        | or_introl qx => or_intror qx
        | or_intror px => or_introl px
        end).
Definition not_exists_forall_not :
  ~(exists x, P x) -> forall x, ~P x
:= fun not_existPx : (exists x, P x) -> False =>
    fun x => fun px : P x =>
        not_existPx (ex_intro P x px).

Definition exists_forall_not_ :
(exists x, A -> P x) -> (forall x, ~P x) -> ~A
:= fun exAPx : exists x, A -> P x =>
    fun allxPx : forall x, ~P x =>
        fun a : A =>
            match exAPx with
            | (ex_intro _ x apx) => (allxPx x) (apx a)
            end.

(*
(** Extra exercise (feel free to skip): the dual Frobenius rule *)
Definition LEM :=
  forall P : Prop, P \/ ~ P.

Definition Frobenius2 :=
  forall (A : Type) (P : A -> Prop) (Q : Prop),
    (forall x, Q \/ P x) <-> (Q \/ forall x, P x).

Definition lem_iff_Frobenius2 :
  LEM <-> Frobenius2
:=
*)
End Quantifiers.

Section Equality.

(** exercise: *)
Definition f_congr {A B} (f : A -> B) (x y : A) :
  x = y  ->  f x = f y
:= fun xy : x = y =>
    match
      xy in (_ = b)
      return (f x = f b)
    with
    | eq_refl => eq_refl (f x)
    end.

Definition f_congr' A B (f g : A -> B) (x y : A) :
  f = g  ->  x = y  ->  f x = g y
:= fun fg : f = g =>
      match fg in (_ = b)
        return (x = y -> f x = b y) (* "return" specifies type of expression after "with" *)
        with | eq_refl =>
        (* at this stage we unificate f&g. Now we can use only f *)
          fun xy : x = y =>
            match xy in (_ = a)
              return (f x = f a)
              with | eq_refl => eq_refl (f x) end end.
(*
(** extra exercise *)
Definition congId A {x y : A} (p : x = y) :
  f_congr (fun x => x) p = p :=
*)
(* exercise *)
Definition pair_inj A B (a1 a2 : A) (b1 b2 : B) :
  (a1, b1) = (a2, b2) -> (a1 = a2) /\ (b1 = b2)
:= fun a1b1a2b2 : (a1, b1) = (a2, b2) =>
    match a1b1a2b2 in (_ = (aa, bb))
      return (a1 = aa) /\ (b1 = bb)
      with | eq_refl =>
      conj (eq_refl a1) (eq_refl b1)
      end.

End Equality.

Section ExtensionalEqualityAndComposition.

Variables A B C D : Type.

(** Exercise 2a *)
(** [\o] is a notation for function composition in MathComp, prove that it's associative *)
From mathcomp Require Import ssreflect ssrfun ssrbool.
(*
Definition compose {A B C} (g : B -> C) (f : A -> B) :=
  fun x : A => g (f x).

Notation " g \o f " := (compose g f)
  (at level 40, left associativity) : type_scope.
*)
Definition compA (f : A -> B) (g : B -> C) (h : C -> D) :
  (h \o g) \o f = h \o (g \o f)
:= eq_refl (fun x => h (g (f x))).

(** [=1] stands for extensional equality on unary functions,
    i.e. [f =1 g] means [forall x, f x = g x].
    This means it's an equivalence relation, i.e. it's reflexive, symmetric and transitive.
    Let us prove a number of facts about [=1]. *)

(** Exercise: Reflexivity *)
Definition eqext_refl :
  forall (f : A -> B), f =1 f
:= fun f => fun x => eq_refl (f x).

(** Exercise: Symmetry *)
Definition eqext_sym :
  forall (f g : A -> B), f =1 g -> g =1 f
:= fun f => fun g => fun pfg : f =1 g =>
    fun x => match pfg x in (_ = h) return (h = f x) with
    | eq_refl => eq_refl (f x) end.

(** Exercise: Transitivity *)
Definition eqext_trans :
  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h
:= fun f => fun g => fun h =>
    fun fg : f =1 g =>
      fun gh : g =1 h =>
        fun x =>
          (* first - we eat fx, only g x exists after this step *)
          match ((eqext_sym f g fg) x) : (g x = f x) in (_ = a) return (a = h x) with | eq_refl =>
          (* now we eat hx, only g x still exists *)
          match                 (gh x) : (g x = h x) in (_ = b) return (g x = b) with | eq_refl =>
              eq_refl (g x)
          end end.

(** Exercise: left congruence *)
Definition eq_compl :
  forall (f g : A -> B) (h : B -> C),
    f =1 g -> h \o f =1 h \o g
:= fun f => fun g => fun h => fun fg1_proof =>
  fun x => match fg1_proof x in (_ = gx) return (h \o f) x = (h gx)
  with | eq_refl => eq_refl (h (f x)) end.

(** Exercise: right congruence *)
Definition eq_compr :
  forall (f g : B -> C) (h : A -> B),
    f =1 g -> f \o h =1 g \o h
:= fun f => fun g => fun h => fun fg1_proof =>
    fun x => match fg1_proof (h x) in (_ = ghx) return (f \o h) x = ghx
    with | eq_refl => eq_refl (f (h x)) end.

End ExtensionalEqualityAndComposition.

From mathcomp Require Import ssreflect ssrfun ssrbool eqtype.

(* After importing `eqtype` you need to either use a qualified name for
`eq_refl`: `Logic.eq_refl`, or use the `erefl` notation.
This is because `eqtype` reuses the `eq_refl` identifier for a
different lemma.
 *)

Definition iff_is_if_and_only_if :
  forall a b : bool, (a ==> b) && (b ==> a) = (a == b)
:= fun a => fun b =>

Definition negbNE :
  forall b : bool, ~~ ~~ b = true -> b = true
:=


Require Export Basics.

Theorem plus_n_O : forall n : nat,
  n = n + 0.
Proof.
  induction n as [|n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite <- IHn'. reflexivity.
Qed.

Theorem mult_0_r : forall n : nat,
  n * 0 = 0.
Proof.
  induction n as [|n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite IHn'. reflexivity. Qed.

Theorem plus_n_Sm : forall n m : nat,
S (n + m) = n + (S m).
Proof.
  intros n m. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite IHn'. reflexivity. Qed.

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros n m. induction n as [|n' IHn'].
  - induction m as [|m' IHm'].
    + reflexivity.
    + simpl. rewrite <- IHm'. simpl. reflexivity.
  - induction m as [|m' IHm'].
    + simpl. rewrite IHn'. simpl. reflexivity.
    + simpl. rewrite IHn'. simpl. rewrite plus_n_Sm. reflexivity.
Qed.

Theorem plus_assoc : forall n m p : nat,
n + (m + p) = (n + m) + p.
Proof.
  intros n m p.
  induction n as [|n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite IHn'. reflexivity. Qed.

Fixpoint double (n:nat) :=
match n with
| O => O
| S n' => S (S (double n' ))
end.

Lemma double_plus : forall n, double n = n + n.
Proof.
  intros n.
  induction n as [|n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite IHn'. rewrite plus_n_Sm. reflexivity. Qed.

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

(* Theorem evenb_S : forall n : nat, *)
(*   evenb (S n) = negb (evenb n). *)
(* Proof. *)
(*   induction n as [|n' IHn']. *)
(*   - simpl. reflexivity. *)
(*   - induction n' as [| n'']. *)

Theorem plus_rearrange : forall n m p q : nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  assert (H : n + m = m + n).
    { rewrite -> plus_comm. reflexivity. }
    rewrite -> H. reflexivity. Qed.

Theorem plus_swap : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite plus_assoc.
  assert (H : n + m = m + n).
         { rewrite plus_comm. reflexivity. }
         rewrite H. rewrite plus_assoc. reflexivity. Qed.

Theorem mult_Sm_n : forall m n : nat,
        S m * n = n * m + n.
Proof.
  intros m n.
  induction n as [|n' IHn'].
  - simpl. rewrite <- mult_n_O. reflexivity.
  - rewrite <- mult_n_Sm.
    rewrite <- plus_n_Sm.
    rewrite IHn'. simpl.
    rewrite <- plus_n_Sm.
    assert (H : m + (n' * m) + n' = (n' * m) + n' + m).
    { rewrite plus_comm.
      rewrite plus_assoc.
      rewrite plus_comm.
      rewrite plus_assoc.
      reflexivity. }
    rewrite H.
    reflexivity.
Qed.

Theorem mult_comm : forall m n : nat,
  m * n = n * m.
Proof.
  intros m n.
  induction m as [|m' IHm'].
  - rewrite mult_0_l. rewrite mult_0_r. reflexivity.
  - rewrite <- mult_n_Sm. rewrite mult_Sm_n. reflexivity. Qed.

(* bin to nat pres incr  *)

Theorem bin_to_nat_pres_incr : forall m : bin,
    bin_to_nat (incr m) = bin_to_nat m + 1.
Proof.
  induction m as [|dm IHdm|sdm IHsdm].
  - simpl. reflexivity.
  - simpl. rewrite <- plus_n_O. reflexivity.
  - simpl. repeat (rewrite <- plus_n_O).
    rewrite IHsdm.
    symmetry.
    rewrite <- plus_assoc.
    rewrite <- plus_assoc.
    rewrite <- plus_assoc.
    rewrite plus_Sn_m. simpl.
    rewrite plus_n_Sm. reflexivity.
Qed.


Require Import Bool.
Require Import Setoid.
Require Import Ring.
Require Import Field.
Require Coq.Program.Tactics.
Require Import ssreflect ssrfun ssrbool.

(** We start by defining a Monoid *)

Class Monoid (A:Set)(dot : A -> A -> A)(one : A)(bool_eq : A-> A-> bool) := {

    dot_assoc : forall x y z : A, dot x (dot y z) = dot (dot x y) z;
    one_left : forall x : A, dot one x = x;
    one_right : forall x : A, dot x one = x;

    (** The set equality should be boolean decidable
        pretty sure ssreflect provides a better way to do this *)

    bool_eq_corr: forall a b : A, bool_eq a b = true <-> a=b;
    bool_neq_corr: forall a b : A, bool_eq a b = false <-> a <> b;
}.

(** We now extend Monoids to various types of groups *)

Class Group (A:Set)(dot : A -> A -> A) (one : A) (bool_eq : A-> A-> bool) (inv : A -> A) := {
  grp_mon :> Monoid A dot one bool_eq;
  inv_left: forall x : A, one =  dot (inv x) x;
  inv_right: forall x : A, one =  dot x (inv x);
}.

Class AbeGroup (A:Set)(dot : A -> A -> A) (one : A) (bool_eq : A-> A-> bool) (inv : A -> A) := {
  abegrp_grp :> Group A dot one bool_eq inv;
  comm : forall a b : A, dot a b = dot b a;
}.

Section AdditionalGroupProperties.

Generalizable Variables A dot Aone Ainv bool_equal.
Context `{AbeGroup A dot Aone bool_equal Ainv}.

Definition abegop `{AbeGroup A dot Aone bool_equal Ainv} := dot.
Definition abegone `{AbeGroup A dot Aone bool_equal Ainv} := Aone.

Infix "*" := abegop.
Notation "1" := Aone.

Notation "- x" :=  (Ainv x).

(** The next three Lemmas simply following proofs *)

Lemma comm_inv : forall a b c x :A,
  a * x * b * -x * c = a * b * c.
Proof.
  intros. replace (a * x * b) with (a * (x * b)).  replace (x * b) with (b * x).
  rewrite dot_assoc. replace (a * b * x * - x * c) with (a * b * (x * -x * c)).
  rewrite <- inv_right. replace (1 * c) with c. trivial. rewrite one_left.
  trivial. rewrite dot_assoc. rewrite dot_assoc. trivial. apply comm. apply dot_assoc.
Qed.

Lemma comm_inv_wa : forall b c x :A,
  x * b * -x * c =  b * c.
Proof.
  intros. replace (x * b * - x * c) with (1 * (x * b * - x * c)).
  replace (b * c) with (1 * (b * c)). rewrite dot_assoc. rewrite dot_assoc. rewrite dot_assoc.
  rewrite dot_assoc. apply comm_inv. apply one_left. apply one_left.
Qed.

Lemma comm_inv_wc : forall a b x :A,
  a * x * b * - x = a * b.
Proof.
  intros. replace (a * x * b * - x ) with (a * x * b * - x * 1).
  replace (a * b) with (a * b * 1). apply comm_inv. apply one_right.
  apply one_right.
Qed.

Lemma left_cancel : forall x y z:A,
 (x * y = x * z) <-> (y = z).
Proof.
  intros. unfold iff. refine (conj _ _).
  (*Case 1 *)
  intros. assert (- x * (x * y) = - x * (x * z)). rewrite H0. trivial.
  rewrite dot_assoc in H1. rewrite dot_assoc in H1. replace (- x * x) with 1 in H1.
  rewrite one_left in H1. rewrite one_left in H1. apply H1. apply inv_left.
  (*Case 2 *)
  intros.  rewrite H0. trivial.
Qed.

Lemma left_cancel_neq : forall x y z:A,
 (x * y <> x * z) <-> (y <> z).
Proof.
  intros. unfold iff. refine (conj _ _).
  (*Case 1 *)
  intros. unfold not. intros. rewrite H1 in H0. apply H0. trivial.
  (*Case 2 *)
  intros. unfold not in *. intros. apply left_cancel in H1.  rewrite H1 in H0. apply H0. trivial.
Qed.

Lemma right_cancel :  forall x y z:A,
 (y * x = z * x) <-> (y = z).
Proof.
  intros. unfold iff. refine (conj _ _).
  (*Case 1 *)
  intros. assert (((y * x) * -x ) = ((z * x) * -x)). rewrite H0. trivial.
  replace (y * x * - x) with (y * (x * - x)) in H1. replace (z * x * - x) with (z * (x * - x)) in H1.
  replace (x * -x) with 1 in H1. rewrite one_right in H1.
  rewrite one_right in H1. apply H1. apply inv_right.
  apply dot_assoc. apply dot_assoc.
  (*Case 2 *)
  intros.  rewrite H0. trivial.
Qed.

Lemma comm_inv_wb : forall a c x :A,
  a * x * -x * c = a * c.
Proof.
  intros. apply right_cancel. rewrite <- dot_assoc. rewrite <- inv_right.
  rewrite one_right. trivial.
Qed.

Lemma comm_inv_wac : forall b x :A,
  x * b *  -x  = b.
Proof.
  intros. rewrite <- dot_assoc. replace (b * -x) with (-x * b) by apply comm.
  rewrite dot_assoc. rewrite <- one_right. symmetry. rewrite comm.
  apply right_cancel. apply inv_right.
Qed.

Lemma eqImplProd:
  forall a b c d : A,
  a = b /\ c = d -> a * c = b * d.
Proof.
  intros. destruct H0. rewrite H0. rewrite H1. trivial.
Qed.

Lemma dob_neg : forall a : A,
  a = - - a.
Proof.
  intros. apply right_cancel with (x:= -a).
  rewrite <- inv_left. symmetry. apply inv_right.
Qed.

Lemma minus_one : forall a : A,
  a = a * (Ainv 1).
Proof.
  intros. apply right_cancel with (x:=1).
  rewrite one_right. rewrite <- dot_assoc. rewrite <- inv_left.
  rewrite one_right. trivial.
Qed.

Lemma inv_dist : forall a b : A,
  -a * -b = -(a * b).
Proof.
  intros. assert (a * b * -a * -b = a * b * -(a*b)).
  rewrite comm_inv_wa. rewrite <- inv_right. rewrite <- inv_right.
  trivial. apply left_cancel with (x := a * b).
  rewrite dot_assoc. apply H0.
Qed.

Lemma inv_dist2 : forall a b : A,
  - a * b = - (a * - b).
Proof.
  intros. remember (-b) as c.
  rewrite <- inv_dist. rewrite Heqc.
  simpl. rewrite <- dob_neg. trivial.
Qed.

Lemma b_equal : forall a b c : A,
  (a = b * c) <-> (a * - c = b).
Proof.
  intros.
  intros. unfold iff. refine (conj _ _).
  (* case 1 *)
  intros. rewrite H0. rewrite <- dot_assoc.
  rewrite <- inv_right. rewrite one_right. trivial.
  (* case 2 *)
  intros. symmetry in H0. rewrite H0. rewrite <- dot_assoc.
  rewrite <- inv_left. rewrite one_right. trivial.
Qed.

Lemma double_chall :  forall (c a : A),
  c * - (c * - a) = a.
Proof.
  intros. replace (- (c * - a)) with (-c * a).
  replace (c * (- c * a)) with (c * -c * a).
  rewrite <- inv_right. rewrite one_left. trivial.
  rewrite dot_assoc. trivial. apply inv_dist2.
Qed.

Lemma bool_true : forall (c : A),
   (bool_equal c c) = false  -> False.
Proof.
  intros. assert (c <> c).
  apply bool_neq_corr. apply H0. assert False.
  apply H1. trivial. congruence.
Qed.

Lemma chall_dist : forall (c1 c2 e1 e2 e3 e4 : A),
  bool_equal c1 c2 = false ->
  c1 = e1 * e2 ->
  c2 = e3 * e4 ->
   bool_equal e1 e3 = false \/
   bool_equal e2 e4 = false.
Proof.
  intros. case_eq (bool_equal e1 e3).
  (* Case 1 *)  intros. right. apply bool_neq_corr in H0. apply bool_neq_corr.
  apply bool_eq_corr in H3. rewrite H3 in H1. rewrite H2 in H0. rewrite H1 in H0.
  apply left_cancel_neq in H0. apply H0.
  (* Case 2 *)
  intros. left. trivial.
Qed.

Lemma zero2 : forall (a b : A),
  a <> b ->
  a * - b <> 1.
Proof.
  intros. unfold not. replace 1 with (b * - b).
  intros. apply right_cancel in H1.
  rewrite H1 in H0. apply H0. trivial. rewrite <- inv_right.
  trivial.
Qed.

Lemma inv_not_equal_zero : forall (a b :A),
  a <> 1 ->
  - a <> 1.
Proof.
  intros. unfold not in *. intros.
  apply left_cancel with (x:= a) in H1.
  rewrite <- inv_right in H1. rewrite one_right in H1.
  symmetry in H1. apply H0 in H1. apply H1.
Qed.

Lemma commHack :
  forall a b c d : A,
   (a * b) * (c * d) =
    (a * c) * (b * d).
Proof.
  intros. do 2 rewrite <- dot_assoc. apply left_cancel.
  do 2 rewrite dot_assoc. apply right_cancel. apply comm.
Qed.

Lemma commHackEq :
  forall a b c d : A,
  a * b = c * d <-> a * - c = d * -b.
Proof.
  intros. unfold iff. refine (conj _ _).
  (* part 1 *)
  intros. apply b_equal. rewrite <- dob_neg.
  rewrite comm. rewrite dot_assoc. symmetry.
  apply b_equal. rewrite <- dob_neg. symmetry.
  rewrite comm. rewrite H0. apply comm.
  (* part 2 *)
  intros. apply b_equal in H0. rewrite comm in H0.
  rewrite dot_assoc in H0. symmetry in H0. apply b_equal in H0.
  symmetry in H0. apply H0.
Qed.

Lemma field_additive_abegrp (F:Set)(Fadd : F -> F -> F) (Fzero : F)
  (Fbool_eq : F-> F-> bool) (Fsub : F -> F -> F)(Finv : F -> F)
  (Fmul : F -> F -> F) (Fone : F)(FmulInv : F -> F)(Fdiv : F-> F-> F) :
  field_theory Fzero Fone Fadd Fmul Fsub Finv Fdiv FmulInv (@eq F) ->
  (forall a b : F, Fbool_eq a b = true <-> a=b) ->
  (forall a b : F, Fbool_eq a b = false <-> a <> b) ->
  AbeGroup F Fadd Fzero Fbool_eq Finv.
Proof.
  intros. constructor. constructor. constructor.
  intros; rewrite (Radd_assoc (rO := Fzero)); trivial; apply H0.
  intros; rewrite (Radd_0_l); trivial; apply H0.
  intros. rewrite (Radd_comm). rewrite (Radd_0_l). trivial. apply H0. apply H0.
  apply H1. apply H2. intros. rewrite (Radd_comm). rewrite (Ropp_def). trivial.
  apply H0. apply H0.
  intros. rewrite (Ropp_def). trivial. apply H0. intros. rewrite (Radd_comm). trivial. apply H0.
Qed.

End AdditionalGroupProperties.

(* We define a group as a module here *)

Module Type GroupSig.
  Parameter G : Set.
  Parameter Gdot : G -> G -> G.
  Parameter Gone : G.
  Parameter Gbool_eq : G-> G-> bool.
  Parameter Ginv : G -> G.

  Axiom module_abegrp : AbeGroup G Gdot Gone Gbool_eq Ginv.

  Infix "o" := Gdot (at level 50) .
  Notation "- x" := (Ginv x).
End GroupSig.


(*Taller 1 Lógica Computacional*)
(*Autor: Guido Salazar*)

(*Variables auxiliares*)

Definition cons1 := 5.

(*Punto 1*)

(*Funcion que me devuelve el cuadrado de un numero*)
Definition cuadrado (n : nat) := n*n.

(*Funcion que me devuelve el cubo de un numero*)
Definition cubo (n : nat) := n*n*n.

Compute cubo 5.
Compute cuadrado 5.

(*Punto 2*)

(*Funcion que me devuelve el cuadrado de de un numero sumado a una constante*)
Definition punto2 (n: nat) := cuadrado (n + cons1).

Compute punto2 0.

(*Punto 3*)

(*Funcion que me devuelve la suma de los cubos de dos numeros*)
Definition punto3 (n1 n2: nat) := (cubo n1) + (cubo n2).

Compute punto3 2 3.

(*Punto 4*)

(*Funcion que me devuelve la suma y el producto de los cuatro numeros*)
Definition punto4 (n1 n2 n3 n4: nat) := (n1+n2+n3+n4, n1*n2*n3*n4).

Compute punto4 1 2 3 4.

(*Punto 5*)

Compute Nat.leb 8 7.
Compute Nat.leb 6 7.
Compute Nat.leb 7 7.
(*La función Nat.double recibe un numero Nat y me devuelve el dobre de ese numero*)
(*La función Nat.div2 recibe un numero Nat y devuelve la mitad del numero con la forma floor(n/2)*)
(*La función Nat.leb recibe dos numero y me devuelve un balor booleano. 0 en caso de que el primer numero sea mayor que el segundo y 1 en caso contario.
  Es decir, la función leb representa x1 <= x2.*)

Print Nat.double.
Print Nat.div2.
Print Nat.leb.

(*Punto 6*)

(*Funcion que recibe un numero y me dice si el numero es par o impar*)
Definition esPar (n : nat) : bool :=
  Nat.leb (Nat.div2 (n + 1)) (Nat.div2 n).

Compute esPar 8.
Compute esPar 9.

(*Punto 7*)

Definition iter2p (f : (nat*nat) -> (nat*nat)) (p : nat*nat) := f (f p).

Compute (iter2p (fun p => (snd p, fst p)) (1, 2),
iter2p (fun p => (fst p + 1, snd p + fst p + 1)) (0,0)).

(*Punto 8*)

Definition componerFunc (f : nat -> nat) (g : (nat -> nat) -> (nat -> nat)) : nat -> nat :=
 g f.

Compute componerFunc (fun a => a + 2) (fun f => f).

Print componerFunc.

(*Punto 9*)

(*Funcion que recibe una parejar de numeros y me devuelve la suma*)
Definition sumaParejas (p : nat*nat) : nat :=
  (fst p) + (snd p).

Compute sumaParejas (5, 4).

(*Punto 10*)

(*Funcion que recibe una terna de numeros y me devuelve la suma*)
Definition sumaTernas (p : nat*nat*nat) : nat :=
  (cubo (fst (fst p))) + (cubo (snd (fst p))) + (cubo (snd p)).

Compute sumaTernas (1, 2, 3).

(*Punto 11*)

(*Funcion que recibe un numero y me devuelve el doble del numero si es par o n + 1 si es impar*)
Definition punto11 (n : nat) : nat :=
  match (esPar n) with
  | true => n + n
  | false => n + 1
  end.

Compute punto11 6.
Compute punto11 7.

(*Punto 12*)

(*Funcion que recibe una pareja y me una pareja con la suma y el producto*)
Definition punto12 (p : nat*nat) : nat*nat :=
  ((fst p) + (snd p), (fst p) * (snd p)).

Compute punto12 (3, 5).

(*Punto 13*)

Definition punto13 (f : nat -> nat -> nat) (g : nat -> nat) (p : nat*nat) : nat*nat :=
  (g (fst p), f (snd p) (fst p)).

Compute punto13 punto3 cuadrado  (3, 4).

(*Punto 14*)

Definition punto14 (f : nat -> nat) (p : nat*nat) : nat :=
  match (Nat.leb (snd p) (fst p)) with
  | true => f ((fst p) - (snd p))
  | false => f ((snd p) + 1)
  end.

Compute punto14 (fun x => x) (4, 5).
Compute punto14 (fun x => x) (5, 4).

(*Punto 15*)

Inductive LP : Set :=
  |p : LP
  |q : LP
  |r : LP.


Require Import Arith.

Fixpoint exp2 (n:nat) : nat :=
  match n with
  | O => 1
  | S p => 2 * exp2 p
  end.

(** Tests: *)

Lemma test: exp2 5 = 32.
Proof. reflexivity. Qed.


(** * Prop: Propositions and Evidence *)

(*Require Export Logic.
*)
(* ####################################################### *)
(** * Inductively Defined Propositions *)

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

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

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

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

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

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

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

(** The first line declares that [ev] is a proposition -- or,
    more formally, a family of propositions "indexed by" natural
    numbers.  (That is, for each number [n], the claim that "[n] is
    even" is a proposition.)  Such a family of propositions is
    often called a _property_ of numbers.

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

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

Fixpoint double (n:nat) : nat :=
  match n with
  | O => O
  | S n' => S (S (double n'))
  end.

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

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

(** For [ev], we had already defined [even] as a function (returning a
   boolean), and then defined an inductive relation that agreed with
   it. However, we don't necessarily need to think about propositions
   first as boolean functions, we can start off with the inductive
   definition.
*)

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

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

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

       - Rule [b_0]: The number [0] is [beautiful].
       - Rule [b_3]: The number [3] is [beautiful].
       - Rule [b_5]: The number [5] is [beautiful].
       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is
         their sum. *)

(** We will see many definitions like this one during the rest
    of the course, and for purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**
                              -----------                               (b_0)
                              beautiful 0

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

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

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

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

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

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

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

(* ####################################################### *)
(** ** Constructing Evidence *)

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

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

(** *** *)
(**
    The rules introduced this way have the same status as proven
    theorems; that is, they are true axiomatically.
    So we can use Coq's [apply] tactic with the rule names to prove
    that particular numbers are [beautiful].  *)

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

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

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

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

(** **** Exercise: 2 stars (b_times2)  *)
Theorem b_times2: forall n, beautiful n -> beautiful (2*n).
Proof.
    intros. simpl. apply b_sum with (m:=n+0).
    apply H.
    rewrite <- plus_n_O. apply H.
Qed.
(** [] *)

(** **** Exercise: 3 stars (b_timesm)  *)
Theorem b_timesm: forall n m, beautiful n -> beautiful (m*n).
Proof.
  induction n. intros. rewrite <- mult_n_O. apply H.
  induction m. intros. simpl.  apply b_0.
  intros. simpl. rewrite <- plus_Sn_m.
  apply b_sum. apply H. apply IHm. apply H.
Qed.
(** [] *)

(* ####################################################### *)
(** * Using Evidence in Proofs *)
(** ** Induction over Evidence *)

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

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

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

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

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

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

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

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

(* FILL IN HERE *)
[]
*)

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

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

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

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

(** *** *)

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

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

(* These exercises also require the use of induction on the evidence. *)

(** **** Exercise: 2 stars (gorgeous_sum)  *)
Theorem gorgeous_sum : forall n m,
  gorgeous n -> gorgeous m -> gorgeous (n + m).
Proof.
 intros. induction H.
 simpl. apply H0. revert IHgorgeous. apply g_plus3.
 revert IHgorgeous. apply g_plus5.
Qed.
(** [] *)

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

(** **** Exercise: 3 stars, optional (g_times2)  *)
(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].
    You might find the following helper lemma useful. *)
Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros. induction n as [| n'].
  (*Case "n = 0".*)
    simpl.
    induction m as [| m'].
    (*Case "m = 0".*)
      simpl. reflexivity.
    (*Case "m = S m'".*)
      simpl. rewrite <- IHm'. reflexivity.
  (*Case "n = S n'".*)
    simpl. rewrite -> IHn'.
    rewrite <- plus_n_Sm. reflexivity.
Qed.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros. induction n as [| n'].
  (*Case "n = 0".*)
  simpl. reflexivity.

  (*Case "n = S n'".*)
  simpl. rewrite -> IHn'. reflexivity.
Qed.

Lemma helper_g_times2 : forall x y z, x + (z + y) = z + x + y.
Proof.
   intros. induction x. simpl. rewrite <- plus_n_O. reflexivity.
   rewrite <- plus_n_Sm. simpl. apply f_equal. apply IHx.
Qed.

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

(** Here is a proof that the inductive definition of evenness implies
the computational one. *)

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

(** **** Exercise: 1 star (ev__even)  *)
(** Could this proof also be carried out by induction on [n] instead
    of [E]?  If not, why not? *)

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

(** Intuitively, the induction principle [ev n] evidence [ev n] is
    similar to induction on [n], but restricts our attention to only
    those numbers for which evidence [ev n] could be generated. *)

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

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

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

Theorem ev_sum : forall n m,
   ev n -> ev m -> ev (n+m).
Proof.
  intros. induction H.
  simpl. apply H0.
  simpl. apply ev_SS. apply IHev.
Qed.
(** [] *)

(* ####################################################### *)
(** ** Inversion on Evidence *)

(** Having evidence for a proposition is useful while proving, because we
   can _look_ at that evidence for more information. For example, consider
    proving that, if [n] is even, then [pred (pred n)] is
    too.  In this case, we don't need to do an inductive proof.  Instead
    the [inversion] tactic provides all of the information that we need.

 *)

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

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

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

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

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

(** ** The Inversion Tactic Revisited *)

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

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

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

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

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

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

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

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

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
  intros. induction H0. simpl in H. apply H.
  apply IHev. simpl in H. inversion H. apply H2.
Qed.

(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)
(** Here's an exercise that just requires applying existing lemmas.  No
    induction or even case analysis is needed, but some of the rewriting
    may be tedious. *)
Lemma double_plus : forall n, double n = n + n .
Proof.
  intros. induction n as [| n'].
  simpl. reflexivity.

  simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.
Qed.

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
  intros. revert H0. apply ev_ev__ev.
  rewrite <- plus_assoc. rewrite (plus_comm p (m + p)).
  rewrite <- plus_assoc.
  rewrite plus_assoc.
  apply ev_sum.  apply H.
  rewrite <- double_plus.
  apply double_even.
Qed.

(** [] *)

(* ####################################################### *)
(** * Discussion and Variations *)
(** ** Computational vs. Inductive Definitions *)

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

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

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

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

(* ####################################################### *)
(** ** Parameterized Data Structures *)

(** So far, we have only looked at propositions about natural numbers. However,
   we can define inductive predicates about any type of data. For example,
   suppose we would like to characterize lists of _even_ length. We can
   do that with the following definition.  *)
Notation "x :: l" := (cons x l) (at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) ..).

Inductive ev_list {X:Type} : list X -> Prop :=
  | el_nil : ev_list []
  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).

(** Of course, this proposition is equivalent to just saying that the
length of the list is even. *)

Lemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).
Proof.
    intros X l H. induction H.
    (*Case "el_nil".*) simpl. apply ev_0.
    (*Case "el_cc".*)  simpl.  apply ev_SS. apply IHev_list.
Qed.

(** However, because evidence for [ev] contains less information than
evidence for [ev_list], the converse direction must be stated very
carefully. *)

Lemma ev_length__ev_list: forall X n, ev n -> forall (l : list X), n = length l -> ev_list l.
Proof.
  intros X n H.
  induction H.
  (*Case "ev_0".*) intros l H. destruct l.
    (*SCase "[]".*) apply el_nil.
    (*SCase "x::l".*) inversion H.
  (*Case "ev_SS".*) intros l H2. destruct l.
    (*SCase "[]".*) inversion H2. destruct l.
    (*SCase "[x]".*) inversion H2.
    (*SCase "x :: x0 :: l".*) apply el_cc. apply IHev. inversion H2. reflexivity.
Qed.

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

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor
        c : forall l, l = rev l -> pal l
      may seem obvious, but will not work very well.)
*)
Fixpoint snoc {X:Type} (l:list X) (v:X) : (list X) :=
  match l with
  | nil      => cons v (nil)
  | cons h t => cons h (snoc t v)
  end.

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 => snoc (rev t) h
  end.

Notation "x ++ y" := (app x y)
                     (at level 60, right associativity).

Inductive pal {X:Type} : list X -> Prop :=
  | pal_nil : pal []
  | pal_x :  forall x, pal [x]
  | pal_xx :  forall x l, pal l -> pal (x :: snoc l x).

Lemma snoc_with_append : forall X : Type,
                         forall l1 l2 : list X,
                         forall v : X,
  snoc (l1 ++ l2) v = (l1 ++ (snoc l2 v))%list.
Proof.
  intros. induction l1 as [|n l1'].
  (*l1=nil*)
  simpl. reflexivity.
  (*l1=n l1'*)
  simpl. rewrite -> IHl1'. reflexivity.
Qed.

Lemma pal_xx_apply : forall (X:Type) (l:list X) (x:X),
  pal (l ++ rev l) -> pal (x :: (l ++ snoc (rev l) x)%list).
Proof.
  intros. rewrite <- snoc_with_append. apply pal_xx.
  apply H.
Qed.

Theorem pal_app_rev: forall (X: Type) (l: list X),
  pal (l ++ rev l).
Proof.
  intros. induction l.
  simpl. apply pal_nil.
  simpl. apply pal_xx_apply. apply IHl.
Qed.

Lemma snoc_rev : forall (X : Type) (l : list X) (n : X),
  rev(snoc l n) = n :: (rev l).
Proof.
  intros. induction l as [|m l'].
  (*l=nil*)
  simpl. reflexivity.
  (*l=m l'*)
  simpl. rewrite -> IHl'.
  simpl. reflexivity.
Qed.

Theorem pal_rev: forall (X: Type) (l: list X),
  pal l -> l = rev l.
Proof.
  intros. induction H.
  reflexivity.
  reflexivity.
  simpl. rewrite snoc_rev.
  rewrite <- IHpal. simpl. reflexivity.
Qed.
(** [] *)

(* Again, the converse direction is much more difficult, due to the
lack of evidence. *)

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

Qed.
*)
(** [] *)

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

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

Module LeModule.

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

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

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

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

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

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

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

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

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

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

End LeModule.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Lemma le_succ : forall n m,
  S n <= m -> n <= m.
Proof.
  intros. assert(H0: n <= S n).
  apply le_S. apply le_n.
  apply le_trans with (m:=n) (n:=S n) (o:=m).
  apply H0. apply H.
Qed.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  intros. inversion H.
  apply le_n. apply le_succ. apply H1.
Qed.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
  intros. induction b.
  rewrite <- plus_n_O. apply le_n.
  rewrite <- plus_n_Sm. apply le_S. apply IHb.
Qed.

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

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

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

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
  induction n as [| n'].
  intros. apply O_le_n.
  destruct m as [| m'].
  intros. inversion H.
  intros.
  apply n_le_m__Sn_le_Sm.
  apply IHn'. simpl in H. apply H.
Qed.

Lemma ble_nat_refl : forall n,
  ble_nat n n = true.
Proof.
  intros. induction n as [| n'].
  reflexivity.
  simpl. apply IHn'.
Qed.

Lemma ble_nat_succ : forall n m,
  ble_nat n m = true -> ble_nat n (S m) = true.
Proof.
  induction n. reflexivity.
  intros. destruct m.
  inversion H.
  simpl. apply IHn. simpl in H. apply H.
Qed.

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
  (* Hint: This may be easiest to prove by induction on [m]. *)
  induction m.
  intros. inversion H. reflexivity.
  intros. inversion H. apply ble_nat_refl.
  destruct n. reflexivity.
  subst. apply ble_nat_succ. apply IHm. apply H1.
Qed.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
  (* Hint: This theorem can be easily proved without using [induction]. *)
  intros. apply ble_nat_true in H. apply ble_nat_true in H0.
  apply le_ble_nat. apply le_trans with (m:=n) (n:=m).
  apply H. apply H0.
Qed.

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

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

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

(** - Which of the following propositions are provable?
      - [R 1 1 2]
      - [R 2 2 6]

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

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

(* FILL IN HERE *)
[]
*)

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

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

End R.

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

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)

    - Prove [subseq_refl] that subsequence is reflexive, that is,
      any list is a subsequence of itself.

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

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

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

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

    - [R 2 [1,0]]
    - [R 1 [1,2,1,0]]
    - [R 6 [3,2,1,0]]
*)

(** [] *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  (* FILL IN HERE *) admit.

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

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

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

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

(*
Fixpoint true_upto_n__true_everywhere
(* FILL IN HERE *)

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

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
From LF Require Export exercise7.

(** **** Exercise: 2 stars, standard (eight_is_even) *)
(* Give a tactic proof and a proof object showing that ev 8. *)
Theorem ev_8 : ev 8.
Proof.
  repeat apply ev_SS. apply ev_0.
Qed.

Definition ev_8' : ev 8 := ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).

Definition add1 : nat -> nat.
  intros n.
  apply S.
  apply n.  Defined.

(** **** Exercise: 2 stars, standard (conj_fact) *)
(* Construct a proof object for the following proposition. *)
Definition conj_fact : forall P Q R, P /\ Q -> Q /\ R -> P /\ R :=
  fun (P Q R : Prop) (H1: P /\ Q) (H2: Q /\ R) =>
    match H1, H2 with
    | conj p q, conj q' r => conj p r
    end.

(** **** Exercise: 2 stars, standard (or_commut') *)
(* Construct a proof object for the following proposition. *)
Definition or_commut: forall P Q, P \/ Q -> Q \/ P :=
  fun (P Q : Prop) (H: P \/ Q) =>
    match H with
    | or_introl p => or_intror p (* Extract and then apply reversely. *)
    | or_intror q => or_introl q
    end.

(* Inductive ex {A : Type} (P : A → Prop) : Prop :=
  | ex_intro : ∀ x : A, P x → ex P.

  First, ex_intro (P) will introduce a universal quantifier forall x : Type, P(x)
  so that we need to find the specific value for proving P(x).

  Then we fill the value and the evidence.

  *)

(** **** Exercise: 2 stars, standard (ex_ev_Sn) *)
(* Construct a proof object for the following proposition. *)
Definition ex_ev_Sn : ex (fun n => ev (S n)) :=
  (* Prop + existential value + evidence. *)
  ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).

(** **** Exercise: 1 star, standard (p_implies_true)
Construct a proof object for the following proposition. *)
Definition p_implies_true : forall P, P -> True :=
  fun P H => I.

(** **** Exercise: 1 star, standard (ex_falso_quodlibet') *)
(* Construct a proof object for the following proposition. *)
Definition ex_falso_quodlibet' : forall P, False -> P :=
  fun P H => match H with end.

Module EqualityPlayground.

Inductive eq {X:  Type} : X -> X -> Prop :=
  | eq_refl : forall x, eq x x.

Notation "x == y" := (eq x y)
                       (at level 70, no associativity)
                     : type_scope.

Definition singleton : forall (X : Type) (x : X), [ ] ++ [x] == x :: [ ] :=
  fun (X : Type) (x : X) => eq_refl [x].

Definition eq_add : forall (n1 n2 : nat), n1 == n2 -> (S n1) == (S n2) :=
fun n1 n2 Heq =>
  match Heq with
  | eq_refl n => eq_refl (S n)
  end.

(** **** Exercise: 2 stars, standard (eq_cons) *)
(* Construct the proof object for this theorem. Use pattern matching against the equality hypotheses. *)
Definition eq_cons : forall (X : Type) (h1 h2 : X) (t1 t2 : list X),
    h1 == h2 -> t1 == t2 -> h1 :: t1 == h2 :: t2 :=
  fun (X : Type) (h1 h2 : X) (t1 t2 : list X) H1 H2 =>
    match H1, H2 with
    | (eq_refl h), (eq_refl t) => eq_refl (h :: t)
    end.

(** **** Exercise: 2 stars, standard (equality__leibniz_equality) *)
(* The inductive definition of equality implies Leibniz equality: what we mean when we say "x and y are
equal" is that every property on P that is true of x is also true of y. Prove that. *)
Lemma equality__leibniz_equality : forall (X : Type) (x y: X),
  x == y -> forall (P : X -> Prop), P x -> P y.
Proof.
  intros.
  destruct H. apply H0.
Qed.

(** **** Exercise: 2 stars, standard (equality__leibniz_equality_term) *)
(* Construct the proof object for the previous exercise. All it requires is anonymous functions and
pattern-matching; the large proof term constructed by tactics in the previous exercise is needessly
complicated. Hint: pattern-match as soon as possible. *)
Definition equality__leibniz_equality_term : forall (X : Type) (x y: X),
    x == y -> forall P : (X -> Prop), P x -> P y :=
  fun X x y H =>
    match H with
    | eq_refl x =>
      fun P H0 => H0
    end.

(** **** Exercise: 3 stars, standard, optional (leibniz_equality__equality) *)
(* Show that, in fact, the inductive definition of equality is equivalent to Leibniz equality. Hint: the
proof is quite short; about all you need to do is to invent a clever property P to instantiate the
antecedent. *)
Lemma leibniz_equality__equality : forall (X : Type) (x y: X),
  (forall P : X -> Prop, P x -> P y) -> x == y.
Proof.
  intros.
  apply (H (eq x)). apply (eq_refl x).
Qed.

End EqualityPlayground.

Definition propositional_extensionality : Prop :=
  forall (P Q : Prop), (P <-> Q) -> P = Q.

Theorem pe_implies_or_eq :
  propositional_extensionality ->
  forall (P Q : Prop), (P \/ Q) = (Q \/ P).
Proof.
  unfold propositional_extensionality.
  intros. apply H. split.
  - intros. destruct H0. right. apply H0. left. apply H0.
  - intros. destruct H0. right. apply H0. left. apply H0.
Qed.

Lemma pe_implies_true_eq :
  propositional_extensionality ->
  forall (P : Prop), P -> True = P.
Proof.
  unfold propositional_extensionality.
  intros.
  apply H. split.
  - intros. apply H0.
  - apply p_implies_true.
Qed.

Definition proof_irrelevance : Prop :=
  forall (P : Prop) (pf1 pf2 : P), pf1 = pf2.

Theorem pe_implies_pi :
  propositional_extensionality -> proof_irrelevance.
Proof.
  unfold proof_irrelevance. intros.
  apply pe_implies_true_eq with P in pf1 as H'. destruct H'.
  - destruct pf1, pf2. trivial.
  - apply H.
Qed.


Require Import Arith Lia.

Definition iffT (X Y : Type) : Type := (X -> Y) * (Y -> X).
Notation "X <=> Y" := (iffT X Y) (at level 95, no associativity).

Definition inj {X Y} (f : X -> Y) :=
  forall x x', f x = f x' -> x = x'.

Definition inv {X Y} (g : Y -> X) (f : X -> Y) :=
  forall x, g (f x) = x.

Definition bijection X Y :=
  { f : X -> Y & { g & inv g f /\ inv f g }}.

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

Section Cantor.

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

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

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

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

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

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

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

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

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

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

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

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

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

Section Cantor.

Section Cantor2.

Definition Cantor x y z := (x + y)*S (x + y) + 2*y = 2*z.
Definition Next x y u v :=
     (x = 0 -> u = S y /\ v = 0)
  /\ (x <> 0 -> (exists p, S p = x /\ u = p) /\ v = S y).

Fact C01 z :
  Cantor 0 0 z <-> z = 0.
Proof. unfold Cantor; lia. Qed.

Fact C02 x y :
  Cantor x y 0 <-> x = 0 /\ y = 0.
Proof. unfold Cantor; lia. Qed.

Fact C1 {y z} :
  Cantor 0 y z <-> Cantor (S y) 0 (S z).
Proof. unfold Cantor; lia. Qed.

Fact C2 {x y z} :
  Cantor (S x) y z <-> Cantor x (S y) (S z).
Proof. unfold Cantor; lia. Qed.

Lemma Code_Next {x y u v z} :
  Next x y u v -> Cantor x y z <-> Cantor u v (S z).
Proof.
  unfold Next. destruct x.
  - intros [H _].
    unshelve refine (let H := H _ in _); auto.
    destruct H as [-> ->]. apply C1.
  - intros [_ H].
    unshelve refine (let H := H _ in _); auto.
    destruct H as [[? [<- ->]] ->]. apply C2.
Qed.

Lemma Zero_or_Next u v :
  (u = 0 /\ v = 0) \/ (exists x y, Next x y u v).
Proof.
  destruct v as [|v].
  - destruct u.
    + now left.
    + right; exists 0, u. unfold Next. lia.
  - right; exists (S u), v.
    unfold Next. repeat split; try lia.
    now exists u.
Qed.

Lemma Next_inj x y u v u' v' :
  Next x y u v -> Next x y u' v' -> u = u' /\ v = v'.
Proof.
  unfold Next. intros [? H] [? H'].
  destruct x; [lia|].
  destruct H as [[p [? ->]] ->], H' as [[p' [? ->]] ->]; lia.
Qed.

Fact Cantor_inj1 x y z z' :
  Cantor x y z -> Cantor x y z' -> z = z'.
Proof. unfold Cantor; lia. Qed.

(* This served as a guide for the proof of Cantor_inj2 *)
Goal inj code.
Proof.
  intros a; pattern a; apply (size_rect code).
  intros p rec p'.
  destruct
    (zero_or_next p) as [[? ->] | ->],
    (zero_or_next p') as [[? ->] | ->].
  {
    rewrite !code_next. intros [=]. f_equal. apply rec.
    rewrite code_next. all: auto.
  }
  all: rewrite ?code_next; cbn; auto; lia.
Qed.

Goal inj code.
Proof.
  unfold inj.
  enough (forall n x x', code x = n -> code x' = n -> x = x').
  {
    intros a b E. eapply H; auto.
  }
  induction n.
  - admit.
  - intros p p'.
    destruct
    (zero_or_next p) as [[a ->] | ->],
    (zero_or_next p') as [[b ->] | ->].
    { rewrite !code_next. intros [=][=]. f_equal.
      now apply IHn. }
    all: cbn; lia.
Admitted.

Lemma Cantor_inj2 z :
  forall x x' y y', Cantor x y z -> Cantor x' y' z -> x = x' /\ y = y'.
Proof.
  pattern z; revert z; apply (size_rect id).
  intros z rect u u' v v'.
  destruct
    (Zero_or_Next u v) as [[-> ->] | [x [y N]] ],
    (Zero_or_Next u' v') as [[-> ->] | [x' [y' N']] ].
  - auto.
  - unfold Cantor; intros ->%C01 ?; lia.
  - unfold Cantor; intros ? ->%C01; lia.
  - destruct z.
    { intros []%C02 []%C02; lia. }
    unshelve refine (fun H H' =>
      let C := proj2 (Code_Next N) H  in
      let C' := proj2 (Code_Next N') H'  in
      let E := rect _ _ _ _ _ _  C C' in _
    ); auto.
    destruct E as [-> ->].
    eapply Next_inj; eauto.
Qed.

Fact Gauss n : {k & n*(S n) = 2*k}.
Proof.
  induction n.
  - now exists 0.
  - destruct IHn as [k ].
    exists (n + k + 1); lia.
Defined.

(* Define coding and projection functions *)

Lemma Coding x y : {z & Cantor x y z}.
Proof.
  unfold Cantor.
  destruct (Gauss (x + y)) as [z ].
  exists (z + y); lia.
Defined.

Definition code' x y := projT1 (Coding x y).
Definition code_ x y : Cantor x y (code' x y) := projT2 (Coding x y).

Lemma Decoding z : {x & {y & Cantor x y z}}.
Proof.
  induction z.
  - exists 0, 0. unfold Cantor; lia.
  - destruct IHz as [x [y IH]], x as [|x].
    + eexists; eexists. erewrite <-C1; eauto.
    + eexists; eexists. erewrite <-C2; eauto.
Defined.

Definition pi1 n := projT1 (Decoding n).
Definition pi2 n := projT1 (projT2 (Decoding n)).
Definition projections n : Cantor (pi1 n) (pi2 n) n := (projT2 (projT2 (Decoding n))).

Lemma code_pi n :
  code' (pi1 n) (pi2 n) = n.
Proof.
  eapply Cantor_inj1.
  apply code_. apply projections.
Qed.

Lemma pi_code x y :
  pi1 (code' x y) = x /\ pi2 (code' x y) = y.
Proof.
  eapply Cantor_inj2.
  apply projections. apply code_.
Qed.

End Cantor2.