(** * 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-style" and
      "backward-style" proofs;
    - how to reason about data constructors (in particular, how to use
      the fact that they are injective and disjoint);
    - how to strengthen an induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis. *)

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

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

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

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

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

  apply eq2.  Qed.

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

Theorem silly2 : forall (n m o p : nat),
     n = m  ->
     (forall (q r : nat), q = r -> [q;o] = [r;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 binds some _universal 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, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

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

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

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

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

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

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

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

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

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

(* ################################################################# *)
(** * 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 recording, once and for all, the fact that equality is
    transitive. *)

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

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

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

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

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

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

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

(** [] *)

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

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O : nat
       | S : nat -> 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 (and in our
    informal understanding of how datatype declarations work in other
    programming languages) are two more facts:

    - The constructor [S] is _injective_.  That is, if [S n = S m], it
      must be the case that [n = m].

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

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

(** Coq provides a tactic called [inversion] that allows us to
    exploit these principles in proofs. To see how to use it, let's
    show explicitly that the [S] constructor is injective: *)

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

(** By writing [inversion H] at this point, we are asking Coq to
    generate all equations that it can infer from [H] as additional
    hypotheses, replacing variables in the goal as it goes. In the
    present example, this amounts to adding a new hypothesis [H1 : n =
    m] and replacing [n] by [m] in the goal. *)

  inversion H.
  reflexivity.
Qed.

(** Here's a more interesting example that shows how multiple
    equations can be derived at once. *)

Theorem inversion_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H. inversion H. reflexivity. Qed.

(** We can name the equations that [inversion] generates with an
    [as ...] clause: *)

Theorem inversion_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.

(** **** Exercise: 1 star (inversion_ex3)  *)
Example inversion_ex3 : forall (X : Type) (x y z w : X) (l j : list X),
  x :: y :: l = w :: z :: j ->
  x :: l = z :: j ->
  x = y.
Proof.
  intros X x y z w l j H1 H2.
  inversion H1. inversion H2. symmetry. apply trans_eq with (x).
  - symmetry. apply H5.
  - apply H0.
Qed.

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately.  Consider the following proof: *)

Theorem beq_nat_0_l : forall n,
   beq_nat 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'].
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming
    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
    clearly contradictory!  The way forward lies in the assumption.
    After simplifying the goal state, we see that [beq_nat 0 (S n') =
    true] has become [false = true]: *)

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

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

    intros H. inversion H. Qed.

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

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

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

(** If you find the principle of explosion confusing, remember
    that these proofs are not actually showing that the conclusion of
    the statement holds.  Rather, they are arguing that, if the
    nonsensical situation described by the premise did somehow arise,
    then the nonsensical conclusion would follow.  We'll explore the
    principle of explosion of more detail in the next chapter. *)

(** **** Exercise: 1 star (inversion_ex6)  *)
Example inversion_ex6 : forall (X : Type)
                          (x y z : X) (l j : list X),
  x :: y :: l = [] ->
  y :: l = z :: j ->
  x = z.
Proof.
  intros X x y z l j H0 H1.
  inversion H0.
Qed.

(** To summarize this discussion, suppose [H] is a hypothesis in the
    context or a previously proven lemma of the form

        c a1 a2 ... an = d b1 b2 ... bm

    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] has the following effect:

    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know that [a1 = b1], [a2 =
      b2], etc.  The [inversion H] adds these facts to the context and
      tries to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory, and the current goal doesn't have to be
      considered at all.  In this case, [inversion H] marks the
      current goal as completed and pops it off the goal stack. *)

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

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  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 in
    the hypothesis named [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     beq_nat (S n) (S m) = b  ->
     beq_nat 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 [L1 -> L2], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]
    against [L1] and, if successful, replaces it with [L2].

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

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

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

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)
(** Practice using "in" variants in this proof.  (Hint: use
    [plus_n_Sm].) *)

(*
Theorem double_m_o : forall m : nat, 0 = m1 + m2 -> m1 = 0.
Proof.
  induction m.
  - simpl. reflexivity.
  - simpl. rewrite -> plus_n_Sm.

*)

Theorem equal_remove_S : forall n m,
  n = m -> S n = S m.
  intros n m eq.
  rewrite eq.
  reflexivity.
