(** * 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,-deprecated-hint-without-locality".
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 : nat),
  n = m ->
  n = m.
Proof.
  intros n m eq.

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

  apply eq.  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 p,
  (forall n, even n = true -> even (S n) = false) ->
  (forall n, even n = false -> odd n = true) ->
  even p = true ->
  odd (S p) = true.
Proof.
  intros eq1 eq2 eq3 eq4.
  apply eq3.
  apply eq2.
  apply eq4.
  Qed.
(** [] *)

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

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

  (** Here we cannot use [apply] directly... *)

  Fail apply H.

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

  symmetry. apply H.  Qed.

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

    You can use [apply] with previously defined theorems, not
    just hypotheses in the context.  Use [Search] to find a
    previously-defined theorem about [rev] from [Lists].  Use
    that theorem as part of your (relatively short) solution to this
    exercise. You do not need [induction]. *)

Theorem rev_exercise1 : forall (l l' : list nat),
  l = rev l' ->
  l' = rev l.
Proof.
  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? *)

(** - [apply] cannot be applied instead of [rewrite <- H],
      I should use [symmetry] before.
    - [apply] automatically solves a goal.
    - [apply] can work with conditional hypotheses. *)
(** [] *)

(* ################################################################# *)
(** * 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, the name [m] in the [with] clause is not required,
    since Coq is often smart enough to figure out which variable we
    are instantiating. We could instead simply write [apply trans_eq
    with [c;d]]. *)

(** Coq also has a built-in 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 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
    additional 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 every inductively defined type:
    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. *)

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

(** **** 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 eq1 eq2.
  injection eq1 as H G.
  rewrite eq2 in G.
  injection G as G.
  rewrite H. rewrite G.
  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., [false = true]), and it solves the current
    goal immediately.  Some examples: *)

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

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

(** These examples are instances of a logical principle known as the
    _principle of explosion_, which asserts that a contradictory
    hypothesis entails anything (even manifestly false things!). *)

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

(** For a slightly more involved example, we can use [discriminate] to
    make a connection between the two different notions of
    equality ([=] and [=?]) on natural numbers. *)
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.

