(** * Tactics: More Basic Tactics *)

(** This chapter introduces several additional proof strategies
    and tactics that allow us to begin proving more interesting
    properties of functional programs.

    We will see:
    - how to use auxiliary lemmas in both "forward-" and
      "backward-style" proofs;
    - how to reason about data constructors -- in particular, how to use
      the fact that they are injective and disjoint;
    - how to strengthen an induction hypothesis, and when such
      strengthening is required; and
    - more details on how to reason by case analysis. *)

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

(* ################################################################# *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    _exactly_ the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.

(** Here, we could finish with "[rewrite -> eq2.  reflexivity.]" as we
    have done several times before.  We can finish this proof in
    a single step by using the [apply] tactic instead: *)

  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
    n = m ->
    (n = m -> [n;o] = [m;p]) ->
    [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that introduces some _universally quantified
    variables_.  When Coq matches the current goal against the
    conclusion of [H], it will try to find appropriate values for
    these variables.  For example, when we do [apply eq2] in the
    following proof, the universal variable [q] in [eq2] gets
    instantiated with [n], and [r] gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** **** Exercise: 2 stars, standard, optional (silly_ex)

    Complete the following proof using only [intros] and [apply]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 2 = true ->
     oddb 3 = true.
Proof.
  (* SOLUTION: *)
  intros eq1 eq2. apply eq2. Qed.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal exactly -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat),
     true = (n =? 5)  ->
     (S (S n)) =? 7 = true.
Proof.
  intros n H.

(** Here we cannot use [apply] directly, but we can use the [symmetry]
    tactic, which switches the left and right sides of an equality in
    the goal. *)

  symmetry.
  simpl. (** (This [simpl] is optional, since [apply] will perform
             simplification first, if needed.) *)
  apply H.  Qed.

(** **** Exercise: 3 stars, standard (apply_exercise1)

    (_Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [Search] is
    your friend.) *)

(** For the slick solution to this exercise, we can use the fact that
    [rev] is involutive. *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* SOLUTION: *)
  intros l l' eq. rewrite -> eq.
  symmetry.
  apply rev_involutive.   Qed.
(** [] *)

(** **** Exercise: 1 star, standard, optional (apply_rewrite)

    Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied? *)

(* SOLUTION:

    The [rewrite] tactic is used to apply a known equality (a
    hypothesis from the context or a previously proved lemma) to
    modify the goal, replacing all occurrences of one side by the
    other.  The [apply] tactic uses a known implication (a hypothesis
    from the context, a previously proved lemma, or a constructor) to
    replace a goal that matches the conclusion of the implication with
    subgoals, one for each premise of the implication.  If the known
    fact is itself an equality (with no premises), then either tactic
    can be used.  (We will see below that each tactic can also be used
    to modify a hypothesis rather than the goal.)

    [] *)

(* ################################################################# *)
(** * The [apply with] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a;b]] to [[e;f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.

(** Since this is a common pattern, we might like to pull it out as a
    lemma that records, once and for all, the fact that equality is
    transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
  reflexivity.  Qed.

(** Now, we should be able to use [trans_eq] to prove the above
    example.  However, to do this we need a slight refinement of the
    [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.

(** If we simply tell Coq [apply trans_eq] at this point, it can
    tell (by matching the goal against the conclusion of the lemma)
    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
    [o] with [[e,f]].  However, the matching process doesn't determine
    an instantiation for [m]: we have to supply one explicitly by
    adding "[with (m:=[c,d])]" to the invocation of [apply]. *)

  apply trans_eq with (m:=[c;d]).
  apply eq1. apply eq2.   Qed.

(** (Actually, we usually don't have to include the name [m] in
    the [with] clause; Coq is often smart enough to figure out which
    variable we are instantiating. We could instead write [apply
    trans_eq with [c;d]].) *)

(** Coq also has a tactic [transitivity] that accomplishes the
    same purpose as applying [trans_eq]. The tactic requires us to
    state the instantiation we want, just like [apply with] does. *)

Example trans_eq_example'' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  transitivity [c;d].
  apply eq1. apply eq2.   Qed.

(** **** Exercise: 3 stars, standard, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* SOLUTION: *)
  intros n m o p eq1 eq2.
  apply trans_eq with m. apply eq2. apply eq1.   Qed.
(** [] *)

(* ################################################################# *)
(** * The [injection] and [discriminate] Tactics *)

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O
       | S (n : nat).

    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition are two more
    facts:

    - The constructor [S] is _injective_, or _one-to-one_.  That is,
      if [S n = S m], it must be that [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n]. *)

(** Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since [true] and
    [false] take no arguments, their injectivity is neither here
    nor there.)  And so on. *)

(** For example, we can prove the injectivity of [S] by using the
    [pred] function defined in [Basics.v]. *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  assert (H2: n = pred (S n)). { reflexivity. }
  rewrite H2. rewrite H1. reflexivity.
Qed.

(** This technique can be generalized to any constructor by
    writing the equivalent of [pred] -- i.e., writing a function that
    "undoes" one application of the constructor. As a more convenient
    alternative, Coq provides a tactic called [injection] that allows
    us to exploit the injectivity of any constructor.  Here is an
    alternate proof of the above theorem using [injection]: *)

Theorem S_injective' : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [injection H as Hmn] at this point, we are asking Coq
    to generate all equations that it can infer from [H] using the
    injectivity of constructors (in the present example, the equation
    [n = m]). Each such equation is added as a hypothesis (with the
    name [Hmn] in this case) into the context. *)

  injection H as Hnm. apply Hnm.
Qed.

(** Here's a more interesting example that shows how [injection] can
    derive multiple equations at once. *)

Theorem injection_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  (* WORKED IN CLASS *)
  injection H as H1 H2.
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** Alternatively, if you just say [injection H] with no [as] clause,
    then all the equations will be turned into hypotheses at the
    beginning of the goal. *)

Theorem injection_ex2 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H.
  (* WORKED IN CLASS *)
  intros H1 H2. rewrite H1. rewrite H2. reflexivity.
Qed.

(** **** Exercise: 3 stars, standard (injection_ex3)  *)
Example injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  (* SOLUTION: *)
  intros X x y z l j eq1 eq2.
  injection eq1 as Hxz Hyl_j.
  assert (Hyl_zl : y :: l = z :: l).
  { apply trans_eq with j.
    - apply Hyl_j.
    - apply eq2. }
  injection Hyl_zl as Hyz.
  rewrite -> Hxz. rewrite -> Hyz. reflexivity.
Qed.
(** [] *)

(** So much for injectivity of constructors.  What about disjointness?

    The principle of disjointness says that two terms beginning with
    different constructors (like [O] and [S], or [true] and [false])
    can never be equal.  This means that, any time we find ourselves
    in a context where we've _assumed_ that two such terms are equal,
    we are justified in concluding anything we want, since the
    assumption is nonsensical. *)

(** The [discriminate] tactic embodies this principle: It is used on a
    hypothesis involving an equality between different
    constructors (e.g., [S n = O]), and it solves the current goal
    immediately.  Here is an example: *)

Theorem eqb_0_l : forall n,
   0 =? n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'] eqn:E.
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming [0
    =? (S n') = true], we must show [S n' = 0]!  The way forward is to
    observe that the assumption itself is nonsensical: *)

  - (* n = S n' *)
    simpl.

(** If we use [discriminate] on this hypothesis, Coq confirms
    that the subgoal we are working on is impossible and removes it
    from further consideration. *)

    intros H. discriminate H.
Qed.

(** This is an instance of a logical principle known as the _principle
    of explosion_, which asserts that a contradictory hypothesis
    entails anything (even false things!). *)

Theorem discriminate_ex1 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. discriminate contra. Qed.

Theorem discriminate_ex2 : forall (n m : nat),
  false = true ->
  [n] = [m].
Proof.
  intros n m contra. discriminate contra. Qed.

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, _if_ the
    nonsensical situation described by the premise did somehow arise,
    _then_ the nonsensical conclusion would also follow, because we'd
    be living in an inconsistent universe where every statement is
    true.  We'll explore the principle of explosion in more detail in
    the next chapter. *)

(** **** Exercise: 1 star, standard (discriminate_ex3)  *)
Example discriminate_ex3 :
  forall (X : Type) (x y z : X) (l j : list X),
    x :: y :: l = [] ->
    x = z.
Proof.
  (* SOLUTION: *)
  intros X x y z l j eq1. discriminate eq1. Qed.
(** [] *)

(** The injectivity of constructors allows us to reason that
    [forall (n m : nat), S n = S m -> n = m].  The converse of this
    implication is an instance of a more general fact about both
    constructors and functions, which we will find convenient in a few
    places below: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.

Theorem eq_implies_succ_equal : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. apply f_equal. apply H. Qed.

(** There is also a tactic named `f_equal` that can prove such
    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],
    the tactic [f_equal] will produce subgoals of the form [f = g],
    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals
    that are simple enough (e.g., immediately provable by
    [reflexivity]) will be automatically discharged by [f_equal]. *)

Theorem eq_implies_succ_equal' : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. f_equal. apply H. Qed.

(* ################################################################# *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic "[simpl in H]" performs simplification on
    the hypothesis [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     (S n) =? (S m) = b  ->
     n =? m = b.
Proof.
  intros n m b H. simpl in H. apply H.  Qed.

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [X -> Y], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [Y] into a subgoal [X]), [apply L in H] matches [H]
    against [X] and, if successful, replaces it with [Y].

    In other words, [apply L in H] gives us a form of "forward
    reasoning": from [X -> Y] and a hypothesis matching [X], it
    produces a hypothesis matching [X].  By contrast, [apply L] is
    "backward reasoning": it says that if we know [X -> Y] and we
    are trying to prove [Y], it suffices to prove [X].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly3' : forall (n : nat),
  (n =? 5 = true -> (S (S n)) =? 7 = true) ->
  true = (n =? 5)  ->
  true = ((S (S n)) =? 7).
Proof.
  intros n eq H.
  symmetry in H. apply eq in H. symmetry in H.
  apply H.  Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_ and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.

    The informal proofs that you've seen in math or computer science
    classes probably tended to use forward reasoning.  In general,
    idiomatic use of Coq favors backward reasoning, but in some
    situations the forward style can be easier to think about. *)

(* ################################################################# *)
(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we sometimes need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that [double] is injective -- i.e., that it maps
    different arguments to different results:

       Theorem double_injective: forall n m,
         double n = double m -> n = m.

    The way we start this proof is a bit delicate: if we begin it with

       intros n. induction n.

    all is well.  But if we begin it with

       intros n m. induction n.

    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n' IHn'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.
  - (* n = S n' *) intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) discriminate eq.
    + (* m = S m' *) apply f_equal.

(** At this point, the induction hypothesis ([IHn']) does _not_ give us
    [n' = m'] -- there is an extra [S] in the way -- so the goal is
    not provable. *)

Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _those particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition

      - [P n] = "if [double n = double m], then [n = m]"

    holds, by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]") and

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular (arbitrary,
    but fixed) [m] -- say, [5].  The statement is then saying that,
    if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help at all with proving
    [R]!  If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing
    helpful about whether [double n] is [10] (indeed, it strongly
    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)

(** Trying to carry out this proof by induction on [n] when [m] is
    already in the context doesn't work because we are then trying to
    prove a statement involving _every_ [n] but just a _single_ [m]. *)

(** A successful proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) simpl in eq. discriminate eq.

  - (* n = S n' *)

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., to prove the statement for _every_ [m]), but the IH
    is correspondingly more flexible, allowing us to choose whichever
    [m] we like when we apply the IH. *)

    intros m eq.

(** Now we've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'] eqn:E.
    + (* m = O *)

(** The 0 case is trivial: *)

      simpl in eq. discriminate eq.

    + (* m = S m' *)
      apply f_equal.

(** At this point, since we are in the second branch of the [destruct
    m], the [m'] mentioned in the context is the predecessor of the
    [m] we started out talking about.  Since we are also in the [S]
    branch of the induction, this is perfect: if we instantiate the
    generic [m] in the IH with the current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.

(** What you should take away from all this is that we need to be
    careful, when using induction, that we are not trying to prove
    something too specific: When proving a property involving two
    variables [n] and [m] by induction on [n], it is sometimes
    crucial to leave [m] generic. *)

(** The following exercise follows the same pattern. *)

(** **** Exercise: 2 stars, standard (eqb_true)  *)
Theorem eqb_true : forall n m,
    n =? m = true -> n = m.
Proof.
  (* SOLUTION: *)
      intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    intros m. destruct m as [| m'] eqn:E.
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) simpl. intros contra. discriminate contra.
  - (* n = S n' *)
    intros m. destruct m as [| m'] eqn:E.
    + (* m = 0 *) simpl. intros contra. discriminate contra.
    + (* m = S m' *) simpl. intros H.
      apply f_equal. apply IHn'. apply H. Qed.
(** [] *)

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

    Give a careful informal proof of [eqb_true], being as explicit
    as possible about quantifiers. *)

(* SOLUTION:

    _Theorem_: For all natural numbers [n] and [m], if [n =? m =
      true], then [n = m].

    _Proof_ (more pedantic, arguably less clear): We argue by
    induction on [n].

      - Base case: [n = 0].  We must show, for all natural numbers
        [m], that [0 =? m = true] implies [0 = m].  We proceed by
        cases on [m].

          - If [m = 0], we must show that [0 =? 0 = true] implies [0 =
            0], which holds by reflexivity.

          - If [m = S m'] for some [m'], we must show that [0 =? S m'
            = true] implies [0 = S m'].  But [0 =? S m'] evaluates to
            [false], so the antecedent of this implication is [false =
            true], which is absurd, and hence the whole implication is
            true.

      - Inductive case: [n = S n']. We must show that for all natural
        numbers [m], [S n' =? m = true] implies [S n' = m].

        We may assume the induction hypothesis: for all natural
        numbers [m], [n' =? m = true], implies [n' = m].

        We again proceed by cases on [m].

          - If [m = 0], we must show that [S n' =? 0 = true] implies
            [S n' = m]. But [S n' =? 0] evaluates to [false], so the
            antecedent of this implies is again absurd, and hence the
            whole implication is true.

          - If [m = S m'] for some [m'], we must show that [S n' =? S
            m' = true] implies [S n' = S m'].  So let us assume the [S
            n' =? S m' = true].  This simplifes to [n' =? m' =
            true]. Hence we can apply the induction hypothesis (with
            [m] instantiated to [m']) to obtain [n' = m'].  Hence, to
            show [S n' = S m'] it suffices to show [S n' = S n'],
            which is true by reflexivity. []

    _Proof_ (somewhat more natural style): By induction on [n].

      - Suppose [n = 0].  We must show that if [0 =? m = true] then [0
        = m]. Now if [m] were of the form [S m'] for some [m'], then
        we would have [0 =? S m' = true], which is absurd. So [m] must
        indeed be 0.

      - Otherwise, we have [n = S n']. The induction hypothesis states
        that for all m, if [n' =? m = true], then [n' = m]; and on the
        assumption [S n' =? m = true], we must show that [S n' = m].
        In this case [m] must have the form [S m'] for some [m'], for
        if [m] were 0, our assumption would be [S n' =? 0 = true],
        which is absurd.  So our assumption has the form [S n' =? S m'
        = true], which simplifies to [n' =? m' = true]. Applying the
        induction hypothesis to the assumption (with [m] instantiated
        to [m']) gives us that [n' = m'], which directly implies our
        goal [S n' = S m']. [] *)

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

(** **** Exercise: 3 stars, standard, recommended (plus_n_n_injective)

    In addition to being careful about how you use [intros], practice
    using "in" variants in this proof.  (Hint: use [plus_n_Sm].) *)
Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  (* SOLUTION: *)
      intros n. induction n as [| n'].
  - (* n = 0 *) intros m. simpl. intros eq. destruct m as [| m'] eqn:E.
      + (* m = 0 *) reflexivity.
      + (* m = S m' *) discriminate eq.
    - (* n = S n' *) intros m eq. destruct m as [| m'] eqn:E.
      + (* m = 0 *) discriminate eq.
      + (* m = S m' *)
        apply f_equal. apply IHn'.
        (* just [simpl in eq] doesn't work here! *)
        rewrite <- plus_n_Sm in eq. rewrite <- plus_n_Sm in eq.
        injection eq as goal. apply goal. Qed.
(** [] *)

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    some _rearrangement_ of quantified variables is needed.  Suppose,
    for example, that we wanted to prove [double_injective] by
    induction on [m] instead of [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m' IHm'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (And if we simply say [induction m] without
    introducing anything first, Coq will automatically introduce [n]
    for us!)  *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables out of the context and putting them
    back at the beginning of the goal.  The [generalize dependent]
    tactic does this. *)

Theorem double_injective_take2 : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m' IHm'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. injection eq as goal. apply goal. Qed.

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

    _Theorem_: For any nats [n] and [m], if [double n = double m], then
      [n = m].

    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
      any [n], if [double n = double m] then [n = m].

      - First, suppose [m = 0], and suppose [n] is a number such
        that [double n = double m].  We must show that [n = 0].

        Since [m = 0], by the definition of [double] we have [double n =
        0].  There are two cases to consider for [n].  If [n = 0] we are
        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']
        for some [n'], we derive a contradiction: by the definition of
        [double], we can calculate [double n = S (S (double n'))], but
        this contradicts the assumption that [double n = 0].

      - Second, suppose [m = S m'] and that [n] is again a number such
        that [double n = double m].  We must show that [n = S m'], with
        the induction hypothesis that for every number [s], if [double s =
        double m'] then [s = m'].

        By the fact that [m = S m'] and the definition of [double], we
        have [double n = S (S (double m'))].  There are two cases to
        consider for [n].

        If [n = 0], then by definition [double n = 0], a contradiction.

        Thus, we may assume that [n = S n'] for some [n'], and again by
        the definition of [double] we have [S (S (double n')) =
        S (S (double m'))], which implies by injectivity that [double n' =
        double m'].  Instantiating the induction hypothesis with [n'] thus
        allows us to conclude that [n' = m'], and it follows immediately
        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just
        what we wanted to show. [] *)

(** **** Exercise: 3 stars, standard, recommended (gen_dep_practice)

    Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     nth_error l n = None.
Proof.
  (* SOLUTION: *)
  intros n X l. generalize dependent n. induction l as [| x l' IHl'].
  - (* l = nil *) reflexivity.
  - (* l = x :: l' *) intros n eq. simpl. simpl in eq.
    rewrite <- eq.  apply IHl'.  reflexivity.  Qed.
(** [] *)

(* ################################################################# *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a name that
    has been introduced by a [Definition] so that we can manipulate
    the expression it denotes.  For example, if we define... *)

Definition square n := n * n.

(** ... and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we appear to be stuck: [simpl] doesn't simplify anything, and
    since we haven't proved any other facts about [square], there is
    nothing we can [apply] or [rewrite] with.

    To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these it is not hard
    to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
    { rewrite mult_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, some discussion of unfolding and simplification is
    in order.

    We already have observed that tactics like [simpl], [reflexivity],
    and [apply] will often unfold the definitions of functions
    automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

(** .... then the [simpl] in the following proof (or the
    [reflexivity], if we omit the [simpl]) will unfold [foo m] to
    [(fun x => 5) m] and then further simplify this expression to just
    [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** However, this automatic unfolding is somewhat conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  It is not smart enough to notice that the
    two branches of the [match] are identical, so it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that cannot itself be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone. *)

(** At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m eqn:E.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress. *)

(** A more straightforward way forward is to explicitly tell Coq to
    unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m eqn:E.
  - reflexivity.
  - reflexivity.
Qed.

(* ################################################################# *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  Sometimes we
    need to reason by cases on the result of some _expression_.  We
    can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if n =? 3 then false
  else if n =? 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (n =? 3) eqn:E1.
    - (* n =? 3 = true *) reflexivity.
    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.
      + (* n =? 5 = true *) reflexivity.
      + (* n =? 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (n =? 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (eqb
    n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c]. *)

(** **** Exercise: 3 stars, standard (combine_split)

    Here is an implementation of the [split] function mentioned in
    chapter [Poly]: *)

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

(** Prove that [split] and [combine] are inverses in the following
    sense: *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* SOLUTION: *)
  intros X Y l. induction l as [| [x y] l' IHl'].
  - (* l = [] *)
    intros l1 l2 H.
    injection H as l2mt l1mt.
    rewrite <- l2mt.
    rewrite <- l1mt.
    reflexivity.
  - (* l = (x, y) :: l' *)
    intros l1 l2 H.
    simpl in H.
    destruct (split l') as [lx ly] eqn:E.
    injection H as l2in l1in.
    rewrite <- l2in.
    rewrite <- l1in.
    simpl.
    rewrite -> IHl'.
      reflexivity.
      reflexivity.  Qed.
(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional: So far,
    we've chosen to include it most of the time, just for the sake of
    documentation.

    However, when [destruct]ing compound expressions, the information
    recorded by the [eqn:] can actually be critical: if we leave it
    out, then [destruct] can erase information we need to complete a
    proof.

    For example, suppose we define a function [sillyfun1] like
    this: *)

Definition sillyfun1 (n : nat) : bool :=
  if n =? 3 then true
  else if n =? 5 then true
  else false.

(** Now suppose that we want to convince Coq that [sillyfun1 n]
    yields [true] only when [n] is odd.  If we start the proof like
    this (with no [eqn:] on the [destruct])... *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3).
  (* stuck... *)
Abort.

(** ... then we are stuck at this point because the context does
    not contain enough information to prove the goal!  The problem is
    that the substitution performed by [destruct] is quite brutal --
    in this case, it thows away every occurrence of [n =? 3], but we
    need to keep some memory of this expression and how it was
    destructed, because we need to be able to reason that, since [n =?
    3 = true] in this branch of the case analysis, it must be that [n
    = 3], from which it follows that [n] is odd.

    What we want here is to substitute away all existing occurences of
    [n =? 3], but at the same time add an equation to the context that
    records which case we are in.  This is precisely what the [eqn:]
    qualifier does. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply eqb_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (* When we come to the second equality test in the body
        of the function we are reasoning about, we can use
        [eqn:] again in the same way, allowing us to finish the
        proof. *)
      destruct (n =? 5) eqn:Heqe5.
        + (* e5 = true *)
          apply eqb_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) discriminate eq.  Qed.

(** **** Exercise: 2 stars, standard (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  (* SOLUTION: *)
  intros f b.
  destruct b.
  - (* b = true *)
    destruct (f true) eqn:Heqftrue.
    + (* f true = true *)
      rewrite Heqftrue.
      apply Heqftrue.
    + (* f true = false *)
      destruct (f false) eqn:Heqffalse.
      * (* f false = true *)
        apply Heqftrue.
      * (* f false = false *)
        apply Heqffalse.
  - (* b = false *)
    destruct (f false) eqn:Heqffalse.
    + (* f false = true *)
      destruct (f true) eqn: Heqftrue.
      * (* f true = true *)
        apply Heqftrue.
      * (* f true = false *)
        apply Heqffalse.
    + (* f false = false *)
      rewrite Heqffalse.
      apply Heqffalse.
Qed.
(** [] *)

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

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  But basically we've got what we need to
    get work done.

    Here are the ones we've seen:

      - [intros]: move hypotheses/variables from goal to context

      - [reflexivity]: finish the proof (when the goal looks like [e =
        e])

      - [apply]: prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]: apply a hypothesis, lemma, or constructor to
        a hypothesis in the context (forward reasoning)

      - [apply... with...]: explicitly specify values for variables
        that cannot be determined by pattern matching

      - [simpl]: simplify computations in the goal

      - [simpl in H]: ... or a hypothesis

      - [rewrite]: use an equality hypothesis (or lemma) to rewrite
        the goal

      - [rewrite ... in H]: ... or a hypothesis

      - [symmetry]: changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]: changes a hypothesis of the form [t=u] into
        [u=t]

      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,
        [x=y] and [y=z]

      - [unfold]: replace a defined constant by its right-hand side in
        the goal

      - [unfold... in H]: ... or a hypothesis

      - [destruct... as...]: case analysis on values of inductively
        defined types

      - [destruct... eqn:...]: specify the name of an equation to be
        added to the context, recording the result of the case
        analysis

      - [induction... as...]: induction on values of inductively
        defined types

      - [injection]: reason by injectivity on equalities
        between values of inductively defined types

      - [discriminate]: reason by disjointness of constructors on
        equalities between values of inductively defined types

      - [assert (H: e)] (or [assert (e) as H]): introduce a "local
        lemma" [e] and call it [H]

      - [generalize dependent x]: move the variable [x] (and anything
        else that depends on it) from the context back to an explicit
        hypothesis in the goal formula

      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)

(* ################################################################# *)
(** * Additional Exercises *)

(** **** Exercise: 3 stars, standard (eqb_sym)  *)
Theorem eqb_sym : forall (n m : nat),
  (n =? m) = (m =? n).
Proof.
  (* SOLUTION: *)
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) reflexivity.
  - (* n = S n' *)
    intros m. destruct m as [| m'].
    + (* m = 0 *) reflexivity.
    + (* m = S m' *) apply IHn'.  Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)

    Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [(n =? m) = (m =? n)].

   Proof: *)
   (* SOLUTION:
   Let an arbitrary nat [n] be given.  We go by induction
   on [n].

   - For the base case, we have [n = 0].  Let [m] be given.
     We must show that

       0 =? m = m =? 0

     Either [m = 0] or not.

     - If [m = 0], we must show [0 =? 0 = 0 =? 0]
       which is true by reflexivity.

     - Otherwise, [m = S m'] for some [m'], and we must show
       [0 =? (S m') = (S m') =? 0]. By the definition
       of [eqb], both sides are [false].

   - In the inductive case, we have [n = S n'] for some
     [n'] such that, for any [m],

       n' =? m = m =? n'

     Let [m] be given.  Again, [m] is either zero or nonzero.

     - Suppose first [m = 0].  It's
       enough to show [(S n') =? 0 = 0 =? (S n')].
       By the definition of [eqb], both sides are [false].

     - Otherwise, [m = S m'] for some [m'].  By the
       assumption, it's enough to show:

         (S n') =? (S m') = (S m') =? (S n')

       And, by the definition of [eqb], this reduces to
       showing:

         m' =? n' = n' =? m'.

       which is exactly the induction hypothesis.  *)
   (** [] *)

(** **** Exercise: 3 stars, standard, optional (eqb_trans)  *)
Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  (* SOLUTION: *)
  intros n m p. intros Hnm Hmp.
  apply eqb_true in Hnm.
  rewrite -> Hnm.
  rewrite -> Hmp.
  reflexivity.  Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)

    We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)

Definition split_combine_statement : Prop
  (* ("[: Prop]" means that we are giving a name to a
     logical proposition here.) *)
  (* SOLUTION: *) :=
  forall (X Y:Type) (l1 : list X) (l2 : list Y),
    length l1 = length l2 -> split (combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
(* SOLUTION: *)
  intros X Y. induction l1 as [| x l1' IHl1'].
  - (* l1 = [] *)
    intros l2 Heq. destruct l2 as [|y l2'].
    + (* l2 = [] *) reflexivity.
    + (* l2 = y :: l2' *) discriminate Heq.
  - (* l1 = x :: l1' *)
    intros l2 Heq. destruct l2 as [|y l2'].
    + (* l2 = [] *) discriminate Heq.
    + (* l2 = y :: l2' *)
      simpl. rewrite IHl1'. reflexivity.
      injection Heq as goal. apply goal. Qed.

(** Here are more approaches *)

Theorem split_combine' : forall (X Y:Type) l (l1 : list X) (l2 : list Y),
  (l1, l2) = split l -> split (combine l1 l2) = (l1, l2).
Proof.
  induction l as [| [x y] l' IHl'].
  - (* l = [] *) intros l1 l2 Heq.
    simpl in Heq. injection Heq as l2mt l1mt.
    rewrite l2mt. rewrite l1mt. reflexivity.
  - (* l = (x,y) :: l' *) intros l1 l2 Heq.
    simpl in Heq. destruct (split l') as [l1' l2'].
    injection Heq as l2in l1in.
    rewrite l2in. rewrite l1in. simpl. rewrite IHl'.
    reflexivity. reflexivity.  Qed.

Theorem split_combine''_equiv :
  forall (X Y:Type) l (l1 : list X) (l2 : list Y),
    (split l = (l1, l2) -> split (combine l1 l2) = (l1, l2))
    <-> (split l = (l1, l2) -> combine l1 l2 = l).
Proof.
  intros X Y.
  induction l; intros; split; intros;
    try solve [inversion H0; auto].
  - inversion H0. destruct x.
    destruct (split l). inversion H2; subst. simpl.
    apply f_equal. apply IHl; auto. apply H in H0.
    inversion H0. destruct (split (combine x0 y0)).
    inversion H3; subst; auto.
  - pose proof H0. apply H in H0. rewrite H0; auto.
Qed.

Theorem split_combine'' : forall X Y (l : list (X * Y)) l1 l2,
    split l = (l1, l2) -> combine l1 l2 = l.
Proof.
  induction l as [| [x y] l' IHl'].
  - (* l = [] *) intros l1 l2 Heq.
    simpl in Heq. injection Heq as l2mt l1mt.
    rewrite <- l2mt. rewrite <- l1mt. reflexivity.
  - (* l = (x,y) :: l' *) intros l1 l2 Heq.
    simpl in Heq. destruct (split l') as [l1' l2'].
    injection Heq as l2in l1in.
    rewrite <- l2in. rewrite <- l1in. simpl. rewrite IHl'.
    reflexivity. reflexivity.  Qed.
(* Do not modify the following line: *)
Definition manual_grade_for_split_combine : option (nat*string) := None.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)

    This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* SOLUTION: *)
  intros X test x l. induction l as [| v' l' IHl'].
    - (* l = [] *) intros lf eq. discriminate eq.
    - (* l = v' :: l' *) intros lf eq.
      simpl in eq.
      destruct (test v') eqn: Heq.
        + (* test v' = true *)
          injection eq as eqhead eqtail. rewrite <- eqhead.
          apply Heq.
        + (* test v' = false *)
          apply IHl' with lf. apply eq.  Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)

    Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:

      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (eqb 5) [] = true

    The second checks whether there exists an element in the list that
    satisfies a given predicate:

      existsb (eqb 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

      existsb evenb [] = false

    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

    Finally, prove a theorem [existsb_existsb'] stating that
    [existsb'] and [existsb] have the same behavior.
*)

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

Example test_forallb_1 : forallb oddb [1;3;5;7;9] = true.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_forallb_2 : forallb negb [false;false] = true.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_forallb_3 : forallb evenb [0;2;4;5] = false.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_forallb_4 : forallb (eqb 5) [] = true.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool
  (* SOLUTION: *) :=
  match l with
    | [] => false
    | x :: l' => orb (test x) (existsb test l')
  end.

Example test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Example test_existsb_4 : existsb evenb [] = false.
Proof. (* SOLUTION: *) reflexivity.  Qed.
Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool
  (* SOLUTION: *) :=
  negb (forallb (fun x => negb (test x)) l).

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof. (* SOLUTION: *)
  intros. unfold existsb'. induction l as [| x l' IHl'].
  - (* l = [] *)
    reflexivity.
  - (* l = x :: l' *)
    simpl.
    destruct (test x).
    + (* test x = true *)
      reflexivity.
    + (* test x = false *)
      simpl.
      rewrite -> IHl'.
      reflexivity.  Qed.

(** [] *)

(* 04 Mar 2020 *)


Require Export Basics.

Theorem plus_n_O : forall n :nat, n = plus n O.
induction n as [|m h].
Show Proof.
reflexivity.
Show Proof.
simpl. rewrite <- h. reflexivity.
Show Proof.
Qed.

Definition plus_n_O' : forall n : nat, n = plus n O :=
(fun n : nat => nat_ind
  (fun n0 : nat => n0 = plus n0 O)
  eq_refl
  (fun (m : nat) (h : m = plus m O) => eq_ind m
    (fun n0 : nat => S m = S n0)
    eq_refl
    (plus m O)
    h
  )
  n
)
.

Theorem minus_diag : forall n:nat, minus n n = O.
induction n as [|m h].
Show Proof.
reflexivity.
Show Proof.
simpl. assumption.
Show Proof.
Qed.

Definition minus_diag' : forall n:nat, minus n n = O :=
(fun n : nat =>
 nat_ind (fun n0 : nat => minus n0 n0 = O) eq_refl
   (fun (m : nat) (h : minus m m = O) => h) n).

Theorem plus_commute : forall n m : nat, (plus n m) = (plus m n).
induction n.
induction m.
reflexivity.
simpl. rewrite <- IHm. simpl. reflexivity.
induction m. simpl. rewrite IHn. simpl. reflexivity.
simpl. simpl in IHm. rewrite IHn. simpl.  rewrite <- IHm. rewrite <- IHn. reflexivity.
Show Proof.
Qed.

Theorem plus_rearrange : forall n m p q : nat, (plus (plus n m) (plus p q)) = (plus (plus m n) (plus p q)).
intros n m p q.
rewrite (plus_commute n m).
reflexivity.
Show Proof.
Qed.

Theorem plus_assoc : forall n m p : nat, (plus n (plus m p)) = (plus (plus n m) p).
induction n.
reflexivity.
intros m p.
simpl.
rewrite <- IHn.
reflexivity.
Show Proof.
Qed.

Theorem thm : forall n m : nat, n = plus n m -> m = O.
induction n.
intro m. intro h. simpl in h. symmetry. assumption.
intro m.
intro h.
apply IHn.
inversion h.
rewrite <- H0.
rewrite <- H0.
reflexivity.
Show Proof.
Qed.

Theorem thm' : forall a : bool, negb a = false -> a = true.
intros a h.
destruct a.
reflexivity.
simpl in h.
inversion h.
Show Proof.
Qed.

Theorem thma : forall n:nat, n=n.
reflexivity.
Show Proof.
Qed.

Theorem thmb : forall n m:nat, n=m -> (plus O n)=(plus O m).
intros n m heq.
rewrite heq.
reflexivity.
Show Proof.
(*
(fun (n m : nat) (heq : n = m) => eq_ind_r
  (fun n0 : nat => plus O n0 = plus O m)
  eq_refl
  heq
)
*)
Qed.

Theorem thmc : forall n m:nat, n=m -> (plus O n)=(plus O m).
intros n m heq.
apply heq.
Show Proof.
Qed.

Theorem thmd : forall n m:nat, n=m -> (plus O n)=(plus O m).
intros n m heq.
rewrite <- heq.
reflexivity.
Show Proof.
(*
(fun (n m : nat) (heq : n = m) => eq_ind
  n
  (fun m0 : nat => plus O n = plus O m0)
  eq_refl
  m
  heq)
*)
Qed.

Theorem thme : forall (n m: nat) (f:nat->nat), n=m -> f n = f m.
intros n m f heq.
rewrite heq.
reflexivity.
Show Proof.
(*
(fun (n m : nat) (f : nat -> nat) (heq : n = m) =>
 eq_ind_r (fun x : nat => f x = f m) eq_refl heq)
*)
Qed.

Print eq_ind_r.
(*
eq_ind_r = fun (A : Type) (x : A) (P : A -> Prop) (H : P x) (y : A) (H0 : y = x) =>
eq_ind x (fun y0 : A => P y0) H y (eq_sym H0) :
forall (A : Type) (x : A) (P : A -> Prop), P x -> forall y : A, y = x -> P y
*)

Print eq_ind.
(*
eq_ind = fun (A : Type) (x : A) (P : A -> Prop) => eq_rect x P :
forall (A : Type) (x : A) (P : A -> Prop), P x -> forall y : A, x = y -> P y
*)

Print eq_rect.
(*
eq_rect = fun (A : Type) (x : A) (P : A -> Type) (f : P x) (y : A) (e : x = y) =>
match e in (_ = y0) return (P y0) with
| eq_refl => f
end :
forall (A : Type) (x : A) (P : A -> Type),P x -> forall y : A, x = y -> P y
*)

Print eq_refl.

Theorem thmf :
forall (f : nat -> nat) (x:nat) (P:nat->Prop) (H:P x) (m:nat) (H0:m=x) (toto:P m),
P = (fun x : nat => f x = f m) ->
@eq_ind_r nat x P H m H0 = toto.
intros f x P H y H0 toto Ph.
unfold eq_ind_r.
unfold eq_ind.
unfold eq_rect.
subst P.
Admitted.


Welcome to Coq 8.4pl4 (November 2015)

Coq < Definition doit3times {X:Type} (f:X -> X) (n:X) : X := f (f (f n)).
doit3times is defined

Coq < Check @doit3times.
doit3times
     : forall X : Type, (X -> X) -> X -> X

Coq < Definition minustwo (n : nat) : nat := match n with | O => O | S O => O | S (S n') => n' end.
minustwo is defined

Coq < Example test_doit3times: doit3times minustwo 9 = 3.
1 subgoal

  ============================
   doit3times minustwo 9 = 3

test_doit3times < reflexivity.
No more subgoals.

test_doit3times < Qed.
reflexivity.

test_doit3times is defined

Coq < Definition negb (b:bool) : bool := match b with | true => false | false => true end.
negb is defined

Coq < Notation "x :: l" := (cons x l) (at level 60, right associativity).

Coq < Notation "[ ]" := nil.
Setting notation at level 0.

Coq < Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) ..).
Setting notation at level 0.

Coq < Fixpoint filter {X:Type} (test: X -> bool) (l:list X) : (list X) := match l with | [] => [] | h :: t => if test h then h :: (filter test t) else filter test t end.
filter is recursively defined (decreasing on 3rd argument)

Coq < Fixpoint evenb (n:nat) : bool := match n with | O => true | S O => false | S (S n') => evenb n' end.
evenb is recursively defined (decreasing on 1st argument)

Coq < Example test_filter1: filter evenb [1;2;3;4] = [2;4].
1 subgoal

  ============================
   filter evenb [1; 2; 3; 4] = [2; 4]

test_filter1 < Proof.
1 subgoal

  ============================
   filter evenb [1; 2; 3; 4] = [2; 4]

test_filter1 < reflexivity.
No more subgoals.

test_filter1 < Qed.
reflexivity.

test_filter1 is defined


From Coq Require Import
     List
     Logic.Decidable
     Relations.

Ltac symm_not :=
  let H := fresh
  in unfold not;
     intros H;
     symmetry in H;
     generalize dependent H.

Open Scope list_scope.

Section forall_dec.
  Context {A} (P : A -> Prop).

  Definition Forall_dec l :
    (forall a, decidable (P a)) ->
    decidable (Forall P l).
  Proof.
    intros Hdec.
    induction l.
    { left. constructor. }
    { destruct IHl as [Hl|Hl].
      - destruct (Hdec a).
        + left. constructor; auto.
        + right. intros H'.
          inversion H'. auto.
      - right. intros H.
        inversion H. auto.
    }
  Defined.
End forall_dec.


Require Import XR_Rsqr.
Require Import XR_Ropp_mult_distr_l.
Require Import XR_Ropp_mult_distr_r.
Require Import XR_Ropp_involutive.

Local Open Scope R_scope.

Lemma Rsqr_neg : forall x:R, Rsqr x = Rsqr (- x).
Proof.
  intro x.
  unfold Rsqr.
  rewrite <- Ropp_mult_distr_l.
  rewrite <- Ropp_mult_distr_r.
  rewrite Ropp_involutive.
  reflexivity.
Qed.


Require Import ZArith.
Require Import Nat_utils.

Lemma add_simpl (m n p : Z) :
  Z.add m p = Z.add n p -> m = n.
Proof.
  intro.
  rewrite <- Z.add_0_r with (n := m).
  rewrite <- Z.add_0_r with (n := n).
  rewrite <- Z.add_opp_diag_r with (n := p).
  rewrite Z.add_assoc with (n := m) (m := p) (p := Z.opp p).
  rewrite Z.add_assoc with (n := n) (m := p) (p := Z.opp p).
  rewrite H.
  reflexivity.
Qed.

Lemma excluded_middle_pos (p q : positive) :
  p = q \/ p <> q.
Proof.
  revert q.
  induction p.
  induction q.
  destruct IHp with (q := q).
  left.
  apply f_equal with (f := xI).
  assumption.
  right.
  injection.
  assumption.
  right.
  discriminate.
  right.
  discriminate.
  induction q.
  right.
  discriminate.
  destruct IHp with (q := q).
  left.
  apply f_equal with (f := xO).
  assumption.
  right.
  injection.
  assumption.
  right.
  discriminate.
  induction q.
  right.
  discriminate.
  right.
  discriminate.
  left.
  reflexivity.
Qed.

Lemma excluded_middle_z (z1 z2 : Z) :
  z1 = z2 \/ z1 <> z2.
Proof.
  revert z2.
  induction z1.
  induction z2.
  left.
  reflexivity.
  right.
  discriminate.
  right.
  discriminate.
  induction z2.
  right.
  discriminate.
  destruct excluded_middle_pos with (p := p) (q := p0).
  left.
  apply f_equal with (f := Z.pos).
  assumption.
  right.
  injection.
  assumption.
  right.
  discriminate.
  induction z2.
  right.
  discriminate.
  right.
  discriminate.
  destruct excluded_middle_pos with (p := p) (q := p0).
  left.
  apply f_equal with (f := Z.neg).
  assumption.
  right.
  injection.
  assumption.
Qed.

Lemma affine_not_constant (a b c : Z) :
  a <> Z.zero -> exists (x : Z), x <> Z.zero /\ (b + a * x)%Z <> c.
Proof.
  intro.
  destruct excluded_middle_z with (z1 := (b + a)%Z) (z2 := c).
  exists (2)%Z.
  split.
  discriminate.
  rewrite Z.two_succ.
  rewrite Z.mul_succ_r.
  rewrite Z.mul_1_r.
  rewrite Z.add_assoc.
  rewrite H0.
  intro.
  apply f_equal with (f := fun z => Z.sub z c) in H1.
  revert H1.
  rewrite Z.add_simpl_l.
  rewrite Z.sub_diag.
  assumption.
  exists Z.one.
  split.
  discriminate.
  rewrite Z.mul_1_r.
  assumption.
Qed.

Import Z.

Lemma z_lt_irrefl (z1 z2 : Z) :
  (z1 < z2)%Z -> z1 <> z2.
Proof.
  intro.
  intro.
  revert H.
  rewrite H0.
  apply Z.lt_irrefl.
Qed.

Lemma z_add_pos (z1 z2 : Z) :
  (0 < z1)%Z -> (0 < z2)%Z -> (0 < z1 + z2)%Z.
Proof.
  induction z1.
  intro.
  apply Z.lt_irrefl in H.
  contradiction.
  intro.
  induction z2.
  intro.
  apply Z.lt_irrefl in H0.
  contradiction.
  intro.
  apply Pos2Z.is_pos.
  intro.
  apply Z.lt_asymm in H0.
  exfalso.
  apply H0.
  apply Pos2Z.neg_is_neg.
  induction z2.
  intros.
  apply Z.lt_irrefl in H0.
  contradiction.
  intros.
  apply Z.lt_asymm in H.
  exfalso.
  apply H.
  apply Pos2Z.neg_is_neg.
  intro.
  apply Z.lt_asymm in H.
  exfalso.
  apply H.
  apply Pos2Z.neg_is_neg.
Qed.

Lemma z_mul_pos (z1 z2 : Z) :
  (0 < z1)%Z -> (0 < z2)%Z -> (0 < z1 * z2)%Z.
Proof.
  induction z1.
  intro.
  apply Z.lt_irrefl in H.
  contradiction.
  intro.
  induction z2.
  intro.
  apply Z.lt_irrefl in H0.
  contradiction.
  intro.
  apply Pos2Z.is_pos.
  intro.
  apply Z.lt_asymm in H0.
  exfalso.
  apply H0.
  apply Pos2Z.neg_is_neg.
  induction z2.
  intros.
  apply Z.lt_irrefl in H0.
  contradiction.
  intros.
  apply Z.lt_asymm in H.
  exfalso.
  apply H.
  apply Pos2Z.neg_is_neg.
  intros.
  apply Pos2Z.is_pos.
Qed.

Lemma z_mul_le_0 (z1 z2 : Z) :
  (0 <= z1)%Z -> (0 <= z2)%Z -> (0 <= z1 * z2)%Z.
Proof.
  induction z1.
  intros.
  rewrite Z.mul_0_l.
  apply Z.le_refl.
  intro.
  induction z2.
  intro.
  rewrite Z.mul_0_r.
  apply Z.le_refl.
  intro.
  apply Z.lt_le_incl.
  apply Pos2Z.is_pos.
  intro.
  apply Zle_not_lt in H0.
  exfalso.
  apply H0.
  apply Pos2Z.neg_is_neg.
  induction z2.
  intros.
  rewrite Z.mul_0_r.
  apply Z.le_refl.
  intros.
  apply Zle_not_lt in H.
  exfalso.
  apply H.
  apply Pos2Z.neg_is_neg.
  intros.
  apply Pos2Z.is_nonneg.
Qed.

Lemma z_pos_ge_1 (z : Z) :
  (0 < z)%Z -> (1 <= z)%Z.
Proof.
  elim z.
  intro.
  exfalso.
  apply Z.lt_irrefl with (x := 0%Z).
  assumption.
  intros.
  apply Pos.le_1_l.
  intros.
  apply Z.lt_asymm in H.
  exfalso.
  apply H.
  apply Pos2Z.neg_is_neg.
Qed.

Lemma z_pos_pos_mul (z1 z2 : Z) :
  (0 < z1)%Z -> (0 < z2)%Z -> (z1 <= z1 * z2)%Z.
Proof.
  intros.
  rewrite <- Z.add_simpl_r with (n := (z1 * z2)%Z) (m := z1).
  rewrite <- Z.add_opp_r.
  rewrite <- Z.add_assoc.
  rewrite <- Z.add_comm with (m := z1) (n := (-z1)%Z).
  rewrite Z.add_assoc.
  rewrite <- Z.mul_1_r with (n := (-z1)%Z).
  rewrite <- Zopp_mult_distr_l with (n := z1) (m := 1%Z).
  rewrite Zopp_mult_distr_r with (n := z1) (m := 1%Z).
  rewrite <- Z.mul_add_distr_l.
  rewrite Z.add_opp_r.
  apply Zplus_le_reg_r with (p := (-z1)%Z).
  rewrite <- Z.add_assoc.
  rewrite Z.add_opp_diag_r with (n := z1).
  rewrite Z.add_0_r.
  apply z_mul_le_0.
  apply Z.lt_le_incl.
  assumption.
  apply Zplus_le_reg_r with (p := 1%Z).
  rewrite Z.add_0_l.
  rewrite <- Z.add_opp_r.
  rewrite <- Z.add_assoc.
  rewrite Z.add_opp_diag_l.
  rewrite Z.add_0_r.
  apply z_pos_ge_1.
  assumption.
Qed.

Lemma pos_plus_neg (z : Z) (p : positive) :
  (z * pos p + z * neg p)%Z = 0%Z.
Proof.
  rewrite <- Z.mul_add_distr_l.
  simpl.
  rewrite pos_sub_diag.
  apply Z.mul_0_r.
Qed.

Lemma z_abs_lt (z1 z2 z3 : Z) :
  (Z.abs z1 < z2)%Z -> z3 <> 0%Z -> (z1 + z2 * z3)%Z <> 0%Z.
Proof.
  elim z1.
  intros.
  intro.
  apply z_integrity in H1.
  destruct H1.
  rewrite H1 in H.
  apply Z.lt_irrefl with (x := 0%Z).
  assumption.
  apply H0.
  assumption.

  elim z3.
  intros.
  exfalso.
  apply H0.
  reflexivity.

  intros.
  intro.
  symmetry in H1.
  revert H1.
  apply z_lt_irrefl with (z1 := 0%Z) (z2 := (pos p0 + z2 * pos p)%Z).
  apply z_add_pos.
  apply Pos2Z.is_pos.
  apply z_mul_pos.
  apply Z.lt_trans with (m := Z.pos p0).
  apply Pos2Z.is_pos.
  assumption.
  apply Pos2Z.is_pos.

  intros.
  apply z_lt_irrefl with (z2 := 0%Z) (z1 := (pos p0 + z2 * neg p)%Z).
  rewrite <- pos_plus_neg with (z := z2) (p := p).
  apply Zplus_lt_compat_r with (n := Z.pos p0) (m := (z2 * pos p)%Z) (p := (z2 * neg p)%Z).
  apply Z.lt_le_trans with (m := z2).
  assumption.
  apply z_pos_pos_mul.
  apply Z.lt_trans with (m := Z.pos p0).
  apply Pos2Z.is_pos.
  assumption.
  apply Pos2Z.is_pos.

  elim z3.
  intros.
  exfalso.
  apply H0.
  reflexivity.

  intros.
  intro.
  symmetry in H1.
  revert H1.
  apply z_lt_irrefl with (z1 := 0%Z) (z2 := (neg p0 + z2 * pos p)%Z).
  rewrite <- pos_plus_neg with (z := z2) (p := p).
  rewrite add_comm.
  apply Zplus_lt_compat_r with (m := Z.neg p0) (n := (z2 * neg p)%Z) (p := (z2 * pos p)%Z).
  rewrite <- Pos2Z.opp_pos.
  rewrite <- Pos2Z.opp_pos.
  rewrite <- Zopp_mult_distr_r with (n := z2) (m := Z.pos p).
  apply Z.opp_lt_mono with (m := (z2 * pos p)%Z) (n := Z.pos p0).
  apply Z.lt_le_trans with (m := z2).
  assumption.
  apply z_pos_pos_mul.
  apply Z.lt_trans with (m := Z.pos p0).
  apply Pos2Z.is_pos.
  assumption.
  apply Pos2Z.is_pos.

  intros.
  apply z_lt_irrefl with (z1 := (neg p0 + z2 * neg p)%Z) (z2 := 0%Z).
  rewrite <- Pos2Z.opp_pos.
  rewrite <- Pos2Z.opp_pos.
  rewrite <- Zopp_mult_distr_r with (n := z2) (m := Z.pos p).
  rewrite <- Z.opp_add_distr.
  apply Z.opp_lt_mono with (m := (pos p0 + z2 * pos p)%Z) (n := 0%Z).
  apply z_add_pos.
  apply Pos2Z.is_pos.
  apply z_mul_pos.
  apply Z.lt_trans with (m := Z.pos p0).
  apply Pos2Z.is_pos.
  assumption.
  apply Pos2Z.is_pos.
Qed.


(** * Tactics: More Basic Tactics *)

(* Suppress some annoying warnings from Coq: *)
Set Warnings "-notation-overridden,-parsing".
From COC Require Export Poly.

(* ################################################################# *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    _exactly_ the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.

(** Here, we could finish with "[rewrite -> eq2.  reflexivity.]" as we
    have done several times before.  We can finish this proof in
    a single step by using the [apply] tactic instead: *)

  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
    n = m ->
    (n = m -> [n;o] = [m;p]) ->
    [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that introduces some _universally quantified
    variables_.  When Coq matches the current goal against the
    conclusion of [H], it will try to find appropriate values for
    these variables.  For example, when we do [apply eq2] in the
    following proof, the universal variable [q] in [eq2] gets
    instantiated with [n], and [r] gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.
Qed.

(** **** Exercise: 2 stars, standard, optional (silly_ex)

    Complete the following proof using only [intros] and [apply]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 2 = true ->
     oddb 3 = true.
Proof.
  intros n eq1.
  apply eq1.
Qed.

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal exactly -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat), true = (n =? 5)  ->
     (S (S n)) =? 7 = true.
Proof.
  intros n H.

(** Here we cannot use [apply] directly, but we can use the [symmetry]
    tactic, which switches the left and right sides of an equality in
    the goal. *)

  symmetry.
  simpl. (** (This [simpl] is optional, since [apply] will perform
             simplification first, if needed.) *)
  apply H.
Qed.

(** **** Exercise: 3 stars, standard (apply_exercise1)

    _Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  You may find earlier lemmas like
    [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],
    etc. helpful.  Also, remember that [Search] is your friend
    (though it may not find earlier lemmas if they were posed as
    optional problems and you chose not to finish the proofs). *)

Theorem rev_exercise1 : forall (l l' : list nat), l = rev l' ->
     l' = rev l.
Proof.
  intros l l' H.
  rewrite -> H.
  symmetry.
  apply rev_involutive.
Qed.

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied? *)

(* When we need to use global variables, "apply" is better than "rewrite". *)

(* ################################################################# *)
(** * The [apply with] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a;b]] to [[e;f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.
Qed.

(** Since this is a common pattern, we might like to pull it out as a
    lemma that records, once and for all, the fact that equality is
    transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2.
  rewrite -> eq1. rewrite -> eq2.
  reflexivity.
Qed.

(** Now, we should be able to use [trans_eq] to prove the above
    example.  However, to do this we need a slight refinement of the
    [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.

(** If we simply tell Coq [apply trans_eq] at this point, it can
    tell (by matching the goal against the conclusion of the lemma)
    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
    [o] with [[e,f]].  However, the matching process doesn't determine
    an instantiation for [m]: we have to supply one explicitly by
    adding "[with (m:=[c,d])]" to the invocation of [apply]. *)
  apply trans_eq with (m:=[c;d]).
  apply eq1. apply eq2.
Qed.

(** (Actually, we usually don't have to include the name [m] in
    the [with] clause; Coq is often smart enough to figure out which
    variable we are instantiating. We could instead write [apply
    trans_eq with [c;d]].) *)

(** Coq also has a tactic [transitivity] that accomplishes the
    same purpose as applying [trans_eq]. The tactic requires us to
    state the instantiation we want, just like [apply with] does. *)

Example trans_eq_example'' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  transitivity [c;d].
  apply eq1. apply eq2.
Qed.

(** **** Exercise: 3 stars, standard, optional (trans_eq_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros n m o p H1 H2.
  transitivity m.
  apply H2.
  apply H1.
Qed.

(* ################################################################# *)
(** * The [injection] and [discriminate] Tactics *)

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O
       | S (n : nat).

    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition are two more
    facts:

    - The constructor [S] is _injective_, or _one-to-one_.  That is,
      if [S n = S m], it must be that [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n]. *)

(** Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since [true] and
    [false] take no arguments, their injectivity is neither here
    nor there.)  And so on. *)

(** For example, we can prove the injectivity of [S] by using the
    [pred] function defined in [Basics.v]. *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  (* insert new hypothesis H2 *)
  assert (H2: n = pred (S n)). { reflexivity. }
  (* prove H1 *)
  rewrite H2.
  rewrite H1.
  reflexivity.
Qed.

(** This technique can be generalized to any constructor by
    writing the equivalent of [pred] -- i.e., writing a function that
    "undoes" one application of the constructor. As a more convenient
    alternative, Coq provides a tactic called [injection] that allows
    us to exploit the injectivity of any constructor.  Here is an
    alternate proof of the above theorem using [injection]: *)

Theorem S_injective' : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [injection H as Hmn] at this point, we are asking Coq
    to generate all equations that it can infer from [H] using the
    injectivity of constructors (in the present example, the equation
    [n = m]). Each such equation is added as a hypothesis (with the
    name [Hmn] in this case) into the context. *)

  injection H as Hnm. apply Hnm.
Qed.

(** Here's a more interesting example that shows how [injection] can
    derive multiple equations at once. *)

Theorem injection_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H as H1 H2.
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** Alternatively, if you just say [injection H] with no [as] clause,
    then all the equations will be turned into hypotheses at the
    beginning of the goal. *)

Theorem injection_ex2 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H.
  intros H1 H2. rewrite H1. rewrite H2. reflexivity.
Qed.

(** **** Exercise: 3 stars, standard (injection_ex3)  *)
Example injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  intros X x y z l j H1 H2.
  injection H1. rewrite -> H2.
  (* insert new hypothesis H3 *)
Admitted.

(** So much for injectivity of constructors.  What about disjointness?

    The principle of disjointness says that two terms beginning with
    different constructors (like [O] and [S], or [true] and [false])
    can never be equal.  This means that, any time we find ourselves
    in a context where we've _assumed_ that two such terms are equal,
    we are justified in concluding anything we want, since the
    assumption is nonsensical. *)

(** The [discriminate] tactic embodies this principle: It is used on a
    hypothesis involving an equality between different
    constructors (e.g., [S n = O]), and it solves the current goal
    immediately.  Here is an example: *)

Theorem eqb_0_l : forall n,
  0 =? n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'] eqn:E.
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming [0
    =? (S n') = true], we must show [S n' = 0]!  The way forward is to
    observe that the assumption itself is nonsensical: *)

  - (* n = S n' *)
    simpl.

(** If we use [discriminate] on this hypothesis, Coq confirms
    that the subgoal we are working on is impossible and removes it
    from further consideration. *)

    intros H. discriminate H.
Qed.

(** This is an instance of a logical principle known as the _principle
    of explosion_, which asserts that a contradictory hypothesis
    entails anything (even false things!). *)

Theorem discriminate_ex1 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. discriminate contra. Qed.

Theorem discriminate_ex2 : forall (n m : nat),
  false = true ->
  [n] = [m].
Proof.
  intros n m contra. discriminate contra. Qed.

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, _if_ the
    nonsensical situation described by the premise did somehow arise,
    _then_ the nonsensical conclusion would also follow, because we'd
    be living in an inconsistent universe where every statement is
    true.  We'll explore the principle of explosion in more detail in
    the next chapter. *)

(** **** Exercise: 1 star, standard (discriminate_ex3)  *)
Example discriminate_ex3 :
  forall (X : Type) (x y z : X) (l j : list X),
    x :: y :: l = [] ->
    x = z.
Proof.
  intros X x y z l j contra.
  discriminate contra.
Qed.

(** To summarize this discussion, suppose [H] is a hypothesis in the
    context or a previously proven lemma of the form
      c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] has the following effect:
    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know that [a1 = b1], [a2 =
      b2], etc.; [inversion H] adds these facts to the context, and
      tries to use them to rewrite the goal.
    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory, and the current goal doesn't have to be
      considered. In this case, [inversion H] marks the current goal
      as completed and pops it off the goal stack. *)

(** The injectivity of constructors allows us to reason that
    [forall (n m : nat), S n = S m -> n = m].  The converse of this
    implication is an instance of a more general fact about both
    constructors and functions, which we will find convenient in a few
    places below: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof.
  intros A B f x y H.
  rewrite H.
  reflexivity.
Qed.

Theorem eq_implies_succ_equal : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. apply f_equal. apply H. Qed.

(** There is also a tactic named `f_equal` that can prove such
    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],
    the tactic [f_equal] will produce subgoals of the form [f = g],
    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals
    that are simple enough (e.g., immediately provable by
    [reflexivity]) will be automatically discharged by [f_equal]. *)

Theorem eq_implies_succ_equal' : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. f_equal. apply H. Qed.

(* ################################################################# *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic "[simpl in H]" performs simplification on
    the hypothesis [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     (S n) =? (S m) = b  ->
     n =? m = b.
Proof.
  intros n m b H. simpl in H. apply H.
Qed.

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [X -> Y], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [Y] into a subgoal [X]), [apply L in H] matches [H]
    against [X] and, if successful, replaces it with [Y].

    In other words, [apply L in H] gives us a form of "forward
    reasoning": from [X -> Y] and a hypothesis matching [X], it
    produces a hypothesis matching [Y].  By contrast, [apply L] is
    "backward reasoning": it says that if we know [X -> Y] and we
    are trying to prove [Y], it suffices to prove [X].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly3' : forall (n : nat),
  (n =? 5 = true -> (S (S n)) =? 7 = true) ->
  true = (n =? 5)  ->
  true = ((S (S n)) =? 7).
Proof.
  intros n eq H.
  symmetry in H. apply eq in H. symmetry in H. apply H.
Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_ and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.

    The informal proofs that you've seen in math or computer science
    classes probably tended to use forward reasoning.  In general,
    idiomatic use of Coq favors backward reasoning, but in some
    situations the forward style can be easier to think about. *)

(* ################################################################# *)
(** * Varying the Induction Hypothesis *)

(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we sometimes need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that [double] is injective -- i.e., that it maps
    different arguments to different results:

       Theorem double_injective: forall n m,
         double n = double m -> n = m.

    The way we start this proof is a bit delicate: if we begin it with

       intros n. induction n.

    all is well.  But if we begin it with

       intros n m. induction n.

    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n' IHn'].
  - (* n = O *)
  simpl. intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *)
    reflexivity.
    + (* m = S m' *)
    discriminate eq.
  - (* n = S n' *)
  intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *)
    discriminate eq.
    + (* m = S m' *)
    apply f_equal.

(** At this point, the induction hypothesis ([IHn']) does _not_ give us
    [n' = m'] -- there is an extra [S] in the way -- so the goal is
    not provable. *)

Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _those particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition

      - [P n] = "if [double n = double m], then [n = m]"

    holds, by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]") and

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular (arbitrary,
    but fixed) [m] -- say, [5].  The statement is then saying that,
    if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help at all with proving
    [R]!  If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing
    helpful about whether [double n] is [10] (indeed, it strongly
    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)

(** Trying to carry out this proof by induction on [n] when [m] is
    already in the context doesn't work because we are then trying to
    prove a statement involving _every_ [n] but just a _single_ [m]. *)

(** A successful proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.

  - (* n = S n' *) simpl.

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., to prove the statement for _every_ [m]), but the IH
    is correspondingly more flexible, allowing us to choose whichever
    [m] we like when we apply the IH. *)

    intros m eq.

(** Now we've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'] eqn:E.
    + (* m = O *)

(** The 0 case is trivial: *)

    discriminate eq.
    + (* m = S m' *)
      apply f_equal.

(** At this point, since we are in the second branch of the [destruct
    m], the [m'] mentioned in the context is the predecessor of the
    [m] we started out talking about.  Since we are also in the [S]
    branch of the induction, this is perfect: if we instantiate the
    generic [m] in the IH with the current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.

(** What you should take away from all this is that we need to be
    careful, when using induction, that we are not trying to prove
    something too specific: When proving a property involving two
    variables [n] and [m] by induction on [n], it is sometimes
    crucial to leave [m] generic. *)

(** The following exercise follows the same pattern. *)

(** **** Exercise: 2 stars, standard (eqb_true)  *)
Theorem eqb_true : forall n m,
    n =? m = true -> n = m.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = O *)
    intros m eq. destruct m as [| m'] eqn:E.
    + (* m = O *) simpl. reflexivity.
    + (* m = S m' *) discriminate eq.
  - (* n = S n' *)
     intros m eq.  destruct m as [| m'] eqn:E.
    + (* m = O *)  discriminate eq.
    + (* m = S m' *) apply f_equal. apply IHn'.
    simpl in eq. apply eq.
Qed.

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    some _rearrangement_ of quantified variables is needed.  Suppose,
    for example, that we wanted to prove [double_injective] by
    induction on [m] instead of [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m' IHm'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (And if we simply say [induction m] without
    introducing anything first, Coq will automatically introduce [n]
    for us!)  *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables out of the context and putting them
    back at the beginning of the goal.  The [generalize dependent]
    tactic does this. *)

Theorem double_injective_take2 : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m' IHm'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. injection eq as goal. apply goal.
Qed.

(* ################################################################# *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a name that
    has been introduced by a [Definition] so that we can manipulate
    the expression it denotes.  For example, if we define... *)

Definition square n := n * n.

(** ... and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we appear to be stuck: [simpl] doesn't simplify anything, and
    since we haven't proved any other facts about [square], there is
    nothing we can [apply] or [rewrite] with. *)

(**  To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these it is not hard
    to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
    { rewrite mult_comm. apply mult_assoc. }
  rewrite -> H. rewrite -> mult_assoc. reflexivity.
Qed.

(** At this point, some discussion of unfolding and simplification is
    in order.

    We already have observed that tactics like [simpl], [reflexivity],
    and [apply] will often unfold the definitions of functions
    automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

(** .... then the [simpl] in the following proof (or the
    [reflexivity], if we omit the [simpl]) will unfold [foo m] to
    [(fun x => 5) m] and then further simplify this expression to just
    [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** However, this automatic unfolding is somewhat conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  It is not smart enough to notice that the
    two branches of the [match] are identical, so it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that cannot itself be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone. *)

(** At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m eqn:E.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress. *)

(** A more straightforward way forward is to explicitly tell Coq to
    unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m eqn:E.
  - reflexivity.
  - reflexivity.
Qed.

(* ################################################################# *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  Sometimes we
    need to reason by cases on the result of some _expression_.  We
    can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if n =? 3 then false
  else if n =? 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (n =? 3) eqn:E1.
    - (* n =? 3 = true *) reflexivity.
    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.
      + (* n =? 5 = true *) reflexivity.
      + (* n =? 5 = false *) reflexivity.
Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (n =? 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (eqb
    n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c]. *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y l l1 l2 H. generalize dependent l. generalize l1.
  induction l2 as [| h2 l2'].
  - intros l0 l. generalize dependent l0. induction l as [|h l'].
    + intros l0 H. assert (l0 = []). { inversion H. reflexivity. } rewrite H0. reflexivity.
    + intros l0 H. inversion H. unfold app_list_pair in H1. Abort.

(** The [eqn:] part of the [destruct] tactic is optional: So far,
    we've chosen to include it most of the time, just for the sake of
    documentation.

    However, when [destruct]ing compound expressions, the information
    recorded by the [eqn:] can actually be critical: if we leave it
    out, then [destruct] can erase information we need to complete a
    proof.

    For example, suppose we define a function [sillyfun1] like
    this: *)

Definition sillyfun1 (n : nat) : bool :=
  if n =? 3 then true
  else if n =? 5 then true
  else false.

(** Now suppose that we want to convince Coq that [sillyfun1 n]
    yields [true] only when [n] is odd.  If we start the proof like
    this (with no [eqn:] on the [destruct])... *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3).
  (* stuck... *)
Abort.

(** ... then we are stuck at this point because the context does
    not contain enough information to prove the goal!  The problem is
    that the substitution performed by [destruct] is quite brutal --
    in this case, it throws away every occurrence of [n =? 3], but we
    need to keep some memory of this expression and how it was
    destructed, because we need to be able to reason that, since [n =?
    3 = true] in this branch of the case analysis, it must be that [n
    = 3], from which it follows that [n] is odd.

    What we want here is to substitute away all existing occurences of
    [n =? 3], but at the same time add an equation to the context that
    records which case we are in.  This is precisely what the [eqn:]
    qualifier does. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply eqb_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (* When we come to the second equality test in the body
        of the function we are reasoning about, we can use
        [eqn:] again in the same way, allowing us to finish the
        proof. *)
      destruct (n =? 5) eqn:Heqe5.
        + (* e5 = true *)
          apply eqb_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) discriminate eq.
Qed.