(** * Logic: Logic in Coq *)

Set Warnings "-notation-overridden,-parsing".
Require Export Tactics.
Require Export Poly.
(** 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 this chapter, we will see how Coq can be used to carry
    out other familiar forms of logical reasoning.

    Before diving into details, let's talk a bit about the status of
    mathematical statements in Coq.  Recall that Coq is a _typed_
    language, which means that every sensible expression in its world
    has an associated type.  Logical claims are no exception: any
    statement we might try to prove in Coq has a type, namely [Prop],
    the type of _propositions_.  We can see this with the [Check]
    command: *)

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

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

(** Note that _all_ syntactically well-formed propositions have type
    [Prop] in Coq, regardless of whether they are true. *)

(** Simply _being_ a proposition is one thing; being _provable_ is
    something else! *)

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

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

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

(** Indeed, propositions don't just have types: they are
    _first-class objects_ that can be manipulated in the same ways as
    the other entities in Coq's world. *)

(** So far, we've seen one primary place that propositions can appear:
    in [Theorem] (and [Lemma] and [Example]) declarations. *)

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

(** But propositions can be used in many other ways.  For example, 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 can also write _parameterized_ propositions -- that is,
    functions that take arguments of some type and return a
    proposition. *)

(** For instance, the following function takes a number
    and returns a proposition asserting that this number is equal to
    three: *)

Definition is_three (n : nat) : Prop :=
  n = 3.
Check is_three.
(* ===> nat -> Prop *)

(** In Coq, functions that return propositions are said to define
    _properties_ of their arguments.

    For instance, here's a (polymorphic) property defining the
    familiar notion of an _injective function_. *)

Definition injective {A B} (f : A -> B) :=
  forall x y : A, f x = f y -> x = y.

Lemma succ_inj : injective S.
Proof.
  intros n m H. inversion H. reflexivity.
Qed.

(** The equality operator [=] is also a function that returns a
    [Prop].

    The expression [n = m] is syntactic sugar for [eq n m] (defined
    using Coq's [Notation] mechanism). Because [eq] can be used with
    elements of any type, it is also polymorphic: *)
Check @eq.
(* ===> forall A : Type, A -> A -> Prop *)

(** (Notice that we wrote [@eq] instead of [eq]: The type
    argument [A] to [eq] is declared as implicit, so we need to turn
    off implicit arguments to see the full type of [eq].) *)

(* ################################################################# *)
(** * Logical Connectives *)

(* ================================================================= *)
(** ** Conjunction *)

(** The _conjunction_, or _logical and_, of propositions [A] and [B]
    is written [A /\ B], representing the claim that both [A] and [B]
    are true. *)

Example and_example : 3 + 4 = 7 /\ 2 * 2 = 4.

(** To prove a conjunction, use the [split] tactic.  It will generate
    two subgoals, one for each part of the statement: *)

Proof.
  (* WORKED IN CLASS *)
  split.
  - (* 3 + 4 = 7 *) reflexivity.
  - (* 2 + 2 = 4 *) reflexivity.
Qed.

(** For any propositions [A] and [B], if we assume that [A] is true
    and we assume that [B] is true, we can conclude that [A /\ B] is
    also true. *)

Lemma and_intro : forall A B : Prop, A -> B -> A /\ B.
Proof.
  intros A B HA HB. split.
  - apply HA.
  - apply HB.
Qed.

(** Since applying a theorem with hypotheses to some goal has the
    effect of generating as many subgoals as there are hypotheses for
    that theorem, we can apply [and_intro] to achieve the same effect
    as [split]. *)

Example and_example' : 3 + 4 = 7 /\ 2 * 2 = 4.
Proof.
  apply and_intro.
  - (* 3 + 4 = 7 *) reflexivity.
  - (* 2 + 2 = 4 *) reflexivity.
Qed.

(** **** Exercise: 2 stars (and_exercise)  *)
Example and_exercise :
  forall n m : nat, n + m = 0 -> n = 0 /\ m = 0.
Proof.
  intros. split.
  - destruct n.
    * reflexivity.
    * destruct m.
    + inversion H.
    + inversion H.
  - destruct m.
    * reflexivity.
    * rewrite <- plus_n_Sm in H.
      inversion H.
Qed.

(** So much for proving conjunctive statements.  To go in the other
    direction -- i.e., to _use_ a conjunctive hypothesis to help prove
    something else -- we employ the [destruct] tactic.

    If the proof context contains a hypothesis [H] of the form
    [A /\ B], writing [destruct H as [HA HB]] will remove [H] from the
    context and add two new hypotheses: [HA], stating that [A] is
    true, and [HB], stating that [B] is true.  *)

Lemma and_example2 :
  forall n m : nat, n = 0 /\ m = 0 -> n + m = 0.
Proof.
  intros n m H.
  destruct H as [Hn Hm].
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** As usual, we can also destruct [H] right when we introduce it,
    instead of introducing and then destructing it: *)

Lemma and_example2' :
  forall n m : nat, n = 0 /\ m = 0 -> n + m = 0.
Proof.
  intros n m [Hn Hm].
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** You may wonder why we bothered packing the two hypotheses [n = 0]
    and [m = 0] into a single conjunction, since we could have also
    stated the theorem with two separate premises: *)

Lemma and_example2'' :
  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.
Proof.
  intros n m Hn Hm.
  rewrite Hn. rewrite Hm.
  reflexivity.
Qed.

(** For this theorem, both formulations are fine.  But it's important
    to understand how to work with conjunctive hypotheses because
    conjunctions often arise from intermediate steps in proofs,
    especially in bigger developments.  Here's a simple example: *)

Lemma and_example3 :
  forall n m : nat, n + m = 0 -> n * m = 0.
Proof.
  (* WORKED IN CLASS *)
  intros n m H.
  assert (H' : n = 0 /\ m = 0).
  { apply and_exercise. apply H. }
  destruct H' as [Hn Hm].
  rewrite Hn. reflexivity.
Qed.

(** Another common situation with conjunctions is that we know
    [A /\ B] but in some context we need just [A] (or just [B]).
    The following lemmas are useful in such cases: *)

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

(** **** Exercise: 1 star, optional (proj2)  *)
Lemma proj2 : forall P Q : Prop,
  P /\ Q -> Q.
Proof.
  intros P Q [HP HQ].
  apply HQ.  Qed.

(** Finally, we sometimes need to rearrange the order of conjunctions
    and/or the grouping of multi-way conjunctions.  The following
    commutativity and associativity theorems are handy in such
    cases. *)

Theorem and_commut : forall P Q : Prop,
  P /\ Q -> Q /\ P.
Proof.
  intros P Q [HP HQ].
  split.
    - (* left *) apply HQ.
    - (* right *) apply HP.  Qed.

(** **** Exercise: 2 stars (and_assoc)  *)
(** (In the following proof of associativity, notice how the _nested_
    [intros] pattern 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 [HP [HQ HR]].
  split .
  - split.
    +  apply HP.
    + apply HQ.
  -  apply HR.
     Qed.

    (** By the way, the infix notation [/\] is actually just syntactic
    sugar for [and A B].  That is, [and] is a Coq operator that takes
    two propositions as arguments and yields a proposition. *)

Check and.
(* ===> and : Prop -> Prop -> Prop *)

(* ================================================================= *)
(** ** Disjunction *)

(** Another important connective is the _disjunction_, or _logical or_,
    of two propositions: [A \/ B] is true when either [A] or [B]
    is.  (Alternatively, we can write [or A B], where [or : Prop ->
    Prop -> Prop].) *)

(** To use a disjunctive hypothesis in a proof, we proceed by case
    analysis, which, as for [nat] or other data types, can be done
    with [destruct] or [intros].  Here is an example: *)

Lemma or_example :
  forall n m : nat, n = 0 \/ m = 0 -> n * m = 0.
Proof.
  (* This pattern implicitly does case analysis on
     [n = 0 \/ m = 0] *)
  intros n m [Hn | Hm].
  - (* Here, [n = 0] *)
    rewrite Hn. reflexivity.
  - (* Here, [m = 0] *)
    rewrite Hm. rewrite <- mult_n_O.
    reflexivity.
Qed.

(** Conversely, to show that a disjunction holds, we need to show that
    one of its sides does. This is done via two tactics, [left] and
    [right].  As their names imply, the first one requires
    proving the left side of the disjunction, while the second
    requires proving its right side.  Here is a trivial use... *)

Lemma or_intro : forall A B : Prop, A -> A \/ B.
Proof.
  intros A B HA.
  left.
  apply HA.
Qed.

(** ... and a slightly more interesting example requiring both [left]
    and [right]: *)

Lemma zero_or_succ :
  forall n : nat, n = 0 \/ n = S (pred n).
Proof.
  (* WORKED IN CLASS *)
  intros [|n].
  - left. reflexivity.
  - right. reflexivity.
Qed.

(** **** Exercise: 1 star (mult_eq_0)  *)
Lemma mult_eq_0 :
  forall n m, n * m = 0 -> n = 0 \/ m = 0.
Proof.
  intros.
  destruct n as [| n'] eqn:eq.
  - left. reflexivity.
  - right. simpl in H. destruct m.
    * reflexivity.
      * inversion H.
Qed.

(** **** Exercise: 1 star (or_commut)  *)
Theorem or_commut : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros.
  destruct H.
  right. apply H.
  left. apply H.
Qed.

(* ================================================================= *)
(** ** Falsehood and Negation *)
(** So far, we have mostly been concerned with proving that certain
    things are _true_ -- addition is commutative, appending lists is
    associative, etc.  Of course, we may also be interested in
    _negative_ results, showing that certain propositions are _not_
    true. In Coq, such negative statements are expressed with the
    negation operator [~]. *)

(** To see how negation works, recall the discussion of the _principle
    of explosion_ from the [Tactics] chapter; it asserts that, if
    we assume a contradiction, then any other proposition can be
    derived.  Following this intuition, we could define [~ P] ("not
    [P]") as [forall Q, P -> Q].  Coq actually makes a slightly
    different choice, defining [~ P] as [P -> False], where [False] is
    a specific contradictory proposition defined in the standard
    library. *)

Module MyNot.

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

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

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

End MyNot.

(** Since [False] is a contradictory proposition, the principle of
    explosion also applies to it. If we get [False] into the proof
    context, we can use [destruct] (or [inversion]) on it to complete
    any goal: *)

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

(** The Latin _ex falso quodlibet_ means, literally, "from falsehood
    follows whatever you like"; this is another common name for the
    principle of explosion. *)

(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)
(** Show that Coq's definition of negation implies the intuitive one
    mentioned above: *)

Fact not_implies_our_not : forall (P:Prop),
  ~ P -> (forall (Q:Prop), P -> Q).
Proof.
  intros.
  destruct H.
  apply H0.
Qed.

(** This is how we use [not] to state that [0] and [1] are different
    elements of [nat]: *)

Theorem zero_not_one : ~(0 = 1).
Proof.
  intros contra. inversion contra.
Qed.

(** Such inequality statements are frequent enough to warrant a
    special notation, [x <> y]: *)

Check (0 <> 1).
(* ===> Prop *)

Theorem zero_not_one' : 0 <> 1.
Proof.
  intros H. inversion H.
Qed.

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

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

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

Theorem double_neg : forall P : Prop,
  P -> ~~P.
Proof.

  intros P H. unfold not. intros G. apply G. apply H.  Qed.

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

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

(* FILL IN HERE *)
(** P -> ~~P is syntatict sugar for P-> ((P->False) -> False)

assume P is true,
and also P-> False, we need to show False.
Since P-> False and P, we know False.*)

(** **** Exercise: 2 stars, recommended (contrapositive)  *)
Theorem contrapositive : forall (P Q : Prop),
  (P -> Q) -> (~Q -> ~P).
Proof.
  intros.
  unfold not.
  intros.
  unfold not in H0.
  apply H in H1.
  apply H0 in H1.
  apply H1.
  Qed.
  (** [] *)

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

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

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

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

Theorem not_true_is_false : forall b : bool,
  b <> true -> b = false.
Proof.
  intros [] H.
  - (* b = true *)
    unfold not in H.
    apply ex_falso_quodlibet.
    apply H. reflexivity.
  - (* b = false *)
    reflexivity.
Qed.

(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq
    provides a built-in tactic, [exfalso], for applying it. *)

Theorem not_true_is_false' : forall b : bool,
  b <> true -> b = false.
Proof.
  intros [] H.
  - (* b = false *)
    unfold not in H.
    exfalso.                (* <=== *)
    apply H. reflexivity.
  - (* b = true *) reflexivity.
Qed.

(* ================================================================= *)
(** ** Truth *)

(** Besides [False], Coq's standard library also defines [True], a
    proposition that is trivially true. To prove it, we use the
    predefined constant [I : True]: *)

Lemma True_is_true : True.
Proof. apply I. Qed.

(** Unlike [False], which is used extensively, [True] is used quite
    rarely, since it is trivial (and therefore uninteresting) to prove
    as a goal, and it carries no useful information as a hypothesis. *)
(** But it can be quite useful when defining complex [Prop]s using
    conditionals or as a parameter to higher-order [Prop]s.  We will
    see examples of such uses of [True] later on. *)

(* ================================================================= *)
(** ** Logical Equivalence *)

(** The handy "if and only if" connective, which asserts that two
    propositions have the same truth value, is just the conjunction of
    two implications. *)

Module MyIff.

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

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

End MyIff.

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

Lemma not_true_iff_false : forall b,
  b <> true <-> b = false.
Proof.
  (* WORKED IN CLASS *)
  intros b. split.
  - (* -> *) apply not_true_is_false.
  - (* <- *)
    intros H. rewrite H. intros H'. inversion H'.
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.
  split.
  intros.
  apply H.
  intros.
  apply H.
Qed.

  Theorem iff_trans : forall P Q R : Prop,
  (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros.
  destruct H.
  destruct H0.
  split.
  intros.
apply H in H3.
apply H0 in H3.
apply H3.
intros.
apply H2 in H3.
apply H1 in H3.
apply H3.
Qed.

(** **** Exercise: 3 stars (or_distributes_over_and)  *)
Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros.
  split.

  intros.
  inversion H.
  split.
  left. apply H0.
  left. apply H0.
  split.
  destruct H0.
  right. apply H0.
  destruct H0. right. apply H1.
  intros.
  destruct H as [[HP1 | HQ] [HP2 | HR]].
  left. apply HP1.
  left.  apply HP1.
  left. apply HP2.
  right. split. apply HQ. apply HR.
Qed.

(** Some of Coq's tactics treat [iff] statements specially, avoiding
    the need for some low-level proof-state manipulation.  In
    particular, [rewrite] and [reflexivity] can be used with [iff]
    statements, not just equalities.  To enable this behavior, we need
    to import a Coq library that supports it: *)

Require Import Coq.Setoids.Setoid.

(** Here is a simple example demonstrating how these tactics work with
    [iff].  First, let's prove a couple of basic iff equivalences... *)

Lemma mult_0 : forall n m, n * m = 0 <-> n = 0 \/ m = 0.
Proof.
  split.
  - apply mult_eq_0.
  - apply or_example.
Qed.

Lemma or_assoc :
  forall P Q R : Prop, P \/ (Q \/ R) <-> (P \/ Q) \/ R.
Proof.
  intros P Q R. split.
  - intros [H | [H | H]].
    + left. left. apply H.
    + left. right. apply H.
    + right. apply H.
  - intros [[H | H] | H].
    + left. apply H.
    + right. left. apply H.
    + right. right. apply H.
Qed.

(** We can now use these facts with [rewrite] and [reflexivity] to
    give smooth proofs of statements involving equivalences.  Here is
    a ternary version of the previous [mult_0] result: *)

Lemma mult_0_3 :
  forall n m p, n * m * p = 0 <-> n = 0 \/ m = 0 \/ p = 0.
Proof.
  intros n m p.
  rewrite mult_0. rewrite mult_0. rewrite or_assoc.
  reflexivity.
Qed.

(** The [apply] tactic can also be used with [<->]. When given an
    equivalence as its argument, [apply] tries to guess which side of
    the equivalence to use. *)

Lemma apply_iff_example :
  forall n m : nat, n * m = 0 -> n = 0 \/ m = 0.
Proof.
  intros n m H. apply mult_0. apply H.
Qed.

(* ================================================================= *)
(** ** Existential Quantification *)

(** Another important logical connective is _existential
    quantification_.  To say that there is some [x] of type [T] such
    that some property [P] holds of [x], we write [exists x : T,
    P]. As with [forall], the type annotation [: T] can be omitted if
    Coq is able to infer from the context what the type of [x] should
    be. *)

(** To prove a statement of the form [exists x, P], we must show that
    [P] holds for some specific choice of value for [x], known as the
    _witness_ of the existential.  This is done in two steps: First,
    we explicitly tell Coq which witness [t] we have in mind by
    invoking the tactic [exists t].  Then we prove that [P] holds after
    all occurrences of [x] are replaced by [t]. *)

Lemma four_is_even : exists n : nat, 4 = n + n.
Proof.
  exists 2. reflexivity.
Qed.

(** Conversely, if we have an existential hypothesis [exists x, P] in
    the context, we can destruct it to obtain a witness [x] and a
    hypothesis stating that [P] holds of [x]. *)

Theorem exists_example_2 : forall n,
  (exists m, n = 4 + m) ->
  (exists o, n = 2 + o).
Proof.
  (* WORKED IN CLASS *)
  intros n [m Hm]. (* note implicit [destruct] here *)
  exists (2 + m). simpl.
simpl in Hm.  apply Hm.  Qed.

(** **** Exercise: 1 star, recommended (dist_not_exists)  *)
(** Prove that "[P] holds for all [x]" implies "there is no [x] for
    which [P] does not hold."  (Hint: [destruct H as [x E]] works on
    existential assumptions!)  *)

Theorem dist_not_exists : forall (X:Type) (P : X -> Prop),
  (forall x, P x) -> ~ (exists x, ~ P x).
Proof.
  intros.
  unfold not.
  intros. destruct H0.
  apply H0 in H.
  apply H.
Qed.
(** **** Exercise: 2 stars (dist_exists_or)  *)
(** Prove that existential quantification distributes over
    disjunction. *)

Theorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),
  (exists x, P x \/ Q x) <-> (exists x, P x) \/ (exists x, Q x).
Proof.
intros.
split.
intros.
destruct H.
destruct H.
left.
exists x.
apply H.
right.
exists x.
apply H.
intros.
destruct H.
destruct H.
exists x.
left.
apply H.
destruct H.
exists x.
right.
apply H.
Qed.

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

(** The logical connectives that we have seen provide a rich
    vocabulary for defining complex propositions from simpler ones.
    To illustrate, let's look at how to express the claim that an
    element [x] occurs in a list [l].  Notice that this property has a
    simple recursive structure: *)
(**    - If [l] is the empty list, then [x] cannot occur on it, so the
         property "[x] appears in [l]" is simply false. *)
(**    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]
         occurs in [l] if either it is equal to [x'] or it occurs in
         [l']. *)

(** We can translate this directly into a straightforward recursive
    function taking an element and a list and returning a proposition: *)

Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
  | nil => False
  | cons x' l' => x' = x \/ In x l'
  end.

(** When [In] is applied to a concrete list, it expands into a
    concrete sequence of nested disjunctions. *)

Example In_example_1 : In 4 [1; 2; 3; 4; 5].
Proof.
  (* WORKED IN CLASS *)
  simpl. right. right. right. left. reflexivity.
Qed.

Example In_example_2 :
  forall n, In n [2; 4] ->
  exists n', n = 2 * n'.
Proof.
  intros.
  simpl in H.
  destruct H as [H | [H | H]].
  exists 1.
  simpl.
  symmetry.
  apply H.
  exists 2.
  simpl.
  symmetry. apply H.
  inversion H.
Qed.
(** (Notice the use of the empty pattern to discharge the last case
    _en passant_.) *)

(** We can also prove more generic, higher-level lemmas about [In].

    Note, in the next, how [In] starts out applied to a variable and
    only gets expanded when we do case analysis on this variable: *)

Lemma In_map :
  forall (A B : Type) (f : A -> B) (l : list A) (x : A),
    In x l ->
    In (f x) (map f l).
Proof.
  intros A B f l x.
  induction l as [|x' l' IHl'].
  - (* l = nil, contradiction *)
    simpl. intros [].
  - (* l = x' :: l' *)
    simpl. intros [H | H].
    + rewrite H. left. reflexivity.
    + right. apply IHl'. apply H.
Qed.

(** This way of defining propositions recursively, though convenient
    in some cases, also has some drawbacks.  In particular, it is
    subject to Coq's usual restrictions regarding the definition of
    recursive functions, e.g., the requirement that they be "obviously
    terminating."  In the next chapter, we will see how to define
    propositions _inductively_, a different technique with its own set
    of strengths and limitations. *)

(** **** Exercise: 2 stars (In_map_iff)  *)
Lemma In_map_iff :
  forall (A B : Type) (f : A -> B) (l : list A) (y : B),
    In y (map f l) <->
    exists x, f x = y /\ In x l.
Proof.
  split.
  intros.
  induction l.
  simpl in H.
  inversion H.
  simpl In in H.
  destruct H.
  exists x.
  split.
  apply H.
  simpl.
  left.
  reflexivity.
  apply IHl in H.
  destruct H.
  exists x0.
  destruct H.
  split.
  apply H.
  simpl.
  right. apply H0.

induction l.
- intros.
  destruct H.
  inversion H.
  inversion H1.
-
  simpl.
  intros.
  generalize dependent IHl.
  destruct H.
  destruct H.
  destruct H0.
  intros.
  rewrite H0.
  left. apply H.
  intros.
  right.
  apply IHl.
  exists x0.
  split. apply H. apply H0.
Qed.

(** **** Exercise: 2 stars (In_app_iff)  *)
Lemma In_app_iff : forall A l l' (a:A),
  In a (l++l') <-> In a l \/ In a l'.
Proof.
split.
- intros.
induction l.
+ simpl in H. right.  apply H.
+ simpl. simpl in H.
  destruct H.
  left. left. apply H.
  rewrite <- or_assoc.
  right.
  apply IHl.
  apply H.
-
  intros.
  induction l.
 + simpl.
  destruct H.
  inversion H.
  apply H.
 + simpl.
   destruct H.
   destruct H.
   left. apply H.
   right. apply IHl.
   left. apply H.
   right. apply IHl.
   right. apply H.
Qed.
   (** **** Exercise: 3 stars, recommended (All)  *)
(** Recall that functions returning propositions can be seen as
    _properties_ of their arguments. For instance, if [P] has type
    [nat -> Prop], then [P n] states that property [P] holds of [n].

    Drawing inspiration from [In], write a recursive function [All]
    stating that some property [P] holds of all elements of a list
    [l]. To make sure your definition is correct, prove the [All_In]
    lemma below.  (Of course, your definition should _not_ just
    restate the left-hand side of [All_In].) *)

Fixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Lemma All_In :
  forall T (P : T -> Prop) (l : list T),
    (forall x, In x l -> P x) <->
    All P l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** 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], and it should return a 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
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

(** To test your definition, 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.
(** [] *)

(* ################################################################# *)
(** * Applying Theorems to Arguments *)

(** One feature of Coq that distinguishes it from many other proof
    assistants is that it treats _proofs_ as first-class objects.

    There is a great deal to be said about this, but it is not
    necessary to understand it in detail in order to use Coq.  This
    section gives just a taste, while a deeper exploration can be
    found in the optional chapters [ProofObjects] and
    [IndPrinciples]. *)

(** We have seen that we can use the [Check] command to ask Coq to
    print the type of an expression.  We can also use [Check] to ask
    what theorem a particular identifier refers to. *)

Check plus_comm.
(* ===> forall n m : nat, n + m = m + n *)

(** Coq prints the _statement_ of the [plus_comm] theorem in the same
    way that it prints the _type_ of any term that we ask it to
    [Check].  Why? *)

(** The reason is that the identifier [plus_comm] actually refers to a
    _proof object_ -- a data structure that represents a logical
    derivation establishing of the truth of the statement [forall n m
    : nat, n + m = m + n].  The type of this object _is_ the statement
    of the theorem that it is a proof of. *)

(** Intuitively, this makes sense because the statement of a theorem
    tells us what we can use that theorem for, just as the type of a
    computational object tells us what we can do with that object --
    e.g., if we have a term of type [nat -> nat -> nat], we can give
    it two [nat]s as arguments and get a [nat] back.  Similarly, if we
    have an object of type [n = m -> n + n = m + m] and we provide it
    an "argument" of type [n = m], we can derive [n + n = m + m]. *)

(** Operationally, this analogy goes even further: by applying a
    theorem, as if it were a function, to hypotheses with matching
    types, we can specialize its result without having to resort to
    intermediate assertions.  For example, suppose we wanted to prove
    the following result: *)

Lemma plus_comm3 :
  forall x y z, x + (y + z) = (z + y) + x.

(** It appears at first sight that we ought to be able to prove this
    by rewriting with [plus_comm] twice to make the two sides match.
    The problem, however, is that the second [rewrite] will undo the
    effect of the first. *)

Proof.
  intros x y z.
  rewrite plus_comm.
  rewrite plus_comm.
  (* We are back where we started... *)
Abort.

(** One simple way of fixing this problem, using only tools that we
    already know, is to use [assert] to derive a specialized version
    of [plus_comm] that can be used to rewrite exactly where we
    want. *)

Lemma plus_comm3_take2 :
  forall x y z, x + (y + z) = (z + y) + x.
Proof.
  intros x y z.
  rewrite plus_comm.
  assert (H : y + z = z + y).
  { rewrite plus_comm. reflexivity. }
  rewrite H.
  reflexivity.
Qed.

(** A more elegant alternative is to apply [plus_comm] directly to the
    arguments we want to instantiate it with, in much the same way as
    we apply a polymorphic function to a type argument. *)

Lemma plus_comm3_take3 :
  forall x y z, x + (y + z) = (z + y) + x.
Proof.
  intros x y z.
  rewrite plus_comm.
  rewrite (plus_comm y z).
  reflexivity.
Qed.

(** You can "use theorems as functions" in this way with almost all
    tactics that take a theorem name as an argument.  Note also that
    theorem application uses the same inference mechanisms as function
    application; thus, it is possible, for example, to supply
    wildcards as arguments to be inferred, or to declare some
    hypotheses to a theorem as implicit by default.  These features
    are illustrated in the proof below. *)

Example lemma_application_ex :
  forall {n : nat} {ns : list nat},
    In n (map (fun m => m * 0) ns) ->
    n = 0.
Proof.
  intros n ns H.
  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)
           as [m [Hm _]].
  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.
Qed.

(** We will see many more examples of the idioms from this section in
    later chapters. *)

(* ################################################################# *)
(** * Coq vs. Set Theory *)

(** Coq's logical core, the _Calculus of Inductive Constructions_,
    differs in some important ways from other formal systems that are
    used by mathematicians for writing down precise and rigorous
    proofs.  For example, in the most popular foundation for
    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set
    Theory (ZFC), a mathematical object can potentially be a member of
    many different sets; a term in Coq's logic, on the other hand, is
    a member of at most one type.  This difference often leads to
    slightly different ways of capturing informal mathematical
    concepts, but these are, by and large, quite natural and easy to
    work with.  For example, instead of saying that a natural number
    [n] belongs to the set of even numbers, we would say in Coq that
    [ev n] holds, where [ev : nat -> Prop] is a property describing
    even numbers.

    However, there are some cases where translating standard
    mathematical reasoning into Coq can be either cumbersome or
    sometimes even impossible, unless we enrich the core logic with
    additional axioms.  We conclude this chapter with a brief
    discussion of some of the most significant differences between the
    two worlds. *)

(* ================================================================= *)
(** ** Functional Extensionality *)

(** The equality assertions that we have seen so far mostly have
    concerned elements of inductive types ([nat], [bool], etc.).  But
    since Coq's equality operator is polymorphic, these are not the
    only possibilities -- in particular, we can write propositions
    claiming that two _functions_ are equal to each other: *)

Example function_equality_ex1 : plus 3 = plus (pred 4).
Proof. reflexivity. Qed.

(** In common mathematical practice, two functions [f] and [g] are
    considered equal if they produce the same outputs:

    (forall x, f x = g x) -> f = g

    This is known as the principle of _functional extensionality_. *)

(** Informally speaking, an "extensional property" is one that
    pertains to an object's observable behavior.  Thus, functional
    extensionality simply means that a function's identity is
    completely determined by what we can observe from it -- i.e., in
    Coq terms, the results we obtain after applying it. *)

(** Functional extensionality is not part of Coq's basic axioms.  This
    means that some "reasonable" propositions are not provable. *)

Example function_equality_ex2 :
  (fun x => plus x 1) = (fun x => plus 1 x).
Proof.
   (* Stuck *)
Abort.

(** However, we can add functional extensionality to Coq's core logic
    using the [Axiom] command. *)

Axiom functional_extensionality : forall {X Y: Type}
                                    {f g : X -> Y},
  (forall (x:X), f x = g x) -> f = g.

(** Using [Axiom] has the same effect as stating a theorem and
    skipping its proof using [Admitted], but it alerts the reader that
    this isn't just something we're going to come back and fill in
    later! *)

(** We can now invoke functional extensionality in proofs: *)

Example function_equality_ex2 :
  (fun x => plus x 1) = (fun x => plus 1 x).
Proof.
  apply functional_extensionality. intros x.
  apply plus_comm.
Qed.

(** Naturally, we must be careful when adding new axioms into Coq's
    logic, as they may render it _inconsistent_ -- that is, they may
    make it possible to prove every proposition, including [False]!

    Unfortunately, there is no simple way of telling whether an axiom
    is safe to add: hard work is generally required to establish the
    consistency of any particular combination of axioms.

    Fortunately, it is known that adding functional extensionality, in
    particular, _is_ consistent. *)

(** To check whether a particular proof relies on any additional
    axioms, use the [Print Assumptions] command.  *)

Print Assumptions function_equality_ex2.
(* ===>
     Axioms:
     functional_extensionality :
         forall (X Y : Type) (f g : X -> Y),
                (forall x : X, f x = g x) -> f = g *)

(** **** Exercise: 4 stars (tr_rev_correct)  *)
(** One problem with the definition of the list-reversing function
    [rev] that we have is that it performs a call to [app] on each
    step; running [app] takes time asymptotically linear in the size
    of the list, which means that [rev] has quadratic running time.
    We can improve this with the following definition: *)

Fixpoint rev_append {X} (l1 l2 : list X) : list X :=
  match l1 with
  | [] => l2
  | x :: l1' => rev_append l1' (x :: l2)
  end.

Definition tr_rev {X} (l : list X) : list X :=
  rev_append l [].

(** This version is said to be _tail-recursive_, because the recursive
    call to the function is the last operation that needs to be
    performed (i.e., we don't have to execute [++] after the recursive
    call); a decent compiler will generate very efficient code in this
    case.  Prove that the two definitions are indeed equivalent. *)

Lemma tr_rev_correct : forall X, @tr_rev X = @rev X.
(* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Propositions and Booleans *)

(** We've seen two different ways of encoding logical facts in Coq:
    with _booleans_ (of type [bool]), and with _propositions_ (of type
    [Prop]).

    For instance, to claim that a number [n] is even, we can say
    either
       - (1) that [evenb n] returns [true], or
       - (2) that there exists some [k] such that [n = double k].
             Indeed, these two notions of evenness are equivalent, as
             can easily be shown with a couple of auxiliary lemmas.

    Of course, it would be very strange if these two characterizations
    of evenness did not describe the same set of natural numbers!
    Fortunately, we can prove that they do... *)

(** We first need two helper lemmas. *)
Theorem evenb_double : forall k, evenb (double k) = true.
Proof.
  intros k. induction k as [|k' IHk'].
  - reflexivity.
  - simpl. apply IHk'.
Qed.

(** **** Exercise: 3 stars (evenb_double_conv)  *)
Theorem evenb_double_conv : forall n,
  exists k, n = if evenb n then double k
                else S (double k).
Proof.
  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)
  (* FILL IN HERE *) Admitted.
(** [] *)

Theorem even_bool_prop : forall n,
  evenb n = true <-> exists k, n = double k.
Proof.
  intros n. split.
  - intros H. destruct (evenb_double_conv n) as [k Hk].
    rewrite Hk. rewrite H. exists k. reflexivity.
  - intros [k Hk]. rewrite Hk. apply evenb_double.
Qed.

(** In view of this theorem, we say that the boolean
    computation [evenb n] _reflects_ the logical proposition
    [exists k, n = double k]. *)

(** Similarly, to state that two numbers [n] and [m] are equal, we can
    say either (1) that [beq_nat n m] returns [true] or (2) that [n =
    m].  Again, these two notions are equivalent. *)

Theorem beq_nat_true_iff : forall n1 n2 : nat,
  beq_nat n1 n2 = true <-> n1 = n2.
Proof.
  intros n1 n2. split.
  - apply beq_nat_true.
  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.
Qed.

(** However, even when the boolean and propositional formulations of a
    claim are equivalent from a purely logical perspective, they need
    not be equivalent _operationally_.

    Equality provides an extreme example: knowing that [beq_nat n m =
    true] is generally of little direct help in the middle of a proof
    involving [n] and [m]; however, if we convert the statement to the
    equivalent form [n = m], we can rewrite with it. *)

(** The case of even numbers is also interesting.  Recall that,
    when proving the backwards direction of [even_bool_prop] (i.e.,
    [evenb_double], going from the propositional to the boolean
    claim), we used a simple induction on [k].  On the other hand, the
    converse (the [evenb_double_conv] exercise) required a clever
    generalization, since we can't directly prove [(exists k, n =
    double k) -> evenb n = true]. *)

(** For these examples, the propositional claims are more useful than
    their boolean counterparts, but this is not always the case.  For
    instance, we cannot test whether a general proposition is true or
    not in a function definition; as a consequence, the following code
    fragment is rejected: *)

Fail Definition is_even_prime n :=
  if n = 2 then true
  else false.

(** Coq complains that [n = 2] has type [Prop], while it expects an
    elements of [bool] (or some other inductive type with two
    elements).  The reason for this error message has to do with the
    _computational_ nature of Coq's core language, which is designed
    so that every function that it can express is computable and
    total.  One reason for this is to allow the extraction of
    executable programs from Coq developments.  As a consequence,
    [Prop] in Coq does _not_ have a universal case analysis operation
    telling whether any given proposition is true or false, since such
    an operation would allow us to write non-computable functions.

    Although general non-computable properties cannot be phrased as
    boolean computations, it is worth noting that even many
    _computable_ properties are easier to express using [Prop] than
    [bool], since recursive function definitions are subject to
    significant restrictions in Coq.  For instance, the next chapter
    shows how to define the property that a regular expression matches
    a given string using [Prop].  Doing the same with [bool] would
    amount to writing a regular expression matcher, which would be
    more complicated, harder to understand, and harder to reason
    about.

    Conversely, an important side benefit of stating facts using
    booleans is enabling some proof automation through computation
    with Coq terms, a technique known as _proof by
    reflection_.  Consider the following statement: *)

Example even_1000 : exists k, 1000 = double k.

(** The most direct proof of this fact is to give the value of [k]
    explicitly. *)

Proof. exists 500. reflexivity. Qed.

(** On the other hand, the proof of the corresponding boolean
    statement is even simpler: *)

Example even_1000' : evenb 1000 = true.
Proof. reflexivity. Qed.

(** What is interesting is that, since the two notions are equivalent,
    we can use the boolean formulation to prove the other one without
    mentioning the value 500 explicitly: *)

Example even_1000'' : exists k, 1000 = double k.
Proof. apply even_bool_prop. reflexivity. Qed.

(** Although we haven't gained much in terms of proof size in this
    case, larger proofs can often be made considerably simpler by the
    use of reflection.  As an extreme example, the Coq proof of the
    famous _4-color theorem_ uses reflection to reduce the analysis of
    hundreds of different cases to a boolean computation.  We won't
    cover reflection in great detail, but it serves as a good example
    showing the complementary strengths of booleans and general
    propositions. *)

(** **** Exercise: 2 stars (logical_connectives)  *)
(** The following lemmas relate the propositional connectives studied
    in this chapter to the corresponding boolean operations. *)

Lemma andb_true_iff : forall b1 b2:bool,
  b1 && b2 = true <-> b1 = true /\ b2 = true.
Proof.
  (* FILL IN HERE *) Admitted.

Lemma orb_true_iff : forall b1 b2,
  b1 || b2 = true <-> b1 = true \/ b2 = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star (beq_nat_false_iff)  *)
(** The following theorem is an alternate "negative" formulation of
    [beq_nat_true_iff] that is more convenient in certain
    situations (we'll see examples in later chapters). *)

Theorem beq_nat_false_iff : forall x y : nat,
  beq_nat x y = false <-> x <> y.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (beq_list)  *)
(** Given a boolean operator [beq] for testing equality of elements of
    some type [A], we can define a function [beq_list beq] for testing
    equality of lists with elements in [A].  Complete the definition
    of the [beq_list] function below.  To make sure that your
    definition is correct, prove the lemma [beq_list_true_iff]. *)

Fixpoint beq_list {A : Type} (beq : A -> A -> bool)
                  (l1 l2 : list A) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Lemma beq_list_true_iff :
  forall A (beq : A -> A -> bool),
    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->
    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, recommended (All_forallb)  *)
(** Recall the function [forallb], from the exercise
    [forall_exists_challenge] in chapter [Tactics]: *)

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => true
  | x :: l' => andb (test x) (forallb test l')
  end.

(** Prove the theorem below, which relates [forallb] to the [All]
    property of the above exercise. *)

Theorem forallb_true_iff : forall X test (l : list X),
   forallb test l = true <-> All (fun x => test x = true) l.
Proof.
  (* FILL IN HERE *) Admitted.

(** Are there any important properties of the function [forallb] which
    are not captured by this specification? *)

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

(* ================================================================= *)
(** ** Classical vs. Constructive Logic *)

(** We have seen that it is not possible to test whether or not a
    proposition [P] holds while defining a Coq function.  You may be
    surprised to learn that a similar restriction applies to _proofs_!
    In other words, the following intuitive reasoning principle is not
    derivable in Coq: *)

Definition excluded_middle := forall P : Prop,
  P \/ ~ P.

(** To understand operationally why this is the case, recall
    that, to prove a statement of the form [P \/ Q], we use the [left]
    and [right] tactics, which effectively require knowing which side
    of the disjunction holds.  But the universally quantified [P] in
    [excluded_middle] is an _arbitrary_ proposition, which we know
    nothing about.  We don't have enough information to choose which
    of [left] or [right] to apply, just as Coq doesn't have enough
    information to mechanically decide whether [P] holds or not inside
    a function. *)

(** However, if we happen to know that [P] is reflected in some
    boolean term [b], then knowing whether it holds or not is trivial:
    we just have to check the value of [b]. *)

Theorem restricted_excluded_middle : forall P b,
  (P <-> b = true) -> P \/ ~ P.
Proof.
  intros P [] H.
  - left. rewrite H. reflexivity.
  - right. rewrite H. intros contra. inversion contra.
Qed.

(** In particular, the excluded middle is valid for equations [n = m],
    between natural numbers [n] and [m]. *)

Theorem restricted_excluded_middle_eq : forall (n m : nat),
  n = m \/ n <> m.
Proof.
  intros n m.
  apply (restricted_excluded_middle (n = m) (beq_nat n m)).
  symmetry.
  apply beq_nat_true_iff.
Qed.

(** It may seem strange that the general excluded middle is not
    available by default in Coq; after all, any given claim must be
    either true or false.  Nonetheless, there is an advantage in not
    assuming the excluded middle: statements in Coq can make stronger
    claims than the analogous statements in standard mathematics.
    Notably, if there is a Coq proof of [exists x, P x], it is
    possible to explicitly exhibit a value of [x] for which we can
    prove [P x] -- in other words, every proof of existence is
    necessarily _constructive_. *)

(** Logics like Coq's, which do not assume the excluded middle, are
    referred to as _constructive logics_.

    More conventional logical systems such as ZFC, in which the
    excluded middle does hold for arbitrary propositions, are referred
    to as _classical_. *)

(** The following example illustrates why assuming the excluded middle
    may lead to non-constructive proofs:

    _Claim_: There exist irrational numbers [a] and [b] such that [a ^
    b] is rational.

    _Proof_: It is not difficult to show that [sqrt 2] is irrational.
    If [sqrt 2 ^ sqrt 2] is rational, it suffices to take [a = b =
    sqrt 2] and we are done.  Otherwise, [sqrt 2 ^ sqrt 2] is
    irrational.  In this case, we can take [a = sqrt 2 ^ sqrt 2] and
    [b = sqrt 2], since [a ^ b = sqrt 2 ^ (sqrt 2 * sqrt 2) = sqrt 2 ^
    2 = 2].  []

    Do you see what happened here?  We used the excluded middle to
    consider separately the cases where [sqrt 2 ^ sqrt 2] is rational
    and where it is not, without knowing which one actually holds!
    Because of that, we wind up knowing that such [a] and [b] exist
    but we cannot determine what their actual values are (at least,
    using this line of argument).

    As useful as constructive logic is, it does have its limitations:
    There are many statements that can easily be proven in classical
    logic but that have much more complicated constructive proofs, and
    there are some that are known to have no constructive proof at
    all!  Fortunately, like functional extensionality, the excluded
    middle is known to be compatible with Coq's logic, allowing us to
    add it safely as an axiom.  However, we will not need to do so in
    this book: the results that we cover can be developed entirely
    within constructive logic at negligible extra cost.

    It takes some practice to understand which proof techniques must
    be avoided in constructive reasoning, but arguments by
    contradiction, in particular, are infamous for leading to
    non-constructive proofs.  Here's a typical example: suppose that
    we want to show that there exists [x] with some property [P],
    i.e., such that [P x].  We start by assuming that our conclusion
    is false; that is, [~ exists x, P x]. From this premise, it is not
    hard to derive [forall x, ~ P x].  If we manage to show that this
    intermediate fact results in a contradiction, we arrive at an
    existence proof without ever exhibiting a value of [x] for which
    [P x] holds!

    The technical flaw here, from a constructive standpoint, is that
    we claimed to prove [exists x, P x] using a proof of
    [~ ~ (exists x, P x)].  Allowing ourselves to remove double
    negations from arbitrary statements is equivalent to assuming the
    excluded middle, as shown in one of the exercises below.  Thus,
    this line of reasoning cannot be encoded in Coq without assuming
    additional axioms. *)

(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)
(** Proving the consistency of Coq with the general excluded middle
    axiom requires complicated reasoning that cannot be carried out
    within Coq itself.  However, the following theorem implies that it
    is always safe to assume 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)] (since [P]
    implies [~ ~ P], by the exercise below), which would be a
    contradiction.  But since we can't, it is safe to add [P \/ ~P] as
    an axiom. *)

Theorem excluded_middle_irrefutable: forall (P:Prop),
  ~ ~ (P \/ ~ P).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (not_exists_dist)  *)
(** It is a theorem of classical logic that the following two
    assertions are equivalent:

    ~ (exists x, ~ P x)
    forall x, P x

    The [dist_not_exists] theorem above proves one side of this
    equivalence. Interestingly, the other direction cannot be proved
    in constructive logic. Your job is to show that it is implied by
    the excluded middle. *)

Theorem not_exists_dist :
  excluded_middle ->
  forall (X:Type) (P : X -> Prop),
    ~ (exists x, ~ P x) -> (forall x, P x).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 5 stars, optional (classical_axioms)  *)
(** For those who like a challenge, here is an exercise taken from the
    Coq'Art book by Bertot and Casteran (p. 123).  Each of the
    following four statements, together with [excluded_middle], can be
    considered as characterizing classical logic.  We can't prove any
    of them in Coq, but we can consistently add any one of them as an
    axiom if we wish to work in classical logic.

    Prove that all five propositions (these four plus
    [excluded_middle]) are equivalent. *)

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

Definition double_negation_elimination := 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 *)
(** [] *)


(*|
##########################################################
Why can I use the constructor tactic to prove reflexivity?
##########################################################

:Link: https://stackoverflow.com/q/65959309
|*)

(*|
Question
********

The constructor tactic allows you to discharge a goal which is an
inductive datatype by automatically applying constructors. However,
definitional equality is not an inductive product in Coq. Then why
does Coq accept this proof?
|*)

Example zeqz : 0 = 0. constructor.

(*|
Answer
******

The equality type in Coq is defined as follows
|*)

Inductive eq (A : Type) (x : A) : A -> Prop :=
  eq_refl : x = x :> A

where "x = y :> A" := (@eq A x y) : type_scope.

(*|
that is it has a single reflexivity constructor.

To prove that ``0 = 0`` you need to construct a term of this type. The
only way to do this is to invoke ``eq_refl``. However in order to
invoke ``eq_refl`` the type checker needs to know that ``0`` is
convertible to ``0`` (that is they are definitionally equal).

----

The type ``eq`` is a semantic notion of equality, whereas definitional
equality is a syntactic notion. **This means that the proof assistant
cannot distinguish between definitionally equal terms, but it can
distinguish between semantically equal terms.** So the constructor
``eq_refl`` can be seen as a guarantee that definitional (syntactic)
equality *subsumes* semantic equality.

It is fruitful to ask whether terms may be semantically equal without
being syntactically equal. Such examples may only be obtained through
an axiom. For example, by the definition of the recursor (``nat_rec``,
or more technically, ``nat_ind``) for the natural numbers, or by an
`extensionality
<https://coq.inria.fr/library/Coq.Logic.FunctionalExtensionality.html>`__
axiom.
|*)


Require Import Arith.

Fixpoint pow (b e:nat) :=
  match e with
  | 0 => 1
  | S f => b * pow b f
  end.

Fixpoint aux_div n m a :=
  match m, a with
  | _, 0 => None (* NOT REACHED *)
  | 0, _ => None
  | S q, S b =>
      match lt_dec n m with
      | left _ => Some 0
      | right _ =>
          match aux_div (n - m) m b with
          | None => None (* NOT REACHED *)
          | Some k => Some (S k)
          end
      end
  end.

Definition div (n m:nat) := aux_div n m (S n).

Definition rem (n m:nat) :=
  match div n m with
  | None => None
  | Some q => Some (n - q * m)
  end.

Lemma nat_strong_ind (P:nat->Prop):
  P 0 ->
  (forall n:nat,
   (forall m:nat, m < n -> P m) -> P n) ->
  (forall n:nat, P n).
Proof.
  intros P0 Hrec n.
  cut (forall n m:nat, m < n -> P m).
  intros Hcut.
  apply Hcut with (n := S n).
  auto.
  clear n.
  induction n.
  intros m m_imp.
  apply False_ind, lt_n_O with (n := m), m_imp.
  intros m mainH.
  cut (m < n \/ m = n).
  intros [baseH | stepH].
  apply IHn, baseH.
  rewrite stepH.
  apply Hrec with (n := n), IHn.
  apply le_lt_or_eq.
  apply le_S_n, mainH.
Qed.

Lemma S_exchange:
  forall a b:nat,
  S a + b * S a = S b + a * S b.
Proof.
  intros a b.
  rewrite mult_comm with (n := b),
          mult_comm with (n := a).
  simpl.
  repeat rewrite plus_assoc.
  rewrite mult_comm, plus_comm with (n := a).
  reflexivity.
Qed.

Lemma not_lt_le:
  forall n m:nat, ~ n < m -> m <= n.
Proof.
  intros n m H.
  cut (m <= n \/ n < m).
  tauto.
  apply le_or_lt.
Qed.

Lemma minus_to_plus:
  forall n m p:nat,
  p <= m -> n = m - p -> m = n + p.
Proof.
  intros n m p p_le_m H.
  rewrite H, plus_comm.
  symmetry.
  apply le_plus_minus_r, p_le_m.
Qed.

Lemma n_le_0:
  forall n:nat, n <= 0 -> n = 0.
Proof.
  intros n n_le_0.
  destruct n.
  reflexivity.
  absurd (S n <= 0).
  apply le_Sn_0.
  assumption.
Qed.

Lemma div_works:
  forall n d:nat,
  d <> 0 ->
  exists q:nat, div n d = Some q /\
  d * q <= n < d * S q.
Proof.
  unfold div.
  cut (forall n d k:nat,
       d <> 0 -> n < k ->
       exists q:nat,
       aux_div n d k = Some q /\
       d * q <= n < d * S q).
  intros Hcut n d d_ne_0.
  apply Hcut with (k := S n); auto.
  intros n.
  elim n using nat_strong_ind.
  intros d k d_ne_0 k_gt_0.
  destruct d as [|d'], k as [|k'].
  apply False_ind; auto.
  apply False_ind; auto.
  apply False_ind, lt_irrefl with (n := 0); auto.
  exists 0; simpl.
  rewrite mult_0_r; split; split;
    [auto | apply lt_0_Sn].
  clear n.
  intros n Hrec.
  intros d k d_ne_0 k_gt_n.
  destruct d as [|d'], k as [|k'].
  apply False_ind; auto.
  apply False_ind; auto.
  apply False_ind, lt_n_O with (n := n); auto.
  simpl.
  destruct lt_dec with (n := n) (m := (S d'))
           as [n_lt_d | n_ge_d].
  exists 0.
  rewrite mult_0_r, plus_0_l, plus_0_l,
          mult_1_r.
  split; split; auto.
  apply le_0_n.
  cut (exists q':nat,
       aux_div (n - S d') (S d') k' = Some q' /\
       S d' * q' <= n - S d' < S d' * S q').
  intros [q' [HrecI1 [HrecI2 HrecI3]]].
  exists (S q').
  rewrite HrecI1.
  split; auto.
  split.
  cut (S d' * q' + S d' <= n).
  intros n_lo_bound.
  rewrite S_exchange, mult_comm, plus_comm; auto.
  rewrite le_plus_minus
    with (n := S d') (m := n).
  rewrite plus_comm with (n := S d').
  apply plus_le_compat_r; auto.
  apply not_lt_le; auto.
  cut (n - S d' + S d' < S d' * S q' + S d').
  intros n_hi_bound.
  rewrite <-le_plus_minus_r
    with (n := S d') (m := n).
  rewrite plus_comm.
  rewrite <-plus_Sn_m, S_exchange.
  rewrite plus_comm with (n := S d').
  rewrite mult_comm; auto.
  apply not_lt_le; auto.
  apply plus_lt_compat_r; auto.
  apply Hrec.
  assert (n - S d' < n) as sub_is_lt.
  apply lt_minus.
  apply not_lt_le; auto.
  apply lt_O_Sn.
  auto.
  auto.
  apply lt_le_trans with (m := n).
  apply lt_minus.
  apply not_lt_le; auto.
  apply lt_0_Sn.
  apply lt_n_Sm_le; auto.
Qed.

Lemma d_q_step:
  forall q q' d:nat,
  q < q' -> d * S q <= d * q'.
Proof.
  intros q q' d q_lt_q'.
  apply mult_le_compat_l, q_lt_q'.
Qed.

Lemma div_unique:
  forall n d q:nat,
  d * q <= n < d * S q -> div n d = Some q.
Proof.
  intros n d q [Hlo Hhi].
  destruct d as [|d'].
  simpl in Hhi.
  absurd (n < 0).
  apply lt_n_O.
  assumption.
  cut (exists q:nat,
       div n (S d') = Some q /\
       S d' * q <= n < S d' * S q).
  intros [q' [EHq' [Hq'lo Hq'hi]]].
  cut (q' < q \/ q = q' \/ q' > q).
  intros [Hqrel | [Hqrel | Hqrel]].
  absurd (S d' * S q' <= S d' * q).
  apply lt_not_le, le_lt_trans with (m := n);
    assumption.
  apply d_q_step; assumption.
  rewrite EHq', Hqrel; reflexivity.
  absurd (S d' * S q <= S d' * q').
  apply lt_not_le, le_lt_trans with (m := n);
    assumption.
  apply d_q_step; assumption.
  cut (q <= q' \/ q' < q).
  intros [Hqle | Hq'lt].
  right.
  unfold gt.
  rewrite or_comm.
  apply le_lt_or_eq; assumption.
  left; assumption.
  apply le_or_lt.
  apply div_works.
  discriminate.
Qed.

Lemma rem_works:
  forall n d:nat,
  d <> 0 ->
  exists q:nat, div n d = Some q /\
  exists r:nat, rem n d = Some r /\
  n = d * q + r.
Proof.
  intros n d d_ne_0.
  cut (exists q:nat, div n d = Some q /\
       d * q <= n < d * S q).
  intros [q [div_result [div_lo_bound
                         div_hi_bound]]].
  cut (exists r:nat, rem n d = Some r).
  intros [r rem_result].
  exists q.
  split.
  apply div_result.
  exists r.
  split.
  apply rem_result.
  unfold rem in rem_result.
  rewrite div_result in rem_result.
  injection rem_result.
  intros div_rem_rel.
  rewrite plus_comm.
  apply minus_to_plus.
  apply div_lo_bound.
  rewrite <-div_rem_rel, mult_comm.
  reflexivity.
  unfold rem.
  rewrite div_result.
  exists (n - q * d).
  reflexivity.
  apply div_works, d_ne_0.
Qed.

Lemma rem_unique:
  forall n d q r:nat,
  (d * q <= n < d * S q /\ r = n - d * q) ->
  rem n d = Some r.
Proof.
  intros n d q r [Hbounds Hrel].
  unfold rem.
  rewrite div_unique with (q := q).
  rewrite Hrel, mult_comm; reflexivity.
  assumption.
Qed.

Lemma div_ge:
  forall n m:nat,
  m <> 0 -> m <= n ->
  exists q, div n m = Some q /\ 1 <= q.
Proof.
  intros n m m_ne_0 m_le_n.
  cut (exists q:nat,
       div n m = Some q /\
       m * q <= n < m * S q).
  intros [q [EHq [Hblo Hbhi]]].
  exists q.
  split; [assumption | ..].
  destruct q as [|q'].
  rewrite mult_1_r in Hbhi.
  absurd (n < m).
  apply le_not_lt; assumption.
  assumption.
  apply le_n_S, le_0_n.
  apply div_works; assumption.
Qed.

(*

Extended GCD adapted from

egcd :: Natural -> Natural -> (Natural,(Natural,Natural))
egcd a 0 = (a,(1,0))
egcd a b =
    if c == 0
    then (b, (1, a `div` b - 1))
    else (g, (u, t + (a `div` b) * u))
  where
    c = a `mod` b
    (g,(s,t)) = egcd c (b `mod` c)
    u = s + (b `div` c) * t

obtained from

https://gilith.wordpress.com/2015/06/24/
natural-number-greatest-common-divisor/

*)

Fixpoint egcd_aux (a b x:nat) :=
  match a, b, x with
  | S _, 0, _ => Some (a, 1, 0)
  | S _, S _, S y =>
    match rem a b, div a b with
    | Some c, Some a_div_b =>
      match c with
      | 0 => Some (b, 1, a_div_b - 1)
      | _ =>
        match rem b c with
        | Some rem_b_c =>
          match egcd_aux c rem_b_c y with
          | Some (g, s, t) =>
            match div b c with
            | Some b_div_c =>
              let u := s + b_div_c * t in
              Some (g, u, t + a_div_b * u)
            | _ => None
            end
          | None => None
          end
        | None => None
        end
      end
      | _, _ => None
    end
  | _, _, _ => None
  end.

Definition egcd (n m:nat) :=
  egcd_aux n m (S(m + n)).

Lemma egcd_works:
  forall n m:nat,
  m <= n -> m <> 0 ->
  exists g, exists s, exists t,
  Some (g, s, t) = egcd n m /\
  rem n g = Some 0 /\
  rem m g = Some 0 /\
  s * n = t * m + g.
Proof.
  (* let's start by generalizing the auxiliary
     parameter *)
  cut (forall n m x:nat,
       m <= n -> m <> 0 -> n + m < x ->
       exists g, exists s, exists t,
       Some (g, s, t) = egcd_aux n m x /\
       rem n g = Some 0 /\
       rem m g = Some 0 /\
       s * n = t * m + g).
  intros Hgen n m m_le_n m_ne_0.
  unfold egcd.
  apply Hgen; auto.
  rewrite plus_comm.
  apply lt_n_Sn.

  (* starts the strong induction *)
  intros n.
  elim n using nat_strong_ind.

  (* eliminates the n = 0 case *)
  intros m x m_le_0 m_ne_0 _.
  absurd (m = 0).
  assumption.
  apply n_le_0; assumption.

  (* starts introducing the strong induction
     hypothesis *)
  clear n.
  intros n Hrec.
  intros m x m_le_n m_ne_0 n_p_m_lt_x.

  (* unfolding the definitions gives us a
     cluttered result *)
  (* let's isolate the right branch *)
  destruct n as [|n'].
  absurd (m = 0).
  assumption.
  apply n_le_0; assumption.
  simpl.
  destruct m as [|m'].
  absurd (0 = 0).
  assumption.
  reflexivity.
  simpl.
  destruct x as [|x'].
  absurd (S n' + S m' < 0).
  apply lt_n_O.
  assumption.
  simpl.
  cut (exists c, rem (S n') (S m') = Some c).
  intros [c EHc].
  rewrite EHc.
  cut (exists a_div_b,
       div (S n') (S m') = Some a_div_b).
  intros [a_div_b EHa_div_b].
  rewrite EHa_div_b.

  (* now we have two different cases, depending
     if c is 0 *)

  (* the c = 0 case is quite simple *)
  destruct c as [|c'].
  exists (S m'), 1, (a_div_b - 1).
  rewrite rem_unique
    with (q := a_div_b) (r := 0).
  rewrite rem_unique
    with (q := 1) (r := 0).
  split.
  reflexivity.
  split.
  reflexivity.
  split.
  reflexivity.
  rewrite mult_minus_distr_r.
  repeat rewrite mult_1_l.
  rewrite plus_comm, le_plus_minus_r.
  cut (exists q:nat,
       div (S n') (S m') = Some q /\
       exists r:nat,
       rem (S n') (S m') = Some r /\
       (S n') = (S m') * q + r).
  intros [q [EHq [r [EHr Hqr]]]].
  rewrite EHc in EHr.
  injection EHr.
  intros r_eq_0.
  rewrite <-r_eq_0 in Hqr.
  rewrite EHq in EHa_div_b.
  injection EHa_div_b.
  intros q_eq_a_div_b.
  rewrite plus_0_r, q_eq_a_div_b,
          mult_comm in Hqr.
  assumption.
  apply rem_works.
  assumption.
  rewrite <-mult_1_l at 1.
  apply mult_le_compat_r.
  cut (exists q,
       div (S n') (S m') = Some q /\
       1 <= q).
  intros [q [q_is_quot quot_ge_1]].
  rewrite EHa_div_b in q_is_quot.
  injection q_is_quot.
  intros q_is_a_div_b.
  rewrite q_is_a_div_b; assumption.
  apply div_ge.
  assumption.
  assumption.
  split.
  split.
  rewrite mult_1_r; apply le_n.
  rewrite mult_comm.
  unfold mult.
  rewrite plus_0_r, <-plus_0_l at 1.
  apply plus_lt_compat_r, lt_0_Sn.
  rewrite mult_1_r, <-minus_n_n; reflexivity.
  (* FIXME: ADMIT *)
  admit.

  (* we start the other case by asssuming the
     existence of some terms *)
  cut (exists rem_b_c,
       rem (S m') (S c') = Some rem_b_c).
  intros [rem_b_c EHrem_b_c].
  rewrite EHrem_b_c.
  cut (exists b_div_c,
       div (S m') (S c') = Some b_div_c).
  intros [b_div_c EHb_div_c].
  rewrite EHb_div_c.

  (* FIXME: INCLUDE THE PROOF IN THE UNFOLDING *)
  admit.
  admit.
  admit.
  admit.
  admit.
Qed.

Fixpoint sum_series
  (f:nat->option nat) (a n:nat) :=
  match n with
  | 0 => Some 0
  | S m =>
      match (f a), (sum_series f (S a) m) with
      | Some fa, Some s => Some (fa + s)
      | _, _ => None
      end
  end.

Theorem num_zeros_end_fact:
  forall n m p q:nat,
  fact n = p * (pow 10 m) /\
  ~exists q, fact n = q * (pow 10 (S m)) ->
  sum_series
    (fun i:nat => (div n (pow 5 i))) 1 n =
  Some m.


(**********************************************************************
    Permutation.v

    Definition and properties of permutations

    Definition: permutation

                                    Laurent.Thery@inria.fr (2006)
  **********************************************************************)
Require Export List.
Require Export ListAux.

Section permutation.

Variable A : Set.

(**************************************
   Definition of permutations as sequences of adjacent transpositions
 **************************************)

Inductive permutation : list A -> list A -> Prop :=
  | permutation_nil : permutation nil nil
  | permutation_skip :
      forall (a : A) (l1 l2 : list A),
      permutation l2 l1 -> permutation (a :: l2) (a :: l1)
  | permutation_swap :
      forall (a b : A) (l : list A), permutation (a :: b :: l) (b :: a :: l)
  | permutation_trans :
      forall l1 l2 l3 : list A,
      permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.

Hint Constructors permutation : core.

(**************************************
   Reflexivity
 **************************************)

Theorem permutation_refl l : permutation l l.
Proof.
induction l as [|a l1 H].
  apply permutation_nil.
apply permutation_skip with (1 := H).
Qed.

Hint Resolve permutation_refl : core.

(**************************************
   Symmetry
   **************************************)

Theorem permutation_sym l m : permutation l m -> permutation m l.
Proof.
intro H'; elim H'.
- apply permutation_nil.
- intros a l1' l2' H1 H2.
  apply permutation_skip with (1 := H2).
- intros a b l1'.
  apply permutation_swap.
- intros l1' l2' l3' H1 H2 H3 H4.
  apply permutation_trans with (1 := H4) (2 := H2).
Qed.

(**************************************
   Compatibility with list length
   **************************************)

Theorem permutation_length l m : permutation l m -> length l = length m.
Proof.
intros H'; elim H'; simpl in |- *; auto.
intros l1 l2 l3 H'0 H'1 H'2 H'3.
rewrite <- H'3; auto.
Qed.

(**************************************
   A permutation of the nil list is the nil list
   **************************************)

Theorem permutation_nil_inv l : permutation l nil -> l = nil.
Proof.
intros H; generalize (permutation_length _ _ H); case l; simpl in |- *;
 auto.
intros; discriminate.
Qed.

(**************************************
   A permutation of the singleton list is the singleton list
   **************************************)

Let permutation_one_inv_aux l1 l2 :
  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.
Proof.
intro H; elim H; clear H l1 l2; auto.
  intros a l3 l4 H0 H1 b H2.
  eq_tac.
    injection H2; auto.
  apply permutation_nil_inv; auto.
  injection H2; intros H3 H4; rewrite <- H3; auto.
  apply permutation_sym; auto.
intros; discriminate.
Qed.

Theorem permutation_one_inv a l : permutation (a :: nil) l -> l = a :: nil.
Proof.
intro H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.
Qed.

(**************************************
   Compatibility with the belonging
   **************************************)

Theorem permutation_in a l m : permutation l m -> In a l -> In a m.
Proof.
intro H; elim H; simpl in |- *; auto; intuition.
Qed.

(**************************************
   Compatibility with the append function
   **************************************)

Theorem permutation_app_comp l1 l2 l3 l4 :
 permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).
Proof.
intro H; revert l3 l4; elim H; clear H l1 l2;
 simpl in |- *; auto.
  intros a b l l3 l4 H.
  cut (permutation (l ++ l3) (l ++ l4)); auto.
    intros; apply permutation_trans with (a :: b :: l ++ l4); auto.
  elim l; simpl in |- *; auto.
intros l1 l2 l3 H H0 H1 H2 l4 l5 H3.
apply permutation_trans with (l2 ++ l4); auto.
Qed.

Hint Resolve permutation_app_comp : core.

(**************************************
   Swap two sublists
   **************************************)

Theorem permutation_app_swap  l1 l2 : permutation (l1 ++ l2) (l2 ++ l1).
Proof.
revert l2; elim l1; auto.
  intros; rewrite <- app_nil_end; auto.
intros a l H l2.
replace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).
  apply permutation_trans with (l ++ l2 ++ a :: nil); auto.
  apply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.
    simpl in |- *; auto.
  apply permutation_trans with (l ++ (a :: nil) ++ l2); auto.
    apply permutation_sym; auto.
  replace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).
    apply permutation_app_comp; auto.
    elim l2; simpl in |- *; auto.
    intros a0 l0 H0.
    apply permutation_trans with (a0 :: a :: l0); auto.
  apply (app_ass l2 (a :: nil) l).
apply (app_ass l2 (a :: nil) l).
Qed.

(**************************************
   A transposition is a permutation
   **************************************)

Theorem permutation_transposition a b l1 l2 l3 :
 permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).
Proof.
apply permutation_app_comp; auto.
change
  (permutation ((a :: nil) ++ l2 ++ (b :: nil) ++ l3)
     ((b :: nil) ++ l2 ++ (a :: nil) ++ l3)) in |- *.
repeat rewrite <- app_ass.
apply permutation_app_comp; auto.
apply permutation_trans with ((b :: nil) ++ (a :: nil) ++ l2); auto.
  apply permutation_app_swap; auto.
repeat rewrite app_ass.
apply permutation_app_comp; auto.
apply permutation_app_swap; auto.
Qed.

(**************************************
   An element of a list can be put on top of the list to get a permutation
   **************************************)

Theorem in_permutation_ex a l :
  In a l -> exists l1 : list A, permutation (a :: l1) l.
Proof.
elim l; simpl in |- *; auto.
intros H; case H; auto.
intros a0 l0 H [H0| H0].
exists l0; rewrite H0; auto.
case H; auto; intros l1 Hl1; exists (a0 :: l1).
apply permutation_trans with (a0 :: a :: l1); auto.
Qed.

(**************************************
   A permutation of a cons can be inverted
   **************************************)

Let permutation_cons_ex_aux a l1 l2 :
  permutation l1 l2 ->
  forall l11 l12 : list A,
  l1 = l11 ++ a :: l12 ->
  exists l3 : list A,
    (exists l4 : list A,
       l2 = l3 ++ a :: l4 /\ permutation (l11 ++ l12) (l3 ++ l4)).
intro H; elim H; clear H l1 l2.
- intros l11 l12; case l11; simpl in |- *; intros; discriminate.
- intros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.
    exists (nil (A:=A)); exists l1; simpl in |- *; split; auto.
      eq_tac; injection H1; auto.
    injection H1; intros H2 H3; rewrite <- H2; auto.
  intros a1 l111 H1.
  case (H0 l111 l12); auto.
    injection H1; auto.
  intros l3 (l4, (Hl1, Hl2)).
  exists (a0 :: l3); exists l4; split; simpl in |- *; auto.
    eq_tac; injection H1; auto.
  injection H1; intros H2 H3; rewrite H3; auto.
- intros a0 b l l11 l12; case l11; simpl in |- *.
    case l12; try (intros; discriminate).
    intros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.
      repeat eq_tac; injection H; auto.
    injection H; intros H1 H2 H3; rewrite H2; auto.
  intros a1 l111; case l111; simpl in |- *.
    intros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.
      repeat eq_tac; injection H; auto.
    injection H; intros H1 H2 H3; rewrite H3; auto.
  intros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;
  split; auto.
  repeat eq_tac; injection H; auto.
- intros l1 l2 l3 H H0 H1 H2 l11 l12 H3.
  case H0 with (1 := H3).
  intros l4 (l5, (Hl1, Hl2)).
  case H2 with (1 := Hl1).
  intros l6 (l7, (Hl3, Hl4)).
  exists l6; exists l7; split; auto.
  apply permutation_trans with (1 := Hl2); auto.
Qed.

Theorem permutation_cons_ex a l1 l2 :
 permutation (a :: l1) l2 ->
 exists l3 : list A,
   (exists l4 : list A, l2 = l3 ++ a :: l4 /\ permutation l1 (l3 ++ l4)).
Proof.
intro H.
apply (permutation_cons_ex_aux a (a :: l1) l2 H nil l1); simpl in |- *; auto.
Qed.

(**************************************
   A permutation can be simply inverted if the two list starts with a cons
   **************************************)

Theorem permutation_inv a l1 l2 :
 permutation (a :: l1) (a :: l2) -> permutation l1 l2.
Proof.
intro H; case permutation_cons_ex with (1 := H).
intros l3 (l4, (Hl1, Hl2)).
apply permutation_trans with (1 := Hl2).
generalize Hl1; case l3; simpl in |- *; auto.
  intros H1; injection H1; intros H2; rewrite H2; auto.
intros a0 l5 H1; injection H1; intros H2 H3; rewrite H2; rewrite H3; auto.
apply permutation_trans with (a0 :: l4 ++ l5); auto.
apply permutation_skip; apply permutation_app_swap.
apply (permutation_app_swap (a0 :: l4) l5).
Qed.

(**************************************
   Take a list and return tle list of all pairs of an element of the
   list and the remaining list
   **************************************)

Fixpoint split_one (l : list A) : list (A * list A) :=
  match l with
  | nil => nil (A:=A * list A)
  | a :: l1 =>
      (a, l1)
      :: map (fun p : A * list A => (fst p, a :: snd p)) (split_one l1)
  end.

(**************************************
   The pairs of the list are a permutation
   **************************************)

Theorem split_one_permutation a l1 l2 :
 In (a, l1) (split_one l2) -> permutation (a :: l1) l2.
Proof.
revert a l1; elim l2; clear l2; simpl in |- *; auto.
  intros a l1 H1; case H1.
intros a l H a0 l1 [H0| H0].
  injection H0; intros H1 H2; rewrite H2; rewrite H1; auto.
generalize H H0; elim (split_one l); simpl in |- *; auto.
  intros H1 H2; case H2.
intros a1 l0 H1 H2 [H3| H3]; auto.
injection H3; intros H4 H5; (rewrite <- H4; rewrite <- H5).
apply permutation_trans with (a :: fst a1 :: snd a1); auto.
apply permutation_skip.
apply H2; auto.
case a1; simpl in |- *; auto.
Qed.

(**************************************
   All elements of the list are there
   **************************************)

Theorem split_one_in_ex a l1 :
 In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).
Proof.
elim l1; simpl in |- *; auto.
  intros H; case H.
intros a0 l H [H0| H0]; auto.
  exists l; left; eq_tac; auto.
case H; auto.
intros x H1; exists (a0 :: x); right; auto.
apply
 (in_map (fun p : A * list A => (fst p, a0 :: snd p)) (split_one l) (a, x));
 auto.
Qed.

(**************************************
   An auxillary function to generate all permutations
   **************************************)

Fixpoint all_permutations_aux (l : list A) (n : nat) {struct n} :
 list (list A) :=
  match n with
  | O => nil :: nil
  | S n1 =>
      flat_map
        (fun p : A * list A =>
         map (cons (fst p)) (all_permutations_aux (snd p) n1)) (
        split_one l)
  end.

(**************************************
   Generate all the permutations
   **************************************)

Definition all_permutations (l : list A) := all_permutations_aux l (length l).

(**************************************
   All the elements of the list are permutations
   **************************************)

Let all_permutations_aux_permutation n l1 l2 :
  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.
Proof.
revert l1 l2; elim n; simpl in |- *; auto.
  intros l1 l2; case l2.
    simpl in |- *; intros H0 [H1| H1].
      rewrite <- H1; auto.
    case H1.
  simpl in |- *; intros; discriminate.
intros n0 H l1 l2 H0 H1.
case in_flat_map_ex with (1 := H1).
clear H1; intros x; case x; clear x; intros a1 l3 (H1, H2).
case in_map_inv with (1 := H2).
simpl in |- *; intros y (H3, H4).
rewrite H4; auto.
apply permutation_trans with (a1 :: l3); auto.
  apply permutation_skip; auto.
  apply H with (2 := H3).
  apply eq_add_S.
  apply trans_equal with (1 := H0).
  change (length l2 = length (a1 :: l3)) in |- *.
  apply permutation_length; auto.
  apply permutation_sym; apply split_one_permutation; auto.
apply split_one_permutation; auto.
Qed.

Theorem all_permutations_permutation l1 l2 :
  In l1 (all_permutations l2) -> permutation l1 l2.
Proof.
intro H; apply all_permutations_aux_permutation with (n := length l2);
 auto.
Qed.

(**************************************
   A permutation is in the list
   **************************************)

Let permutation_all_permutations_aux n l1 l2 :
  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).
Proof.
revert l1 l2; elim n; simpl in |- *; auto.
  intros l1 l2; case l2.
    intros H H0; rewrite permutation_nil_inv with (1 := H0); auto.
  simpl in |- *; intros; discriminate.
  intros n0 H l1; case l1.
  intros l2 H0 H1;
  rewrite permutation_nil_inv with (1 := permutation_sym _ _ H1) in H0;
  discriminate.
clear l1; intros a1 l1 l2 H1 H2.
case (split_one_in_ex a1 l2); auto.
  apply permutation_in with (1 := H2); auto with datatypes.
intros x H0.
apply in_flat_map with (b := (a1, x)); auto.
apply in_map; simpl in |- *.
apply H; auto.
  apply eq_add_S.
  apply trans_equal with (1 := H1).
  change (length l2 = length (a1 :: x)) in |- *.
  apply permutation_length; auto.
  apply permutation_sym; apply split_one_permutation; auto.
apply permutation_inv with (a := a1).
apply permutation_trans with (1 := H2).
apply permutation_sym; apply split_one_permutation; auto.
Qed.

Theorem permutation_all_permutations l1 l2 :
  permutation l1 l2 -> In l1 (all_permutations l2).
Proof.
intro H; unfold all_permutations in |- *;
 apply permutation_all_permutations_aux; auto.
Qed.

(**************************************
   Permutation is decidable
   **************************************)

Definition permutation_dec :
  (forall a b : A, {a = b} + {a <> b}) ->
  forall l1 l2, {permutation l1 l2} + {~ permutation l1 l2}.
Proof.
intros H l1 l2.
case (In_dec (list_eq_dec H) l1 (all_permutations l2)).
  intros i; left; apply all_permutations_permutation; auto.
intros i; right; contradict i; apply permutation_all_permutations; auto.
Defined.

(* A more efficient version *)
Definition permutation_dec1 :
  (forall a b : A, {a = b} + {a <> b}) ->
  forall l1 l2, {permutation l1 l2} + {~ permutation l1 l2}.
Proof.
intros dec; fix permutation_dec1 1; intros l1; case l1.
  intros l2; case l2.
    left; auto.
  intros a l3; right; intros H; generalize (permutation_length _ _ H);
  discriminate.
intros a l3 l2.
case (In_dec1 dec a l2); intros H1.
  case H1.
  intros x; case x; simpl.
  intros l4 l5 Hl4l5.
  case (permutation_dec1 l3 (l4 ++ l5)); intros H2.
    left; subst.
    apply permutation_trans with ((a::l5) ++ l4); auto.
      simpl; apply permutation_skip; auto.
      apply permutation_trans with (1 := H2); auto.
      apply permutation_app_swap.
    apply permutation_app_swap.
  right; contradict H2.
  apply permutation_inv with a.
  apply permutation_trans with (1 := H2).
  rewrite Hl4l5.
  apply permutation_trans with ((a::l5) ++ l4); auto.
    apply permutation_app_swap.
  simpl; apply permutation_skip; auto.
  apply permutation_app_swap.
right; contradict H1.
apply permutation_in with (1 := H1); auto with datatypes.
Defined.

End permutation.

(**************************************
   Hints
   **************************************)

Hint Constructors permutation : core.
Hint Resolve permutation_refl : core.
Hint Resolve permutation_app_comp : core.
Hint Resolve permutation_app_swap : core.

(**************************************
   Implicits
   **************************************)

Arguments permutation [A].
Arguments split_one [A].
Arguments all_permutations [A].
Arguments permutation_dec [A].
Arguments permutation_dec1 [A].

(**************************************
   Permutation is compatible with map
   **************************************)

Theorem permutation_map  (A B : Set) (f : A -> B) l1 l2 :
 permutation l1 l2 -> permutation (map f l1) (map f l2).
Proof.
intro H; elim H; simpl in |- *; auto.
intros l0 l3 l4 H0 H1 H2 H3; apply permutation_trans with (2 := H3); auto.
Qed.
Hint Resolve permutation_map : core.

(**************************************
  Permutation  of a map can be inverted
  *************************************)

Local Definition permutation_map_ex_aux (A B : Set) (f : A -> B) l1 l2 l3 :
  permutation l1 l2 ->
  l1 = map f l3 -> exists l4, permutation l4 l3 /\ l2 = map f l4.
Proof.
intro H; generalize l3; elim H; clear H l1 l2 l3.
- intros l3; case l3; simpl in |- *; auto.
    intros H; exists (nil (A := A)); auto.
  intros; discriminate.
- intros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.
    intros; discriminate.
  intros a1 l H1; case (H0 l); auto.
    injection H1; auto.
  intros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.
  eq_tac; auto; injection H1; auto.
- intros a0 b l l3; case l3.
  intros; discriminate.
  intros a1 l0; case l0; simpl in |- *.
    intros; discriminate.
  intros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.
  repeat eq_tac; injection H; auto.
- intros l1 l2 l3 H H0 H1 H2 l0 H3.
  case H0 with (1 := H3); auto.
  intros l4 (HH1, HH2).
  case H2 with (1 := HH2); auto.
  intros l5 (HH3, HH4); exists l5; split; auto.
  apply permutation_trans with (1 := HH3); auto.
Qed.

Theorem permutation_map_ex (A B : Set) (f : A -> B) l1 l2 :
 permutation (map f l1) l2 ->
 exists l3, permutation l3 l1 /\ l2 = map f l3.
Proof.
intro H; apply permutation_map_ex_aux with (l1 := map f l1);
 auto.
Qed.

(**************************************
   Permutation is compatible with flat_map
 **************************************)

Theorem permutation_flat_map (A B : Set) (f : A -> list B) l1 l2 :
 permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).
Proof.
intro H; elim H; simpl in |- *; auto.
  intros a b l; auto.
  repeat rewrite <- app_ass.
  apply permutation_app_comp; auto.
intros k3 l4 l5 H0 H1 H2 H3; apply permutation_trans with (1 := H1); auto.
Qed.


(*******************************************************)
(* Theorem: there exist infinitely many prime numbers. *)
(*******************************************************)
(* Euclid's proof *)
(******************)
(* Coq file largely inspired by a proof given by Frédéric Blanqui in a blog discussion *)
(***************************************************************************************)

Require Import Arith Omega.

(**********************************************)
(* Two lemmas about multiplication and order. *)
(**********************************************)

Lemma mult_gt_0 : forall x y : nat, x * y > 0 <-> x > 0 /\ y > 0.
Proof.
  intros x y. destruct x. omega. destruct y. omega.
  split. omega. intros _. simpl. apply gt_Sn_O.
Qed.

Lemma mult_le_r : forall x y : nat, y > 0 -> x <= x * y.
Proof.
  intros x y H. rewrite <- (mult_1_r x) at 1. apply mult_le_compat_l. exact H.
Qed.

(*****************)
(* Divisibility. *)
(*****************)

Definition div (x y : nat) := exists z : nat, y = x * z.

Notation "x & y" := (div x y) (at level 70).

(* Four lemmas about divisibility. *)

Lemma div_le : forall x y : nat, y > 0 -> x & y -> x <= y.
Proof.
  intros x y. intros Hy [z Hdiv].
  subst. apply mult_le_r. rewrite mult_gt_0 in Hy. tauto.
Qed.

Lemma div_mult_l : forall x y z : nat, x & y -> x & z * y.
Proof.
  intros x y z [z' Hdiv]. subst. exists (z * z'). ring.
Qed.

Lemma div_minus : forall x y z : nat, x & y -> x & z -> x & y - z.
Proof.
  intros x y z [z1 Hdiv_xy] [z2 Hdiv_xz]. subst. exists (z1 - z2).
  rewrite <- mult_minus_distr_l. reflexivity.
Qed.

Lemma div_trans : forall x y z : nat, x & y -> y & z -> x & z.
Proof.
  intros x y z [z1 Hdiv_xy] [z2 Hdiv_yz]. exists (z1 * z2). subst. ring.
Qed.

(*****************************************)
(* Product of a list of natural numbers. *)
(*****************************************)

Require Import List.

Fixpoint prod (l : list nat) : nat :=
  match l with
    | nil => 1
    | x::l' => x * prod l'
  end.

(* Three lemmas about product and order. *)

Lemma prod_gt_0 : forall l : list nat, ~In 0 l <-> prod l > 0.
Proof.
  induction l; simpl. omega. rewrite mult_gt_0. intuition.
Qed.

Lemma prod_div : forall l : list nat, forall x : nat, In x l -> x & prod l.
Proof.
  intros l x. induction l; simpl. tauto.
  intros [Ha|Hx]. subst. exists (prod l). reflexivity.
  destruct (IHl Hx) as [z Hdiv]. rewrite Hdiv. exists (a * z). ring.
Qed.

Corollary prod_le_x : forall l : list nat, forall x : nat, ~In 0 l -> In x l -> x <= prod l.
Proof.
  intros l x H0 Hx.
  apply prod_gt_0 in H0.
  exact (div_le x (prod l) H0 (prod_div l x Hx)).
Qed.

(******************)
(* Prime numbers. *)
(******************)

Definition prime (p : nat) := p >= 2 /\ (forall x : nat, x & p -> x = 1 \/ x = p).

Lemma zero_is_not_prime : ~prime 0.
Proof.
  unfold prime. omega.
Qed.

(* We use classical reasoning to simplify the proof a little bit. *)
Require Import Classical.

Lemma nontrivial_divisor : forall x : nat, x >= 2 -> ~prime x -> exists y, y >= 2 /\ y < x /\ y & x.
Proof.
  intros x x_le_2 x_is_not_prime.
  apply not_and_or in x_is_not_prime. intuition. apply not_all_ex_not in H.
  destruct H as [d Hd]. apply imply_to_and in Hd. destruct Hd as [H1 H2].
  apply not_or_and in H2.
  assert (p_lt_x : d < x). apply div_le in H1. omega. omega.
  assert (p_ge_2 : d >= 2). destruct H2 as [Hd_not_1 Hd_not_x].
  destruct (eq_nat_dec d 0). subst. destruct H1. omega. omega. clear H2.
  exists d. tauto.
Qed.

Lemma prime_divisor : forall x : nat, x >= 2 -> exists p, prime p /\ p & x.
Proof.
  intro x. pattern x. apply lt_wf_ind. clear x. intros n H n_le_2.
  (* Law of excluded middle: x is prime or x is not prime. *)
  destruct (classic (prime n)) as [n_is_prime | n_is_not_prime].
  (* n is prime *)
  exists n. split ; [assumption | exists 1 ; ring].
  (* n is not prime *)
  set (divisor := nontrivial_divisor n n_le_2 n_is_not_prime).
  destruct divisor as [d Hdiv]. destruct Hdiv as [d_le_2 [d_lt_n Hdn]].
  destruct (H d d_lt_n d_le_2) as [p Hyp].
  exists p. split. tauto. apply div_trans with (x := p) (y := d) (z := n) ; tauto.
Qed.

Theorem primes_are_infinite : ~ (exists l : list nat, forall x : nat, prime x <-> In x l).
Proof.
  intros [l all_primes_in_l]. set (n := S (prod l)).
  (* We prove that n is prime. *)
    assert (n_is_prime : prime n). split.
    (* n >= 2 *)
    apply le_n_S. apply lt_le_S. apply prod_gt_0.
    rewrite <- all_primes_in_l. apply zero_is_not_prime.
    (* We now prove that assuming that there is a divider a of n that is
    different from 1 and n leads to a contradiction. *)
    intros a a_div_n. destruct (eq_nat_dec a 1). tauto.
    right. destruct (eq_nat_dec a n). assumption. apply False_rec.
    (* We prove that a is >= 2. *)
    assert (a_ge_2 : a >= 2). destruct a_div_n as [q hn].
    destruct (eq_nat_dec a 0). subst. rewrite mult_0_l in hn. omega. omega.
    (* Hence, a has a prime divider p. *)
    destruct (prime_divisor a a_ge_2) as [p [p1 p2]].
    (* By transitivity, p divides n. *)
    generalize (div_trans p a n p2 a_div_n) ; intro p_div_n.
    (* Since all primes are in l, p is in l and p divides prod l. *)
    assert (p_in_l : In p l). rewrite <- all_primes_in_l. assumption.
    apply (prod_div l p) in p_in_l.
    (* Thus p divides n - (prod l) = 1. *)
    generalize (div_minus p n (prod l) p_div_n p_in_l).
    unfold n. rewrite <- minus_Sn_m, minus_diag. 2: reflexivity.
    (* Therefore p = 1 but 1 is not prime. Hence, n is prime. *)
    intro p_div_1. apply div_le in p_div_1. 2: omega. unfold prime in p1. omega.
  (* We now prove that n is not in l. *)
  rewrite all_primes_in_l in n_is_prime.
  assert (zero_not_in_l : ~In 0 l).
  rewrite <- all_primes_in_l. exact zero_is_not_prime.
  generalize (prod_le_x l n zero_not_in_l n_is_prime).
  unfold n. omega.
Qed.


Load MyLists.

Require Import PeanoNat.

Fixpoint beq_natlist (l1 l2 : natlist) : bool :=
  match l1 with
  | []       => match l2 with
          | [] => true
          | _  => false
          end
  | cons x l1' => match l2 with
          | []         => false
          | cons y l2' => match (Nat.eqb x y) with
                          | true  => beq_natlist l1' l2'
                          | false => false
                          end
          end
  end.

Example test_beq_natlist1 : (beq_natlist nil nil = true).
Proof.
  simpl.
  reflexivity.
Qed.

Example test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.
Proof.
  simpl.
  reflexivity.
Qed.

Example test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.
Proof.
  simpl.
  reflexivity.
Qed.

(*
Axiom woot : forall n, Nat.eqb n n = true.
Search (Nat.eqb _ _). (* We find Nat.eqb_refl *)
*)

Theorem beq_natlist_refl : forall l:natlist, true = beq_natlist l l.
Proof.
  intros l.
  induction l.
  - (* base *) simpl. reflexivity.
  - (* i.h. *) simpl. (* use simpl to rewrite from definition of beq_natlist *)
               rewrite Nat.eqb_refl. exact IHl.
Qed.