(** * Logic: Logic in Coq *)

Set Warnings "-notation-overridden,-parsing".
Require Export Tactics.

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

(** 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 n m H. split.
  destruct n as [|n'] eqn:H1.
  { reflexivity. } { simpl in H. inversion H. }
  destruct m as [|m'].
  { reflexivity. } { simpl in H. 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.
  (* WORKED IN CLASS *)
  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.
  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.
  (* WORKED IN CLASS *)
  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_
    intro 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.
  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 n m H. destruct n as [|n'].
  - left. reflexivity.
  - destruct m as [|m'].
    + right. reflexivity.
    + left. simpl in H. inversion H.
Qed.
(** [] *)

(** **** Exercise: 1 star (or_commut)  *)
Theorem or_commut : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros P Q [HP | HQ].
  - right. apply HP.
  - left. apply HQ.
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
    particular 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 P Hn Q HP. destruct Hn. apply HP.
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.
  (* WORKED IN CLASS *)
  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 *)
(** [] *)

(** **** Exercise: 2 stars, recommended (contrapositive)  *)
Theorem contrapositive : forall (P Q : Prop),
  (P -> Q) -> (~Q -> ~P).
Proof.
  intros P Q H1 H2. unfold not. unfold not in H2. intros HP.
  apply H2. apply H1. 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 [HP HNP].
  apply HNP. apply HP.
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 *)
(** [] *)

(** 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 P. split.
  - intros HP. apply HP.
  - intros HP. apply HP.
Qed.

Theorem iff_trans : forall P Q R : Prop,
  (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros P Q R [HPQ HQP] [HQR HRQ]. split.
  - intros HP. apply HQR. apply HPQ. apply HP.
  - intros HR. apply HQP. apply HRQ. apply HR.
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 P Q R. split.
  - intros [HP|[HQ HR]].
    + split. { left. apply HP. } { left. apply HP. }
    + split. { right. apply HQ. } { right. apply HR. }
  - intros [[HP|HQ] [HP'|HR]].
    + left. apply HP. + left. apply HP.
    + left. apply HP'. + 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 special Coq library that allows rewriting with other
    formulas besides equality: *)

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).
  apply Hm.  Qed.

(** **** Exercise: 1 star (dist_not_exists)  *)
(** Prove that "[P] holds for all [x]" implies "there is no [x] for
    which [P] does not hold." *)

Theorem dist_not_exists : forall (X:Type) (P : X -> Prop),
  (forall x, P x) -> ~ (exists x, ~ P x).
Proof.
  intros X P H. unfold not. intros [x H2].
  apply H2. 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 X P Q. split.
  - intros [x [HPx|HQx]].
    { left. exists x. apply HPx. }
    { right. exists x. apply HQx. }
  - intros [[x HPx]|[x HQx]].
    { exists x. left. apply HPx. }
    { exists x. right. apply HQx. }
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 from taking an element and a list and returning a
    proposition: *)

Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
  | [] => False
  | 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.
  (* WORKED IN CLASS *)
  simpl.
  intros n [H | [H | []]].
  - exists 1. rewrite <- H. reflexivity.
  - exists 2. rewrite <- H. reflexivity.
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.
  intros A B f l y. split.
  - induction l as [|h t IHl].
    { simpl. intros []. }
    { intros [H1|H1].
      - exists h. split.
        + apply H1.
        + left. reflexivity.
      - apply IHl in H1. inversion H1. inversion H.
        exists x. split.
        + apply H0. + simpl. right. apply H2.
    }
  - induction l as [|h t IHl].
    { simpl. intros [x [_ []]]. }
    { intros [x [H1 H2]]. simpl in H2.
      inversion H2.
      - simpl. left. rewrite H. apply H1.
      - simpl. right. apply IHl. exists x.
        + split. apply H1. apply H.
    }
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.
  intros A l l' a. split.
  - (* In a (l++l') -> In a l \/ In a l' *)
    intros H. induction l as [|h t IHl].
    + simpl in H. right. apply H.
    + simpl in H. inversion H.
      { rewrite H0. simpl. left. left. reflexivity. }
      { apply IHl in H0. inversion H0.
        { simpl. left. right. apply H1. }
        { right. apply H1. }
      }
  - (* In a l \/ In a l' -> In a (l++l') *)
    intros [Hel|Hel'].
    { induction l as [|h t IHl].
      - simpl. simpl in Hel. exfalso. apply Hel.
      - simpl. simpl in Hel. inversion Hel as [H1|H2].
        + left. apply H1.
        + right. apply IHl. apply H2.
    }
    { induction l as [|h t IHl].
      - simpl. apply Hel'.
      - simpl. right. apply IHl.
    }
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 :=
  match l with
  | nil => True
  | h :: t => P h /\ All P t
  end.

Lemma All_In :
  forall T (P : T -> Prop) (l : list T),
    (forall x, In x l -> P x) <->
    All P l.
Proof.
  intros T P l. split.
  - (* _ -> All P l *)
    induction l as [|h t IHl].
    + simpl. intros _. apply I.
    + simpl. intros H. split.
      { apply H. left. reflexivity. }
      { apply IHl. intros x H1.
        apply H. right. apply H1. }
  - (* All P l -> _ *)
    induction l as [|h t IHl].
    + simpl. intros _ x [].
    + simpl. intros [H1 H2] x. intros [H3|H3].
      { rewrite <- H3. apply H1. }
      { apply IHl. apply H2. apply H3. }
Qed.
(** [] *)

(** **** 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 :=
  fun n =>
    match oddb n with
    | true => Podd n
    | false => Peven n
    end.

(** 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.
  intros Podd Peven n Ht Hf. unfold combine_odd_even.
  destruct (oddb n).
  - apply Ht. reflexivity.
  - apply Hf. reflexivity.
Qed.

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.
  intros Podd Peven n H1 H2. unfold combine_odd_even in H1.
  destruct (oddb n).
  - apply H1.
  - inversion H2.
Qed.

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.
  intros Podd Peven n H1 H2. unfold combine_odd_even in H1.
  destruct (oddb n).
  - inversion H2. - apply H1.
Qed.
(** [] *)

(* ################################################################# *)
(** * 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 n m p, n + (m + p) = (p + m) + n.

(** 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 n m p.
  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 n m p, n + (m + p) = (p + m) + n.
Proof.
  intros n m p.
  rewrite plus_comm.
  assert (H : m + p = p + m).
  { 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 n m p, n + (m + p) = (p + m) + n.
Proof.
  intros n m p.
  rewrite plus_comm.
  rewrite (plus_comm m).
  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.

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

Lemma tr_rev_helper : forall X (l1 l2 : list X),
  rev_append l1 l2 = rev l1 ++ l2.
Proof.
  intros X l1. induction l1 as [|h1 t1 IHl1].
  - reflexivity.
  - simpl. intros l2. rewrite <- app_assoc. apply IHl1.
Qed.

(** 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.
Proof.
  intros X. apply functional_extensionality.
  induction x as [|h t IHl].
  - reflexivity.
  - simpl. rewrite <- IHl. unfold tr_rev.
    rewrite tr_rev_helper. simpl. rewrite <- IHl.
    rewrite app_nil_r. reflexivity.
Qed.
(** [] *)

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

    We often say that the boolean [evenb n] _reflects_ the proposition
    [exists k, n = double k].  *)

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.
  induction n as [|n' Hn].
  - exists 0. reflexivity.
  - rewrite evenb_S. destruct Hn as [x Hx].
    destruct (evenb n').
    + exists x. rewrite Hx. reflexivity.
    + exists (S x). rewrite Hx. reflexivity.
Qed.
(** [] *)

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.

(** 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].  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.
  destruct b1.
  + destruct b2.
    { simpl. split.
      + intros _. split. reflexivity. reflexivity.
      + intros _. reflexivity.
    }
    { simpl. split.
      + intros H. inversion H.
      + intros [_ H]. inversion H.
    }
  + destruct b2.
    { simpl. split.
      + intros H. inversion H.
      + intros [H _]. inversion H.
    }
    { simpl. split.
      + intros H. inversion H.
      + intros [H _]. inversion H.
    }
Qed.

Lemma orb_true_iff : forall b1 b2,
  b1 || b2 = true <-> b1 = true \/ b2 = true.
Proof.
  destruct b1.
  + destruct b2.
    { simpl. split.
      + intros _. left. reflexivity.
      + intros _. reflexivity.
    }
    { simpl. split.
      + intros _. left. reflexivity.
      + intros _. reflexivity.
    }
  + destruct b2.
    { simpl. split.
      + intros _. right. reflexivity.
      + intros _. reflexivity.
    }
    { simpl. split.
      + intros H. inversion H.
      + intros [H|H].
        - inversion H. - inversion H.
    }
Qed.
(** [] *)

(** **** 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.
  split.
  { destruct x.
    - destruct y.
      { simpl. intros H. inversion H. }
      { simpl. intros _ H. inversion H. }
    - destruct y.
      { simpl. intros _ H. inversion H. }
      { simpl. intros H1 H2. inversion H2.
        rewrite H0 in H1. rewrite <- beq_nat_refl in H1.
        inversion H1. }
  }
  { intros H. destruct x.
    + destruct y.
      { destruct H. reflexivity. }
      { simpl. reflexivity. }
    + destruct y.
      { reflexivity. }
      { simpl. destruct (beq_nat x y) eqn:He.
        - rewrite beq_nat_true_iff in He.
          rewrite He in H. destruct H. reflexivity.
        - reflexivity.
      }
  }
Qed.
(** [] *)

(** **** 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 :=
  match l1,l2 with
  | nil, nil => true
  | h1 :: t1, h2 :: t2 => beq h1 h2 && beq_list beq t1 t2
  | _, _ => false
  end.

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.
  intros A beq H. intros l1 l2. generalize dependent l2.
  induction l1 as [|h1 t1].
  - destruct l2 as [|h2 t2].
    + split. reflexivity. reflexivity.
    + simpl. split. { intros H1. inversion H1. } { intros H1. inversion H1. }
  - destruct l2 as [|h2 t2].
    + simpl. split. { intros H1. inversion H1. } { intros H1. inversion H1. }
    + simpl. destruct (beq h1 h2) eqn:He.
      { simpl. rewrite IHt1. rewrite H in He.
        split.
        { intros He2. rewrite He, He2. reflexivity. }
        { intros H1. inversion H1. reflexivity. }
      }
      { simpl. split.
        { intros H1. inversion H1. }
        { intros H1. inversion H1. rewrite <- H in H2. rewrite H2 in He.
          inversion He. }
      }
Qed.
(** [] *)

(** **** 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.
  intros X test l.
  induction l as [|h t IHl].
  - simpl. split.
    { intros _. apply I. } { reflexivity. }
  - simpl. split.
    { intros H. rewrite andb_true_iff in H.
      destruct H as [H1 H2]. split.
      { apply H1. } { rewrite IHl in H2. apply H2. }
    }
    { intros [H1 H2]. rewrite <- IHl in H2.
      rewrite H1, H2. reflexivity.
    }
Qed.

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

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

(** **** 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.
  intros Hem X P H x. assert (H1 : P x \/ ~(P x)). { apply Hem. }
  destruct H1 as [H2|H2].
  - apply H2.
  - destruct H. exists x. intros H3. apply H2. apply H3.
Qed.
(** [] *)

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

Theorem excluded_middle_implies_peirce :
  excluded_middle -> peirce.
Proof.
  intros Hem. intros P.
  assert (H : P \/ ~P). { apply Hem. }
  intros Q. destruct H as [H1|H1].
  { intros _. apply H1. }
  { intros H2. apply H2. intros H3. exfalso. apply H1. apply H3. }
Qed.

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

(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)


Set Warnings "-notation-overridden,-parsing".
From LF Require Export Tactics.

Check forall n m: nat, n+m=m+n.

Check forall n: nat, n=2.

Check 3=4.

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

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

Example and_exercise:
  forall n m: nat, n+m=0 -> n=0 /\ m=0.
Proof.
  intros.
  destruct n.
  - destruct m.
    split. reflexivity. reflexivity.
    split. reflexivity. discriminate.
  - destruct m.
    split. discriminate. reflexivity.
    split. discriminate. discriminate.
Qed.

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

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.

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

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

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.

Theorem and_assoc : forall P Q R: Prop,
    P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R [HP HQR].
  split.
  - split. apply HP.
    apply proj1 in HQR.
    apply HQR.
  - apply proj2 in HQR.
    apply HQR.
Qed.

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.

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

Lemma or_intro2: forall A B: Prop, B -> A \/ B.
Proof.
  intros. right. apply H. Qed.

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

Module MyNot.
Definition not (P:Prop) := P -> False.
Notation "~ x" := (not x) : type_scope.
Check not.
(* ===> Prop -> Prop *)
End MyNot.

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

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

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

Theorem zero_not_one : 0 <> 1.
Proof.
  unfold not.
  intros constra.
  discriminate.
Qed.

Theorem not_false :
  not False.
Proof.
  unfold not.
  intros. destruct H. Qed.

Theorem contradiction_implies_anything : forall P Q : Prop,
  (P /\ not 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.
  (* WORKED IN CLASS *)
  intros P H. unfold not. intros G. apply G. apply H. Qed.

Theorem contrapositive : forall (P Q: Prop),
    (P -> Q) -> (not Q -> not P).
Proof.
  unfold not.
  intros.
  apply H0. apply H. apply H1.
Qed.

Theorem not_both_true_and_false: forall P: Prop, ~(P /\ not P).
Proof.
  unfold not.
  intros P [Left Right].
  apply Right. apply Left.
Qed.

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.

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

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.
  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'. discriminate H'.
Qed.

Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  (* FILL IN HERE *) Admitted.

From Coq Require Import Setoids.Setoid.

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

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).
  apply Hm. Qed.

Theorem dist_not_exists : forall (X: Type)(P:X -> Prop),
    (forall x, P x) -> not(exists x, ~ P x).
Proof.
  unfold not.
  intros.
  destruct H0 as [x E].
  apply E. apply H. Qed.

(* the exists of an element in a list *)
Fixpoint In {A: Type} (x: A) (l: list A): Prop :=
  match l with
  | [] => False
  | x' :: l' => x'=x \/ In x l'
  end.

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.
  (* WORKED IN CLASS *)
  simpl.
  intros n [H | [H | []]].
  - exists 1. rewrite <- H. reflexivity.
  - exists 2. rewrite <- H. reflexivity.
Qed.

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.

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.
  intros. split.
  - induction l.
    + simpl. intros. destruct H.
    + simpl. intros.
      destruct H as [ HFX | HIN].
      exists x. split.
      (* left f x = y case*)
      * apply HFX.
      * apply or_intro. reflexivity.
      (* right (In y map f l)*)
      * apply  IHl in HIN.
        destruct HIN. exists x0.
        split.
        apply proj1 in H. apply H. destruct H.
        right. apply H0.
  - intros. destruct H. destruct H as [ HFX HIN].
    rewrite <- HFX. apply In_map. apply HIN.
Qed.

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.

Lemma in_not_nil :
  forall A (x : A) (l : list A), In x l -> l <> [].
Proof.
  intros A x l H. unfold not. intro Hl. destruct l.
  - simpl in H. destruct H.
  - discriminate Hl.
Qed.

Lemma in_not_nil_42_take2 :
  forall l : list nat, In 42 l -> l <> [].
Proof.
  intros l H.
  apply in_not_nil with (x := 42).
  apply H.
Qed.

(* apply ... in ... *)
Lemma in_not_nil_42_take3 :
  forall l : list nat, In 42 l -> l <> [].
Proof.
  intros l H.
  apply in_not_nil in H.
  apply H.
Qed.

(* Explicitly apply the lemma to the value for x. *)
Lemma in_not_nil_42_take4 :
  forall l : list nat, In 42 l -> l <> [].
Proof.
  intros l H.
  apply (in_not_nil nat 42).
  apply H.
Qed.

(* Explicitly apply the lemma to a hypothesis. *)
Lemma in_not_nil_42_take5 :
  forall l : list nat, In 42 l -> l <> [].
Proof.
  intros l H.
  apply (in_not_nil _ _ _ H).
Qed.

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

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 [].

Print rev.

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

Theorem evenb_double : forall k, evenb (double k) = true.
Proof.
  intros k. induction k as [|k' IHk'].
  - reflexivity.
  - simpl. apply IHk'.
Qed.

Theorem eqb_eq : forall n1 n2 : nat,
  n1 =? n2 = true <-> n1 = n2.
Proof.
  Admitted.

Print eqb_eq.

Lemma plus_eqb_example : forall n m p : nat,
    n =? m = true -> n + p =? m + p = true.
Proof.
  (* WORKED IN CLASS *)
Admitted.

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

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


Require Import Coq.NArith.NArith.

Local Open Scope N_scope.

Definition Nlt_dec: forall (l r : N), {l < r} + {l >= r}.
  refine (fun l r =>
    match Ncompare l r as k return Ncompare l r = k -> _ with
      | Lt => fun pf => left _ _
      | _ => fun pf => right _ _
    end (refl_equal _));
  abstract congruence.
Defined.


(* This file contains some important results on lists of elements from an ordered type.
   Following are some important notions formalized in this file----------------------

 IsOrd l           <==> l is an strictly increasing list
 isOrd l           ==> boolean function to check if the list is strictly increasing

 Some of the useful results in this file are:

 Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.
 Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).

 Lemma head_equal (a b: A)(l s: list A):
            IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a=b.
 Lemma tail_equal (a b: A)(l s:list A):
            IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.
 Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.
 Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|.
                                                                             ------- *)

Require Export Lists.List.
Require Export GenReflect SetSpecs OrdType.

Set Implicit Arguments.

Section OrderedLists.
  Context {A: ordType}.
  (* Variable A: ordType.  *)

  Lemma decA (x y:A): {x=y}+{x<>y}.
  Proof. eapply reflect_dec with (b:= eqb x y). apply eqP. Qed.

  Lemma EM_A (x y: A): x=y \/ x<>y.
  Proof. eapply reflect_EM with (b:= eqb x y). apply eqP. Qed.

  (* ------------IsOrd Predicate  -----------------------------------------------  *)
  Inductive IsOrd :list A -> Prop:=
  |  IsOrd_nil: IsOrd nil
  | IsOrd_singl: forall x:A, IsOrd (x::nil)
  | IsOrd_cons: forall (x y: A)(l: list A), (ltb x y)-> IsOrd (y::l) -> IsOrd (x::y::l).

  Lemma IsOrd_elim (l: list A)(x y: A): IsOrd (x::y::l)-> IsOrd (y::l).
  Proof. intro H;inversion H; auto. Qed.
  Lemma IsOrd_elim1 (l: list A)(x y: A): IsOrd (x::y::l)-> (ltb x y).
  Proof. intro H;inversion H; auto. Qed.
  Lemma IsOrd_elim0 (l:list A)(x:A): IsOrd (x::l)-> IsOrd(l).
  Proof. case l. constructor. intros s l0. apply IsOrd_elim. Qed.

  Lemma IsOrd_intro (a:A)(l: list A): IsOrd l-> (forall x, In x l -> ltb a x)-> IsOrd (a::l).
  Proof. intros H H1. case l eqn:H2. constructor. constructor.
         apply H1. all: auto. Qed.

  Hint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.

  Lemma IsOrd_elim2(l:list A): forall a:A, IsOrd (a::l)-> (forall x:A, In x l-> ltb a x).
  Proof. { induction l.
         { intros a H x H0. inversion H0.  }
         { intros a0 H x H0.
           assert (H1: x=a \/ In x l); auto.
           destruct H1 as [H1 | H1]. rewrite H1. eapply IsOrd_elim1; exact H.
           assert (H2: a <b x). apply IHl; eauto.
           assert (H3 : a0 <b a). eapply IsOrd_elim1;exact H. eauto.   } } Qed.

   Lemma IsOrd_elim2a(l:list A)(a x:A): IsOrd (a::l)-> In x l -> ltb a x.
  Proof. { intros H H1. eapply (@IsOrd_elim2 l a) in H. exact H. auto. } Qed.

  Lemma IsOrd_elim3 (x a: A)(l: list A): IsOrd (a::l)-> ltb x a -> ~ In x (a::l).
  Proof. { intros H H0 H1.
         assert (H2: x=a \/ In x l); eauto.
         destruct H2. eapply ltb_not_eq; eauto.
         assert (H3: a <b x). eapply IsOrd_elim2;eauto.  eapply ltb_antisym;eauto. } Qed.

  Lemma IsOrd_elim4 (a:A)(l: list A): IsOrd (a::l)-> ~ In a l.
  Proof. { intros H H1. assert (H2: ltb a a). eapply IsOrd_elim2;eauto.
           absurd (a <b a); auto. } Qed.

  Lemma IsOrd_elim5 (a b:A)(l: list A): IsOrd (a::l)-> In b (a::l)-> (b=a \/ a <b b).
    Proof.  { intros H1 H2. cut (b=a \/ In b l).
           intro H0; destruct H0 as [Ha | Hb]. left;auto.
           right; eapply IsOrd_elim2;eauto.  eauto. } Qed.

  Hint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core.

  Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.
  Proof. { intros. induction l. constructor.
         constructor. eapply IsOrd_elim4;auto.  eauto. } Qed.

  Fixpoint isOrd (l: list A): bool:=
    match l with
    |nil => true
    |x ::l1=> match l1 with
             | nil => true
             | y::l2 => (ltb x y) && (isOrd l1)
             end
    end.
   Lemma isOrd_elim (l: list A)(x y: A): isOrd (x::y::l)-> isOrd (y::l).
   Proof.  simpl; move /andP; tauto.  Qed.
   Lemma isOrd_elim1 (l: list A)(x y: A): isOrd (x::y::l)-> (ltb x y).
   Proof. simpl; move /andP; tauto. Qed.
   Lemma isOrd_elim0 (l:list A)(x:A): isOrd (x::l)-> isOrd(l).
   Proof. case l. simpl;auto.  intros s l0. simpl; move /andP; tauto. Qed.

   Hint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.

  Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).
  Proof. { apply reflect_intro. split.
         { intro H. induction l.
         { simpl;auto. }
         { simpl. case l eqn:H1.  auto. apply /andP.
           split. eapply IsOrd_elim1;exact H. apply IHl. eauto. } }
         {  intro H. induction l. constructor. case l eqn:H1.
            constructor. constructor. eapply isOrd_elim1;exact H.
            apply IHl. eapply isOrd_elim. apply H.  } } Qed.

  Hint Resolve isOrdP: core.

  Lemma NoDup_elim1(a:A)(l:list A): NoDup (a::l) -> ~ In a l.
  Proof. eapply NoDup_cons_iff. Qed.

  Lemma NoDup_elim2 (a: A)(l: list A): NoDup (a::l) -> NoDup l.
  Proof. eapply NoDup_cons_iff. Qed.

  Lemma NoDup_intro (a: A)(l: list A): ~ In a l -> NoDup l -> NoDup (a::l).
  Proof. intros; eapply NoDup_cons_iff;auto. Qed.

  Hint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.

  (* --------------------Equality of Ordered Lists---------------------------------------*)

  Definition empty: list A:= nil.

  Lemma empty_equal_nil (l: list A): l [=] empty -> l = empty.
  Proof. { case l. auto. intros s l0. unfold "[=]". intro H.
           destruct H as [H1 H2]. absurd (In s empty). all: eauto. } Qed.

  Lemma head_equal (a b: A)(l s: list A): IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a = b.
  Proof. { intros H H1 H2.
         assert(H3: In b (a::l)).
         unfold "[=]" in H2. apply H2. auto.
         assert(H3A: b=a \/ a <b b).  eapply IsOrd_elim5; eauto.
         assert(H4: In a (b::s)). unfold "[=]" in H2. apply H2. auto.
         assert(H4A: a = b \/ b <b a). eapply IsOrd_elim5; eauto.
         destruct H3A; destruct H4A.
         auto. symmetry;auto. auto. absurd (b <b a); auto. } Qed.

  Lemma tail_equal (a b: A)(l s:list A):IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.
  Proof. { intros H H1 H2. unfold "[=]".
         assert(H0: a = b). eapply head_equal;eauto. subst b.
         split; intro x.
         { intro H3. assert (H3A: a <b x).
           eapply IsOrd_elim2a. exact H. auto.
           assert (H3B: In x (a::l)). auto.
           assert (H3C: x=a \/ In x s).
           { cut (In x (a::s)). eauto. apply H2;auto. }
           destruct H3C. absurd (a <b x); eauto. auto. }
          { intro H3. assert (H3A: a <b x). eapply IsOrd_elim2a. exact H1. auto.
           assert (H3B: In x (a::s)). auto.
           assert (H3C: x=a \/ In x l).
           { cut (In x (a::l)). auto.  apply H2;auto. }
           destruct H3C. absurd (a <b x); auto. auto. } } Qed.

  Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.
  Proof. { revert s. induction l; induction s.
         { auto. }
         { intros; symmetry; apply empty_equal_nil; unfold empty; auto.  }
         { intros; apply empty_equal_nil; unfold empty; auto. }
         { intros H H1 H2. replace a0 with a. replace s with l.
           auto. apply IHl. eauto. eauto.
           eapply tail_equal; eauto. eapply head_equal;eauto. } } Qed.

  Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|.
  Proof. intros. replace s with l. auto. eapply set_equal; eauto. Qed.

  Hint Resolve head_equal tail_equal set_equal length_equal: core.

  (*----------Misc property on ordList-------------------------------*)
  Lemma nodup_Subset_elim(a:A)(l s: list A):
    NoDup (a::l)-> NoDup (a::s)-> a::l [<=] a::s -> l [<=] s.
  Proof. { intros H H1 H2 x H3. assert (Hs: In x (a::s)). apply H2; auto.
         destruct Hs. subst x; absurd (In a l); auto. auto. } Qed.

  Lemma IsOrd_Subset_elim1 (e a: A)(l s: list A):
    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> a <=b e.
  Proof. intros H H1 H2. match_up a e. subst a;auto. auto. absurd (In e (a::s)); auto.  Qed.

  Lemma IsOrd_Subset_elim2 (e a: A)(l s: list A):
    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> e<>a -> e::l [<=] s.
  Proof. { intros H H1 H2 H3 x Hl.
         destruct Hl.
         { subst x. cut (In e (a::s)). intro H4. destruct H4.
           symmetry in H0. contradiction. auto. auto. }
         { assert(H4: In x (a::s)). auto. destruct H4. subst x.
           assert (H4: e <b a).
           { apply leb_antisym2. exact H3. apply ltb_leb; eapply IsOrd_elim2a.
             exact H. auto. }
           assert (H5: a <=b e). eapply IsOrd_Subset_elim1;eauto.
           by_conflict. auto. } } Qed.

End OrderedLists.

Hint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.
Hint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core.
Hint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.
Hint Resolve isOrdP: core.

Hint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.
Hint Immediate head_equal tail_equal set_equal length_equal: core.
Hint Resolve IsOrd_NoDup: core.

Hint Resolve nodup_Subset_elim IsOrd_Subset_elim1 IsOrd_Subset_elim2:core.


(* Exercise 63a *)

Require Import BenB.

Variables A B C D : Prop.

Theorem exercise_063a : ~~((~A -> B) /\ (~A -> ~B) -> A).
Proof.
neg_i (((~A -> B) /\ (~A -> ~B) -> A)) a1.
hyp a1.
imp_i a2.
neg_e' (B) a3.
imp_e (~A).
con_e2 (~A -> B).
hyp a2.
hyp a3.
imp_e (~A).
con_e1 (~A -> ~B).
hyp a2.
hyp a3.
Qed.


Require Export Axioms.

Definition Sing (x : set): set := {x, x}.

Lemma Sing_I : ∀ x, x ∈ (Sing x).
Proof. intros. compute. auto. Qed.

Hint Resolve Sing_I.

Lemma Sing_E : ∀ x y, y ∈ (Sing x) → y = x.
Proof.
  intros. compute in *.
  apply UPair_E in H. inversion H; auto.
Qed.

Hint Resolve Sing_E.

Ltac sing := apply Sing_I ; try auto.
Ltac sing_e H := apply Sing_E in H ; try auto.

Definition Zero := ∅.
Definition One := Sing ∅.
Definition Two := { ∅, One }.

(* We need to be able to extract information from equalities of unordered
   pairs and or singltons.
*)
Lemma UU_ex : forall W X Y Z, UPair W X = UPair Y Z ->
  ( W = Y /\ X = Z ) \/ ( W = Z /\ X = Y ).
Proof.
  intros.
  assert (C: W ∈ UPair Y Z). rewrite <- H. pair_1.
  assert (D: X ∈ UPair Y Z). rewrite <- H. pair_2.
  assert (E: Y ∈ UPair W X). rewrite H. pair_1.
  assert (F: Z ∈ UPair W X). rewrite H. pair_2.
  pair_e C; pair_e D; pair_e E; pair_e F.
Qed.

Lemma SU_ex : forall X Y Z, Sing X = UPair Y Z -> X = Y /\ X = Z.
Proof.
  intros.
  assert (C: X ∈ UPair Y Z). rewrite <- H. pair_1.
  assert (D: Y ∈ Sing X). rewrite H. pair_1.
  assert (E: Z ∈ Sing X). rewrite H. pair_2.
  pair_e C; pair_e D; pair_e E.
Qed.

Lemma US_ex : forall X Y Z, UPair Y Z = Sing X -> X = Y /\ X = Z.
Proof.
  intros.
  assert (C: Y ∈ Sing X). rewrite <- H. pair_1.
  assert (D: Z ∈ Sing X). rewrite <- H. pair_2.
  assert (E: X ∈ UPair Y Z). rewrite H. pair_1.
  pair_e C; pair_e D; pair_e E.
Qed.

Lemma SS_ex : forall X Y, Sing X = Sing Y -> X = Y.
Proof.
  intros.
  assert (C: X ∈ Sing Y). rewrite <- H. sing.
  assert (D: Y ∈ Sing X). rewrite H. sing.
  pair_e C; pair_e D.
Qed.

Ltac inv_SU_eq :=
  repeat let E1 := fresh "E" in
         let E2 := fresh "E" in
         let E3 := fresh "E" in
         let E4 := fresh "E" in
         match goal with
         | [H : UPair ?A ?B = UPair ?C ?D |- _ ] =>
             destruct (UU_ex H) as [[E1 E2] | [E3 E4]]; clear H; subst
         | [H : Sing ?A = UPair ?B ?C |- _ ] =>
             destruct (SU_ex H) as [E1 E2]; clear H; subst
         | [H : UPair ?A ?B = Sing ?C |- _ ] =>
             destruct (US_ex H) as [E1 E2]; clear H; subst
         | [H : Sing ?A = Sing ?B |- _ ] =>
             apply SS_ex in H; subst
         end.


Require Export Induction.
Require Export Basics.

Module Lists.

Inductive natprod : Type :=
  pair : nat -> nat -> natprod.

Check (pair 3 4).

Definition fst (p: natprod) :=
  match p with
      | pair x y => x
  end.

Definition snd (p: natprod) :=
  match p with
      | pair x y => y
  end.

Eval compute in (fst (pair 3 5)).

(* Note the spacings! *)
Notation "( x , y )" := (pair x y).

Eval compute in (fst (3,5)).
Eval compute in (snd (3,5)).

Definition fst' (p: natprod) :=
  match p with
    | (x,y) => x
  end.

Definition snd' (p:natprod) :=
  match p with
    | (x,y) => y
  end.

Definition swap_pair (p: natprod) : natprod :=
  match p with
    | (x,y) => (y,x)
  end.

Theorem surjective_pairing' : forall (n m : nat),
  (n,m) = (fst (n,m), snd (n,m)).
Proof.
  intros n m.
  simpl.
  reflexivity.
Qed.

Theorem surjective_pairing_stuck : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  intros p.
  destruct p as [n m].
  simpl.
  reflexivity.
Qed.

Theorem snd_fst_is_swap : forall (p : natprod),
  (snd p, fst p) = swap_pair p.
Proof.
  intros p.
  destruct p as [n m].
  simpl.
  reflexivity.
Qed.

Theorem fst_swap_is_snd : forall (p : natprod),
  fst (swap_pair p) = snd p.
Proof.
  intros p.
  destruct p as [n m].
  reflexivity.
Qed.

Inductive natlist : Type :=
  | nil : natlist
  | cons : nat -> natlist -> natlist.

Definition mylist := cons 1 (cons 2 (cons 3 nil)).

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

Fixpoint repeat (n count : nat) : natlist :=
  match count with
    | O => nil
    | (S n') => cons n (repeat n n')
  end.

Fixpoint length (l:natlist) : nat :=
  match l with
    | [] => O
    | x :: xs => 1 + length xs
  end.

Check (length mylist).
Eval compute in (length mylist).

Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
      | nil => l2
      | x :: xs => x :: (app xs l2)
  end.

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

Example test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].
Proof. reflexivity. Qed.
Example test_app2: nil ++ [4;5] = [4;5].
Proof. reflexivity. Qed.
Example test_app3: [1;2;3] ++ nil = [1;2;3].
Proof. reflexivity. Qed.

Definition hd (default:nat) (l:natlist) : nat :=
  match l with
    | nil => default
    | (x :: xs) => x
  end.

Definition tl (l:natlist) : natlist :=
  match l with
    | nil => nil
    | (x::xs) => xs
  end.

Example test_hd1: hd 0 [1;2;3] = 1.
Proof. reflexivity. Qed.

Example test_hd2: hd 0 [] = 0.
Proof. reflexivity. Qed.

Example test_tl: tl [1;2;3] = [2;3].
Proof. reflexivity. Qed.

Fixpoint listFilter (l:natlist) (fn: nat -> bool) : natlist :=
  match l with
    | nil => nil
    | (x::xs) => match (fn x) with
                   | true => (x::(listFilter xs fn))
                   | false => listFilter xs fn
                 end
  end.

Definition checkZero (x : nat) : bool :=
  match x with
    | O => false
    | S n => true
  end.

Fixpoint nonzeros (l:natlist) : natlist :=
  listFilter l checkZero.

Example test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].
Proof. reflexivity. Qed.

Fixpoint oddmembers (l:natlist) : natlist :=
  listFilter l (fun n => oddb n).

Example test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].
Proof. reflexivity. Qed.

Fixpoint countoddmembers (l:natlist) : nat :=
  length (oddmembers l).

Example test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.
Proof. reflexivity. Qed.

Example test_countoddmembers2: countoddmembers [0;2;4] = 0.
Proof. reflexivity. Qed.

Example test_countoddmembers3: countoddmembers nil = 0.
Proof. reflexivity. Qed.

Definition singleton (n : nat) : natlist :=
  n :: nil.

Fixpoint alternate (l1 l2 : natlist) : natlist :=
  match l1, l2 with
    | nil, _ => l2
    | _, nil => l1
    | x::xs, y::ys => (x::y::alternate xs ys)
  end.

Example test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
Proof. reflexivity. Qed.

Example test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].
Proof. reflexivity. Qed.
Example test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].
Proof. reflexivity. Qed.
Example test_alternate4: alternate [] [20;30] = [20;30].
Proof. reflexivity. Qed.

Definition bag := natlist.

Fixpoint count (v:nat) (s:bag) : nat :=
  length (listFilter s (fun n => beq_nat n v)).

Example test_count1: count 1 [1;2;3;1;4;1] = 3.
Proof. reflexivity. Qed.
Example test_count2: count 6 [1;2;3;1;4;1] = 0.
Proof. reflexivity. Qed.

Definition sum : bag -> bag -> bag :=
  app.

Eval compute in (sum [1;2;3] [1]).

Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.
Proof. reflexivity. Qed.

Definition add (v:nat) (s:bag) : bag :=
v :: s.

Example test_add1: count 1 (add 1 [1;4;1]) = 3.
Proof. reflexivity. Qed.
Example test_add2: count 5 (add 1 [1;4;1]) = 0.
Proof. reflexivity. Qed.

Definition member (v:nat) (s:bag) : bool :=
match (count v s) with
  | O => false
  | _ => true
end.

Example test_member1: member 1 [1;4;1] = true.
Proof. reflexivity. Qed.
Example test_member2: member 2 [1;4;1] = false.
Proof. reflexivity. Qed.

Fixpoint remove_one (v:nat) (s:bag) : bag :=
  (* When remove_one is applied to a bag without the number to remove,
     it should return the same bag unchanged. *)
  match s with
    | nil => nil
    | (x::xs) => match (beq_nat x v) with
                   | true => xs
                   | false => (x::remove_one v xs)
                 end
  end.

Example test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.
Example test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
Proof. reflexivity. Qed.

Fixpoint remove_all (v:nat) (s:bag) : bag :=
  listFilter s (fun n => negb (beq_nat v n)).

Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.
Example test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
Proof. reflexivity. Qed.

Fixpoint subset (s1:bag) (s2:bag) : bool :=
  match s1 with
    | nil => true
    | (x::xs) => match (beq_nat (count x s2) 0) with
                   | true => false
                   | false => subset xs (remove_one x s2)
                 end
  end.

Example test_subset1: subset [1;2] [2;1;4;1] = true.
Proof. reflexivity. Qed.
Example test_subset2: subset [1;2;2] [2;1;4;1] = false.
Proof. reflexivity. Qed.

Theorem same_equal: forall (n: nat),
  beq_nat n n = true.
Proof.
  intros n.
  induction n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl.
    rewrite -> IHn'.
    reflexivity.
Qed.

Theorem bag_theorem: forall n: nat, forall b: bag,
  blt_nat O (count n (add n b)) = true.
Proof.
  intros n b.
  destruct n as [| n'].
  Case "n = 0".
    simpl.
    reflexivity.
  Case "n = S n'".
    simpl.
    assert (H1: beq_nat n' n' = true).
      rewrite -> same_equal.
      reflexivity.
    rewrite -> H1.
    simpl.
    reflexivity.
Qed.

Theorem nil_app : forall l:natlist,
  [] ++ l = l.
Proof. reflexivity. Qed.

Theorem tl_length_pred : forall l:natlist,
  pred (length l) = length (tl l).
Proof.
  intros l.
  destruct l as [| n l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n l'".
    reflexivity. Qed.

Check pred.
Example pred_one: (pred 3 = 2).
Proof.
  simpl.
  reflexivity.
Qed.

Example pred_two: (pred 0 = 0).
Proof.
  simpl.
  reflexivity.
Qed.

Theorem app_assoc : forall l1 l2 l3 : natlist,
  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
Proof.
  intros l1 l2 l3.
  induction l1 as [| n l1'].
  - simpl. reflexivity.
  - simpl.
    rewrite -> IHl1'.
    reflexivity.
Qed.

Theorem app_length : forall l1 l2 : natlist,
  length (l1 ++ l2) = (length l1) + (length l2).
Proof.
  intros l1 l2.
  induction l1 as [| n l1'].
  - simpl.
    reflexivity.
  - simpl.
    rewrite -> IHl1'.
    reflexivity.
Qed.

Fixpoint snoc (l:natlist) (v:nat) : natlist :=
  match l with
    | nil => [v]
    | (cons n l') => n :: (snoc l' v)
  end.

Example snoc_eg1: (snoc (1::2::3::nil)  4= [1;2;3;4]).
Proof.
  reflexivity.
Qed.

Fixpoint rev (l:natlist) : natlist :=
  match l with
    | nil => nil
    | (h :: t) => snoc (rev t) h
  end.

Example test_rev1: rev [1;2;3] = [3;2;1].
Proof.
  reflexivity.
Qed.

Example test_rev2: rev nil = nil.
Proof. reflexivity. Qed.

Theorem rev_length_firsttry : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l'].
  Case "l = []".
    reflexivity.
  Case "l = cons n l'".
    simpl.
    rewrite <- IHl'.
Abort.

Lemma length_snoc : forall n : nat, forall l : natlist,
  length (snoc l n) = S (length l).
Proof.
  intros n l.
  induction l as [| n' l'].
  Case "n = nil".
    reflexivity.
  Case "n = cons n' l'".
    simpl.
    rewrite -> IHl'.
    reflexivity.
Qed.

Theorem rev_length : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l.
  induction l as [| n' l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n' l'".
    simpl.
    rewrite -> length_snoc.
    rewrite -> IHl'.
    reflexivity.
Qed.

(* rev_length: forall l : natlist, length (rev l) = length l *)
(* test_rev2: rev [] = [] *)
(* test_rev1: rev [1; 2; 3] = [3; 2; 1] *)

Theorem app_nil_end : forall l : natlist,
  l ++ [] = l.
Proof.
  intros l.
  induction l as [| n l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n l'".
    simpl.
    rewrite -> IHl'.
    reflexivity.
Qed.

Lemma rev_helper : forall l : natlist, forall n: nat,
    rev (snoc l n) = n :: rev l.
Proof.
  intros l n.
  induction l as [| l' n'].
  Case "l = nil".
    reflexivity.
  Case "l = cons l' n'".
    simpl.
    rewrite -> IHn'.
    reflexivity.
Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  intros l.
  induction l as [| n l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n l'".
    simpl.
    rewrite -> rev_helper.
    rewrite -> IHl'.
    reflexivity.
Qed.

Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,
  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.
Proof.
  intros l1 l2 l3 l4.
  rewrite -> app_assoc.
  induction l1 as [| n l1'].
  Case "l1 = nil".
    simpl.
    reflexivity.
  Case "l1 = cons n l1'".
    simpl.
    rewrite -> IHl1'.
    reflexivity.
Qed.

Theorem snoc_append : forall (l:natlist) (n:nat),
  snoc l n = l ++ [n].
Proof.
  intros l n.
  induction l as [|n' l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n' l'".
    simpl.
    rewrite -> IHl'.
    reflexivity.
Qed.

Lemma distr_snoc_helper : forall l1 l2:natlist, forall n:nat,
  snoc (l1 ++ l2) n = l1 ++ snoc l2 n.
Proof.
  intros l1 l2 n.
  induction l1 as [| n' l1'].
  Case "l1 = nil".
    reflexivity.
  Case "l1 = cons n' l1'".
    simpl.
    rewrite -> IHl1'.
    reflexivity.
Qed.

Theorem distr_rev : forall l1 l2 : natlist,
  rev (l1 ++ l2) = (rev l2) ++ (rev l1).
Proof.
  intros l1 l2.
  induction l1 as [| n l1'].
  Case "l1 = nil".
    simpl.
    rewrite -> app_nil_end.
    reflexivity.
  Case "l1 = cons n l1'".
    simpl.
    rewrite -> IHl1'.
    rewrite -> distr_snoc_helper.
    reflexivity.
Qed.

Lemma nonzeros_app : forall l1 l2 : natlist,
  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
Proof.
  intros l1 l2.
  induction l1 as [| n l1'].
Admitted.

Fixpoint beq_natlist (l1 l2 : natlist) : bool :=
  match l1,l2 with
    | nil, nil => true
    | _, nil => false
    | nil, _ => false
    | (x::xs), (y::ys) => if (beq_nat x y)
                          then beq_natlist xs ys
                          else false
  end.

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

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

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

Theorem beq_natlist_refl : forall l:natlist,
  true = beq_natlist l l.
Proof.
  intros l.
  induction l as [| n l'].
  Case "l = nil".
    reflexivity.
  Case "l = n :: l'".
    simpl.
    rewrite -> same_equal.
    rewrite <- IHl'.
    reflexivity.
Qed.

Inductive natoption : Type :=
| Some : nat -> natoption
| None : natoption.

Fixpoint index (n:nat) (l:natlist) : natoption :=
  match l with
    | nil => None
    | a :: l => match beq_nat n 0 with
                    | true => Some a
                    | false => index (n-1) l
                end
  end.

Example test_index1 : index 0 [4;5;6;7] = Some 4.
Proof. reflexivity. Qed.
Example test_index2 : index 3 [4;5;6;7] = Some 7.
Proof. reflexivity. Qed.
Example test_index3 : index 10 [4;5;6;7] = None.
Proof. reflexivity. Qed.

Definition option_elim (d : nat) (o : natoption) : nat :=
  match o with
    | Some o' => o'
    | None => d
  end.

Definition hd_opt (l : natlist) : natoption :=
  match l with
    | [] => None
    | (x::xs) => Some x
  end.

Example test_hd_opt1 : hd_opt [] = None.
reflexivity. Qed.

Example test_hd_opt2 : hd_opt [1] = Some 1.
reflexivity. Qed.

Example test_hd_opt3 : hd_opt [5;6] = Some 5.
reflexivity. Qed.

Definition hd_error (l : natlist) : natoption :=
  match l with
    | [] => None
    | (x::xs) => Some x
  end.

Example test_hd_error1 : hd_error [] = None. simpl. reflexivity. Qed.

Example test_hd_error2 : hd_error [1] = Some 1.
reflexivity. Qed.

Example test_hd_error3 : hd_error [5;6] = Some 5.
reflexivity. Qed.

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_error l).
Proof.
  intros.
  destruct l.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

Theorem app_nil_r : forall l : natlist,
  l ++ [] = l.
Proof.
  intros l.
  induction l as [| n l'].
  - simpl. reflexivity.
  - simpl.
    rewrite <- IHl' at 2.
    reflexivity.
Qed.

Theorem rev_app_distr: forall l1 l2 : natlist,
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  intros l1 l2.
  induction l1 as [| n l1'].
  - simpl.
    symmetry.
    rewrite -> app_nil_r with (l := rev l2) at 1.
    reflexivity.
  - simpl. rewrite -> IHl1'.
    rewrite -> snoc_append at 1.
    symmetry.
    rewrite -> snoc_append at 1.
    rewrite -> app_assoc.
    reflexivity.
Qed.

Theorem count_member_nonzero : forall (s : bag),
  leb 1 (count 1 (1 :: s)) = true.
Proof.
  intros s.
  simpl.
  reflexivity.
Qed.

Theorem ble_n_Sn : forall n,
  leb n (S n) = true.
Proof.
  intros n.
  induction n as [| n'].
  - simpl.
    reflexivity.
  - simpl.
    rewrite -> IHn'.
    reflexivity.
Qed.

Theorem remove_decreases_count: forall (s : bag),
  leb (count 0 (remove_one 0 s)) (count 0 s) = true.
Proof.
  intros s.
  induction s as [| n s'].
  - simpl. reflexivity.
  - simpl.
Abort.

End Lists.

Module PartialMap.

Export Lists.

Inductive id: Type :=
  | Id : nat -> id.

Definition beq_id (x1 x2 : id) :=
  match x1, x2 with
    | Id n1, Id n2 => beq_nat n1 n2
  end.

Theorem beq_id_refl : forall x, true = beq_id x x.
Proof.
  intros x.
  destruct x.
  - simpl. rewrite -> same_equal. reflexivity.
Qed.

Inductive partial_map : Type :=
  | empty : partial_map
  | record : id -> nat -> partial_map -> partial_map.

Definition update (d : partial_map) (x : id) (value : nat) : partial_map :=
  record x value d.

Fixpoint find (x : id) (d : partial_map) : natoption :=
  match d with
  | empty => None
  | record y v d' => if beq_id x y
                     then Some v
                     else find x d'
  end.

Theorem update_eq :
  forall (d : partial_map) (x : id) (v: nat),
    find x (update d x v) = Some v.
Proof.
  intros d x v.
  simpl.
  destruct x. simpl. rewrite -> same_equal. reflexivity.
Qed.

Theorem update_neq :
  forall (d : partial_map) (x y : id) (o: nat),
    beq_id x y = false -> find x (update d y o) = find x d.
Proof.
  intros d x y o.
  intros H1.
  induction d as [| z o' d' IHdd'].
  - simpl. rewrite -> H1. reflexivity.
  - simpl. rewrite -> H1 at 1. reflexivity.
Qed.

End PartialMap.


Load LFindLoad.
From lfind Require Import LFind.
Unset Printing Notations.
Set Printing Implicit.

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

Inductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .

Inductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.

Inductive Pair : Type := mkpair : natural -> natural -> Pair
with Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural
           := match plus_arg0, plus_arg1 with
              | Zero, n => n
              | Succ n, m => Succ (plus n m)
              end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural
           := match mult_arg0, mult_arg1 with
              | Zero, n => Zero
              | Succ n, m => plus (mult n m) m
              end.

Fixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural
           := match qmult_arg0, qmult_arg1, qmult_arg2 with
              | Zero, n, m => m
              | Succ n, m, p => qmult n m (plus p m)
              end.

Lemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. reflexivity.
Qed.

Lemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. reflexivity.
Qed.

Lemma plus_zero : forall (x : natural), plus x Zero = x.
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. reflexivity.
Qed.

Lemma plus_commut : forall (x y : natural), plus x y = plus y x.
Proof.
   intros.
   induction x.
   - rewrite plus_zero. reflexivity.
   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.
Qed.

Lemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).
Proof.
   intro.
   induction x.
   - reflexivity.
   - intros.  simpl.  rewrite IHx. lfind.  rewrite (plus_commut y a).
Admitted.

Theorem mult_eq_qmult : forall (x : natural) (y : natural), eq (mult x y) (qmult x y Zero).
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. rewrite plus_qmult. reflexivity.
Qed.