(** 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 directly.  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": given [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 silly4 : forall (n m p q : nat),
  (n = m -> p = q) ->
  m = n ->
  q = p.
Proof.
  intros n m p q 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 seen in math or computer science classes tend
    to use forward reasoning.  By contrast, idiomatic use of Coq
    generally favors backward reasoning, though 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.

    then all is well.  But if we begin it with introducing both variables

       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 _these 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 [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] universally
    quantified 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' *)

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., we must prove the statement for _every_ [m]), but
    the IH is correspondingly more flexible, allowing us to choose any
    [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.

(** The thing to take away from all this is that you need to be
    careful, when using induction, that you 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, which further strengthens the link between
    [=?] and [=], 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 *)
    destruct m.
    + reflexivity.
    + intros contra. discriminate contra.
  - (* n = S n' *)
    destruct m.
    + intros contra. discriminate contra.
    + intros H. apply IHn' in H.
      rewrite -> H. reflexivity.
Qed.
(** [] *)

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

    Give a careful informal proof of [eqb_true], stating the induction
    hypothesis explicitly and being as explicit as possible about
    quantifiers, everywhere. *)

(* FILL IN HERE *)

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

(** **** Exercise: 3 stars, standard, especially useful (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.
  intros n. induction n as [| n'].
  - (* n = 0 *)
    destruct m.
    + reflexivity.
    + intros contra.
      discriminate contra.
  - (* n = S n' *)
    destruct m.
    + intros contra. discriminate contra.
    + intros H.
      rewrite <- plus_n_Sm in H.
      rewrite <- plus_n_Sm in H.
      injection H as H1.
      apply IHn' in H1.
      rewrite <- H1.
      reflexivity.
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.
        (* We are stuck 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, especially useful (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.
  intros n X l.
  generalize dependent n.
  induction l as [| x l'].
  - reflexivity.
  - destruct n.
    + intros contra. discriminate contra.
    + intros H. injection H as H1. simpl. apply IHl' in H1. apply H1.
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 mul_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, some deeper 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.

(** But 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.
  intros X Y l.
  induction l.
  - intros l1 l2 H. simpl in H. injection H as H. rewrite <- H. rewrite <- H0. reflexivity.
  - destruct x as (x, y).
    destruct l1 as [| x'].
    + intros l2 H. simpl in H. destruct (split l) in H. discriminate H.
    + destruct l2 as [| y'].
      * intros H. simpl in H. destruct (split l) in H. discriminate H.
      * intros H.
        simpl.
        assert (G: split l = (l1, l2)). {
          simpl in H. destruct (split l).
          injection H as H. rewrite -> H0. rewrite -> H2. reflexivity.
        }
        apply IHl in G.
        simpl in H. destruct (split l) in H. injection H as H.
        rewrite -> G. rewrite <- H. rewrite <- H1. reflexivity.
Qed.
(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional; although
    we've chosen to include it most of the time, for the sake of
    documentation, it can often be omitted without harm.

    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 ->
  odd 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 occurrences 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 ->
  odd 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.
  intros f b.
  destruct b.
  + destruct (f true) eqn:T.
    - rewrite -> T. rewrite -> T. reflexivity.
    - destruct (f false) eqn:F.
      * rewrite -> T. reflexivity.
      * rewrite -> F. reflexivity.
  + destruct (f false) eqn:F.
    - destruct (f true) eqn:T.
      * rewrite -> T. reflexivity.
      * rewrite -> F. reflexivity.
    - rewrite -> F. rewrite -> F. reflexivity.
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... as...]: 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.
  intros n m.
  destruct (n =? m) eqn:E.
  + (* true *)
    symmetry. apply eqb_true in E. rewrite -> E. apply eqb_refl.
  + (* false *)
    generalize dependent m.
    induction n.
    - destruct m.
      * intros E. discriminate E.
      * reflexivity.
    - destruct m.
      * reflexivity.
      * intros E. simpl in E. apply IHn in E. simpl. rewrite <- E. reflexivity.
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: *)
   (* FILL IN HERE

    [] *)

(** **** Exercise: 3 stars, standard, optional (eqb_trans) *)
Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  intros n m p eq1 eq2.
  apply eqb_true in eq1. apply eqb_true in eq2.
  rewrite -> eq1. rewrite <- eq2.
  apply eqb_refl.
Qed.
(** [] *)

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

    We proved, in an exercise above, that [combine] is the inverse of
    [split].  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.

    Hint: Take a look at the definition of [combine] in [Poly].
    Your property will need to account for the behavior of [combine]
    in its base cases, which possibly drop some list elements. *)

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

Theorem split_combine : split_combine_statement.
Proof.
  intros X Y.
  induction l1 as [| x].
  + intros l2 H.
    destruct l2 as [| y].
    - reflexivity.
    - discriminate H.
  + intros l2 H. destruct l2 as [| y].
    - discriminate H.
    - injection H as H. apply IHl1 in H.
      simpl. rewrite -> H.
      reflexivity.
Qed.

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

(** **** Exercise: 3 stars, advanced (filter_exercise) *)
Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                                 (x : X) (l lf : list X),
  filter test l = x :: lf ->
  test x = true.
Proof.
  intros X test x l lf.
  destruct l as [| x'].
  + simpl. intros H. discriminate H.
  + induction (x' :: l).
    - simpl. intros H. discriminate H.
    - simpl. destruct (test x0) eqn:T.
      * intros H. injection H as H. rewrite -> H in T. apply T.
      * apply IHl0.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced, especially useful (forall_exists_challenge)

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

      forallb odd [1;3;5;7;9] = true
      forallb negb [false;false] = true
      forallb even [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 odd [1;0;0;0;0;3] = true
      existsb even [] = 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
  := match l with
     | [] => true
     | x :: l' => if test x then forallb test l' else false
     end.

Example test_forallb_1 : forallb odd [1;3;5;7;9] = true.
Proof. reflexivity. Qed.

Example test_forallb_2 : forallb negb [false;false] = true.
Proof. reflexivity. Qed.

Example test_forallb_3 : forallb even [0;2;4;5] = false.
Proof. reflexivity. Qed.

Example test_forallb_4 : forallb (eqb 5) [] = true.
Proof. reflexivity. Qed.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool
  := match l with
     | [] => false
     | x :: l' => if test x then true else existsb test l'
     end.

Example test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.
Proof. reflexivity. Qed.

Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. reflexivity. Qed.

Example test_existsb_3 : existsb odd [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.

Example test_existsb_4 : existsb even [] = false.
Proof. reflexivity. Qed.

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool
  := 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. intros X test.
  induction l.
  + reflexivity.
  + simpl.
    unfold existsb'.
    destruct (test x) eqn:T.
    - simpl. rewrite -> T. reflexivity.
    - simpl. rewrite -> T. rewrite -> IHl. reflexivity.
Qed.

(** [] *)

(* 2022-08-08 17:13 *)


From Hammer Require Import Hammer.

From Topology Require Export Subbases.
From ZornsLemma Require Export Relation_Definitions_Implicit.
From Topology Require Export SeparatednessAxioms.

Section OrderTopology.

Variable X:Type.
Variable R:relation X.
Hypothesis R_ord: order R.

Inductive order_topology_subbasis : Family X :=
| intro_lower_interval: forall x:X,
In order_topology_subbasis [ y:X | R y x /\ y <> x ]
| intro_upper_interval: forall x:X,
In order_topology_subbasis [ y:X | R x y /\ y <> x].

Definition OrderTopology : TopologicalSpace :=
Build_TopologicalSpace_from_subbasis X order_topology_subbasis.

Section if_total_order.

Hypothesis R_total: forall x y:X, R x y \/ R y x.

Lemma lower_closed_interval_closed: forall x:X,
closed [ y:X | R y x ] (X:=OrderTopology).
Proof. hammer_hook "OrderTopology" "OrderTopology.lower_closed_interval_closed".
intro.
red.
match goal with |- open ?U => cut (U = interior U) end.
intro.
rewrite H; apply interior_open.
apply Extensionality_Ensembles; split.
2:apply interior_deflationary.
intros y ?.
red in H.
red in H.
assert (R x y).
destruct (R_total x y); trivial.
contradiction H.
constructor; trivial.
exists ([z:X | R x z /\ z <> x]).
constructor; split.
apply (Build_TopologicalSpace_from_subbasis_subbasis
_ order_topology_subbasis).
constructor.
red; intros z ?.
destruct H1.
destruct H1.
intro.
destruct H3.
contradiction H2.
apply (ord_antisym R_ord); trivial.
constructor.
split; trivial.
intro.
contradiction H.
constructor.
destruct H1; apply (ord_refl R_ord).
Qed.

Lemma upper_closed_interval_closed: forall x:X,
closed [y:X | R x y] (X:=OrderTopology).
Proof. hammer_hook "OrderTopology" "OrderTopology.upper_closed_interval_closed".
intro.
red.
match goal with |- open ?U => cut (U = interior U) end.
intro.
rewrite H; apply interior_open.
apply Extensionality_Ensembles; split.
2:apply interior_deflationary.
intros y ?.
red in H.
red in H.
assert (R y x).
destruct (R_total x y); trivial.
contradiction H.
constructor; trivial.
exists ([z:X | R z x /\ z <> x]).
constructor; split.
apply (Build_TopologicalSpace_from_subbasis_subbasis
_ order_topology_subbasis).
constructor.
red; intros z ?.
destruct H1.
destruct H1.
intro.
destruct H3.
contradiction H2.
apply (ord_antisym R_ord); trivial.
constructor.
split; trivial.
intro.
contradiction H.
constructor.
destruct H1; apply (ord_refl R_ord).
Qed.

Lemma order_topology_Hausdorff: Hausdorff OrderTopology.
Proof. hammer_hook "OrderTopology" "OrderTopology.order_topology_Hausdorff".
red.
match goal with |- forall x y:point_set OrderTopology, ?P =>
cut (forall x y:point_set OrderTopology, R x y -> P)
end.
intros.
destruct (R_total x y).
exact (H x y H1 H0).
assert (y <> x).
auto.
destruct (H y x H1 H2) as [V [U [? [? [? []]]]]].
exists U; exists V; repeat split; trivial.
transitivity (Intersection V U); trivial.
apply Extensionality_Ensembles; split; red; intros.
destruct H8; constructor; trivial.
destruct H8; constructor; trivial.

intros.
pose proof (Build_TopologicalSpace_from_subbasis_subbasis
_ order_topology_subbasis).
destruct (classic (exists z:X, R x z /\ R z y /\ z <> x /\ z <> y)).
destruct H2 as [z [? [? []]]].
exists ([w:X | R w z /\ w <> z]);
exists ([w:X | R z w /\ w <> z]).
repeat split; trivial.
apply H1.
constructor.
apply H1.
constructor.
auto.
auto.
apply Extensionality_Ensembles; split; red; intros.
destruct H6.
destruct H6.
destruct H7.
destruct H6.
destruct H7.
contradiction H8.
apply (ord_antisym R_ord); trivial.
destruct H6.

exists ([w:X | R w y /\ w <> y]);
exists ([w:X | R x w /\ w <> x]).
repeat split.
apply H1.
constructor.
apply H1.
constructor.
trivial.
trivial.
trivial.
auto.
apply Extensionality_Ensembles; split; red; intros.
destruct H3.
destruct H3.
destruct H4.
destruct H3.
destruct H4.
contradiction H2.
exists x0; repeat split; trivial.
destruct H3.
Qed.

End if_total_order.

End OrderTopology.

Arguments OrderTopology {X}.


Require Import Iron.Language.Simple.Step.
Require Import Iron.Language.Simple.SubstExpExp.
Require Import Iron.Language.Simple.Ty.

(* If a closed, well typed expression takes an evaluation step
   then the result has the same type as before. *)
Theorem preservation
 :  forall x x' t
 ,  TYPE nil x  t
 -> STEP x x'
 -> TYPE nil x' t.
Proof.
 intros x x' t HT HS. gen t.
 induction HS; rip.

 Case "EsContext".
  destruct H; inverts_type; burn.

 Case "EsLamApp".
  inverts_type.
  burn using subst_exp_exp.
Qed.

(* If a closed, well typed expression takes several evaluation steps
   then the result has the same type as before. *)
Lemma preservation_steps
 :  forall x1 t1 x2
 ,  TYPE nil x1 t1
 -> STEPS    x1 x2
 -> TYPE nil x2 t1.
Proof.
 intros x1 t1 x2 HT HS.
 induction HS; burn using preservation.
Qed.

(* If a closed, well typed expression takes several evaluation steps
   then the result has the same type as before.
   Usses the left linearised version of steps judement. *)
Lemma preservation_stepsl
 :  forall x1 t1 x2
 ,  TYPE nil x1 t1
 -> STEPSL   x1 x2
 -> TYPE nil x2 t1.
Proof.
 intros x1 t1 x2 HT HS.
 induction HS; burn using preservation.
Qed.


Set Implicit Arguments.

Require Import
        Discrete.DiscType
        List
        Tactics.Tactics.

Import ListNotations.

(** decidabitity of list membership *)

Fixpoint In {A : discType}(x : A)(xs : list A) : Prop :=
  match xs with
  | [] => False
  | (y :: ys) => x = y \/ In x ys
  end.

Instance In_dec {A : discType} : forall (x : A) xs, dec (In x xs).
Proof.
  intros x xs ; gen x ; induction xs ; intros ; crush.
Qed.

Notation "x 'el' A" := (In x A) (at level 70).

(** facts about In *)

Lemma In_app_iff {A : discType}
  : forall xs ys (x : A), In x (xs ++ ys) <-> In x xs \/ In x ys.
Proof.
  induction xs ; intros ; crush.
  +
    destruct* (IHxs ys x) ; crush.
Qed.

Hint Resolve In_app_iff.

Lemma In_rev_iff {A : discType}
  : forall xs (x : A) , In x (rev xs) <-> In x xs.
Proof.
  induction xs ; crush ; try solve [apply In_app_iff ; crush].
  +
    apply In_app_iff in H ; crush.
    destruct* (IHxs x) ; right*.
Qed.

Hint Resolve In_rev_iff.

Lemma In_map {A B : discType}
  : forall (xs : list A)(f : A -> B)(x : A),
    In x xs -> In (f x) (map f xs).
Proof.
  induction xs ; crush.
Qed.

Lemma In_map_iff {A B : discType}
  : forall (xs : list A)(f : A -> B)(x : B),
    In x (map f xs) <-> exists (y : A), f y = x /\ In y xs.
Proof.
  induction xs ; intros f x ; splits ; intros H ; try solve [crush].
  +
    simpl in *.
    destruct H. exists* a.
    destruct (IHxs f x) as [Hl Hr].
    specialize (Hl H). crush. eexists ; eauto.
  +
    crush.
    apply In_map with (f0 := f) in H.
    destruct (IHxs f (f x0)) as [Hl Hr].
    specialize (Hl H).
    crush ; eexists ; eauto.
Qed.

Hint Resolve In_map.

Lemma In_eq {A : discType}
  : forall (xs : list A) x, In x (x :: xs).
Proof.
  crush.
Qed.

Lemma In_cons {A : discType}
  : forall (xs : list A) x y, In x xs -> In x (y :: xs).
Proof.
  induction xs ; crush.
Qed.

Lemma In_nil {A : discType}
  : forall (x : A), ~ In x nil.
Proof.
  crush.
Qed.

Lemma In_sing {A : discType}
  : forall (x y : A), In x (y :: []) -> x = y.
Proof.
  crush.
Qed.

Lemma In_cons_neq {A : discType}
  : forall (xs : list A) x y, In x (y :: xs) -> x <> y -> In x xs.
Proof.
  induction xs ; crush.
Qed.

Lemma not_In_cons {A : discType}
  : forall (xs : list A) x y, ~ In x (y :: xs) -> x <> y /\ ~ In x xs.
Proof.
  induction xs ; crush.
Qed.


Require Import List.
Set Implicit Arguments.

(* infinite lists *)
CoInductive stream (A:Type): Type :=
  | Cons : A -> stream A -> stream A.

(* finite or infinite lists *)
CoInductive llist (A:Type): Type :=
  | LNil : llist A
  | LCons : A -> llist A -> llist A.

(* finite or infinite binary trees *)
CoInductive ltree (A:Type): Type :=
  | LLeaf : ltree A
  | LBin  : A -> ltree A -> ltree A -> ltree A.

Check (LCons 1 (LCons 2 (LCons 3 (LNil nat)))).

Fixpoint embed {A:Type} (l:list A) : llist A :=
  match l with
    | nil       => LNil A
    | cons a l' => LCons a (embed l')
  end.

Lemma embed_injective: forall (A:Type)(l m:list A),
  embed l = embed m -> l = m.
Proof.
  intros A l. elim l.
    clear l. intros m. elim m.
      clear m. intros. reflexivity.
      clear m. simpl. intros. discriminate.
    clear l. intros a l IH m. elim m.
      clear m. simpl. intros. discriminate.
      clear m. intros b m H0 H1. clear H0.
        simpl in H1. injection H1. clear H1. intros H1 H2.
        rewrite <- H2. rewrite (IH m). reflexivity. exact H1.
Qed.

(* cannot use a recursive definition with 'Fixpoint' *)
CoFixpoint from (n:nat) : llist nat := LCons n (from (S n)).

Definition Nats : llist nat := from 0.

Check Nats.

(* 'cofix' for anonymous co-recursive functions *)
Definition Squares_from :=
  let sqr := fun n:nat => n*n in
  cofix F : nat -> llist nat :=
    fun n:nat => LCons (sqr n)(F (S n)).

(* insight : co-recursive -> codomain is a coinductive type
             recursive    -> domain is an inductive type
*)

Eval simpl in (from 3).

Eval compute in (from 3).

CoFixpoint repeat {A:Type}(a:A) : llist A :=  LCons a (repeat a).

CoFixpoint lappend {A:Type}(u v: llist A) : llist A :=
  match u with
    | LNil        => v
    | LCons a u'  => LCons a (lappend u' v)
  end.


(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

(** Properties of addition.

 This file is mostly OBSOLETE now, see module [PeanoNat.Nat] instead.

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

Require Import PeanoNat.

Local Open Scope nat_scope.

(** * Neutrality of 0, commutativity, associativity *)

Notation plus_0_l := Nat.add_0_l (only parsing).
Notation plus_0_r := Nat.add_0_r (only parsing).
Notation plus_comm := Nat.add_comm (only parsing).
Notation plus_assoc := Nat.add_assoc (only parsing).

Notation plus_permute := Nat.add_shuffle3 (only parsing).

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

Lemma plus_assoc_reverse n m p : n + m + p = n + (m + p).
Proof.
  symmetry. apply Nat.add_assoc.
Qed.

(** * Simplification *)

Lemma plus_reg_l n m p : p + n = p + m -> n = m.
Proof.
 apply Nat.add_cancel_l.
Qed.

Lemma plus_le_reg_l n m p : p + n <= p + m -> n <= m.
Proof.
 apply Nat.add_le_mono_l.
Qed.

Lemma plus_lt_reg_l n m p : p + n < p + m -> n < m.
Proof.
 apply Nat.add_lt_mono_l.
Qed.

(** * Compatibility with order *)

Lemma plus_le_compat_l n m p : n <= m -> p + n <= p + m.
Proof.
 apply Nat.add_le_mono_l.
Qed.

Lemma plus_le_compat_r n m p : n <= m -> n + p <= m + p.
Proof.
 apply Nat.add_le_mono_r.
Qed.

Lemma plus_lt_compat_l n m p : n < m -> p + n < p + m.
Proof.
 apply Nat.add_lt_mono_l.
Qed.

Lemma plus_lt_compat_r n m p : n < m -> n + p < m + p.
Proof.
 apply Nat.add_lt_mono_r.
Qed.

Lemma plus_le_compat n m p q : n <= m -> p <= q -> n + p <= m + q.
Proof.
 apply Nat.add_le_mono.
Qed.

Lemma plus_le_lt_compat n m p q : n <= m -> p < q -> n + p < m + q.
Proof.
 apply Nat.add_le_lt_mono.
Qed.

Lemma plus_lt_le_compat n m p q : n < m -> p <= q -> n + p < m + q.
Proof.
 apply Nat.add_lt_le_mono.
Qed.

Lemma plus_lt_compat n m p q : n < m -> p < q -> n + p < m + q.
Proof.
 apply Nat.add_lt_mono.
Qed.

Lemma le_plus_l n m : n <= n + m.
Proof.
 apply Nat.le_add_r.
Qed.

Lemma le_plus_r n m : m <= n + m.
Proof.
 rewrite Nat.add_comm. apply Nat.le_add_r.
Qed.

Theorem le_plus_trans n m p : n <= m -> n <= m + p.
Proof.
  intros. now rewrite <- Nat.le_add_r.
Qed.

Theorem lt_plus_trans n m p : n < m -> n < m + p.
Proof.
  intros. apply Nat.lt_le_trans with m. trivial. apply Nat.le_add_r.
Qed.

(** * Inversion lemmas *)

Lemma plus_is_O n m : n + m = 0 -> n = 0 /\ m = 0.
Proof.
  destruct n; now split.
Qed.

Definition plus_is_one m n :
  m + n = 1 -> {m = 0 /\ n = 1} + {m = 1 /\ n = 0}.
Proof.
  destruct m as [| m]; auto.
  destruct m; auto.
  discriminate.
Defined.

(** * Derived properties *)

Notation plus_permute_2_in_4 := Nat.add_shuffle1 (only parsing).

(** * Tail-recursive plus *)

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

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

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

(** * Discrimination *)

Lemma succ_plus_discr n m : n <> S (m+n).
Proof.
 apply Nat.succ_add_discr.
Qed.

Lemma n_SSn n : n <> S (S n).
Proof (succ_plus_discr n 1).

Lemma n_SSSn n : n <> S (S (S n)).
Proof (succ_plus_discr n 2).

Lemma n_SSSSn n : n <> S (S (S (S n))).
Proof (succ_plus_discr n 3).

(** * Compatibility Hints *)

Hint Immediate plus_comm : arith.
Hint Resolve plus_assoc plus_assoc_reverse : arith.
Hint Resolve plus_le_compat_l plus_le_compat_r : arith.
Hint Resolve le_plus_l le_plus_r le_plus_trans : arith.
Hint Immediate lt_plus_trans : arith.
Hint Resolve plus_lt_compat_l plus_lt_compat_r : arith.

(** For compatibility, we "Require" the same files as before *)

Require Import Le Lt.


Require Export D.

(** **** Exercise: 3 stars (eval__multistep)  *)
(** The key idea behind the proof comes from the following picture:
       P t1 t2 ==>            (by ST_Plus1)
       P t1' t2 ==>           (by ST_Plus1)
       P t1'' t2 ==>          (by ST_Plus1)
       ...
       P (C n1) t2 ==>        (by ST_Plus2)
       P (C n1) t2' ==>       (by ST_Plus2)
       P (C n1) t2'' ==>      (by ST_Plus2)
       ...
       P (C n1) (C n2) ==>    (by ST_PlusConstConst)
       C (n1 + n2)
    That is, the multistep reduction of a term of the form [P t1 t2]
    proceeds in three phases:
       - First, we use [ST_Plus1] some number of times to reduce [t1]
         to a normal form, which must (by [nf_same_as_value]) be a
         term of the form [C n1] for some [n1].
       - Next, we use [ST_Plus2] some number of times to reduce [t2]
         to a normal form, which must again be a term of the form [C
         n2] for some [n2].
       - Finally, we use [ST_PlusConstConst] one time to reduce [P (C
         n1) (C n2)] to [C (n1 + n2)]. *)

(** To formalize this intuition, you'll need to use the congruence
    lemmas from above (you might want to review them now, so that
    you'll be able to recognize when they are useful), plus some basic
    properties of [==>*]: that it is reflexive, transitive, and
    includes [==>]. *)

Theorem multi_R : forall (X:Type) (R:relation X) (x y : X),
       R x y -> (multi R) x y.
Proof.
  intros X R x y H.
  apply multi_step with y. apply H. apply multi_refl.   Qed.

Theorem multi_trans :
  forall (X:Type) (R: relation X) (x y z : X),
      multi R x y  ->
      multi R y z ->
      multi R x z.
Proof.
  intros X R x y z G H.
  induction G.
    - (* multi_refl *) assumption.
    - (* multi_step *)
      apply multi_step with y. assumption.
      apply IHG. assumption.  Qed.

Lemma multistep_congr_1 : forall t1 t1' t2,
     t1 ==>* t1' ->
     P t1 t2 ==>* P t1' t2.
Proof.
  intros t1 t1' t2 H. induction H.
    - (* multi_refl *) apply multi_refl.
    - (* multi_step *) apply multi_step with (P y t2).
        apply ST_Plus1. apply H.
        apply IHmulti.  Qed.

Lemma multistep_congr_2 : forall t1 t2 t2',
     value t1 ->
     t2 ==>* t2' ->
     P t1 t2 ==>* P t1 t2'.
Proof.
  intros t1 t2 t2' Ht1 H. induction H.
  - apply multi_refl.
  - apply multi_step with (P t1 y).
    inversion Ht1. apply ST_Plus2. assumption. assumption.
Qed.

Theorem eval__multistep : forall t n,
  t \\ n -> t ==>* C n.
Proof.
  intros t n H. induction H.
  - apply multi_refl.
  - apply multistep_congr_1 with (t1 := t1) (t1' := C n1) (t2 := t2) in IHeval1.
    apply multistep_congr_2 with (t1 := C n1) (t2 := t2) (t2' := C n2) in IHeval2.
    apply multi_trans with (x := P t1 t2) (y := P (C n1) t2) (z := P (C n1) (C n2))in IHeval1.
    apply multi_trans with (x := P t1 t2) (y := P (C n1) (C n2)) (z := C (n1 + n2)).
    assumption.  apply multi_R. constructor. assumption. constructor.
Qed.


(*
  Copyright 2022 ZhengPu Shi
  This file is part of CoqExt. It is distributed under the MIT
  "expat license". You should have recieved a LICENSE file with it.

  在解一元二次方程时碰到的一个问题：
  标准库提供了 Rsqr_sol_eq_0_1 引理，提供了求根公式，但是要求 nonzeroreal 类型，
  该类型是一个struct，内部使用了 Real 类型。

  现在想要建立一个 Real 类型的引理，如何将“nonzeroreal类型”予以回避，或者内部封装起来？
*)

Require Import Reals.
Open Scope R.

(* 检查一些定义 *)
Print nonzeroreal.
Check Rsqr_sol_eq_0_1.

(* nonzeroreal类型可直接使用 *)
Lemma quadratic_equation_prop1 : forall (a:nonzeroreal) (b c x:R) ,
  x = (-b + sqrt(b² - 4 * a * c)) * ( / (2 * a)) ->
  0 <= b² - 4 * a * c ->
  a * x² + b * x + c = 0.
  intros.
  apply Rsqr_sol_eq_0_1.
  - trivial.
  - left. unfold sol_x1, Delta. auto.
Qed.

(* Real类型暂时没有办法 *)
Lemma quadratic_equation_prop2 : forall (a b c x:R) ,
  x = (-b + sqrt(b² - 4 * a * c)) * ( / (2 * a)) ->
  0 <= b² - 4 * a * c ->
  a * x² + b * x + c = 0.
  intros.
  Abort.

(* 找到 Rsqr_sol_eq_0_1 源码，仿照其实现重写一个版本 *)
Lemma Rsqr_sol_eq_0_1' :
  forall (a:R) (b c x:R),
    a <> 0 ->
    0 <= b ^ 2 - 4 * a * c ->
    x = (- b + sqrt (b ^ 2 - 4 * a * c)) / (2 * a) \/
    x = (- b - sqrt (b ^ 2 - 4 * a * c)) / (2 * a)
    -> a * x ^ 2 + b * x + c = 0.
Proof.
  intros.
  elim H1.
  - intro.
    rewrite H2. field_simplify; auto.
    rewrite <- (Rsqr_pow2 (sqrt (b ^ 2 - 4 * a * c))).
    rewrite Rsqr_sqrt; auto.
    field; auto.
  - intro.
    rewrite H2. field_simplify; auto.
    rewrite <- (Rsqr_pow2 (sqrt (b ^ 2 - 4 * a * c))).
    rewrite Rsqr_sqrt; auto.
    field; auto.
Qed.


(*
 * Module: TLB
 *
 * Description:
 *  This module defines the functions used to represent a TLB entry.
 *)

Require Import Arith.

(*
 * Define basic inductive types for a TLB entry.
 *)
Inductive ReadTy  : Type := | Read  | NoRead.
Inductive WriteTy : Type := | Write | NoWrite.
Inductive ExecTy  : Type := | Exec  | NoExec.
Inductive TLBTy : Type :=
  | emptyTLB
  | TLB : nat -> ReadTy -> WriteTy -> ExecTy -> TLBTy.

(*
 * Function: definedTLB
 *
 * Description:
 *   Determine whether this TLB represents a defined translation from a
 *   virtual address to a physical address.
 *)
Definition definedTLB (tlb : TLBTy) :=
  match tlb with
  | emptyTLB => False
  | TLB n R W X => True
end.

(*
 * Function: getPhysical
 *
 * Description:
 *   Get the physical address out of the TLB.
 *)
Definition getPhysical (tlb : TLBTy) :=
  match tlb with
  | emptyTLB => 0
  | TLB n R W X => n
end.

(*
 * Functions for determining whether a TLB entry permits
 * read/write/execute access.
 *)
Definition TLBPermitsRead (tlb : TLBTy) : Prop :=
  match tlb with
  | emptyTLB => False
  | TLB n Read   W X => True
  | TLB n NoRead W X => False
end.

Definition TLBPermitsWrite (tlb : TLBTy) : Prop :=
  match tlb with
  | emptyTLB => False
  | TLB n R Write   X => True
  | TLB n R NoWrite X => False
end.

Definition TLBPermitsExec (tlb : TLBTy) : Prop :=
  match tlb with
  | emptyTLB => False
  | TLB n R W Exec => True
  | TLB n R W NoExec => False
end.

Lemma PermitsWriteImpliesWrite : forall (n : nat) (r : ReadTy) (w : WriteTy) (e : ExecTy),
TLBPermitsWrite (TLB n r w e) -> w = Write.
intros.
induction w.
reflexivity.
contradiction H.
Qed.


(* http://www.iij-ii.co.jp/lab/techdoc/coqt/coqt4.html *)
Require Import Arith.

Goal forall (n : nat), (exists m : nat, n = m * 4) -> exists k : nat, n = k * 2.
  intros.destruct H.exists (x * 2).rewrite mult_assoc_reverse.simpl.apply H.Qed.

Theorem lt_Snm_nm : forall (n m :nat), S n < m -> n < m.
  intros.apply (lt_trans n (S n) m).apply lt_n_Sn.apply H.Qed.

Inductive InList (A : Type)(a : A) : list A -> Prop :=
| headIL : forall xs, InList A a (a::xs)
| consIL : forall x xs, InList A a xs -> InList A a (x::xs).

Require Import List.

Theorem pigeonhole : forall (xs : list nat),
    length xs < fold_right plus 0 xs -> exists x : nat, InList nat (S (S x)) xs.
  intros.
induction xs.
simpl in H.
apply False_ind.
apply (lt_n_O 0 H).
simpl in H.
destruct a.
apply lt_Snm_nm in H.
apply IHxs in H.
destruct H.
exists x.
constructor.
apply H.
destruct a.
simpl in H.
apply lt_S_n in H.
apply IHxs in H.
destruct H.
exists x.
constructor.
apply H.
exists a.
constructor.
Qed.


Require Import Nat.
Require Import List.
Require Import Program.
Import ListNotations.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.Euclid.
Require Import Coq.Init.Logic.
Require Import Coq.Program.Wf.
Require Import Coq.Logic.Classical_Prop.

Definition sort : Type :=
  forall (A : Type), (A -> A -> bool) -> list A -> list A.

Definition sort_length (f : sort) : Prop :=
  forall (A : Type) (le : A -> A -> bool) (xs : list A),
  length (f A le xs) = length xs.

Inductive list_sorted {A : Type} (le : A -> A -> bool): list A -> Prop :=
| sorted_nil : list_sorted le []
| sorted_cons :
    forall x xs,
    Forall (fun y => le x y = true) xs
    -> list_sorted le xs
    -> list_sorted le (x :: xs).

Definition sort_sorted (f : sort) : Prop :=
  forall (A : Type) (le : A -> A -> bool) (xs : list A),
  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->
  (forall k l : A, le k l = le l k -> l = k) ->
  (forall k : A, le k k = true) ->
  list_sorted le (f A le xs).

Definition sort_members (f : sort) : Prop :=
  forall (A : Type) (le : A -> A -> bool) (xs : list A) (x : A),
  In x xs <-> In x (f A le xs).

Definition valid_sort sort : Prop :=
  sort_length sort /\ sort_sorted sort /\ sort_members sort.

Fixpoint split_at {A : Type} (n : nat) (xs : list A) : list A * list A :=
  match n, xs with
  | O, _ => ([], xs)
  | S _, [] => ([], [])
  | S n', x :: xs' =>
      let (ys, zs) := split_at n' xs' in
      (x :: ys, zs)
  end.

Theorem list_sorted_cons :
  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),
  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->
  le a b = true -> list_sorted le (b :: xs) ->
  list_sorted le (a :: b :: xs).
Proof.
  intros A le a b xs le_trans le_a_b H.
  constructor; try assumption.
  constructor; try assumption.
  inversion H.
  apply Forall_impl with (P:=fun y : A => le b y = true); try assumption.
  intro. apply le_trans. assumption.
Qed.

Theorem list_sorted_cons_cons :
  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),
  list_sorted le (a :: b :: xs) -> le a b = true.
Proof.
  intros A le a b xs H.
  inversion H.
  destruct (Forall_forall (fun y : A => le a y = true) (b :: xs)) as (Hall & _).
  apply Hall.
  assumption.
  constructor.
  reflexivity.
Qed.

Theorem list_sorted_cons_cons_sorted :
  forall (A : Type) (le : A -> A -> bool) (a b : A) (xs : list A),
  list_sorted le (a :: b :: xs) -> list_sorted le (a :: xs).
Proof.
  intros A le a b xs H.
  constructor.
  - inversion H. inversion H2. assumption.
  - inversion H. inversion H3. assumption.
Qed.

Lemma split_at_concat : forall (A : Type) (n : nat) (xs ys zs : list A),
    (ys, zs) = split_at n xs -> ys ++ zs = xs.
Proof.
  induction n; induction xs;
    simpl; intros ys zs H; try (inversion H; reflexivity).
  destruct (split_at n xs) as (ys' & zs') eqn:S in H. inversion H. simpl.
  rewrite (IHn xs ys' zs' (eq_sym S)). reflexivity.
Qed.

Lemma split_at_length : forall (A : Type) (n : nat) (xs ys zs : list A),
    n < length xs -> (ys, zs) = split_at n xs -> length ys = n.
Proof.
  intros A n.
  induction n as [|n'].
  - intros xs ys zs Hlt Hsplit. simpl in Hsplit. inversion Hsplit. reflexivity.
  - induction xs as [|x xs'].
    * intros ys zs Hlt Hsplit. inversion Hlt.
    * intros ys zs Hlt Hsplit.
      simpl in Hsplit. destruct (split_at n' xs') eqn:S in Hsplit.
      inversion Hsplit. simpl.
      simpl in Hlt. apply lt_S_n in Hlt.
      rewrite (IHn' xs' l l0 Hlt (eq_sym S)).
      reflexivity.
Qed.

Definition split {A : Type} (xs : list A) : list A * list A :=
  match xs with
  | [] => ([], [])
  | _ :: _ =>
    match eucl_dev 2 (gt_Sn_O 1) (length xs) with
    | divex _ _ q r _ _ => split_at q xs
    end
  end.

Theorem split_concat :
  forall (A : Type) (xs ys zs : list A), (ys, zs) = split xs -> ys ++ zs = xs.
Proof.
  induction xs; try (intros ys zs H; inversion H; reflexivity).
  unfold split.
  destruct (eucl_dev 2 (gt_Sn_O 1) (length (a :: xs))).
  apply split_at_concat.
Qed.

Theorem split_length :
  forall (A : Type) (xs ys zs : list A),
  (ys, zs) = split xs -> length ys + length zs = length xs.
Proof.
  intros A xs ys zs H.
  rewrite <- split_concat with (xs:=xs) (ys:=ys) (zs:=zs); try assumption.
  symmetry. apply app_length.
Qed.

Theorem split_members :
  forall (A : Type) (a : A) (xs ys zs : list A),
  (ys, zs) = split xs -> In a ys \/ In a zs <-> In a xs.
Proof.
  intros A a xs ys zs Hsplit.
  split; intro H.
  - rewrite <- split_concat with (ys:=ys) (zs:=zs); try assumption.
    apply in_or_app; assumption.
  - rewrite <- split_concat with (ys:=ys) (zs:=zs) in H; try assumption.
    apply in_app_or; assumption.
Qed.

Theorem split_smaller_l :
  forall (A : Type) (a b : A) (xs ys zs : list A),
  (ys, zs) = split (a :: b :: xs) -> length ys < length (a :: b :: xs).
Proof.
  intros A a b xs ys zs H.
  simpl in H. destruct (eucl_dev 2 (gt_Sn_O 1) (S (S (length xs)))).
  destruct q.
  - simpl in e. unfold gt in g. rewrite <- e in g.
    repeat apply lt_S_n in g. inversion g.
  - assert (forall n : nat, n < S (n * 2) + r).
    {
      induction n.
      * apply Nat.lt_0_succ.
      * simpl. apply lt_n_S. rewrite <- plus_Sn_m.
        apply Nat.lt_lt_succ_r. apply IHn.
    }
    rewrite split_at_length with (n:=S q) (xs:=a::b::xs) (zs:=zs);
      apply H || simpl; rewrite e; simpl; apply lt_n_S; apply H0.
Qed.

Theorem split_smaller_r : forall (A : Type) (a b : A) (xs ys zs : list A),
    (ys, zs) = split (a :: b :: xs) -> length zs < length (a :: b :: xs).
Proof.
  intros A a b xs ys zs H.
  rewrite <- split_concat with (xs:=a::b::xs) (ys:=ys) (zs:=zs).
  - rewrite app_length. apply Nat.lt_add_pos_l.
    simpl in H. destruct (eucl_dev 2 (gt_Sn_O 1) (S (S (length xs)))).
    destruct q.
    * simpl in e. rewrite <- e in g.
      repeat apply lt_S_n in g. inversion g.
    * rewrite split_at_length with (n:=S q) (xs:=a::b::xs) (ys:=ys) (zs:=zs).
      apply Nat.lt_0_succ.
      simpl. rewrite e. rewrite Nat.mul_comm. apply lt_plus_trans. simpl.
      apply lt_n_S. apply Nat.lt_add_pos_r. apply Nat.lt_0_succ.
      assumption.
  - assumption.
Qed.

Program Fixpoint merge_sorted_lists {A : Type} (le : A -> A -> bool)
    (xs ys : list A) { measure (length (xs ++ ys)) } : list A :=
  match xs, ys with
  | [], _ => ys
  | _, [] => xs
  | x :: xs', y :: ys' =>
      if le x y
        then x :: merge_sorted_lists le xs' ys
        else y :: merge_sorted_lists le xs ys'
  end.
Next Obligation.
  rewrite app_length. rewrite app_length. simpl.
  destruct (length xs'); try auto.
  simpl. repeat rewrite <- Nat.succ_lt_mono. rewrite <- Nat.add_lt_mono_l.
  auto.
Qed.

Lemma merge_sorted_lists_body :
  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),
  merge_sorted_lists le xs ys =
  match xs, ys with
  | [], _ => ys
  | _, [] => xs
  | x :: xs', y :: ys' =>
      if le x y
        then x :: merge_sorted_lists le xs' ys
        else y :: merge_sorted_lists le xs ys'
  end.
Proof.
  intros A le xs ys.
  unfold merge_sorted_lists.
  unfold merge_sorted_lists_func; rewrite WfExtensionality.fix_sub_eq_ext;
    fold merge_sorted_lists_func; simpl.
  destruct xs; destruct ys; try reflexivity.
Qed.

Lemma merge_sorted_lists_length :
  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),
  length (merge_sorted_lists le xs ys) = length xs + length ys.
Proof.
  intros A le xs ys.
  rewrite merge_sorted_lists_body.
  revert ys; induction xs as [|x xs']; try reflexivity.
  induction ys as [|y ys']; simpl; try rewrite Nat.add_0_r; try reflexivity.
  destruct (le x y).
  - simpl. apply eq_S. rewrite merge_sorted_lists_body.
    apply IHxs' with (ys:=y::ys').
  - simpl. apply eq_S. rewrite merge_sorted_lists_body.
    rewrite <- plus_n_Sm. apply IHys'.
Qed.

Theorem merge_sorted_lists_nil_l :
  forall (A : Type) (le : A -> A -> bool) (xs : list A),
  merge_sorted_lists le [] xs = xs.
Proof.
  intros A le xs.
  rewrite merge_sorted_lists_body.
  reflexivity.
Qed.

Theorem merge_sorted_lists_nil_r :
  forall (A : Type) (le : A -> A -> bool) (xs : list A),
  merge_sorted_lists le xs [] = xs.
Proof.
  intros A le xs.
  rewrite merge_sorted_lists_body.
  destruct xs; reflexivity.
Qed.

Lemma merge_sorted_lists_singleton_le_l :
  forall (A : Type) (le : A -> A -> bool) (a y : A) (ys : list A),
  le a y = true ->
  merge_sorted_lists le [a] (y :: ys) = a :: y :: ys.
Proof.
  intros A le a y ys H.
  rewrite merge_sorted_lists_body. rewrite H.
  reflexivity.
Qed.

Lemma merge_sorted_lists_singleton_le_r :
  forall (A : Type) (le : A -> A -> bool) (a y : A) (ys : list A),
  (forall k l : A, le k l = le l k -> l = k) ->
  list_sorted le (y :: ys) -> le a y = true ->
  merge_sorted_lists le (y :: ys) [a] = a :: y :: ys.
Proof.
  intros A le a y ys le_antisymm Hsorted le_a_y.
  rewrite merge_sorted_lists_body.
  destruct (le y a) eqn:le_y_a.
  - rewrite <- le_antisymm  with (k:=a) (l:=y); try assumption.
    induction ys as [|y' ys]; try reflexivity.
    destruct (le y' y) eqn:le_yp_a.
    * inversion Hsorted.
      assert (y = y') as Hyyp.
      {
        destruct (Forall_forall (fun y0 : A => le y y0 = true) (y' :: ys))
          as (Hall & _).
        rewrite le_antisymm with (k:=y') (l:=y);
          try assumption; try reflexivity.
        rewrite Hall. assumption. assumption. constructor. reflexivity.
      }
      rewrite merge_sorted_lists_body. rewrite le_yp_a. rewrite <- Hyyp.
      rewrite IHys.
      repeat rewrite merge_sorted_lists_body. reflexivity.
      rewrite <- Hyyp in H2. assumption.
    * rewrite merge_sorted_lists_body. rewrite le_yp_a.
      rewrite merge_sorted_lists_body. reflexivity.
    * rewrite le_a_y; rewrite le_y_a; reflexivity.
  - rewrite merge_sorted_lists_nil_r.
    reflexivity.
Qed.

Theorem merge_sorted_lists_same_head :
  forall (A : Type) (le : A -> A -> bool) (a : A) (xs ys : list A),
  (forall k l : A, le k l = le l k -> l = k) ->
  list_sorted le (a :: xs) -> list_sorted le (a :: ys) ->
  merge_sorted_lists le (a :: xs) (a :: ys)
    = a :: a :: merge_sorted_lists le xs ys.
Proof.
  intros A le a xs ys le_antisymm. revert ys.
  induction xs as [|x xs']; induction ys as [|y ys']; intros H1 H2.
  - repeat rewrite merge_sorted_lists_body. destruct (le a a); reflexivity.
  - rewrite merge_sorted_lists_body.
    destruct (le a a).
    * repeat rewrite merge_sorted_lists_body. reflexivity.
    * rewrite merge_sorted_lists_singleton_le_l; try reflexivity.
      apply list_sorted_cons_cons with (xs:=ys').
      assumption.
  - destruct (le a a) eqn:le_a_a;
      rewrite merge_sorted_lists_nil_r; rewrite merge_sorted_lists_body;
      rewrite le_a_a; try (rewrite merge_sorted_lists_body; reflexivity).
    rewrite merge_sorted_lists_singleton_le_r;
      inversion H1; try (reflexivity || assumption).
    destruct (Forall_forall (fun y : A => le a y = true) (x :: xs'))
      as (Hall & _).
    apply Hall with (x0:=x). assumption. constructor; reflexivity.

  (* xs := x :: xs' and ys := y :: ys' *)
  - rewrite merge_sorted_lists_body.
    destruct (le a a) eqn:le_a_a.

    (* le a a = true *)
    * destruct (le x a) eqn:le_x_a.
      + inversion H1.
        rewrite le_antisymm with (k:=a) (l:=x); try assumption.
        rewrite IHxs'; try assumption.
        rewrite merge_sorted_lists_body with (xs:=a::xs').
        inversion H2.
        destruct (Forall_forall (fun y : A => le a y = true) (y :: ys'))
          as (Hall & _).
        rewrite Hall with (x:=y); try (reflexivity || assumption).
        constructor; reflexivity.
        apply list_sorted_cons_cons_sorted with (b:=x); assumption.
        destruct (Forall_forall (fun y : A => le a y = true) (x :: xs'))
          as (Hall & _).
        rewrite Hall with (x0:=x); try assumption.
        rewrite le_x_a; reflexivity.
        constructor; reflexivity.
      + rewrite merge_sorted_lists_body. rewrite le_x_a. reflexivity.

    (* le a a = false *)
    * rewrite merge_sorted_lists_body.
      inversion H2.
      destruct (Forall_forall (fun y : A => le a y = true) (y :: ys'))
        as (Hall & _).
      rewrite Hall with (x:=y).
      reflexivity. assumption. constructor. reflexivity.
Qed.

Theorem merge_sorted_lists_cons_l :
  forall (A : Type) (le : A -> A -> bool) (x : A) (xs ys : list A),
  (forall k l : A, le k l = le l k -> l = k) ->
  list_sorted le (x :: xs) -> list_sorted le (x :: ys) ->
  merge_sorted_lists le (x :: xs) ys = x :: merge_sorted_lists le xs ys.
Proof.
  intros A le x xs ys le_antisymm Hxxs_sorted Hxys_sorted.
  rewrite merge_sorted_lists_body.
  induction ys as [|y ys'].
  - rewrite merge_sorted_lists_nil_r. reflexivity.
  - inversion Hxys_sorted.
    assert (le x y = true) as le_x_y.
    { inversion H1. assumption. }
    rewrite le_x_y.
    reflexivity.
Qed.

Theorem merge_sorted_lists_cons_r :
  forall (A : Type) (le : A -> A -> bool) (y : A) (xs ys : list A),
  (forall k l : A, le k l = le l k -> l = k) ->
  list_sorted le (y :: xs) -> list_sorted le (y :: ys) ->
  merge_sorted_lists le xs (y :: ys) = y :: merge_sorted_lists le xs ys.
Proof.
  intros A le y xs ys le_antisymm Hyxs_sorted Hyys_sorted.
  induction xs as [|x xs'].
  - rewrite merge_sorted_lists_body.
    rewrite merge_sorted_lists_nil_l. reflexivity.
  - inversion Hyxs_sorted.
    rewrite merge_sorted_lists_body.
    destruct (le x y) eqn:le_x_y; try reflexivity.
    assert (x = y) as eq_x_y.
    {
      inversion Hyxs_sorted.
      destruct (Forall_forall (fun y0 : A => le y y0 = true) (x :: xs'))
        as (Hall & _).
      apply le_antisymm with (k:=y) (l:=x).
      rewrite le_x_y. apply Hall.
      assumption. constructor; reflexivity.
    }
    rewrite merge_sorted_lists_cons_l; try (reflexivity || assumption).
    rewrite IHxs'.
    rewrite eq_x_y; reflexivity.
    apply list_sorted_cons_cons_sorted with (b:=x); assumption.
    rewrite eq_x_y; assumption.
Qed.

Theorem merge_sorted_lists_comm :
  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),
  (forall k l : A, le k l = le l k -> l = k) ->
  list_sorted le xs -> list_sorted le ys ->
  merge_sorted_lists le xs ys = merge_sorted_lists le ys xs.
Proof.
  intros A le xs ys le_antisymm. revert ys.
  induction xs as [|x xs'];
    try (intro; rewrite merge_sorted_lists_nil_l;
          rewrite merge_sorted_lists_nil_r; reflexivity).
  induction ys as [|y ys'];
    try (rewrite merge_sorted_lists_nil_l; rewrite merge_sorted_lists_nil_r;
          reflexivity).
  intros Hxs_sorted Hys_sorted; inversion Hxs_sorted; inversion Hys_sorted.
  rewrite merge_sorted_lists_body;
    rewrite merge_sorted_lists_body with (xs:=y::ys') (ys:=x::xs').
  destruct (le x y) eqn:le_x_y; destruct (le y x) eqn:le_y_x.

  (* le x y = true and le y x = true *)
  - rewrite le_antisymm with (k:=x) (l:=y) at 2; try assumption.
    rewrite IHxs'; try assumption.
    rewrite le_antisymm with (k:=x) (l:=y); try assumption.
    assert (list_sorted le (x :: ys')) as Hxysp_sorted.
    {
      rewrite <- le_antisymm with (k:=x) (l:=y).
      assumption. rewrite le_y_x. assumption.
    }
    rewrite merge_sorted_lists_cons_l;
      try rewrite merge_sorted_lists_cons_r;
      try reflexivity; try assumption.
    rewrite le_y_x; rewrite le_x_y; reflexivity.
    rewrite le_y_x; rewrite le_x_y; reflexivity.

  (* le x y = true and le y x = false *)
  - rewrite IHxs' with (ys:=y::ys'); try (reflexivity || assumption).

  (* le x y = false and le y x = true *)
  - rewrite IHys'; try (reflexivity || assumption).

  (* le x y = false and le y x = false *)
  - rewrite le_antisymm with (k:=x) (l:=y); try assumption.
    rewrite IHys'; try assumption.
    assert (list_sorted le (x :: ys')).
    {
      rewrite <- le_antisymm with (k:=x) (l:=y).
      assumption. rewrite le_x_y. rewrite le_y_x. reflexivity.
    }
    rewrite merge_sorted_lists_cons_l;
      try rewrite merge_sorted_lists_cons_r;
      try reflexivity; try assumption.
    rewrite le_x_y. rewrite le_y_x. reflexivity.
Qed.

Theorem merge_sorted_lists_members :
  forall (A : Type) (le : A -> A -> bool) (a : A) (xs ys : list A),
  In a (merge_sorted_lists le xs ys) <-> In a xs \/ In a ys.
Proof.
  induction xs as [|x xs']; induction ys as [|y ys']; try simpl; try tauto.
  split; rewrite merge_sorted_lists_body; destruct (le x y) eqn:le_x_y; intro H.

  - inversion H.
    * auto.
    * destruct IHxs' with (ys:=y::ys') as (H1 & _).
      destruct (H1 H0); try auto.

  - inversion H; try auto.
    destruct IHys' as (H1 & _).
    destruct (H1 H0); auto.

  - destruct IHxs' with (ys:=y::ys') as (_ & H1).
    simpl. destruct H; destruct H; try auto.
    * right. apply H1. simpl. auto.
    * right. apply H1. simpl. auto.

  - destruct IHys' as (_ & H1).
    simpl. destruct H; destruct H; try auto.
    * right. apply H1. simpl. auto.
    * right. apply H1. simpl. auto.
Qed.

(* Lemma merge_sorted_lists_sorted_1 :
  forall (A : Type) (le : A -> A -> bool) (x y : A) (xs ys : list A),
  list_sorted le (x :: xs) -> list_sorted le (y ::ys) -> le x y = true ->
  list_sorted le (x :: merge_sorted_lists le xs (y :: ys)). *)

Lemma le_trans_contra :
  forall (A : Type) (le : A -> A -> bool) (h k l : A),
  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->
  (forall k l : A, le k l = le l k -> l = k) ->
  le k l = true -> le k h = false -> le h l = true.
Proof.
  intros A le h k l le_trans le_antisymm H1 H2.
  destruct (le h k) eqn:le_h_k.
  - apply le_trans with (k:=k); assumption.
  - rewrite le_antisymm with (l:=h) (k:=k).
    assumption. rewrite H2. rewrite le_h_k. reflexivity.
Qed.

Theorem merge_sorted_lists_sorted :
  forall (A : Type) (le : A -> A -> bool) (xs ys : list A),
  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->
  (forall k l : A, le k l = le l k -> l = k) ->
  (forall k : A, le k k = true) ->
  list_sorted le xs -> list_sorted le ys ->
  list_sorted le (merge_sorted_lists le xs ys).
Proof.
  intros A le xs ys le_trans le_antisymm  le_refl Hxs Hys.
  revert ys Hys. induction xs as [|x xs']; intros ys Hys; try apply Hys.
  induction ys as [|y ys']; try apply Hxs.
  rewrite merge_sorted_lists_body.
  destruct (le x y) eqn:le_x_y.

  (* le x y = true *)
  - inversion Hxs.
    constructor; try (apply IHxs' with (ys:=y::ys'); assumption).
    apply Forall_forall; intros a Ha.
    destruct merge_sorted_lists_members
      with (le:=le) (a:=a) (xs:=xs') (ys:=y::ys') as (Hin & _).
    destruct (Hin Ha).
    * destruct (Forall_forall (fun y : A => le x y = true) xs') as (Hall & _).
      apply Hall; try assumption.
    * inversion H3.
      + rewrite <- H4. assumption.
      + apply le_trans with (k:=y); try assumption.
        inversion Hys.
        destruct (Forall_forall (fun y0 : A => le y y0 = true) ys')
          as (Hall & _).
        apply Hall; try assumption.

  (* le x y = false *)
  - inversion Hys.
    constructor; try (apply IHys'; assumption).
    apply Forall_forall; intros a Ha.
    destruct merge_sorted_lists_members
      with (a:=a) (le:=le) (xs:=x::xs') (ys:=ys') as (Hin & _).
    destruct (Hin Ha).
    * apply le_trans_contra with (k:=x); try assumption.
      inversion H3.
      rewrite H4. apply le_refl.
      inversion Hxs.
      destruct (Forall_forall (fun y : A => le x y = true) xs') as (Hall & _).
      apply Hall; try assumption.
    * destruct (Forall_forall (fun y0 : A => le y y0 = true) ys') as (Hall & _).
      apply Hall; try assumption.
Qed.

Program Fixpoint merge_sort (A : Type) (le : A -> A -> bool)
    (xs : list A) { measure (length xs) } : list A :=
  match xs with
  | [] => []
  | [x] => [x]
  | _ :: _ :: _ =>
    match split xs with
    | (ys, zs) =>
      let sorted_ys := merge_sort A le ys in
      let sorted_zs := merge_sort A le zs in
      merge_sorted_lists le sorted_ys sorted_zs
    end
  end.

Next Obligation.
  apply split_smaller_l with (zs:=zs).
  assumption.
Qed.

Next Obligation.
  apply split_smaller_r with (ys:=ys).
  assumption.
Qed.

Theorem merge_sort_nil :
  forall (A : Type) (le : A -> A -> bool), merge_sort A le [] = [].
Proof. reflexivity. Qed.

Example merge_sort_list_nat :
  merge_sort nat leb [1;7;2;9;3;5;2] = [1;2;2;3;5;7;9].
Proof. reflexivity. Qed.

Lemma merge_sort_body :
  forall (A : Type) (le : A -> A -> bool) (xs : list A),
  merge_sort A le xs =
  match xs with
  | [] => []
  | [x] => [x]
  | _ :: _ :: _ =>
    match split xs with
    | (ys, zs) =>
      let sorted_ys := merge_sort A le ys in
      let sorted_zs := merge_sort A le zs in
      merge_sorted_lists le sorted_ys sorted_zs
    end
  end.
Proof.
  intros A le xs.
  unfold merge_sort.
  unfold merge_sort_func; rewrite WfExtensionality.fix_sub_eq_ext;
    fold merge_sort_func; simpl.
  induction xs; try reflexivity.
  induction xs; try reflexivity.
  destruct (split (a :: a0 :: xs)).
  reflexivity.
Qed.

Lemma merge_sort_length_le_n0 :
  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (xs : list A),
  length xs <= n0 -> length (merge_sort A le xs) = length xs.
Proof.
  induction n0 as [|n0']; intros.
  - destruct xs. reflexivity. inversion H.
  - induction xs as [|a xs]; try reflexivity.
    induction xs as [|b xs]; try reflexivity.
    rewrite merge_sort_body.
    destruct (split (a :: b :: xs)) as (ys & zs) eqn:S; symmetry in S.
    simpl. rewrite merge_sorted_lists_length.
    repeat rewrite IHn0'.
    rewrite split_length with (xs:=a::b::xs); reflexivity || assumption.
    apply lt_n_Sm_le;
      apply lt_le_trans with (m:=length (a::b::xs)); try assumption.
    apply split_smaller_r with (ys:=ys). assumption.
    apply lt_n_Sm_le;
      apply lt_le_trans with (m:=length (a::b::xs)); try assumption.
    apply split_smaller_l with (zs:=zs). assumption.
Qed.

Theorem merge_sort_length : sort_length merge_sort.
Proof.
  intros A le xs.
  apply merge_sort_length_le_n0 with (n0:=length xs).
  apply Nat.le_refl.
Qed.

Lemma merge_sort_sorted_le_n0 :
  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (xs : list A),
  (forall h k l : A, le h k = true -> le k l = true -> le h l = true) ->
  (forall k l : A, le k l = le l k -> l = k) ->
  (forall k : A, le k k = true) ->
  length xs <= n0 -> list_sorted le (merge_sort A le xs).
Proof.
  intros A le n0 xs le_trans le_antisymm le_refl.
  revert xs; induction n0 as [|n0']; intros xs H.
  - destruct xs. constructor. inversion H.
  - induction xs as [|a xs]; try constructor.
    induction xs as [|b xs].
    * constructor. apply Forall_nil. constructor.
    * rewrite merge_sort_body.
      destruct (split (a::b::xs)) eqn:Hsplit.
      simpl.
      apply merge_sorted_lists_sorted; try assumption; try apply IHn0'.
      + apply lt_n_Sm_le.
        apply Nat.lt_le_trans with (m:=length (a::b::xs)); try assumption.
        apply split_smaller_l with (a:=a) (b:=b) (xs:=xs) (ys:=l) (zs:=l0).
        symmetry; assumption.
      + apply lt_n_Sm_le.
        apply Nat.lt_le_trans with (m:=length (a::b::xs)); try assumption.
        apply split_smaller_r with (a:=a) (b:=b) (xs:=xs) (ys:=l) (zs:=l0).
        symmetry; assumption.
Qed.

Theorem merge_sort_sorted : sort_sorted merge_sort.
Proof.
  intros A le xs le_trans le_antisymm le_refl.
  apply merge_sort_sorted_le_n0 with (n0:=length xs); try assumption.
  apply Nat.le_refl.
Qed.

Lemma merge_sort_members_le_n0 :
  forall (A : Type) (le : A -> A -> bool) (n0 : nat) (x : A) (xs : list A),
  length xs <= n0 ->
  In x xs <-> In x (merge_sort A le xs).
Proof.
  intros A le n0 x.
  induction n0 as [|n0']; intros xs Hlen.
  - destruct xs. rewrite merge_sort_nil. tauto. inversion Hlen.
  - induction xs as [|a xs]; try (simpl; tauto).
    induction xs as [|b xs]; try (simpl; tauto).
    split; intro H.

    (* In x (a :: b :: xs) -> In x (merge_sort A le (a :: b :: xs)) *)
    * rewrite merge_sort_body.
      destruct (split (a::b::xs)) eqn:Hsplit.
      simpl.
      destruct merge_sorted_lists_members
        with (le:=le) (a:=x) (xs:=merge_sort A le l) (ys:=merge_sort A le l0)
        as (_ & Hin).
      apply Hin.
      destruct IHn0' with (xs:=l) as (Hl & _).
        apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).
        apply split_smaller_l with (zs:=l0). symmetry; assumption. assumption.
      destruct IHn0' with (xs:=l0) as (Hl0 & _).
        apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).
        apply split_smaller_r with (ys:=l). symmetry; assumption. assumption.
      apply imply_and_or2 with (P:=In x l); try assumption.
      apply or_comm.
      apply imply_and_or2 with (P:=In x l0); try assumption.
      apply or_comm.
      apply in_app_or with (a:=x) (l:=l) (m:=l0).
      rewrite split_concat with (xs:=a::b::xs); try symmetry; try assumption.

    (* In x (merge_sort A le (a :: b :: xs)) -> In x (a :: b :: xs) *)
    * rewrite merge_sort_body in H.
      destruct (split (a::b::xs)) eqn:Hsplit.
      simpl in H.
      destruct merge_sorted_lists_members
        with (le:=le) (a:=x) (xs:=merge_sort A le l) (ys:=merge_sort A le l0)
        as (Hin & _).
      destruct (split_members A x (a::b::xs) l l0) as (Hin' & _);
        try (symmetry; assumption).
      apply Hin'.
      destruct (Hin H).
      + left.
        destruct IHn0' with (xs:=l) as (_ & Hinl).
          apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).
          apply split_smaller_l with (zs:=l0). symmetry; assumption. assumption.
        apply Hinl. assumption.
      + right.
        destruct IHn0' with (xs:=l0) as (_ & Hinl0).
          apply lt_n_Sm_le. apply Nat.lt_le_trans with (m:=length (a::b::xs)).
          apply split_smaller_r with (ys:=l). symmetry; assumption. assumption.
        apply Hinl0. assumption.
Qed.

Theorem merge_sort_members : sort_members merge_sort.
Proof.
  intros A le xs x.
  apply merge_sort_members_le_n0 with (n0:=length xs).
  auto.
Qed.

Theorem merge_sort_valid : valid_sort merge_sort.
Proof.
  split.
  apply merge_sort_length.
  split.
  apply merge_sort_sorted.
  apply merge_sort_members.
Qed.


From Hammer Require Import Hammer.

Section Relations_1.
Variable U : Type.

Definition Relation := U -> U -> Prop.
Variable R : Relation.

Definition Reflexive : Prop := forall x:U, R x x.

Definition Transitive : Prop := forall x y z:U, R x y -> R y z -> R x z.

Definition Symmetric : Prop := forall x y:U, R x y -> R y x.

Definition Antisymmetric : Prop := forall x y:U, R x y -> R y x -> x = y.

Definition contains (R R':Relation) : Prop :=
forall x y:U, R' x y -> R x y.

Definition same_relation (R R':Relation) : Prop :=
contains R R' /\ contains R' R.

Inductive Preorder : Prop :=
Definition_of_preorder : Reflexive -> Transitive -> Preorder.

Inductive Order : Prop :=
Definition_of_order :
Reflexive -> Transitive -> Antisymmetric -> Order.

Inductive Equivalence : Prop :=
Definition_of_equivalence :
Reflexive -> Transitive -> Symmetric -> Equivalence.

Inductive PER : Prop :=
Definition_of_PER : Symmetric -> Transitive -> PER.

End Relations_1.
Hint Unfold Reflexive Transitive Antisymmetric Symmetric contains
same_relation: sets.
Hint Resolve Definition_of_preorder Definition_of_order
Definition_of_equivalence Definition_of_PER: sets.