Qed.

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [|n'].
  - destruct m. reflexivity.
    { simpl. intro H. inversion H. }
  - destruct m as [|m'].
    { intros H. inversion H. }
    {
  intro H. apply equal_remove_S.
  apply IHn'.
  simpl in H.
  inversion H.
  rewrite <- plus_n_Sm in H1.
  rewrite <- plus_n_Sm in H1.
  inversion H1.
  reflexivity.
    }
Qed.

(** [] *)

(* ################################################################# *)
(** * 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 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 the [double] function 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 with

      intros n. induction n.

    all is well.  But if we begin it with

      intros n m. induction n.

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

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *) intros eq. destruct m as [| m'].
    + (* m = O *) inversion 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: it says 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 about
    whether [double n] is [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 relation involving _every_ [n] but just a _single_ [m]. *)

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

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

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

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

(** The 0 case is trivial: *)

      inversion 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'. inversion eq. reflexivity. Qed.

(** What you should take away from all this is that we need to be
    careful about using induction to try to prove something too
    specific: To prove a property of [n] and [m] by induction on [n],
    it is sometimes important to leave [m] generic. *)

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

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  intros n. induction n as [| n'].
  - simpl. intros m . destruct m as [| m'].
    + reflexivity.
    + intro contra. inversion contra.

  - intros m. simpl. induction m.
    + intros H. inversion H.
    + intros H. apply IHn' in H. rewrite H. reflexivity.
Qed.

(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)

(* FILL IN HERE *)

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

(** 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'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *) apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (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'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. inversion eq. reflexivity. 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 inversion 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. [] *)

(** Before we close this section and move on to some exercises,
    let's digress briefly and use [beq_nat_true] to prove a similar
    property of identifiers that we'll need in later chapters: *)

Theorem beq_id_true : forall x y,
  beq_id x y = true -> x = y.
Proof.
  intros [m] [n]. simpl. intros H.
  assert (H' : m = n). { apply beq_nat_true. apply H. }
  rewrite H'. reflexivity.
Qed.

(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     nth_error l n = None.
Proof.
  intros n X l. generalize dependent n. induction l as [| h' l'].
  - reflexivity.
  - simpl. intros n H. induction n as [| n'].
    + inversion H.
    + simpl. apply S_injective in H. apply IHl' in H. apply H.
Qed.

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

(** It sometimes happens that we need to manually unfold a Definition
    so that we can manipulate its right-hand side.  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 get stuck: [simpl] doesn't simplify anything at this point,
    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 facts it is not
    hard to finish the proof. *)

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

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

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

Definition foo (x: nat) := 5.

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

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

(** However, this automatic unfolding is rather 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, itself, cannot 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.
  - 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 to make progress 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.
  - 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.  But
    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 beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

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

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

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

(** **** Exercise: 3 stars, optional (combine_split)  *)
(** 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 as [| p l'] .
  - intros l1 l2 H. inversion H. reflexivity.
  - intros l1 l2 H. inversion H. destruct p as [x y]; destruct (split l') as [xs' ys'];
inversion H1. simpl. rewrite IHl'. reflexivity. reflexivity.

Qed.
(** [

] *)

(** However, [destruct]ing compound expressions requires a bit of
    care, as such [destruct]s can sometimes erase information we need
    to complete a proof. *)
(** For example, suppose we define a function [sillyfun1] like
    this: *)

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

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact that [sillyfun1 n] yields [true] only when [n] is
    odd.  By analogy with the proofs we did with [sillyfun] above, it
    is natural to start the proof like this: *)

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

(** We get 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 too brutal -- it threw
    away every occurrence of [beq_nat 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 [beq_nat 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 would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation, giving it a
    name that we choose. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat 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 beq_nat_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, allow us to finish the
        proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

(** **** Exercise: 2 stars (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 (f b) eqn:Hyp_bool.
  - destruct b .
    + rewrite Hyp_bool. apply Hyp_bool.
    + destruct (f true) eqn:Hyp_true.
      { rewrite Hyp_true. reflexivity. }
      { apply Hyp_bool. }
  - destruct b .
    + destruct (f false) eqn:Hyp_false.
      { apply Hyp_bool. }
      { apply Hyp_false. }
    + rewrite Hyp_bool. apply Hyp_bool.
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]

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

      - [inversion]: reason by injectivity and distinctness of
        constructors

      - [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 *)

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

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  intros n m. generalize dependent m. induction n as [| n'].
  - simpl. induction m.
    + reflexivity.
    + reflexivity.
  - simpl. induction m.
    + reflexivity.
    + apply IHn'.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

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

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

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

Definition split_combine_statement : Prop
  (* ("[: Prop]" means that we are giving a name to a
     logical proposition here.) *)
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.

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

(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:

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

      forallb negb [false;false] = true

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

      forallb (beq_nat 5) [] = true

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

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

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

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

      existsb evenb [] = false

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

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

(* FILL IN HERE *)

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


Require Import ct15 ct18 ct19.

Lemma sort_prog_pair : forall (a1 a2 : nat) (l l' l'0 : list nat),
  sorted l' -> permutation l' l ->
  sorted l'0 -> permutation l'0 [a1; a2] ->
  {l'1 : list nat | sorted l'1 /\ permutation l'1 (a1 :: a2 :: l)}.
Proof.
intros; exists (merge l'0 l'); split.
- apply merge_sorted; auto.
- rewrite permutation_merge_concat, H0, H2; simpl; repeat constructor; auto.
Defined.


From Test Require Import tactic.

Section FOFProblem.

Variable Universe : Set.
Variable UniverseElement : Universe.

Variable per_ : Universe -> Universe -> Universe -> Prop.
Variable out_ : Universe -> Universe -> Universe -> Prop.
Variable congA_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.
Variable cong_ : Universe -> Universe -> Universe -> Universe -> Prop.
Variable col_ : Universe -> Universe -> Universe -> Prop.
Variable betS_ : Universe -> Universe -> Universe -> Prop.

Variable lemma_equalanglessymmetric_1 : (forall A B C Xa Xb Xc : Universe, (congA_ A B C Xa Xb Xc -> congA_ Xa Xb Xc A B C)).
Variable defequalangles_2 : (forall A B C Ca Cb Cc : Universe, (exists U V Su Sv : Universe, (congA_ A B C Ca Cb Cc -> (out_ B A U /\ (out_ B C V /\ (out_ Cb Ca Su /\ (out_ Cb Cc Sv /\ (cong_ B U Cb Su /\ (cong_ B V Cb Sv /\ (cong_ U V Su Sv /\ ~(col_ A B C))))))))))).
Variable defequalangles2_3 : (forall A B C Ca Cb Cc U V Su Sv : Universe, ((out_ B A U /\ (out_ B C V /\ (out_ Cb Ca Su /\ (out_ Cb Cc Sv /\ (cong_ B U Cb Su /\ (cong_ B V Cb Sv /\ (cong_ U V Su Sv /\ ~(col_ A B C)))))))) -> congA_ A B C Ca Cb Cc)).
Variable lemma_8_3_4 : (forall A B C D : Universe, ((per_ A B C /\ out_ B C D) -> per_ A B D)).
Variable lemma_8_2_5 : (forall A B C : Universe, (per_ A B C -> per_ C B A)).
Variable lemma_raystrict_6 : (forall A B C : Universe, (out_ A B C -> A <> C)).
Variable lemma_inequalitysymmetric_7 : (forall A B : Universe, (A <> B -> B <> A)).
Variable defrightangle_8 : (forall A B C : Universe, (exists X : Universe, (per_ A B C -> (betS_ A B X /\ (cong_ A B X B /\ (cong_ A C X C /\ B <> C)))))).
Variable defrightangle2_9 : (forall A B C X : Universe, ((betS_ A B X /\ (cong_ A B X B /\ (cong_ A C X C /\ B <> C))) -> per_ A B C)).
Variable axiom_nocollapse_10 : (forall A B C D : Universe, ((A <> B /\ cong_ A B C D) -> C <> D)).
Variable lemma_extension_11 : (forall A B P Q : Universe, (exists X : Universe, ((A <> B /\ P <> Q) -> (betS_ A B X /\ cong_ B X P Q)))).
Variable lemma_doublereverse_12 : (forall A B C D : Universe, (cong_ A B C D -> (cong_ D C B A /\ cong_ B A D C))).
Variable lemma_congruencetransitive_13 : (forall A B C D E F : Universe, ((cong_ A B C D /\ cong_ C D E F) -> cong_ A B E F)).
Variable lemma_congruenceflip_14 : (forall A B C D : Universe, (cong_ A B C D -> (cong_ B A D C /\ (cong_ B A C D /\ cong_ A B D C)))).
Variable lemma_congruencesymmetric_15 : (forall A B C D : Universe, (cong_ B C A D -> cong_ A D B C)).
Variable cn_sumofparts_16 : (forall A B C E F G : Universe, ((cong_ A B E F /\ (cong_ B C F G /\ (betS_ A B C /\ betS_ E F G))) -> cong_ A C E G)).
Variable axiom_5_line_17 : (forall A B C D E F G H : Universe, ((betS_ A B C /\ (betS_ E F G /\ (cong_ B C F G /\ (cong_ A D E H /\ (cong_ B D F H /\ cong_ A B E F))))) -> cong_ D C H G)).
Variable lemma_ray5_18 : (forall A B C : Universe, (out_ A B C -> out_ A C B)).

Theorem lemma_equaltorightisright_19 : (forall A B C Xa Xb Xc : Universe, ((per_ A B C /\ congA_ Xa Xb Xc A B C) -> per_ Xa Xb Xc)).
Proof.
  time tac.
Qed.

End FOFProblem.


(*

  Copyright 2016 University of Luxembourg

  This file is part of our formalization of Platzer's
    "A Complete Uniform Substitution Calculus for Differential Dynamic Logic"
  available here: http://arxiv.org/pdf/1601.06183.pdf (July 27, 2016).
  We refer to this formalization as DdlCoq here.

  DdlCoq is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  DdlCoq is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with DdlCoq.  If not, see <http://www.gnu.org/licenses/>.

  authors:
    Vincent Rahli
    Marcus Völp
    Ivana Vukotic

 *)

Require Export symbol.
Require Export String.
Require Export Reals.
Require Export Coq.Lists.List.
Export List.ListNotations.
Require Vector.

(**

  This file implements ddl syntax for Terms, Formulas, Hybrid programs and ODEs.
  This file is similar to expressions.v but instead of having
  several expression sorts, here we have only one reals (expression
  sorts seem to only be used to build tuples for n-ary functions
  anyway).
  This implementation works with functions with multiple arguments.

 *)

(*This file is similar to sexpressions.v but instead of having only 1 parameter,
functions can now have a multiple parameters. *)

Inductive KTnum :=
| KTNnat  (n : nat) : KTnum
| KTNreal (r : R)   : KTnum.

(** Terms --- see Definition 1, Section 2.1 *)
Inductive Term : Type :=
| KTdot          (n : nat)             : Term        (* dot symbol for terms *)
| KTfuncOf       (f : FunctionSymbol)
                 (n : nat)
                 (a : Vector.t Term n) : Term        (* application of function symbol *)
| KTnumber       (r : KTnum)           : Term        (* number constant *)
| KTread         (var : KAssignable)   : Term        (* read variable x or diff. symbol x' *)
| KTneg          (child : Term)        : Term        (* negation       -x  *)
| KTplus         (left right : Term)   : Term        (* addition       x+y *)
| KTminus        (left right : Term)   : Term        (* subtraction    x-y *)
| KTtimes        (left right : Term)   : Term        (* multiplication x*y *)
| KTdifferential (child : Term)        : Term        (* differential   x'  *)
.

Coercion KTread : KAssignable >-> Term.

Definition nat2term (n : nat) : Term := KTnumber (KTNnat n).
Coercion nat2term : nat >-> Term.

(* A couple of dummy terms *)
Definition DTD : Term := KTdot 0.
Definition DTN : Term := 0.

(** Atomic ODE *)
Inductive AtomicODE : Type :=
| ODEconst (name : ODEConst) : AtomicODE (* constant *)
| ODEsing (xp : KAssignable) (e : Term) : AtomicODE (* x' = e *)
.

(** ODE *)
Inductive ODE : Type :=
| ODEatomic (child : AtomicODE)  : ODE
| ODEprod (left righ : ODE)      : ODE (* . , . *)
.

Coercion ODEatomic : AtomicODE >-> ODE.

(** Formulas --- see Definition 2, Section 2.1 *)
Inductive Formula : Type :=
| KFdot                             : Formula           (* dot symbol for formulas *)
| KFtrue                            : Formula           (* true   *)
| KFfalse                           : Formula           (* false  *)
| KFequal       (left right : Term) : Formula           (* x == y *)
| KFnotequal    (left right : Term) : Formula           (* x != y *)
| KFgreaterEqual(left right : Term) : Formula           (* x >= y *)
| KFgreater     (left right : Term) : Formula           (* x > y  *)
| KFlessEqual   (left right : Term) : Formula           (* x =< y *)
| KFless        (left right : Term) : Formula           (* x < y  *)
| KFpredOf      (f : PredicateSymbol)
                (n : nat)
                (a : Vector.t Term n)                : Formula          (* appliction of predicate symbol *)
(* predicational or quantifier symbol applied to argument formula child *)
| KFquantifier  (f : QuantifierSymbol) (a : Formula) : Formula
| KFnot         (child : Formula)                    : Formula           (* ~p *)
| KFand         (left right : Formula)               : Formula           (* p /\ q *)
| KFor          (left right : Formula)               : Formula           (* p \/ q *)
| KFimply       (left right : Formula)               : Formula           (* p -> q *)
| KFequiv       (left right : Formula)               : Formula           (* p <-> q *)
(* quantifiers *)
| KFforallVars  (vars : list KVariable) (child : Formula)    : Formula           (* Forall x,y,z. p *)
| KFexistsVars  (vars : list KVariable) (child : Formula)    : Formula           (* Exists x,y,z. p *)
(* modal formulas *)
| KFbox         (prog : Program) (child : Formula)           : Formula           (* [alpha] p *)
| KFdiamond     (prog : Program) (child : Formula)           : Formula           (* <alpha> p *)

(** Hybrid programs --- see Definition 3, Section 2.1 *)
with Program : Type :=
     | KPconstant     (name : ProgramConstName)                : Program           (* program constant e.g., alpha *)
     | KPassign       (x : KAssignable) (e : Term)             : Program           (* x := e or x' := e *)
     | KPassignAny    (x : KAssignable)                        : Program           (* x := * or x' := * *)
     | KPtest         (cond : Formula)                         : Program           (* ?cond *)
     | KPchoice       (left : Program)(right : Program)        : Program           (* alpha u beta *)
     | KPcompose      (left : Program)(right : Program)        : Program           (* alpha ; beta *)
     | KPloop         (child : Program)                        : Program           (* alpha* *)
     | KPodeSystem (ode : ODE) (constraint : Formula) : Program
.

(** In order to prove properties for Box and Diamond we have to combine definitions for Formulas and Programs *)
Scheme Formula_ind_2 := Induction for Formula Sort Prop
                        with Program_ind_2 := Induction for Program Sort Prop.

Combined Scheme Formula_Program_multind from Formula_ind_2, Program_ind_2.

Scheme Formula_rec_2 := Induction for Formula Sort Type
                        with Program_rec_2 := Induction for Program Sort Type.

(** expressions of dL *)
Inductive Expression : Type :=
| term    : Term    -> Expression (* terms    *)
| program : Program -> Expression (* programs *)
| formula : Formula -> Expression (* formulas *)
.


(******************************************************************************)
(* This file contains material that should be included into                   *)
(* Coquelicot                                                                 *)
(******************************************************************************)

From mathcomp Require Import ssreflect.
Require Import Reals Coquelicot.Coquelicot Psatz generalities.

(*****************************************************************************)
(* Definition of a < filter                                                  *)
(* Most of this was borrowed from Yves Bertot                                *)
(*****************************************************************************)

Definition filter_Rlt F1 F2 :=
  exists m, filter_prod F1 F2 (fun p => fst p < m < snd p).

Lemma filter_Rlt_witness m (F1 F2  : (R -> Prop) -> Prop) :
  F1 (Rgt m) -> F2 (Rlt m) ->  filter_Rlt F1 F2.
Proof.
exists m; split with (Rgt m) (Rlt m); simpl; auto with real.
Qed.

Lemma filter_Rlt_m_infty_p_infty :
  filter_Rlt (Rbar_locally m_infty) (Rbar_locally p_infty).
Proof.
apply (filter_Rlt_witness 0); exists 0; tauto.
Qed.

Lemma filter_Rlt_m_infty_at_left b :
  filter_Rlt (Rbar_locally m_infty) (at_left b).
Proof.
apply (filter_Rlt_witness (b - 1)).
  now exists (b - 1); intros x cmpx; apply Rlt_gt.
exists posreal_half; intros x yb _.
enough (b - x  < 1) by lra.
apply Rle_lt_trans with (abs (minus b x)).
  now apply Rle_abs.
apply ball_sym in yb; apply AbsRing_norm_compat2 in yb.
apply Rlt_trans with (1 := yb).
rewrite Rmult_1_l; simpl.
lra.
Qed.

Lemma filter_Rlt_at_right_p_infty b :
  filter_Rlt (at_right b) (Rbar_locally p_infty).
Proof.
apply (filter_Rlt_witness (b + 1)).
  exists posreal_half; intros y yb _.
  enough (y - b < 1) by lra.
  apply Rle_lt_trans with (abs (minus y b)).
    now apply Rle_abs.
  apply AbsRing_norm_compat2 in yb.
  apply Rlt_trans with (1 := yb).
  rewrite Rmult_1_l; simpl.
  lra.
now exists (b + 1); intros x cmpx.
Qed.

Lemma filter_Rlt_at_point_p_infty b :
  filter_Rlt (at_point b) (Rbar_locally p_infty).
Proof.
apply (filter_Rlt_witness (b + 1)).
  now unfold at_point; lra.
now exists (b + 1); tauto.
Qed.

Lemma filter_Rlt_m_infty_at_point b :
  filter_Rlt (Rbar_locally m_infty) (at_point b).
Proof.
apply (filter_Rlt_witness (b - 1)).
  now exists (b - 1); tauto.
now unfold at_point; lra.
Qed.

Local Lemma compare_half_sum a b (altb : a < b) : a < (a + b) / 2 < b.
Proof.
assert ((a + b) / 2 * 2 = a + b) by field.
split; apply Rmult_lt_reg_r with 2; lra.
Qed.

Lemma filter_Rlt_at_point a b : a < b ->
  filter_Rlt (at_point a) (at_point b).
Proof.
intros altb; apply filter_Rlt_witness with ((a + b) / 2).
  unfold at_point.
  now destruct (compare_half_sum _ _ altb); tauto.
unfold at_point.
now destruct (compare_half_sum _ _ altb); tauto.
Qed.

Lemma Rplus_minus_cancel1 : forall a b, a + b - a = b.
Proof. intros; ring. Qed.

Lemma filter_Rlt_locally a b : a < b ->
  filter_Rlt (Rbar_locally a) (Rbar_locally b).
Proof.
intros ab.
assert (bmap: 0 < (b - a)/2).
  apply Rmult_lt_reg_r with 2;[lra | ].
  unfold Rdiv; rewrite -> Rmult_0_l, Rmult_assoc.
  rewrite -> Rinv_l, Rmult_1_r;[ | apply Rgt_not_eq]; lra.
apply (filter_Rlt_witness ((a + b)/2)).
  exists (mkposreal _ bmap); intros y ya.
  enough (yma : y * 2 - a * 2 < b - a).
    apply Rmult_lt_reg_r with 2;[lra | ].
    unfold Rdiv; rewrite -> Rmult_assoc, Rinv_l;[ | apply Rgt_not_eq; lra].
    rewrite -> Rmult_1_r; lra.
  rewrite <- Rmult_minus_distr_r; apply Rmult_lt_reg_r with (/2).
    apply Rinv_0_lt_compat; lra.
  rewrite -> Rmult_assoc, Rinv_r, Rmult_1_r;[|apply Rgt_not_eq; lra].
  apply Rle_lt_trans with (abs (minus y a)).
    now apply Rle_abs.
  apply AbsRing_norm_compat2 in ya; apply Rlt_le_trans with (1 := ya).
  now rewrite -> Rmult_1_l; simpl; auto with real.
exists (mkposreal _ bmap); intros y yb.
enough (yma : b * 2 - y * 2 < b - a).
  apply Rmult_lt_reg_r with 2;[lra | ].
  unfold Rdiv; rewrite -> Rmult_assoc, Rinv_l;[ | apply Rgt_not_eq; lra].
  rewrite -> Rmult_1_r; lra.
rewrite <- Rmult_minus_distr_r; apply Rmult_lt_reg_r with (/2).
  apply Rinv_0_lt_compat; lra.
rewrite -> Rmult_assoc, Rinv_r, Rmult_1_r;[|apply Rgt_not_eq; lra].
apply Rle_lt_trans with (abs (minus b y)).
  now apply Rle_abs.
apply ball_sym in yb; apply AbsRing_norm_compat2 in yb.
  apply Rlt_le_trans with (1 := yb).
now rewrite -> Rmult_1_l; simpl; auto with real.
Qed.

Lemma filter_Rlt_left_right  a b : a <= b ->
  filter_Rlt (at_left a) (at_right b).
intros ab; apply (filter_Rlt_witness a).
  now exists posreal_half; intros y _; apply Rgt_lt.
now exists posreal_half; intros y _ yb ; apply Rle_lt_trans with b.
Qed.

Lemma filter_Rlt_trans a F G {FF : Filter F} {GG : Filter G} :
  filter_Rlt F (at_point a) ->
  filter_Rlt (at_point a) G -> filter_Rlt F G.
Proof.
intros [m1 Pm1] [m2 Pm2].
apply filter_Rlt_witness with a.
  destruct Pm1 as [P Q FP atQ cnd1].
  assert (qa : Q a) by now apply atQ; intros; apply ball_center.
  apply (filter_imp P); auto.
  intros x px.
  assert (t := cnd1 x a px qa); simpl in t; destruct t; lra.
destruct Pm2 as [P Q atP GQ cnd2].
assert (pa : P a) by now apply atP; intros; apply ball_center.
apply (filter_imp Q); auto.
intros x qx.
assert (t := cnd2 a x pa qx); simpl in t; destruct t; lra.
Qed.

Lemma filter_Rlt_right_left a b : a < b ->
  filter_Rlt (at_right a) (at_left b).
Proof.
intros ab.
assert (bmap: 0 < (b - a)/2).
  apply Rmult_lt_reg_r with 2;[lra | ].
  unfold Rdiv; rewrite -> Rmult_0_l, Rmult_assoc.
  rewrite -> Rinv_l, Rmult_1_r;[ | apply Rgt_not_eq]; lra.
apply (filter_Rlt_witness ((a + b)/2)).
  exists (mkposreal _ bmap); intros y ya cmp.
  enough (yma : y * 2 - a * 2 < b - a).
    apply Rmult_lt_reg_r with 2;[lra | ].
    unfold Rdiv; rewrite -> Rmult_assoc, Rinv_l;[ | apply Rgt_not_eq; lra].
    rewrite -> Rmult_1_r; lra.
  rewrite <- Rmult_minus_distr_r; apply Rmult_lt_reg_r with (/2).
    apply Rinv_0_lt_compat; lra.
  rewrite -> Rmult_assoc, Rinv_r, Rmult_1_r;[|apply Rgt_not_eq; lra].
  apply Rle_lt_trans with (abs (minus y a)).
    now apply Rle_abs.
  apply AbsRing_norm_compat2 in ya; apply Rlt_le_trans with (1 := ya).
  now rewrite -> Rmult_1_l; simpl; auto with real.
exists (mkposreal _ bmap); intros y yb cmp.
enough (yma : b * 2 - y * 2 < b - a).
  apply Rmult_lt_reg_r with 2;[lra | ].
  unfold Rdiv; rewrite -> Rmult_assoc, Rinv_l;[ | apply Rgt_not_eq; lra].
  rewrite -> Rmult_1_r; lra.
rewrite <- Rmult_minus_distr_r; apply Rmult_lt_reg_r with (/2).
  apply Rinv_0_lt_compat; lra.
rewrite -> Rmult_assoc, Rinv_r, Rmult_1_r;[|apply Rgt_not_eq; lra].
apply Rle_lt_trans with (abs (minus b y)).
  now apply Rle_abs.
apply ball_sym in yb; apply AbsRing_norm_compat2 in yb.
  apply Rlt_le_trans with (1 := yb).
now rewrite -> Rmult_1_l; simpl; auto with real.
Qed.

Local Ltac chain_comparisons :=
  match goal with
  | h : ?a <= _ |- ?a < _ => apply Rle_lt_trans with (1 := h)
  | h : _ <= ?a |- _ < ?a => apply Rlt_le_trans with (2 := h)
  | h : ?a < _ |- ?a < _ => apply Rlt_trans with (1 := h)
  | h : _ < ?a |- _ < ?a => apply Rlt_trans with (2 := h)
  end.

Lemma ex_RInt_gen_bound (g : R -> R) (f : R -> R) F G
  {PF : ProperFilter F} {PG : ProperFilter G} :
  filter_Rlt F G ->
  ex_RInt_gen g F G ->
  filter_prod F G
    (fun p => (forall x, fst p < x < snd p -> 0 <= f x <= g x) /\
       ex_RInt f (fst p) (snd p)) ->
    ex_RInt_gen f F G.
Proof.
intros [m mmid] [gl intg] cmp.
assert (F (Rgt m)).
  destruct mmid as [pf pg fpf gpg cmp'].
  apply (filter_imp pf); destruct (filter_ex pg) as [y py]; auto.
  intros x px; destruct (cmp' x y px py) as [it _]; exact it.
assert (G (Rlt m)).
  destruct mmid as [pf pg fpf gpg cmp'].
  apply (filter_imp pg); destruct (filter_ex (F := F) pf) as [x px]; auto.
  intros y py; destruct (cmp' x y px py) as [_ it]; exact it.
exists (lim (filtermap (fun p => RInt f (fst p) (snd p)) (filter_prod F G))).
destruct cmp as [Q1 R1 fq1 gr1 cmp]; simpl in cmp.
assert (cc : cauchy (filtermap (fun p => RInt f (fst p) (snd p))
                       (filter_prod F G))).
  intros eps.
  destruct (intg _ (locally_ball gl (pos_div_2 eps))) as [Qg Rg FQg GRg main].
  assert (fq : F (fun x => Q1 x /\ Qg x /\ m > x))
    by now repeat apply filter_and.
  assert (gr : G (fun x => R1 x /\ Rg x /\ m < x))
    by now repeat apply filter_and.
  destruct (filter_ex _ fq) as [x qx], (filter_ex _ gr) as [y ry].
    exists (RInt f x y).
  exists (fun x => Q1 x /\ Qg x /\ m > x)
         (fun y => R1 y /\ Rg y /\ m < y);
    try now repeat apply filter_and.
  intros u v Qu Rv.
  assert (wlog_cc : forall a b c d,
            Q1 a /\ Qg a ->
            Q1 b /\ Qg b ->
            R1 c /\ Rg c ->
            R1 d /\ Rg d ->
            a <= b -> c <=d -> b < m -> m < c ->
            (ball (RInt f a d) eps (RInt f b c) /\
            ball (RInt f a c) eps (RInt f b d))).
    clear x y qx ry u v Qu Rv; intros a b c d Qa Qb Rc Rd ab cd bm mc.
    assert (ex_RInt f a c /\ ex_RInt f b c /\ ex_RInt f b d).
      now repeat apply conj; apply cmp.
    move main after mc.
    destruct (main a c) as [gac [acP acQ]]; try tauto; simpl in acP.
    assert (ex_RInt g a c) by (eapply ex_intro; eauto).
    destruct (main b c) as [gbc [bcP bcQ]]; try tauto; simpl in bcP.
    assert (ex_RInt g b c) by (eapply ex_intro; eauto).
    destruct (main b d) as [gbd [bdP bdQ]]; try tauto; simpl in bdP.
    assert (ex_RInt g b d) by (eapply ex_intro; eauto).
    assert (ex_RInt f a b).
      now apply ex_RInt_Chasles with c;[ | apply ex_RInt_swap].
    assert (ex_RInt f c d).
      now apply ex_RInt_Chasles with b;[apply ex_RInt_swap | ].
    assert (ex_RInt g a b).
      now apply ex_RInt_Chasles with c;[ | apply ex_RInt_swap];
       eapply ex_intro; eauto.
    assert (ex_RInt g c d).
      now apply ex_RInt_Chasles with b;[apply ex_RInt_swap | ];
       eapply ex_intro; eauto.
    assert (bc : b < c) by (apply Rlt_trans with m; tauto).
    split.
      apply ball_sym, Rle_lt_trans with (Rabs (RInt g a d - RInt g b c)).
        rewrite <- (RInt_Chasles f a b d), <- (RInt_Chasles f b c d),
                <- (RInt_Chasles g a b d), <- (RInt_Chasles g b c d),
               !(Rplus_comm (RInt _ a b)), !Rplus_assoc, !Rplus_minus_cancel1;
         try tauto.
        unfold abs; simpl; rewrite -> !Rabs_right;
        try (apply Rle_ge, Rplus_le_le_0_compat; apply RInt_ge_0; auto);
(* The following fragment duplicated several times. *)
        try (intros x [x1 x2]; enough (0 <= f x <= g x)
           by (solve[tauto | apply Rle_trans with (f x); tauto]);
           apply (cmp a d); try tauto; split;
           solve[repeat (auto; chain_comparisons)]).
        apply Rplus_le_compat; apply RInt_le; try tauto;
(* the following fragment duplicated several times. *)
        try (intros x [x1 x2]; enough (0 <= f x <= g x)
           by (solve[tauto | apply Rle_trans with (f x); tauto]);
           apply (cmp a d); try tauto; split;
           solve[repeat (auto; chain_comparisons)]).
      change (ball (RInt g b c) eps (RInt g a d)).
      replace (pos eps) with (pos_div_2 eps + pos_div_2 eps) by (simpl; field).
      apply ball_triangle with gl.
        now rewrite -> (is_RInt_unique _ _ _ _ bcP); apply ball_sym.
      destruct (main a d) as [gad [adP adQ]]; try tauto; simpl in adP.
      now rewrite -> (is_RInt_unique _ _ _ _ adP).
    change (Rabs (RInt f b d + - RInt f a c) < eps).
    rewrite <- (RInt_Chasles f b c d), <- (RInt_Chasles f a b c),
      Ropp_plus_distr, !Rplus_assoc, (Rplus_comm (RInt f b c)), !Rplus_assoc,
      Rplus_opp_l, Rplus_0_r; try tauto.
    apply Rle_lt_trans with (1 := Rabs_triang _ _);
       rewrite -> Rabs_Ropp, !Rabs_right;
    try (apply Rle_ge, RInt_ge_0; try tauto);
(* the following fragment duplicated several times. *)
        try (intros x [x1 x2]; enough (0 <= f x <= g x)
           by (solve[tauto | apply Rle_trans with (f x); tauto]);
           apply (cmp a d); try tauto; split;
           solve[repeat (auto; chain_comparisons)]).
    replace (pos eps) with (pos_div_2 eps + pos_div_2 eps)
             by (simpl; field).
    assert (dc : RInt f c d <= RInt g c d /\ RInt f a b <= RInt g a b).
      split; apply RInt_le; try tauto;
(* the following fragment duplicated several times. *)
        try (intros x [x1 x2]; enough (0 <= f x <= g x)
           by (solve[tauto | apply Rle_trans with (f x); tauto]);
           apply (cmp a d); try tauto; split;
           solve[repeat (auto; chain_comparisons)]).
    apply Rle_lt_trans with (1 := Rplus_le_compat _ _ _ _ (proj1 dc)(proj2 dc)).
    apply Rle_lt_trans with (1 := Rle_abs _).
    replace (RInt _ _ _ + _) with
      ((RInt g a d - gl) - (RInt g b c - gl)) by (*TODO : explain this! *)
    (rewrite <- (RInt_Chasles g a b d), <- (RInt_Chasles g b c d);
            try tauto; set (zoo := plus); change zoo with Rplus; ring).
    apply Rle_lt_trans with (1 := Rabs_triang _ _), Rplus_lt_compat.
      destruct (main a d) as [gad [adP adQ]]; try tauto; simpl in adP.
      now rewrite -> (is_RInt_unique _ _ _ _ adP).
    now rewrite -> Rabs_Ropp; rewrite -> (is_RInt_unique _ _ _ _ bcP).
  destruct (Rlt_dec x u), (Rlt_dec v y);
   [apply (wlog_cc x u v y) | apply (wlog_cc x u y v) |
    apply ball_sym, (wlog_cc u x v y) | apply ball_sym, (wlog_cc u x y v)];
    try split;
    try solve[tauto | apply Rlt_le; tauto |
      apply Rge_le; tauto | apply Rle_ge; tauto|
      apply Rnot_lt_le; tauto].
intros P [eps Peps].
move cc after Peps.
unfold filtermapi.
assert (tmp := complete_cauchy _ _ cc eps).
destruct tmp as [Q2 R2 Q2P R2P PP2].
exists (fun x => Q2 x /\ Q1 x) (fun x => R2 x /\ R1 x);
  try (apply filter_and; auto).
intros x y [Q2x Q1x] [R2x R1x].
destruct (cmp x y Q1x R1x) as [cmp' [fxy intxy]].
exists fxy; split;[assumption | apply Peps].
rewrite <- (is_RInt_unique _ _ _ _ intxy); apply PP2; auto.
Qed.

Lemma is_RInt_gen_Rle (g : R -> R) gl (f : R -> R) fl F G
  {PF : ProperFilter F} {PG : ProperFilter G} :
  filter_Rlt F G ->
  is_RInt_gen g F G gl ->
  is_RInt_gen f F G fl ->
  filter_prod F G
    (fun p => (forall x, fst p < x < snd p -> f x <= g x)) ->
    fl <= gl.
Proof.
intros [m mmid] intg intf cmp.
apply (filterlim_le (F := filter_prod F G) (fun p => RInt f (fst p) (snd p))
          (fun p => RInt g (fst p) (snd p)) fl gl).
    specialize (intf _ (locally_ball fl (mkposreal _ Rlt_0_1))).
    specialize (intg _ (locally_ball gl (mkposreal _ Rlt_0_1))).
    unfold filtermapi in intg, intf.
    apply: filter_imp (filter_and _ _ (filter_and _ _ intg intf)
                          (filter_and _ _ mmid cmp)).
    intros [a b]; simpl; intros [[[Ig [Hg1 Hg2]] [If [Hf1 Hf2]]] [cmp']].
    apply RInt_le;
      [apply Rle_trans with m;apply Rlt_le | exists If| exists Ig| ]; tauto.
  intros P HP; specialize (intf P HP); unfold filtermapi, filtermap in intf |- *.
  apply: filter_imp intf.
  intros [a b]; simpl; intros [y [inty Py]].
  now  rewrite -> (is_RInt_unique _ _ _ _ inty).
intros P HP; specialize (intg P HP); unfold filtermapi, filtermap in intg |- *.
apply: filter_imp intg.
intros [a b]; simpl; intros [y [inty Py]].
now  rewrite -> (is_RInt_unique _ _ _ _ inty).
Qed.

Lemma is_RInt_gen_at_point_at_right (f : R -> R) (a : R) F {FF : ProperFilter F}
  v : locally a (continuous f) -> is_RInt_gen f (at_point a) F v ->
  filter_Rlt (at_point a) F ->  is_RInt_gen f (at_right a) F v.
Proof.
intros [delta1 pd1] intf [m [P Q FP FQ cmp]]; simpl in cmp.
destruct (pd1 a (ball_center a delta1)
          (ball (f a) (mkposreal _ Rlt_0_1)) (locally_ball _ _)) as
    [delta2 Pd2].
assert (pa : P a) by (apply FP; intros; apply ball_center).
assert (intf2 := intf).
intros P2 PP2; specialize (intf P2 PP2); destruct PP2 as [eps P2eps].
set (M := Rabs (f a) + 1).
assert (M0 : 0 < eps / M).
  apply Rmult_lt_0_compat;[apply cond_pos | apply Rinv_0_lt_compat].
  now assert (0 <= Rabs (f a)) by apply Rabs_pos; unfold M; lra.
assert (close : forall y, y <> a -> ball a delta2 y -> Rabs (f y) < M).
  intros y ay b_y; unfold M.
  replace (f y) with (f a + (f y - f a)) by ring.
  apply Rle_lt_trans with (1 := Rabs_triang _ _).
  now apply Rplus_lt_compat_l, Pd2; auto.
assert (exrint_close : forall a', ball a delta1 a' -> ex_RInt f a a').
  intros a' baa'.
  apply (ex_RInt_continuous f); intros z pz; apply pd1.
  destruct (Rle_dec a a') as [aa' | a'a].
    rewrite -> Rmin_left, Rmax_right in pz; auto.
    change (Rabs (z - a) < delta1).
    rewrite -> Rabs_right; cycle 1.
      destruct pz; lra.
    destruct pz; apply Rle_lt_trans with (a' - a); try lra.
    rewrite <- (Rabs_right (a' - a)); try lra.
    tauto.
  change (Rabs (z - a) < delta1).
  destruct (Rle_dec a z) as [az | za].
    apply Rnot_le_lt in a'a.
    rewrite -> Rmin_right, Rmax_left in pz; try (destruct pz; lra).
    assert (za' : z = a).
      now apply Rle_antisym; (destruct pz; lra).
    now rewrite -> za', Rminus_eq_0, Rabs_R0; case delta1; tauto.
  apply Rnot_le_lt in a'a; apply Rnot_le_lt in za.
  rewrite -> Rmin_right, Rmax_left in pz; try lra.
  rewrite -> Rabs_left;[ | lra].
  apply Rle_lt_trans with (a - a'); try (intuition lra).
  rewrite <- (Rabs_right (a - a')); try (intuition lra).
  now change (ball a' delta1 a); apply ball_sym; tauto.
assert (pre_ep2 : 0 < eps / 2 * /M).
  repeat apply Rmult_lt_0_compat; try lra;[destruct eps; tauto | ].
  now apply Rinv_0_lt_compat; unfold M; assert (t := Rabs_pos (f a)); lra.
set (ep2 := mkposreal _ pre_ep2).
assert (at_right a (fun x => ball a delta1 x /\ ball a ep2 x /\
                             ball a delta2 x /\ a < x /\ x < m)).
  repeat apply filter_and; try (now apply filter_le_within, locally_ball).
    now exists ep2; intros; tauto.
  destruct (filter_ex _ FQ) as [y' Py'].
  assert (ma0 : 0 < m - a).
    now destruct (cmp a y'); auto; lra.
  exists (mkposreal _ ma0); simpl; intros y.
  intros bay ay; change (Rabs (y - a) < m - a) in bay.
  now rewrite -> Rabs_right in bay; lra.
specialize (intf2 _ (locally_ball v (pos_div_2 eps))).
destruct intf2 as [Pl Ql FPl FQl closerint].
assert (pla : Pl a) by (apply FPl; intros; apply ball_center).
assert (F (fun y => Q y /\ Ql y)) by (apply filter_and; auto).
exists (fun x => ball a delta1 x /\ ball a ep2 x /\
                 ball a delta2 x /\ a < x /\ x < m)
       (fun y => Q y /\ Ql y); auto.
intros x y bx Ry; exists (RInt f x y).
destruct (closerint a y) as [fay [close_fay]]; try tauto.
split.
  simpl. apply (RInt_correct f x y).
  apply (ex_RInt_Chasles_2 f a);[ | exists fay; tauto].
  split; apply Rlt_le;
    [| apply Rlt_trans with m; assert (t := cmp a y pa (proj1 Ry))]; tauto.
apply P2eps.
assert (Rabs (RInt f a x) < pos_div_2 eps).
  apply Rle_lt_trans with ((x - a) * M).
    apply abs_RInt_le_const;[apply Rlt_le; tauto | | ].
      now apply exrint_close; tauto.
    intros t atx.
    replace (f t) with (f a + (f t - f a)) by ring.
    apply Rle_trans with (1 := Rabs_triang _ _).
    apply Rplus_le_compat;[apply Rle_refl | ].
    apply Rlt_le, (Pd2 t).
    change (Rabs (t - a) < delta2); rewrite -> Rabs_right;[ | intuition lra].
    apply Rle_lt_trans with (x - a);[intuition lra | ].
    now rewrite <- (Rabs_right (x - a));[tauto | intuition lra].
  replace (pos (pos_div_2 eps)) with (ep2 * M).
    rewrite <- (Rabs_right (x - a));[|intuition lra].
    apply Rmult_lt_compat_r;[unfold M  | tauto].
    now assert (t := Rabs_pos (f a)); lra.
  simpl; field; unfold M; apply Rgt_not_eq; assert (t := Rabs_pos (f a)).
  now lra.
replace (pos eps) with (pos_div_2 eps + pos_div_2 eps) by (simpl; field).
apply ball_triangle with (RInt f a y); cycle 1.
  change (Rabs (RInt f x y - RInt f a y) < pos_div_2 eps).
  replace (RInt f a y) with (RInt f a x + RInt f x y); cycle 1.
  apply (RInt_Chasles f).
      now apply exrint_close; tauto.
    apply (ex_RInt_Chasles_2 f a).
      split;[apply Rlt_le; tauto | apply Rlt_le, Rlt_trans with m; try tauto].
    now destruct (cmp a y); tauto.
  now exists fay.
  match goal with |- Rabs ?v < _ => replace v with (-RInt f a x) by ring end.
  now rewrite -> Rabs_Ropp.
now rewrite -> (is_RInt_unique f a y fay).
Qed.

Lemma ex_RInt_gen_cut (a : R) (F G: (R -> Prop) -> Prop)
   {FF : ProperFilter F} {FG : ProperFilter G} (f : R -> R) :
   filter_Rlt F (at_point a) -> filter_Rlt (at_point a) G ->
   ex_RInt_gen f F G -> ex_RInt_gen f (at_point a) G.
Proof.
intros lFa laG [vfg Pvfg].
assert (lFG := filter_Rlt_trans _ _ _ lFa laG).
set (v := R_complete_lim (filtermap (fun x => RInt f a x) G)).
exists v; intros P PP2.
destruct laG as [m [S1 S2 p1 p2 laG]]; cbn in laG.
destruct lFa as [m' [S5 S6 p5 p6 lFa]]; cbn in lFa.
assert (S6 a) by apply p6.
assert (S1 a) by apply p1.
assert (t': forall eps : posreal, exists x,
         filtermap (fun x => RInt f a x) G (ball x eps)).
  intros eps.
  specialize (Pvfg (ball vfg (pos_div_2 eps)) (locally_ball _ _)).
  destruct Pvfg as [S7 S8 p7 p8 vfg'].
  destruct (filter_ex (F := G)
                (fun y => S8 y /\ S2 y)) as [y Py].
    repeat apply filter_and; tauto.
  exists (RInt f a y); destruct (filter_ex (F := F)
                        (fun x => S7 x /\ S5 x)) as [x Px].
    repeat apply filter_and; tauto.
  unfold filtermap; apply (filter_imp (fun y => S8 y /\ S2 y)).
  intros z PZ; change (Rabs (RInt f a z - RInt f a y) < eps).
  replace (RInt f a z - RInt f a y) with
          ((RInt f x a + RInt f a z) - (RInt f x a + RInt f a y)) by ring.
    destruct (vfg' x y) as [xy pxy]; try tauto.
    destruct (vfg' x z) as [xz pxz]; try tauto.
    assert (ex_RInt f x y) by (exists xy; tauto).
    assert (ex_RInt f x z) by (exists xz; tauto).
    assert (x < a) by (destruct (lFa x a); intuition lra || tauto).
    assert (a < y) by (destruct (laG a y); intuition lra || tauto).
    assert (a < z) by (destruct (laG a z); intuition lra || tauto).
    assert (ex_RInt f x a).
      apply (ex_RInt_Chasles_1 f x a y);[intuition lra | assumption].
    rewrite -> !(RInt_Chasles f); auto;
       try (apply (ex_RInt_Chasles_2 f x); auto; intuition lra); cycle 1.
    change (ball (RInt f x y) eps (RInt f x z)).
    replace (pos eps) with (pos_div_2 eps + pos_div_2 eps) by (simpl; field).
    replace (RInt f x y) with xy by (symmetry; apply is_RInt_unique; tauto).
    replace (RInt f x z) with xz by (symmetry; apply is_RInt_unique; tauto).
    now apply (ball_triangle _ vfg); [apply ball_sym | ]; tauto.
  now repeat apply filter_and; tauto.
destruct PP2 as [eps Peps].
assert (t := (R_complete
            (filtermap (fun x => RInt f a x) G) _
            t' eps)).
unfold filtermap, filtermapi in t |- *.
assert (atpa : at_point a (eq a)) by reflexivity.
enough (H1 : exists S4, G S4 /\ forall x, S4 x -> is_RInt f a x (RInt f a x)).
  destruct H1 as [S4 [gs4 Ps4]].
  apply (Filter_prod (at_point a) G _ (eq a)
           (fun x => ball
             (R_complete_lim
                (fun P : R -> Prop => G (fun x0 => P (RInt f a x0)))) eps
           (RInt f a x) /\ S4 x) atpa (filter_and _ _ t gs4)).
  intros x y <- dist.
  now exists (RInt f a y);split;[apply Ps4; tauto| apply Peps; tauto].
destruct (Pvfg (ball vfg (mkposreal _ Rlt_0_1))) as [S3 S4 fs3 gs4 Ps4].
  now apply locally_ball.
assert (F (Rgt a)).
  apply (filter_imp S5); [intros x s5x | auto].
  assert (s6a : S6 a) by apply p6.
  destruct (lFa x a s5x s6a); lra.
destruct (filter_ex (F := F) (fun x => a > x /\ S3 x)) as [w Pw];
  [apply filter_and; auto | ].
exists (fun x => S4 x /\ a < x); split;[ | intros x px; apply (RInt_correct f)].
  apply filter_and;[assumption | apply (filter_imp S2);[intros x s2x | easy]].
  assert (s1a : S1 a) by apply p1.
  destruct (laG a x s1a s2x); lra.
apply ex_RInt_Chasles_2 with w;[split; apply Rlt_le; tauto | ].
destruct (Ps4 w x) as [wx [Pwx closewx]]; try tauto; exists wx; tauto.
Qed.

Lemma is_RInt_gen_at_point_at_left (f : R -> R) (a : R) F {FF : ProperFilter F}
  v : locally a (continuous f) -> is_RInt_gen f F (at_point a) v ->
  filter_Rlt F (at_point a) ->  is_RInt_gen f F (at_left a) v.
Proof.
move=> [delta1 pd1] intf [m [P Q FP FQ /= cmp]] P2 PP2.
have [delta2 Pd2] :=
   (pd1 a (ball_center a delta1)
          (ball (f a) (mkposreal _ Rlt_0_1)) (locally_ball _ _)).
have qa : Q a by (apply: FQ => *; apply: ball_center).
have intf2 := intf P2 PP2.
have [eps P2eps] := PP2.
pose M := Rabs (f a) + 1.
have M0 : 0 < eps / M.
  apply: Rmult_lt_0_compat; first by apply: cond_pos.
  apply: Rinv_0_lt_compat.
  have RH : 0 <= Rabs (f a) by apply: Rabs_pos.
  by rewrite /M; lra.
have close y : y <> a -> ball a delta2 y -> Rabs (f y) < M.
  move=> ay b_y; rewrite /M (_: f y = f a + (f y - f a)); last by lra.
  apply: Rle_lt_trans (Rabs_triang _ _) _.
  by apply/Rplus_lt_compat_l/Pd2.
have exrint_close a' : ball a delta1 a' -> ex_RInt f a' a.
  move=> baa'.
  apply: (ex_RInt_continuous f)=> z pz; apply: pd1.
  have [aa' | a'a] := Rle_dec a a'.
    move: pz; rewrite Rmin_right // Rmax_left // => pz.
    change (Rabs (z - a) < delta1).
    rewrite Rabs_right; try lra.
    apply: Rle_lt_trans (_ : a' - a < _); try lra.
    rewrite -(Rabs_right (a' - a)); try lra.
    tauto.
  change (Rabs (z - a) < delta1).
  have [az | za] := Rle_dec a z.
    have a'aW :=  Rnot_le_lt _ _ a'a.
    move: pz; rewrite Rmin_left; try lra.
    rewrite Rmax_right => [pz|]; try lra.
    have za' : z = a by apply: Rle_antisym; lra.
    by rewrite za' Rminus_eq_0 Rabs_R0; case delta1.
  have a'a1 :=  Rnot_le_lt _ _ a'a; have za1 :=  Rnot_le_lt _ _ za.
  move: pz; rewrite Rmin_left; try lra.
  rewrite Rmax_right => [pz|]; try lra.
  apply: Rle_lt_trans (_ : a - a' < _); try (split_Rabs; lra).
  rewrite -(Rabs_right (a - a')); try (split_Rabs; lra).
  by change (ball a' delta1 a); apply: ball_sym.
have pre_ep2 : 0 < eps / 2 * /M.
  repeat apply: Rmult_lt_0_compat; try lra.
    by destruct eps; tauto.
  by apply: Rinv_0_lt_compat; rewrite /M; assert (t := Rabs_pos (f a)); lra.
pose ep2 := mkposreal _ pre_ep2.
have aH : (at_left a (fun x => ball a delta1 x /\ ball a ep2 x /\
                             ball a delta2 x /\ m < x /\ x < a)).
  repeat apply: filter_and;
     try (by apply: filter_le_within; apply: locally_ball).
    have  [y' Py'] := filter_ex _ FP.
    have ma0 : 0 < a - m by case:  (cmp y' a) => //; lra.
    exists (mkposreal _ ma0) => /= y.
    rewrite ball_Rabs => bay ay; rewrite Rabs_left in bay; lra.
  by exists ep2.
have [Pl Ql FPl FQl closerint] := intf _ (locally_ball v (pos_div_2 eps)).
have pla : Ql a by apply: FQl => *; apply: ball_center.
have HF : F (fun y => P y /\ Pl y) by apply: filter_and.
exists (fun y => P y /\ Pl y)
       (fun x => ball a delta1 x /\ ball a ep2 x /\
                 ball a delta2 x /\ m < x /\ x < a) => // x y bx Ry.
exists (RInt f x y).
have [||fxa [close_fxa]] // := closerint x a; first by tauto.
split => /=.
  apply: (RInt_correct f x y).
  apply: (ex_RInt_Chasles_1 f _ _ a); last by exists fxa; tauto.
  split; apply: Rlt_le; last by tauto.
  apply: Rlt_trans (_ : m < _); last by tauto.
  by assert (t := cmp x a (proj1 bx) qa); tauto.
apply: P2eps.
have RH :  Rabs (RInt f y a) < pos_div_2 eps.
  apply: Rle_lt_trans (_ : (a - y) * M < _).
    apply: abs_RInt_le_const => [||t yta]; first by apply: Rlt_le; tauto.
      by apply: exrint_close; tauto.
    rewrite (_ : f t =f a + (f t - f a)); last by lra.
    apply: Rle_trans (Rabs_triang _ _) _.
    apply: Rplus_le_compat (Rle_refl _) _.
    apply/Rlt_le/(Pd2 t).
    change (Rabs (t - a) < delta2); rewrite Rabs_left1; try lra.
    apply: Rle_lt_trans (_ : a - y < _); try lra.
    rewrite -(Rabs_right (a - y)); try lra.
    by rewrite -Rabs_Ropp Ropp_minus_distr; tauto.
  rewrite (_ : pos (pos_div_2 eps) = ep2 * M) /=.
    rewrite -(Rabs_right (a - y)); try lra.
    apply: Rmult_lt_compat_r.
      by assert (t := Rabs_pos (f a)); rewrite /M; lra.
    by rewrite -Rabs_Ropp Ropp_minus_distr; tauto.
  by field; rewrite /M; apply: Rgt_not_eq; assert (t := Rabs_pos (f a)); lra.
rewrite (_ : pos eps = pos_div_2 eps + pos_div_2 eps) /=; last by field.
apply: ball_triangle (_ : ball v (eps / 2) (RInt f x a)) _; last first.
  change (Rabs (RInt f x y - RInt f x a) < pos_div_2 eps).
  rewrite (_ : RInt f x a = RInt f x y + RInt f y a); last first.
    apply/sym_equal/(RInt_Chasles f); last by apply: exrint_close; tauto.
    apply: (ex_RInt_Chasles_1 f _ _ a); last by exists fxa.
    split.
      by apply/Rlt_le/(Rlt_trans _ _ _ _ (_ : m < _)); case: (cmp x a); tauto.
    by apply: Rlt_le; tauto.
  by split_Rabs; lra.
by rewrite (is_RInt_unique f x a fxa).
Qed.


Require Export XR_R.
Require Export XR_R0.
Require Export XR_Rmult.
Require Export XR_Rmult_integral_contrapositive.

Local Open Scope R_scope.
Implicit Type r : R.

Lemma Rmult_integral_contrapositive_currified :
  forall r1 r2, r1 <> R0 -> r2 <> R0 -> r1 * r2 <> R0.
Proof.
  intros x y.
  intros hx hy.
  apply Rmult_integral_contrapositive.
  split.
  { exact hx. }
  { exact hy. }
Qed.


From Hammer Require Import Hammer.

Set Warnings "-notation-overridden".

Require Import Coq.NArith.NArith.
Require Import Coq.FSets.FMaps.

Require Import Category.Lib.
Require Import Category.Lib.Nomega.
Require Import Category.Lib.FMapExt.
Require Import Category.Lib.MapDecide.
Require Import Category.Theory.Functor.

Generalizable All Variables.
Set Primitive Projections.
Set Universe Polymorphism.

Record Metacategory := {
arrow := N;
pairs : M.t arrow;

composite (f g h : arrow) := M.find (f, g) pairs = Some h;
defined (f g : arrow) := ∃ h, composite f g h;

composite_defined {f g h : arrow} (H : composite f g h) :
defined f g := (h; H);

composite_correct {f g h fg gh : arrow} :
composite f g fg ->
composite g h gh -> ∃ fgh, composite fg h fgh;

composition_law {f g h fg gh : arrow} :
composite f g fg ->
composite g h gh ->
∀ fgh, composite fg h fgh ↔ composite f gh fgh;

is_identity (u : arrow) :=
(∀ f, defined f u -> composite f u f) ∧
(∀ g, defined u g -> composite u g g);

identity_law (x y f : arrow) : composite x y f ->
∃ u u', is_identity u -> is_identity u' ->
composite f u f ∧ composite u' f f
}.

Section Category.

Context (M : Metacategory).

Record object := {
obj_arr : arrow M;
obj_def : composite M obj_arr obj_arr obj_arr;
obj_id  : is_identity M obj_arr
}.

Record morphism (dom cod : object) := {
mor_arr : arrow M;
mor_dom : composite M mor_arr (obj_arr dom) mor_arr;
mor_cod : composite M (obj_arr cod) mor_arr mor_arr
}.

Arguments mor_arr {_ _} _.
Arguments mor_dom {_ _} _.
Arguments mor_cod {_ _} _.

Definition identity (x : object) : morphism x x :=
{| mor_arr := obj_arr x
; mor_dom := obj_def x
; mor_cod := obj_def x |}.

Lemma composition_left {x y z : object}
{f : morphism y z} {g : morphism x y} {fg : arrow M} :
composite M (mor_arr f) (mor_arr g) fg ->
composite M (obj_arr z) (mor_arr f) (mor_arr f) ->
composite M (obj_arr z) fg fg.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_left".
intros.
destruct z, obj_id0, f, g; simpl in *.
specialize (c0 _ (composite_defined M H0)); clear H0.
destruct (composite_correct M c0 H).
spose (fst (composition_law M c0 H _) e) as X.
unfold composite, arrow in *.
rewrite X, <- H, <- e; reflexivity.
Qed.

Lemma composition_right {x y z : object}
{f : morphism y z} {g : morphism x y} {fg : arrow M} :
composite M (mor_arr f) (mor_arr g) fg ->
composite M (mor_arr g) (obj_arr x) (mor_arr g) ->
composite M fg (obj_arr x) fg.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_right".
intros.
destruct x, obj_id0, f, g; simpl in *.
specialize (c _ (composite_defined M H0)); clear H0.
destruct (composite_correct M H c).
spose (fst (composition_law M H c _) e) as X.
unfold composite, arrow in *.
rewrite e, <- H, <- X; reflexivity.
Qed.

Definition composition {x y z : object}
(f : morphism y z) (g : morphism x y) : morphism x z :=
let fg := composite_correct M (mor_dom f) (mor_cod g) in
{| mor_arr := `1 fg
; mor_dom := composition_right (f:=f) (`2 fg) (mor_dom g)
; mor_cod := composition_left  (g:=g) (`2 fg) (mor_cod f) |}.

Global Program Instance morphism_preorder : PreOrder morphism := {
PreOrder_Reflexive  := identity;
PreOrder_Transitive := fun _ _ _ g f => composition f g
}.

Global Program Instance morphism_setoid (x y : object) :
Setoid (morphism x y) := {
equiv := fun f g => mor_arr f = mor_arr g
}.

Lemma composition_respects {x y z : object} :
Proper (equiv ==> equiv ==> equiv) (@composition x y z).
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_respects".
proper.
destruct x0, y0, x1, y1; simpl in *; subst.
repeat destruct (composite_correct _ _ _); simpl in *.
unfold composite, arrow in *.
rewrite e in e0.
inversion_clear e0.
reflexivity.
Qed.

Lemma composition_identity_left {x y : object} (f : morphism x y) :
composition (identity y) f ≈ f.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_identity_left".
destruct f; simpl.
destruct (composite_correct _ _ _); simpl in *.
unfold composite, arrow in *.
rewrite mor_cod0 in e.
inversion_clear e.
reflexivity.
Qed.

Lemma composition_identity_right {x y : object} (f : morphism x y) :
composition f (identity x) ≈ f.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_identity_right".
destruct f; simpl.
destruct (composite_correct _ _ _); simpl in *.
unfold composite, arrow in *.
rewrite mor_dom0 in e.
inversion_clear e.
reflexivity.
Qed.

Lemma composition_associative {x y z w : object}
(f : morphism z w) (g : morphism y z) (h : morphism x y) :
composition f (composition g h) ≈ composition (composition f g) h.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composition_associative".
destruct f, g, h; simpl.
repeat destruct (composite_correct _ _ _); simpl in *.
spose (fst (composition_law M e1 e x3) e2) as X1.
unfold composite, arrow in *.
rewrite e0 in X1.
inversion_clear X1.
reflexivity.
Qed.

Program Definition Category_from_Metacategory : Category := {|
obj     := object;
hom     := morphism;
homset  := fun _ _ => {| equiv := fun f g => mor_arr f = mor_arr g |};
id      := @identity;
compose := @composition;

compose_respects := @composition_respects;

id_left    := @composition_identity_left;
id_right   := @composition_identity_right;
comp_assoc := @composition_associative;
comp_assoc_sym := fun x y z w f g h =>
symmetry (@composition_associative x y z w f g h);
|}.

End Category.

Arguments mor_arr _ {_ _} _.
Arguments mor_dom _ {_ _} _.
Arguments mor_cod _ {_ _} _.

Import FMapExt.

Lemma mapsto_inv : ∀ elt f g (fg : elt) x y z m,
M.MapsTo (f, g) fg (M.add (x, y) z m) ->
(x = f ∧ y = g ∧ z = fg) ∨ M.MapsTo (f, g) fg m.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.mapsto_inv".
intros.
apply add_mapsto_iffT in H.
destruct H; simpl in *; intuition.
Defined.

Lemma find_add_inv : ∀ f g (fg : N) x y z m,
M.find (f, g) (M.add (x, y) z m) = Some fg ->
(x = f ∧ y = g ∧ z = fg) ∨ M.find (f, g) m = Some fg.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.find_add_inv".
intros.
destruct (N.eq_dec x f).
destruct (N.eq_dec y g).
destruct (N.eq_dec z fg).
subst; left; intuition.
contradiction n.
rewrite F.add_eq_o in H.
inversion_clear H.
reflexivity.
simpl; intuition.
rewrite F.add_neq_o in H; intuition.
rewrite F.add_neq_o in H; intuition.
Defined.

Ltac destruct_maps :=
repeat match goal with
| [ H : M.find (?X, ?Y) (M.empty _) = Some ?F |- _ ] =>
inversion H
| [ H : M.find (?X, ?Y) (M.add _ _ _) = Some ?F |- _ ] =>
apply find_add_inv in H;
(destruct H as [[? [? ?]]|]; [subst; try nomega|])
| [ |- ∃ v, M.find _ _ = Some v ] =>
vm_compute; eexists; reflexivity

| [ H : M.find _ _ = Some _ |- _ ] =>
apply F.find_mapsto_iff in H
| [ |- M.find _ _ = Some _ ] =>
apply F.find_mapsto_iff
| [ |- ∃ v, M.find _ _ = Some v ] =>
apply find_mapsto_iff_ex

| [ H : M.MapsTo _ _ (M.empty _) |- _ ] =>
contradiction (proj1 (F.empty_mapsto_iff _ _) H)

| [ H : M.MapsTo (?X, ?Y) ?F (M.add _ _ _) |- _ ] =>
apply mapsto_inv in H; destruct H as [[? [? ?]]|]

| [ H : ?X = ?Y |- context[M.MapsTo (?Y, _)] ] =>
rewrite <- H; cbn
| [ H : ?X = ?Y |- context[M.MapsTo (_, ?Y)] ] =>
rewrite <- H; cbn
| [ H : ?X = ?Y |- context[M.MapsTo _ ?Y] ] =>
rewrite <- H; cbn

| [ |- ∃ _, M.MapsTo (?X, ?Y) _ _ ] =>
match goal with
[ |- context[M.add (X, Y) ?F _ ] ] =>
exists F
end
| [ |- M.MapsTo (?X, ?Y) ?F (M.add (?X, ?Y) ?F _) ] =>
simplify_maps
| [ |- M.MapsTo _ _ (M.add _ _ _) ] =>
simplify_maps; right; split; [idtac|]
end;
try congruence.

Ltac reflect_on_maps :=
simpl; intros;
match goal with
| [ |- ∃ _, M.find _ _ = _ ] => destruct_maps
| [ |- _ ↔ _ ] => split; intros; map_decide
| [ |- ∃ _ _, _ ] =>
destruct_maps;
eexists; eexists; split; intros; clear;
first [ instantiate (1 := 0%N); vm_compute; reflexivity
| instantiate (1 := 1%N); vm_compute; reflexivity
| instantiate (1 := 2%N); vm_compute; reflexivity
| instantiate (1 := 3%N); vm_compute; reflexivity
| instantiate (1 := 4%N); vm_compute; reflexivity
| instantiate (1 := 5%N); vm_compute; reflexivity
| instantiate (1 := 6%N); vm_compute; reflexivity
| instantiate (1 := 7%N); vm_compute; reflexivity
| instantiate (1 := 8%N); vm_compute; reflexivity
| instantiate (1 := 9%N); vm_compute; reflexivity ]
end.

Local Open Scope N_scope.

Definition triangular_number (n : N) := (n * (n + 1)) / 2.

Definition composable_pairs_step (n : N) (z : M.t N) : M.t N :=
let next := triangular_number (N.pred n) in
let go i rest :=
let k j r :=
let mor := next + i in
let dom := triangular_number (j + i) + i in
let cod := mor + j in
M.add (cod, dom) mor r in
N.peano_rect _ rest k (n - i) in
N.peano_rect _ z go n.

Definition composable_pairs : N -> M.t N :=
N.peano_rect _ (M.empty _) (composable_pairs_step \o N.succ).

Definition tetrahedral_number (n : N) := (n * (n + 1) * (n + 2)) / 6.

Local Obligation Tactic :=
simpl; intros; vm_compute triangular_number in *; reflect_on_maps.

Program Definition Zero  : Metacategory := {| pairs := composable_pairs 0 |}.
Program Definition One   : Metacategory := {| pairs := composable_pairs 1 |}.
Program Definition Two   : Metacategory := {| pairs := composable_pairs 2 |}.
Program Definition Three : Metacategory := {| pairs := composable_pairs 3 |}.
Program Definition Four  : Metacategory := {| pairs := composable_pairs 4 |}.

Ltac elimobj X :=
elimtype False;
unfold composite in X; simpl in X;
clear -X;
vm_compute triangular_number in *;
destruct_maps; nomega.

Lemma peano_rect' : ∀ P : N → Type, P 0%N → (∀ n : N, P (N.succ n)) → ∀ n : N, P n.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.peano_rect'".
intros.
induction n using N.peano_rect.
apply X.
apply X0.
Defined.

Ltac reflect_on_pairs X Y F D C :=
repeat (
destruct X using peano_rect';
first
[ elimobj D | elimobj C
| repeat (
destruct Y using peano_rect';
first
[ elimobj D | elimobj C
| repeat (
destruct F using peano_rect';
first
[ elimobj D | elimobj C
| intuition idtac
| reflect_on_pairs ]) ]) ]);
intuition.

Require Import Category.Instance.Two.

Monomorphic Lemma object_Two_rect :
∀ (P : object Two -> Type),
(∀ x, obj_arr Two x = 0%N -> P x) ->
(∀ x, obj_arr Two x = 2%N -> P x) ->
∀ (x : object Two), P x.
Proof.
intros; destruct x.
repeat (destruct obj_arr0 using peano_rect'; elimobj obj_def0 || auto).
Defined.

Program Definition Two_2_object (x : object Two) : TwoObj.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.Two_2_object".
induction x using object_Two_rect.
- exact TwoX.
- exact TwoY.
Defined.

Monomorphic Lemma morphism_Two_rect :
∀ {x y : object Two} (P : morphism Two x y -> Type),
(∀ f, obj_arr Two x = 0%N -> obj_arr Two y = 0%N -> mor_arr Two f = 0%N -> P f) ->
(∀ f, obj_arr Two x = 0%N -> obj_arr Two y = 2%N -> mor_arr Two f = 1%N -> P f) ->
(∀ f, obj_arr Two x = 2%N -> obj_arr Two y = 2%N -> mor_arr Two f = 2%N -> P f) ->
∀ (f : morphism Two x y), P f.
Proof.
intros; destruct x, y, f.
reflect_on_pairs obj_arr0 obj_arr1 mor_arr0 mor_dom0 mor_cod0.
Defined.

Program Definition Two_2_morphism (x y : object Two) (f : morphism Two x y) :
TwoHom (Two_2_object x) (Two_2_object y).
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.Two_2_morphism".
induction f using morphism_Two_rect;
destruct x, y, f; simpl in *; subst; simpl.
- exact TwoIdX.
- exact TwoXY.
- exact TwoIdY.
Defined.

Local Obligation Tactic := intros.

Program Definition Two_to_Two : Category_from_Metacategory Two ⟶ _2 := {|
fobj := Two_2_object;
fmap := Two_2_morphism
|}.
Next Obligation.
proper.
destruct x0, y0; simpl in X; subst.
apply f_equal.
apply f_equal2;
apply Eqdep_dec.UIP_dec;
decide equality;
apply N.eq_dec.
Qed.
Next Obligation.
simpl.
induction x using object_Two_rect;
destruct x;
simpl in H; subst;
vm_compute; reflexivity.
Qed.
Next Obligation.
simpl in *.
induction f using morphism_Two_rect;
induction g using morphism_Two_rect;
destruct x, y, z, f, f0;
simpl in H, H0, H1, H2, H3, H4; subst;
(elimtype False; simpl in *; discriminate)
|| (vm_compute; reflexivity).
Qed.

Local Obligation Tactic :=
program_simpl;
try solve [ subst; unfold composite; simpl;
subst; vm_compute; reflexivity ].

Program Definition _2_Two_object (x : TwoObj) : object Two :=
match x with
| TwoX => {| obj_arr := 0%N; obj_def := _; obj_id  := _ |}
| TwoY => {| obj_arr := 2%N; obj_def := _; obj_id  := _ |}
end.
Next Obligation.
unfold is_identity, defined, composite;
simpl; split; intros; destruct H; subst;
rewrite e; destruct_maps.
Defined.
Next Obligation.
unfold is_identity, defined, composite;
simpl; split; intros; destruct H; subst;
rewrite e; destruct_maps.
Defined.

Program Definition _2_Two_morphism (x y : TwoObj) (f : TwoHom x y) :
morphism Two (_2_Two_object x) (_2_Two_object y) :=
match x as x' in TwoObj
return x = x' -> morphism Two (_2_Two_object x) (_2_Two_object y) with
| TwoX => fun _ =>
match y as y' in TwoObj
return y = y' -> morphism Two (_2_Two_object x) (_2_Two_object y) with
| TwoX => fun _ => {| mor_arr := 0%N; mor_dom := _; mor_cod := _ |}
| TwoY => fun _ => {| mor_arr := 1%N; mor_dom := _; mor_cod := _ |}
end eq_refl
| TwoY => fun _ =>
match y as y' in TwoObj
return y = y' -> morphism Two (_2_Two_object x) (_2_Two_object y) with
| TwoY => fun _ => {| mor_arr := 2%N; mor_dom := _; mor_cod := _ |}
| TwoX => fun _ => !
end eq_refl
end eq_refl.
Next Obligation. inversion f. Defined.

Local Obligation Tactic := program_simpl.

Program Definition Two_from_Two : _2 ⟶ Category_from_Metacategory Two := {|
fobj := _2_Two_object;
fmap := _2_Two_morphism
|}.
Next Obligation. destruct x; reflexivity. Defined.
Next Obligation.
destruct f; simpl;
destruct x; simpl;
spose (TwoHom_inv _ _ g) as H; subst;
contradiction || reflexivity.
Defined.

Require Import Category.Instance.Cat.

Program Instance Two_iso_2 : Category_from_Metacategory Two ≅ _2 := {
to   := Two_to_Two;
from := Two_from_Two
}.
Next Obligation.
unshelve eexists; intros.
induction x; reflexivity.
induction f; reflexivity.
Qed.
Next Obligation.
unshelve eexists; intros.
induction x using object_Two_rect;
destruct x; simpl in H; subst.
{ isomorphism; simpl.
- construct; [exact 0%N|..]; auto.
- construct; [exact 0%N|..]; auto.
- reflexivity.
- reflexivity.
}
{ isomorphism; simpl.
- construct; [exact 2%N|..]; auto.
- construct; [exact 2%N|..]; auto.
- reflexivity.
- reflexivity.
}
induction f using morphism_Two_rect;
destruct x, y, f;
simpl in H, H0, H1; subst;
vm_compute; reflexivity.
Qed.

Local Obligation Tactic := simpl; intros.

Lemma composable_pairs_succ n :
composable_pairs (N.succ n)
= composable_pairs_step (N.succ n) (composable_pairs n).
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composable_pairs_succ".
unfold composable_pairs.
rewrite N.peano_rect_succ; reflexivity.
Qed.

Lemma composable_pairs_step_disjoint n m :
P.Disjoint m (composable_pairs n) ->
P.Disjoint (composable_pairs_step (N.succ n) m) (composable_pairs n).
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composable_pairs_step_disjoint".
intros.
generalize dependent m.
induction n using N.peano_rect; intros.
apply P.Disjoint_alt; intros.
inversion H1.
rewrite composable_pairs_succ in H.
Abort.

Lemma composable_pairs_step_find n f g fg :
M.find (f, g) (composable_pairs_step (N.succ n) (composable_pairs n)) = Some fg
-> M.find (f, g) (composable_pairs n) = Some fg ∨
M.find (f, g) (composable_pairs_step (N.succ n) (M.empty _)) = Some fg.
Proof. hammer_hook "ArrowsOnly" "ArrowsOnly.composable_pairs_step_find".
generalize dependent fg.
generalize dependent g.
generalize dependent f.
induction n using N.peano_rect; intros.
right; auto.
rewrite composable_pairs_succ in *.
Abort.


(*|
###########################################################################
Applying a Program Definition fails with "unable to unify Prop with [goal]"
###########################################################################

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

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

In Coq, I showed the associativity of ``append`` on vectors using:
|*)

Require Import Coq.Vectors.VectorDef Coq.micromega.Lia.

Program Definition t_app_assoc v p q r (a : t v p) (b : t v q) (c : t v r) :=
  append (append a b) c = append a (append b c).
Next Obligation. lia. Qed.

(*|
I now want to apply this equality in a proof. Below is the easiest
goal that I would expect to be provable with ``t_app_assoc``. Of
course it can be proven by ``simpl`` - this is just an example.

This ``apply`` fails:
|*)

Goal (append (append (nil nat) (nil _)) (nil _)
      = append (nil _) (append (nil _) (nil _))).
  Fail apply t_app_assoc. (* .fails .unfold .no-goals *)
Abort. (* .none *)

(*|
How can I apply ``t_app_assoc``? Or is there a better way to define
it? I thought I needed a ``Program Definition``, because simply using
a ``Lemma`` leads to a type error because ``t v (p + (q + r))`` and
``t v (p + q + r)`` are not the same to Coq.
|*)

(*|
Answer
******

Prologue
========

I guess what you want to to is to prove that the vector concatenation
is associative and then use that fact as a lemma.

But ``t_app_assoc`` as you define it has the following type:
|*)

Check t_app_assoc. (* .unfold .messages *)

(*| You basically want to use ``:`` instead of ``:=`` as follows. |*)

From Coq Require Import Vector Arith.
Import VectorNotations.
Import EqNotations.                  (* rew notation, see below *)
Require Import Coq.Program.Equality. (* heterogeneous equality *)

Section Append.

  Variable A : Type.
  Variable p q r : nat.
  Variables (a : t A p) (b : t A q) (c : t A r).

  Fail Lemma t_app_assoc :
    append (append a b) c = append a (append b c).

(*|
Unfortunately, we cannot even state a lemma like this using the usual
homogeneous equality.

The left-hand side has the following type:
|*)

  Check append (append a b) c : t A (p + q + r).

(*| whereas the right-hand side is of type |*)

  Check append a (append b c) : t A (p + (q + r)).

(*|
Since ``t A (p + q + r)`` is not the same as ``t A (p + (q + r))`` we
cannot use ``=`` to state the above lemma.

Let me describe some ways of working around this issue:

``rew`` notation
================
|*)

  Lemma t_app_assoc_rew :
    append (append a b) c = rew (plus_assoc _ _ _) in
      append a (append b c).
  Admitted.

(*|
Here we just use the law of associativity of addition for natural
numbers to cast the type of RHS to ``t A (p + q + r)``.

To make it work one needs to ``Import EqNotations.`` before.

``cast`` function
=================

This is a common problem, so the authors of the ``Vector`` library
decided to provide a ``cast`` function with the following type:
|*)

  Check cast. (* .unfold .messages *)

(*|
Let me show how one can use it to prove the law of associativity for
vectors. But let's prove the following auxiliary lemma first:
|*)

  Lemma uncast {X n} {v : Vector.t X n} e :
    cast v e = v.
  Proof. induction v as [|??? IH]; simpl; rewrite ?IH; reflexivity. Qed.

(*| Now we are all set: |*)

  Lemma t_app_assoc_cast :
    append (append a b) c = cast (append a (append b c)) (plus_assoc _ _ _).
  Proof.
    generalize (Nat.add_assoc p q r).
    induction a as [|h p' a' IH]; intros e.
    - now rewrite uncast.
    - simpl. f_equal. now apply IH.
  Qed.

(*|
Heterogeneous equality (a.k.a. John Major equality)
===================================================
|*)

  Lemma t_app_assoc_jmeq :
    append (append a b) c ~= append a (append b c).
  Admitted.

End Append.

(*| If you compare the definition of the homogeneous equality |*)

Print eq. (* .unfold .messages *)

(*| and the definition of heterogeneous equality |*)

Print JMeq. (* .unfold .messages *)

(*|
you will see that with ``JMeq`` the LHS and RHS don't have to be of
the same type and this is why the statement of ``t_app_assoc_jmeq``
looks a bit simpler than the previous ones.

Other approaches to vectors
===========================

See e.g. `this question
<https://stackoverflow.com/q/42302300/2747511>`__ and `this one
<https://stackoverflow.com/q/49477427/2747511>`__; I also find `this
answer <https://stackoverflow.com/a/27640467/2747511>`__ very useful
too.
|*)