(** * Tactics: More Basic Tactics *)

(** This chapter introduces several more proof strategies and
    tactics that allow us to prove 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 create a strong induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis. *)

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.

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

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** 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) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  intros. apply H. apply H0.
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.
  simpl.
  (* Here we cannot use [apply] directly *)
Abort.

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

Theorem silly3 : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  symmetry.
  simpl. (* Actually, this [simpl] is unnecessary, since
            [apply] will perform simplification first. *)
  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 [SearchAbout] is
    your friend.) *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  intros. induction l'.
  - simpl. rewrite H. symmetry. apply rev_involutive.
  - simpl. intros. rewrite H. rewrite rev_involutive. reflexivity.
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. apply trans_eq with (n:=n+p) (m:=m).
  - apply H0.
  - apply H.
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 an
    issue.)  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 ask 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.

(** It is possible to name the equations that [inversion]
    generates with an [as ...] clause: *)

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

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

(** [] *)

(** While 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
    constructors and functions, which we will find useful 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.

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately. To see why this makes sense, 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 general logical principle known as
    the _principle of explosion_, which asserts that a contradiction
    entails anything, even false things.  For instance: *)

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 the situation
    described by the premise can never arise, so the implication is
    vacuous.  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. inversion H.
Qed.

(** [] *)

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

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

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

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

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

(* ################################################################# *)
(** * 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 exercise.  (Hint: use
    [plus_n_Sm].) *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  - intros. destruct m.
    + reflexivity.
    + inversion H.
  - simpl. intros. destruct m.
    + rewrite <- plus_n_O in H. inversion H.
    + rewrite <- plus_n_Sm in H. simpl in H. rewrite <- plus_n_Sm in H.
      inversion H. rewrite (IHn' _ 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 always 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.) *)

(** To summarize: 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 good 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: If we're proving a property of [n] and [m] by induction
    on [n], we may need 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.
  induction n.
  - intros. destruct m.
    + reflexivity.
    + inversion H.
  - intros. destruct m.
    + inversion H.
    + simpl in H. rewrite (IHn m 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 *)
(** [] *)

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    a little _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 here 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 .  This
    will work, 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 -- we want to state them in the most clear and
    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
    about 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.
  generalize dependent n.
  induction l.
  - simpl. intros. reflexivity.
  - intros. simpl in H. destruct n.
    + inversion H.
    + inversion H. simpl. rewrite H1. apply IHl. apply H1.
Qed.

(** [] *)

(** **** Exercise: 3 stars, optional (app_length_cons)  *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  induction l1.
  - simpl. intros. apply H.
  - destruct n.
    + simpl. intros. inversion H.
    + simpl. intros. inversion H. rewrite (IHl1 _ _ _ H1). symmetry. apply H.
Qed.

(** [] *)

(** **** Exercise: 4 stars, optional (app_length_twice)  *)
(** Prove this by induction on [l], without using [app_length] from [Lists]. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  intros.
  generalize dependent n.
  induction l.
  - simpl. intros. rewrite <- H. reflexivity.
  - simpl. intros. destruct n.
    + inversion H.
    + inversion H. simpl.
      rewrite <- plus_n_Sm. rewrite <- IHl by reflexivity.
      apply f_equal with (f:=S). symmetry. apply app_length_cons with (x:=x).
      reflexivity.
Qed.

(** [] *)

(** **** Exercise: 3 stars, optional (double_induction)  *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  intros P H H1 H2 H3 m. induction m.
  + induction n.
    * apply H.
    * apply H2. apply IHn.
  + induction n.
    * apply H1. apply IHm.
      * apply H3. apply IHm.
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 it 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 finish the proof 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)  *)
Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y. induction l.
  - intros. inversion H. reflexivity.
  - simpl. destruct (split l). intros. destruct x.
    inversion H. simpl. apply f_equal with (f:=cons (x,y)).
    apply IHl. 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. destruct (f b) eqn:H1.
  - destruct (f true) eqn:H2.
    + destruct (f true) eqn:H3.
      * reflexivity.
      * inversion H2.
    + destruct (f false) eqn:H3.
      * reflexivity.
      * destruct b. rewrite H1 in H2. inversion H2. rewrite H1 in H3. inversion H3.
  - destruct (f false) eqn:H2.
    + destruct b.
      * rewrite H1. reflexivity.
      * rewrite H1 in H2. inversion H2.
    + apply H2.
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 (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.
  induction n.
  - intros. destruct m.
    + reflexivity.
    + reflexivity.
  - intros. destruct m.
    + intros. reflexivity.
    + simpl. 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 *)
[]
*)

Lemma beq_same : forall n, beq_nat n n = true.
Proof.
  induction n.
  - reflexivity.
  - simpl. apply IHn.
Qed.

(** **** 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.
  intros. induction n.
  - simpl. rewrite (beq_nat_0_l _ H) in H0. rewrite (beq_nat_0_l _ H0). reflexivity.
  - simpl. rewrite (beq_nat_true _ _ H0) in H. rewrite <- (beq_nat_true _ _ H).
    apply beq_same.
Qed.

(** [] *)

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

    When the lengths of l1 and l2 are the same.

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

Theorem split_combine :
  forall (X Y : Type) (l1 : list X) (l2 : list Y),
  length l1 = length l2 -> split (combine l1 l2) = (l1,l2).
Proof.
  induction l1.
  - simpl. intros. destruct l2.
    + reflexivity.
    + simpl in H. inversion H.
  - simpl. intros. destruct l2.
    + simpl in H. inversion H.
    + simpl in H. inversion H. simpl. rewrite (IHl1 _ H1). reflexivity.
Qed.

(** [] *)

(** **** 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.
  induction l.
  - simpl. intros. inversion H.
  - simpl. intros. destruct (test x0) eqn:H1.
    + inversion H. rewrite H2 in H1. apply H1.
    + apply (IHl _ H).
Qed.

(** [] *)

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

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

      forallb negb [false;false] = true

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

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

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

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

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=
  negb (forallb (fun y => negb (test y)) l).

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
    existsb test l = existsb' test l.
Proof.
  intros. induction l.
  - reflexivity.
  - unfold existsb'. simpl. destruct (test x).
    + reflexivity.
    + simpl. rewrite IHl. reflexivity.
Qed.

(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)


Require Import Coq.Reals.Reals.
Require Export Coq.Lists.List.

Require Export Autosubst.Autosubst.

Require Import utils.
Require Export entropy.

Local Open Scope ennr.

(** * Types *)

(** Types for our language are traditional real numbers (positive and negative,
    no infinity) and arrows. *)
Inductive Ty :=
| ℝ : Ty
| Arrow : Ty -> Ty -> Ty
.
Notation "x ~> y" := (Arrow x y) (at level 69, right associativity).

Lemma ty_eq_dec : forall (τ τ' : Ty), {τ = τ'} + {τ <> τ'}.
Proof.
  decide equality.
Defined.

(** Environments are De Bruijn indexed lists. While doing lookup in a list is
    slightly annoying and slightly mismatched with autosubst, the finiteness
    allows for things to be unique and decidable. *)
Definition Env (T : Type) := list T.
Definition empty_env {T : Type} : Env T := nil.
Notation "·" := empty_env.

Fixpoint lookup {T} (ρ : Env T) x : option T :=
  match ρ with
  | nil => None
  | v :: ρ' =>
    match x with
    | O => Some v
    | S x' => lookup ρ' x'
    end
  end.

(** * Expressions

    While Autosubst (https://www.ps.uni-saarland.de/autosubst/) brings light and
    joy into the miserable world of doing substitutions, it has some issues that
    affect our representation of terms.

    We define expressions using a GADT so that all terms are well typed.
    However, autosubst is unable to either derive instances (not that much of a
    problem) or reason about substitutions (big problem) of these terms.

    We work around this by also defining a mostly type-erased version of the
    terms for autosubst to work with. The type erasure is done carefully (i.e.
    we keep the annotations on ambiguous terms (i.e. lambda)) so that the
    erasure is injective. This means that whenever autosubst can demonstrate an
    equality between to erased terms we can leverage the injectivity to get an
    equality between fully typed terms.

    ---- *)

(** First, the well-typed terms: *)
Inductive expr (Γ : Env Ty) : Ty -> Type :=
| e_real (r : R) : expr Γ ℝ
| e_var {τ : Ty} (x : var)
        (H : lookup Γ x = Some τ)
  : expr Γ τ
| e_lam {τa τr}
        (body : expr (τa :: Γ) τr)
  : expr Γ (τa ~> τr)
| e_app {τa τr}
        (ef : expr Γ (τa ~> τr))
        (ea : expr Γ τa)
  : expr Γ τr
| e_factor (e : expr Γ ℝ)
  : expr Γ ℝ
| e_sample
  : expr Γ ℝ
| e_plus (el : expr Γ ℝ)
         (er : expr Γ ℝ)
  : expr Γ ℝ.

Arguments e_real {Γ} r.
Arguments e_var {Γ τ} x H.
Arguments e_lam {Γ τa τr} body.
Arguments e_app {Γ τa τr} ef ea.
Arguments e_factor {Γ} e.
Arguments e_sample {Γ}.
Arguments e_plus {Γ} el er.

(** Now, the erased terms: (u stands for untyped) *)
Inductive u_expr :=
| u_app : u_expr -> u_expr -> u_expr
| u_factor : u_expr -> u_expr
| u_sample : u_expr
| u_plus : u_expr -> u_expr -> u_expr
| u_real : R -> u_expr
| u_lam : Ty -> {bind u_expr} -> u_expr
| u_var : var -> u_expr
.

Instance Ids_u_expr : Ids u_expr. derive. Defined.
Instance Rename_u_expr : Rename u_expr. derive. Defined.
Instance Subst_u_expr : Subst u_expr. derive. Defined.
Instance SubstLemmas_u_expr : SubstLemmas u_expr. derive. Defined.

Fixpoint erase {Γ τ} (e : expr Γ τ) : u_expr :=
  match e with
  | e_real r => u_real r
  | e_var x _ => u_var x
  | @e_lam _ τa τr body => u_lam τa (erase body)
  | e_app ef ea => u_app (erase ef) (erase ea)
  | e_factor e => u_factor (erase e)
  | e_sample => u_sample
  | e_plus el er => u_plus (erase el) (erase er)
  end.
Coercion erase' {Γ τ} : expr Γ τ -> u_expr := erase.
Arguments erase' / {_ _} _.

(** The first step towards proving injectivity of [erase] is uniqueness of
    typing for an erased term. *)
Lemma expr_type_unique {Γ τ0 τ1} (e0 : expr Γ τ0) (e1 : expr Γ τ1) :
  erase e0 = erase e1 ->
  τ0 = τ1.
Proof.
  intros Heq.
  revert τ1 e1 Heq.
  dependent induction e0; intros;
    dep_destruct (e1, Heq);
    auto.
  {
    rewrite H0 in H.
    inject H.
    reflexivity.
  } {
    rewrite (IHe0 _ _ x).
    reflexivity.
  } {
    specialize (IHe0_1 _ _ x).
    inject IHe0_1.
    reflexivity.
  }
Qed.

Require Import FinFun.
Lemma erase_injective Γ τ : Injective (@erase Γ τ).
Proof.
  intro x.
  dependent induction x;
    intros y Hxy;
    dep_destruct (y, Hxy);
    auto.
  {
    f_equal.
    apply UIP_dec.
    decide equality.
    apply ty_eq_dec.
  } {
    f_equal.
    apply IHx; auto.
  } {
    pose proof expr_type_unique _ _ x.
    inject H.
    erewrite IHx1, IHx2; auto.
  } {
    erewrite IHx; auto.
  } {
    erewrite IHx1, IHx2; auto.
  }
Qed.
Arguments erase_injective {_ _ _ _} _.

(** * Values

    While it would be nice to define values and exprs as mutually inductive
    types, autosubst can't handle mutual induction at the moment. Instead,
    values are defined as a subset type of expressions. For convenience, a
    coercion to expressions is defined. *)

Definition is_val (e : u_expr) : Prop :=
  match e with
  | u_real _ | u_lam _ _ => True
  | _ => False
  end.

Inductive val τ :=
  mk_val (e : expr · τ) (H : is_val e).
Arguments mk_val {τ} e H.
Coercion expr_of_val {τ} : val τ -> expr · τ :=
  fun v => let (e, _) := v in e.

(** proof irrelevance for [is_val], which also nicely means that coercion from a
    value to an expression is reversible. *)
Lemma is_val_unique {e : u_expr} (iv0 iv1 : is_val e) :
  iv0 = iv1.
Proof.
  destruct e; try contradiction; destruct iv0, iv1; auto.
Qed.

Lemma val_eq {τ} {v0 v1 : val τ} :
  v0 = v1 :> (expr · τ) ->
  v0 = v1 :> (val τ).
Proof.
  intros.
  destruct v0, v1.
  cbn in *.
  subst.

  f_equal.
  apply is_val_unique.
Qed.

(** the constructors for values I wish I had *)
Definition v_real r : val ℝ :=
  mk_val (e_real r) I.

Definition v_lam {τa τr} body : val (τa ~> τr) :=
  mk_val (e_lam body) I.

(** If a rewrite or other tactic is expecting a value, but sees an expression it
    will refuse to work. These two lemmas can be used to help the process along.
    *)
Definition rewrite_v_real r : e_real r = v_real r := eq_refl.
Definition rewrite_v_lam {τa τr} body : e_lam body = @v_lam τa τr body := eq_refl.

(** specialize destruction principles for values *)
Definition val_arrow_rect {τa τr}
           (P : val (τa ~> τr) -> Type)
           (case_lam : forall body, P (v_lam body)) :
  forall v, P v.
Proof.
  intros [v Hv].
  dependent destruction v; try contradiction Hv.
  destruct Hv.
  apply case_lam.
Qed.

Lemma val_real_rect
      (P : val ℝ -> Type)
      (case_real : forall r, P (v_real r)) :
  forall v, P v.
Proof.
  intros.
  destruct v as [v Hv].
  dependent destruction v; try contradiction Hv.
  destruct Hv.
  apply case_real.
Qed.

Lemma wt_val_rect {τ}
      (P : val τ -> Type)
      (case_real :
         forall r (τeq : ℝ = τ),
           P (rew τeq in v_real r))
      (case_lam :
         forall τa τr
                (τeq : (τa ~> τr) = τ)
                body,
           P (rew τeq in v_lam body)) :
  forall v, P v.
Proof.
  intros.
  destruct τ. {
    apply val_real_rect.
    intros.
    exact (case_real r eq_refl).
  } {
    apply val_arrow_rect.
    intros.
    exact (case_lam _ _ eq_refl body).
  }
Qed.

Ltac destruct_val wt_v :=
  match (type of wt_v) with
  | val ℝ =>
    destruct wt_v using val_real_rect
  | val (?τa ~> ?τr) =>
    destruct wt_v using val_arrow_rect
  | val ?τ =>
    destruct wt_v using wt_val_rect
  end.

(** Quite often we will with a goal containing a [mk_val e False] hidden
    somewhere inside it. The tactic [absurd_val] hunts for that [False] in
    common places and contradicts it. *)

Lemma for_absurd_val {τ} {v : val τ} {e : expr · τ} :
  (expr_of_val v) = e ->
  is_val e.
Proof.
  intros.
  destruct v.
  subst.
  auto.
Qed.

Ltac absurd_val :=
  match goal with
  | [ H : (expr_of_val _) = _ |- _ ] =>
    contradiction (for_absurd_val H)
  | [ H : _ = (expr_of_val _) |- _ ] =>
    contradiction (for_absurd_val (eq_sym H))
  end.

(** *** Tactics

    Some tactics useful for making use of equalities between erased expressions.
    *)

Ltac inject_erase_directly :=
  match goal with
  | [ H : erase ?x = erase ?y |- _ ] =>
    match type of x with
    | (expr _ ?τx) =>
      match type of y with
      | (expr _ τx) =>
        apply erase_injective in H;
          try subst x
      | (expr _ ?τy) =>
        let H' := fresh "H" in
        pose proof (expr_type_unique _ _ H) as H';
          (subst τx || dep_destruct H');
          apply erase_injective in H;
          try subst x
      end
    end
  end.

Ltac match_erase_eqs :=
  let H := fresh "H" in
  let H' := fresh "H" in
  match goal with
  | [H0 : erase ?x = ?s, H1 : erase ?y = ?s |- _ ] =>
    pose proof (eq_trans H0 (eq_sym H1)) as H;
    let z := type of y in
    let kill_τ τ :=
        pose proof (expr_type_unique _ _ H) as H';
        (subst τ || dep_destruct H') in
    match type of x with
    | z => idtac
    | val ?τ => kill_τ τ
    | expr · ?τ => kill_τ τ
    end;
    apply erase_injective in H;
    subst x
  end;
  clear_dups.

Ltac subst_erase_eq :=
  match goal with
  | [ H : erase ?e = _, H' : context [ erase ?e ] |- _ ] =>
    rewrite H in H';
      try clear H e
  end.

(** dep_destruct is often slow, do don't use unless we need *)
(* TODO: speed up even more for exprs *)
Ltac expr_destruct e :=
  match type of e with
  | expr _ (_ ~> _) => dep_destruct e
  | expr _ ℝ => dep_destruct e
  | expr _ _ => destruct e
  end.

Ltac inject_erased :=
  let go e H :=
      expr_destruct e; inject H
  in match goal with
     | [ H : erase ?e = u_app _ _ |- _ ] => go e H
     | [ H : erase ?e = u_factor _ |- _ ] => go e H
     | [ H : erase ?e = u_sample |- _ ] => go e H
     | [ H : erase ?e = u_plus _ _ |- _ ] => go e H
     | [ H : erase ?e = u_real _ |- _ ] => go e H
     | [ H : erase ?e = u_lam _ _ |- _ ] => go e H
     | [ H : erase ?e = u_var _ |- _ ] => go e H
     | [ H : erase ?e = ids _ |- _ ] => go e H
     end.

(** [elim_erase_eqs]'s main objective is to eliminate hypothesis of the form
    [erase e = ...] *)
Ltac elim_erase_eqs :=
  progress repeat (subst_erase_eq
                   || inject_erase_directly
                   || match_erase_eqs
                   || inject_erased);
  clear_dups.

(** ** Using [sig] to program by tactics *)

(** As types get more dependent and pattern matching in Gallina becomes more
    challenging, we will make use of an idiom to define functions. If we want to
    define a function of type [A -> B], instead of defining it directly, we will
    opaquely define a function of the form [A -> {b : B | P b}] using tactics.

    The idea is to put all the information needed about the internals into [P]
    so that you can eliminate calls to the function (wich now look like
    [proj1_sig (f x)]) using [destruct (f x)] and rewriting insead
    of standard computation.

    The tactic [elim_sig_exprs] attempts to do exactly that destruction on
    results of type [expr]. *)

Ltac elim_sig_exprs :=
  let doit Γ τ pair stac :=
      (let e := fresh "e" in
       let He := fresh "H" e in
       destruct pair as [e He];
       stac;
       asimpl in He) in
  progress repeat
           match goal with
           | [ H : context [ @proj1_sig (expr ?Γ ?τ) _ ?pair ] |- _ ] =>
             doit Γ τ pair ltac:(simpl in H)
           | [ |- context [ @proj1_sig (expr ?Γ ?τ) _ ?pair ] ] =>
             doit Γ τ pair ltac:(simpl)
           end.

(** * Substitution

    Thanks to autosubst, substitution has been easily defined on erased terms.
    The goal now is to define substitution on well-typed terms. The process of
    defining it will be what is often called "proving a substitution lemma".

    {TODO: is that the right wording?} *)

(** First, we are going to need environments of well-typed terms. These will
    essentially be dependent lists. *)
Inductive dep_list {A} (v : A -> Type) : Env A -> Type :=
| dep_nil : dep_list v ·
| dep_cons {τ Γ'} : v τ -> dep_list v Γ' -> dep_list v (τ :: Γ')
.
Arguments dep_nil {_ _}.
Arguments dep_cons {_ _ _ _} _ _.

Fixpoint dep_lookup {A} {v : A -> Type} {Γ} (ρ : dep_list v Γ) (x : nat)
  : option {τ : A & v τ} :=
  match ρ with
  | dep_nil => None
  | dep_cons e ρ' =>
    match x with
    | O => Some (existT _ _ e)
    | S x' => dep_lookup ρ' x'
    end
  end.

Fixpoint dep_map {A} {v0 v1 : A -> Type} {Γ}
         (f : forall a, v0 a -> v1 a)
         (ρ : dep_list v0 Γ)
  : dep_list v1 Γ :=
  match ρ with
  | dep_nil => dep_nil
  | dep_cons e ρ' => dep_cons (f _ e) (dep_map f ρ')
  end.

Fixpoint dep_env_allT {A} {v : A -> Type} {Γ}
         (P : forall a, v a -> Type)
         (ρ : dep_list v Γ) : Type
  :=
    match ρ with
    | dep_nil => True
    | dep_cons e ρ' => P _ e * dep_env_allT P ρ'
    end.

(** Although in the end we only care about environments of closed values, for
    the intermediate stages of substitution we will need to work with
    environments of open terms as well.

    We will lift the erase function over environments, but we will do it as a
    separate function for open expressions vs values. The reason for this is to
    keep the casts between [val] and [expr ·] at cases better suited for
    computation. *)
Fixpoint erase_wt_expr_env {Γ Δ} (ρ : dep_list (expr Δ) Γ)
  : nat -> u_expr :=
  match ρ with
  | dep_nil => ids
  | dep_cons e ρ' => erase e .: erase_wt_expr_env ρ'
  end.

Definition wt_env := dep_list val.

Fixpoint erase_wt_env {Γ} (ρ : wt_env Γ) : nat -> u_expr :=
  match ρ with
  | dep_nil => ids
  | dep_cons e ρ' => erase e .: erase_wt_env ρ'
  end.

Lemma erase_envs_equiv {Γ} (ρ : wt_env Γ) :
  erase_wt_expr_env (dep_map (@expr_of_val) ρ) =
  erase_wt_env ρ.
Proof.
  induction ρ; auto.
  cbn.
  f_equal.
  auto.
Qed.

(** A downside to the list representation of environments is that doing lookup
    from a dependent list is awkward. *)
Lemma env_search {A Γ} {v : A -> Type} (ρ : dep_list v Γ) {x τ} :
  lookup Γ x = Some τ ->
  {e : v τ | dep_lookup ρ x = Some (existT v τ e)}.
Proof.
  intros.
  revert Γ ρ H.
  induction x; intros. {
    destruct Γ; inject H.
    dep_destruct ρ.
    eexists.
    reflexivity.
  } {
    destruct Γ; [discriminate |].
    dep_destruct ρ.
    simpl in *.
    exact (IHx _ _ H).
  }
Qed.

Lemma env_search_subst {Γ} (ρ : wt_env Γ) {x τ} :
  lookup Γ x = Some τ ->
  {v : val τ | erase v = erase_wt_env ρ x}.
Proof.
  intros.
  revert Γ ρ H.
  induction x; intros. {
    destruct Γ; inject H.
    dep_destruct ρ.
    eexists.
    reflexivity.
  } {
    destruct Γ; [discriminate |].
    dep_destruct ρ.
    simpl in *.
    exact (IHx _ _ H).
  }
Qed.

Lemma weaken_lookup {A} {Γ : Env A} {x τ Γw} :
  lookup Γ x = Some τ ->
  lookup (Γ ++ Γw) x = Some τ.
Proof.
  intros.
  revert Γ H.
  induction x; intros. {
    destruct Γ; inversion H.
    auto.
  } {
    destruct Γ; try discriminate H.
    simpl in *.
    apply IHx.
    auto.
  }
Qed.

Fixpoint weaken {Γ τ} (e : expr Γ τ) Γw : expr (Γ ++ Γw) τ :=
  match e with
  | e_real r => e_real r
  | e_var x H => e_var x (weaken_lookup H)
  | e_lam body => e_lam (weaken body Γw)
  | e_app ef ea => e_app (weaken ef Γw) (weaken ea Γw)
  | e_factor e => e_factor (weaken e Γw)
  | e_sample => e_sample
  | e_plus el er => e_plus (weaken el Γw) (weaken er Γw)
  end.

(** The definition of typed substitution borrows from
    https://www.ps.uni-saarland.de/autosubst/doc/Plain.Demo.html *)

(** A combination of weakening and renaming preserves types *)
Lemma expr_ren {Γ τ} ξ (e : expr Γ τ) Δ :
  lookup Γ = ξ >>> lookup Δ ->
  {e' : expr Δ τ |
   erase e' = rename ξ (erase e)}.
Proof.
  revert ξ Δ.
  induction e; intros. {
    exists (e_real r).
    simpl.
    auto.
  } {
    simple refine (exist _ (e_var (ξ x) _) _); simpl; auto.
    rewrite <- H.
    rewrite H0.
    auto.
  } {
    assert (lookup (τa :: Γ) = upren ξ >>> lookup (τa :: Δ)). {
      extensionality x.
      destruct x; auto.
      simpl.
      rewrite H.
      auto.
    }
    destruct (IHe _ _ H0).
    exists (e_lam x).
    simpl.
    rewrite e0.
    auto.
  } {
    edestruct IHe1, IHe2; eauto.
    eexists (e_app _ _).
    simpl.
    rewrite e, e0.
    auto.
  } {
    edestruct IHe; eauto.
    eexists (e_factor _).
    simpl.
    rewrite e0.
    auto.
  } {
    exists e_sample; auto.
  } {
    edestruct IHe1, IHe2; eauto.
    eexists (e_plus _ _).
    simpl.
    rewrite e, e0.
    auto.
  }
Qed.

(** lift's autosubst's untyped [up] function to well-typed environments *)
Lemma up_expr_env {Γ Δ : Env Ty}
      (σ : dep_list (expr Δ) Γ)
      (τa : Ty)
  : { σ' : dep_list (expr (τa :: Δ)) (τa :: Γ) |
      forall x τ,
        lookup (τa :: Γ) x = Some τ ->
        erase_wt_expr_env σ' x = up (erase_wt_expr_env σ) x }.
Proof.
  simple refine (exist _ _ _); auto. {
    constructor. {
      apply (e_var O).
      auto.
    } {
      refine (dep_map _ σ).
      intros a e.
      apply (expr_ren S e).
      auto.
    }
  } {
    simpl.
    intros.
    revert Γ Δ σ H.
    destruct x; auto.
    induction x; intros. {
      simpl.
      destruct σ; inversion H; subst.
      simpl.
      destruct expr_ren.
      rewrite e0.
      auto.
    } {
      destruct σ; try discriminate H; simpl in *.
      rewrite IHx; auto.
    }
  }
Qed.

(** Autosubst works with infinite substitution environments, but we never want
    to (and never have to) deal with the parts of the substitution that lie
    outside Γ. *)
Lemma subst_only_matters_up_to_env {Γ τ} (e : expr Γ τ) σ0 σ1 :
  (forall x τ,
      lookup Γ x = Some τ ->
      σ0 x = σ1 x) ->
  (erase e).[σ0] = (erase e).[σ1].
Proof.
  revert σ0 σ1.
  induction e; simpl; intros; f_equal; eauto.

  apply IHe.
  intros.
  destruct x; auto.
  simpl in H0.
  specialize (H _ _ H0).
  unfold up.
  simpl.
  rewrite H.
  auto.
Qed.

(** Finally we are armed with enough lemmas to define type-preserving
    substitution. *)
Lemma ty_subst {Γ τ} (e : expr Γ τ) :
  forall Δ (ρ : dep_list (expr Δ) Γ),
    {e' : expr Δ τ |
     erase e' = (erase e).[erase_wt_expr_env ρ]}.
Proof.
  induction e; intros. {
    exists (e_real r).
    reflexivity.
  } {
    simpl.
    destruct (env_search ρ H).
    exists x0.
    revert Γ H ρ e.
    induction x; intros. {
      destruct ρ; inversion e; subst.
      auto.
    } {
      destruct ρ; inversion e; subst.
      simpl.
      apply IHx; auto.
    }
  } {
    destruct (up_expr_env ρ τa).
    destruct (IHe _ x).

    eexists (e_lam _).
    simpl.
    f_equal.
    rewrite e1.

    apply subst_only_matters_up_to_env.
    auto.
  } {
    edestruct IHe1, IHe2; auto.
    eexists (e_app _ _).
    simpl.
    rewrite e, e0.
    reflexivity.
  } {
    edestruct IHe; auto.
    exists (e_factor x).
    simpl.
    rewrite e0.
    reflexivity.
  } {
    exists e_sample.
    reflexivity.
  } {
    edestruct IHe1, IHe2; auto.
    exists (e_plus x x0).
    simpl.
    rewrite e, e0.
    reflexivity.
  }
Qed.

Lemma close {Γ} (ρ : wt_env Γ) {τ} (e : expr Γ τ) :
  {e' : expr · τ |
   erase e' = (erase e).[erase_wt_env ρ]}.
Proof.
  rewrite <- erase_envs_equiv.
  apply ty_subst.
Qed.

Lemma close_nil (ρ : wt_env ·) {τ} (e : expr · τ) :
  proj1_sig (close ρ e) = e.
Proof.
  dep_destruct ρ.
  elim_sig_exprs.
  elim_erase_eqs.
  reflexivity.
Qed.

(** Since most day-to-day substitution is done by β, it's nice to have a small
    helper function to substitute exactly one value into a lambda body. *)
Definition ty_subst1 {τa τr}
      (e : expr (τa :: ·) τr)
      (v : val τa) :
  { e' : expr · τr |
    erase e' = (erase e).[erase v /] }
  := ty_subst e · (dep_cons (v : expr · τa) dep_nil).

(** * Evaluation *)

(** Evaluation is defined as a big-step relation. While it would have been nicer
    to instead define it as a partial function so that it's determinism is more
    obvious, the complicated recursion done by application means that
    determinism is instead done by logical relation in a more difficult manner.
    (See [eval_dec] in determinism.v) *)
Reserved Notation "'EVAL' σ ⊢ e ⇓ v , w" (at level 69, e at level 99, no associativity).
Inductive eval (σ : Entropy) : forall {τ} (e : expr · τ) (v : val τ) (w : R+), Type :=
| EVAL_val {τ} (v : val τ) :
    (EVAL σ ⊢ v ⇓ v, 1)
| EVAL_app {τa τr}
       {ef : expr · (τa ~> τr)}
       {ea : expr · τa}
       {body : expr (τa :: ·) τr}
       {va : val τa}
       {vr : val τr}
       {w0 w1 w2 : R+}
  : (EVAL (π 0 σ) ⊢ ef ⇓ mk_val (e_lam body) I, w0) ->
    (EVAL (π 1 σ) ⊢ ea ⇓ va, w1) ->
    (EVAL (π 2 σ) ⊢ proj1_sig (ty_subst1 body va) ⇓ vr, w2) ->
    (EVAL σ ⊢ e_app ef ea ⇓ vr, w0 * w1 * w2)
| EVAL_factor {e : expr · ℝ} {r : R} {w : R+} {is_v} (rpos : (0 <= r)%R)
  : (EVAL σ ⊢ e ⇓ mk_val (e_real r) is_v, w) ->
    (EVAL σ ⊢ e_factor e ⇓ v_real r, finite r rpos * w)
| EVAL_sample
  : (EVAL σ ⊢ e_sample ⇓ v_real (proj1_sig (σ O)), 1)
| EVAL_plus {e0 e1 : expr · ℝ} {r0 r1 : R} {is_v0 is_v1} {w0 w1 : R+}
  : (EVAL (π 0 σ) ⊢ e0 ⇓ mk_val (e_real r0) is_v0, w0) ->
    (EVAL (π 1 σ) ⊢ e1 ⇓ mk_val (e_real r1) is_v1, w1) ->
    (EVAL σ ⊢ e_plus e0 e1 ⇓ v_real (r0 + r1), w0 * w1)
where "'EVAL' σ ⊢ e ⇓ v , w" := (@eval σ _ e v w)
.

(** Misc lemmas *)

(** [inversion] has a hard time recognizing that [EVAL_val] is the only
    constructor that evaluates a value, so we use lemma instead. *)
Lemma invert_eval_val {σ τ} {v v' : val τ} {w} :
  (EVAL σ ⊢ v ⇓ v', w) ->
  v = v' /\ w = 1.
Proof.
  intros.
  destruct τ;
    destruct_val v;
    destruct_val v';
    dependent destruction H;
    auto.
Qed.

(** Equality of expressions is decidable. Currently unused, but a nice tool to
    have for feeding to UIP_dec. *)
Lemma u_expr_eq_dec (u0 u1 : u_expr) :
  {u0 = u1} + {u0 <> u1}.
Proof.
  decide equality. {
    apply Req_EM_T.
  } {
    decide equality.
  } {
    decide equality.
  }
Qed.

(** The GADTs in [expr] are too much for the [decide equality] tactic.
    Fortunately, the hard work of converting it to a GADT-less version has
    already been done in erase_injective. *)
Lemma expr_eq_dec {Γ τ} (e0 e1 : expr Γ τ) :
  {e0 = e1} + {e0 <> e1}.
Proof.
  destruct (u_expr_eq_dec (erase e0) (erase e1)). {
    left.
    exact (erase_injective e).
  } {
    right.
    contradict n.
    subst.
    auto.
  }
Qed.


From QuickChick Require Import QuickChick.
Inductive natural : Type := Succ : natural -> natural |  Zero : natural.
Derive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.
Inductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.

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

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

Fixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst
           := match append_arg0, append_arg1 with
              | Nil, x => x
              | Cons x y, z => Cons x (append y z)
              end.

Fixpoint rev (rev_arg0 : lst) : lst
           := match rev_arg0 with
              | Nil => Nil
              | Cons x y => append (rev y) (Cons x Nil)
              end.

Lemma lem2: forall l n, Cons n (rev l) = rev (append l (Cons n Nil)).
Proof.
intros. induction l.
  - simpl. rewrite <- IHl. reflexivity.
  - reflexivity.
Qed.

Lemma lem: forall l, rev (rev l) = l.
Proof.
induction l.
  - simpl. rewrite <- lem2. rewrite IHl. reflexivity.
  - reflexivity.
Qed.

Theorem theorem0 : forall (x : lst) (y : lst), eq (rev (rev (append x y))) (append (rev (rev x)) (rev (rev y))).
Proof.
  intros. rewrite lem.
  rewrite lem.
  rewrite lem. reflexivity.
Qed.


From Coq Require Import ZArith Reals Psatz.
From Flocq Require Import Binary.

Import List ListNotations.

Set Bullet Behavior "Strict Subproofs".

From Iterative Require Import   lemmas.

From mathcomp Require Import matrix bigop all_algebra all_ssreflect.
From mathcomp.analysis Require Import Rstruct.
From Coquelicot Require Import Lub Rbar.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(** We will open the real scope and the Ring scope
  separately **)

Open Scope ring_scope.

(** We instantiate the ring scope with real scope using
  Delimit Scope ... **)
Delimit Scope ring_scope with Ri.
Delimit Scope R_scope with Re.

(** We next import the ring theory so that we can use
  it for reals **)
Import Order.TTheory GRing.Theory Num.Def Num.Theory.

(** Infinity norm of a vector is the maximum of
    absolute values of the entries of a vector
**)
Definition vec_inf_norm {n:nat} (v : 'cV[R]_n) :=
 bigmaxr 0%Re [seq (Rabs (v i 0)) | i <- enum 'I_n].

(** Infinity norm of a matrix is the maximum of the columm sums **)
Definition matrix_inf_norm {n:nat} (A: 'M[R]_n) :=
  bigmaxr 0%Re [seq (row_sum A i) | i <- enum 'I_n].

Lemma vec_inf_norm_0_is_0 {n:nat}:
  @vec_inf_norm n.+1 0 = 0%Re.
Proof.
rewrite /vec_inf_norm. apply bigmaxrP.
split.
+ apply /mapP. exists (@ord0 n).
  - by rewrite mem_enum.
  - by rewrite mxE Rabs_R0.
+ intros. rewrite nth_seq_0_is_0. apply /RleP. apply Rle_refl.
  by rewrite size_map size_enum_ord in H.
Qed.

Lemma triang_ineq {n:nat} : forall a b: 'cV[R]_n.+1,
vec_inf_norm(a + b) <= vec_inf_norm a + vec_inf_norm b.
Proof.
intros.
rewrite /vec_inf_norm. apply /RleP.
apply bigmax_le.
+ by rewrite size_map size_enum_ord.
+ intros. rewrite -RplusE.
  apply Rle_trans with
    ([seq Rabs (a i0 0) | i0 <- enum 'I_n.+1]`_i +
     [seq Rabs (b i0 0) | i0 <- enum 'I_n.+1]`_i)%Re.
  - assert ([seq Rabs ((a + b)%Ri i0 0) | i0 <- enum 'I_n.+1] =
               mkseq (fun i =>  Rabs ((a + b)%Ri (@inord n i) 0)) n.+1).
    { unfold mkseq. rewrite -val_enum_ord.
      rewrite -[in RHS]map_comp.
      apply eq_map. unfold eqfun. intros.
      rewrite !mxE //=. rewrite !mxE. by rewrite inord_val.
    } rewrite H0 nth_mkseq; last by rewrite size_map size_enum_ord in H.
    assert ([seq Rabs (a i0 0) | i0 <- enum 'I_n.+1] =
               mkseq (fun i =>  Rabs (a (@inord n i) 0)) n.+1).
    { unfold mkseq. rewrite -val_enum_ord.
      rewrite -[in RHS]map_comp.
      apply eq_map. unfold eqfun. intros. by rewrite //= inord_val //=.
    } rewrite H1 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
    assert ([seq Rabs (b i0 0) | i0 <- enum 'I_n.+1] =
               mkseq (fun i =>  Rabs (b (@inord n i) 0)) n.+1).
    { unfold mkseq. rewrite -val_enum_ord.
      rewrite -[in RHS]map_comp.
      apply eq_map. unfold eqfun. intros. by rewrite //= inord_val //=.
    } rewrite H2 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
    rewrite !mxE //=. rewrite -RplusE. apply Rabs_triang.
  - apply Rplus_le_compat.
    * apply /RleP.
      apply (@bigmaxr_ler _ 0%Re [seq Rabs (a i0 0) | i0 <- enum 'I_n.+1] i).
      rewrite size_map size_enum_ord.
      by rewrite size_map size_enum_ord in H.
    * apply /RleP.
      apply (@bigmaxr_ler _ 0%Re [seq Rabs (b i0 0) | i0 <- enum 'I_n.+1] i).
      rewrite size_map size_enum_ord.
      by rewrite size_map size_enum_ord in H.
Qed.

Lemma submult_prop {n:nat} (A: 'M[R]_n.+1) (v : 'cV[R]_n.+1):
  vec_inf_norm (A *m v) <=
  matrix_inf_norm A * vec_inf_norm v.
Proof.
rewrite /vec_inf_norm /matrix_inf_norm. rewrite mulrC.
rewrite -bigmaxr_mulr.
+ apply /RleP. apply bigmax_le.
  - by rewrite size_map size_enum_ord.
  - intros.
    apply Rle_trans with
    [seq (bigmaxr 0
           [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *
         row_sum A i0)%Ri
      | i0 <- enum 'I_n.+1]`_i.
    * assert ([seq Rabs ((A *m v) i0 0) | i0 <- enum 'I_n.+1] =
              mkseq (fun i => Rabs ((A *m v) (@inord n i) 0)) n.+1).
      { unfold mkseq. rewrite -val_enum_ord.
        rewrite -[in RHS]map_comp.
        apply eq_map. unfold eqfun. intros.
        rewrite !mxE //=. rewrite !mxE. by rewrite //= inord_val //=.
      } rewrite H0 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
      assert ([seq bigmaxr 0
                  [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *  row_sum A i0
                    | i0 <- enum 'I_n.+1] =
               mkseq (fun i =>  bigmaxr 0
                        [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] *  row_sum A (@inord n i)) n.+1).
      { unfold mkseq. rewrite -val_enum_ord.
        rewrite -[in RHS]map_comp.
        apply eq_map. unfold eqfun. intros.
        by rewrite //= inord_val //=.
      } rewrite H1 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
      rewrite -RmultE. rewrite !mxE.
      apply Rle_trans with
        (\sum_j Rabs (A (inord i) j * v j 0)).
      ++ apply /RleP. apply Rabs_ineq.
      ++ assert (\sum_j Rabs (A (inord i) j * v j 0) =
                  \sum_j (Rabs (A (inord i) j) * Rabs (v j 0))).
         { apply eq_big. by []. intros. by rewrite Rabs_mult. }
         rewrite H2. rewrite Rmult_comm. apply /RleP. rewrite RmultE. rewrite -bigmaxr_mulr.
         apply /RleP.
         rewrite bigmaxr_mulr. rewrite -RmultE. rewrite /row_sum.
         rewrite big_distrl //=.
         apply /RleP. apply big_sum_ge_ex_abstract. intros.
         rewrite -!RmultE. apply Rmult_le_compat_l.
         -- apply Rabs_pos.
         -- apply Rle_trans with [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1]`_i0.
            ** assert ([seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] =
                       mkseq (fun i => Rabs (v (@inord n i) 0)) n.+1).
               { unfold mkseq. rewrite -val_enum_ord.
                 rewrite -[in RHS]map_comp.
                 apply eq_map. unfold eqfun. intros.
                 by rewrite //= inord_val //=.
               } rewrite H4 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
               rewrite //= inord_val. nra.
            ** apply /RleP. apply (@bigmaxr_ler _ 0%Re [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] i0).
                rewrite size_map size_enum_ord.
                by rewrite size_map size_enum_ord in H.
         -- unfold row_sum. apply big_ge_0_ex_abstract. intros.
            apply /RleP. apply Rabs_pos.
         -- unfold row_sum. apply big_ge_0_ex_abstract. intros.
            apply /RleP. apply Rabs_pos.
    * apply /RleP.
      apply (@bigmaxr_ler _ 0%Re [seq bigmaxr 0
                [seq Rabs (v i1 0) | i1 <- enum 'I_n.+1] * row_sum A i0
                  | i0 <- enum 'I_n.+1] i).
      rewrite size_map size_enum_ord.
      by rewrite size_map size_enum_ord in H.
+ apply bigmax_le_0.
  - by apply /RleP; apply Rle_refl.
  - intros.
    assert ([seq Rabs (v i0 0) | i0 <- enum 'I_n.+1]=
              mkseq (fun i => Rabs (v (@inord n i) 0)) n.+1).
    { unfold mkseq. rewrite -val_enum_ord.
      rewrite -[in RHS]map_comp.
      apply eq_map. unfold eqfun. intros.
      by rewrite //= inord_val //=.
    } rewrite H0 nth_mkseq ; last by rewrite size_map size_enum_ord in H.
    unfold row_sum. apply /RleP. apply Rabs_pos.
Qed.

Lemma matrix_norm_pd {n:nat} (A : 'M[R]_n.+1):
  0 <= matrix_inf_norm A.
Proof.
rewrite /matrix_inf_norm.
apply bigmax_le_0.
+ by apply /RleP; apply Rle_refl.
+ intros. rewrite seq_equiv.
  rewrite nth_mkseq; last by rewrite size_map size_enum_ord in H.
  rewrite /row_sum. apply big_ge_0_ex_abstract.
  intros. apply /RleP. apply Rabs_pos.
Qed.

Lemma vec_norm_pd {n:nat} (v : 'cV[R]_n.+1):
  0 <= vec_inf_norm v.
Proof.
rewrite /vec_inf_norm.
apply bigmax_le_0.
+ by apply /RleP; apply Rle_refl.
+ intros. rewrite seq_equiv.
  rewrite nth_mkseq; last by rewrite size_map size_enum_ord in H.
  apply /RleP. apply Rabs_pos.
Qed.

Lemma reverse_triang_ineq:
  forall n a b c,
  @vec_inf_norm n.+1 (a - b) <= c ->
  @vec_inf_norm n.+1 (a) - @vec_inf_norm n.+1 (b) <= c.
Proof.
intros. apply /RleP. rewrite -RminusE.
apply Rle_trans with (vec_inf_norm (a - b)).
+ assert (forall x y z:R, (x  <= y + z)%Re -> (x  - y <= z)%Re).
  { intros. nra. } apply H0.
  apply Rle_trans with (vec_inf_norm (b + (a - b))).
  - assert (a = b + (a - b)).
    { apply matrixP. unfold eqrel. intros. rewrite !mxE.
      rewrite -RplusE -RminusE.
      assert ((b x y + (a x y - b x y))%Re = a x y).
      { nra. } by rewrite H1.
    } rewrite -H1. apply Rle_refl.
  - apply /RleP. apply triang_ineq.
+ by apply /RleP.
Qed.

Lemma vec_inf_norm_opp {n:nat}:
  forall v: 'cV[R]_n,
  vec_inf_norm v = vec_inf_norm (-v).
Proof.
intros. rewrite /vec_inf_norm.
assert ([seq Rabs (v i 0) | i <- enum 'I_n] =
        [seq Rabs ((- v)%Ri i 0) | i <- enum 'I_n]).
{ apply eq_map. unfold eqfun. intros.
  rewrite! mxE. rewrite -RoppE. by rewrite  Rabs_Ropp.
} by rewrite H.
Qed.

Lemma cs_ineq_vec_inf_norm :
forall len, forall a b c d: 'cV[R]_len,
(0 < len)%N ->
vec_inf_norm(a - b + c -d) <= vec_inf_norm(a - b) + vec_inf_norm(c -d).
Proof.
intros.
  assert ((a - b + c -d) = (a - b) + (c - d)).
  { apply matrixP. unfold eqrel. intros. rewrite !mxE.
    rewrite -!RplusE -!RoppE. nra.
  } rewrite H0.
  assert (len = len.-1.+1).
  {  rewrite prednK; auto. }
  move: a  b c d H0. rewrite H1. intros. by apply triang_ineq.
Qed.

Lemma matrix_norm_le {n:nat}:
  forall (A B : 'M[R]_n.+1),
  matrix_inf_norm (A *m B) <= matrix_inf_norm A * matrix_inf_norm B.
Proof.
intros. rewrite /matrix_inf_norm.
apply /RleP. apply bigmax_le.
+ by rewrite size_map size_enum_ord.
+ intros. rewrite seq_equiv. rewrite nth_mkseq.
  - rewrite /row_sum.
    apply Rle_trans with
    (\sum_(j < n.+1) (\sum_(k < n.+1) (Rabs (A (inord i) k) * Rabs (B k j))%Re)).
    * apply /RleP. apply big_sum_ge_ex_abstract. intros.
      rewrite !mxE.
      apply Rle_trans with
      (\sum_j (Rabs ((A (inord i) j) * B j i0))).
      ++ apply /RleP. apply Rabs_ineq.
      ++ assert (\sum_j Rabs (A (inord i) j * B j i0) =
                  \sum_(k < n.+1) (Rabs (A (inord i) k) * Rabs (B k i0))%Re).
         { apply eq_big. by []. intros. by rewrite Rabs_mult. }
         rewrite H1. nra.
    * assert (\sum_(j < n.+1)
                \sum_(k < n.+1)
                   (Rabs (A (inord i) k) * Rabs (B k j))%Re =
               \sum_(k < n.+1)
                  \sum_(j < n.+1)
                     (Rabs (A (inord i) k) * Rabs (B k j))%Re).
      { apply exchange_big. } rewrite H0.
      rewrite mulrC. rewrite -bigmaxr_mulr.
      apply Rle_trans with
      (nth 0 [seq (bigmaxr 0 [seq \sum_(j < n.+1) Rabs (B i1 j)
                      | i1 <- enum 'I_n.+1] *
                    (\sum_(j < n.+1) Rabs (A i0 j)))%Ri | i0 <- enum 'I_n.+1] i).
      ++ rewrite seq_equiv. rewrite nth_mkseq.
         -- rewrite big_distrr //=. apply /RleP.
            apply big_sum_ge_ex_abstract. intros.
            rewrite -RmultE. rewrite Rmult_comm.
            rewrite -big_distrr //=. rewrite -RmultE.
            apply Rmult_le_compat_l.
            ** apply Rabs_pos.
            ** apply /RleP.
               assert (\sum_(i1 < n.+1) Rabs (B i0 i1) =
                        nth 0 [seq \sum_(j < n.+1) Rabs (B i1 j)
                               | i1 <- enum 'I_n.+1]  i0).
                { rewrite seq_equiv. rewrite nth_mkseq. by rewrite inord_val. apply ltn_ord. }
                rewrite H2.
                apply (@bigmaxr_ler _ 0  [seq \sum_(j < n.+1) Rabs (B i1 j)
                                           | i1 <- enum 'I_n.+1] i0).
                rewrite size_map size_enum_ord. apply ltn_ord.
         -- by rewrite size_map size_enum_ord in H.
      ++ apply /RleP.
         apply (@bigmaxr_ler _ 0%Re [seq bigmaxr 0
                       [seq \sum_(j < n.+1) Rabs (B i1 j)
                          | i1 <- enum 'I_n.+1] *
                     (\sum_(j < n.+1) Rabs (A i0 j))
                   | i0 <- enum 'I_n.+1] i).
         rewrite size_map size_enum_ord.
         by rewrite size_map size_enum_ord in H.
      ++ apply bigmax_le_0.
         -- apply /RleP. apply Rle_refl.
         -- intros. rewrite seq_equiv. rewrite nth_mkseq.
            ** apply big_ge_0_ex_abstract. intros.
               apply /RleP. apply Rabs_pos.
            ** by rewrite size_map size_enum_ord in H1.
  - by rewrite size_map size_enum_ord in H.
Qed.

Lemma matrix_norm_add {n:nat}:
  forall (A B : 'M[R]_n.+1),
  matrix_inf_norm (A + B) <= matrix_inf_norm A + matrix_inf_norm B.
Proof.
intros. rewrite /matrix_inf_norm.
apply /RleP. apply bigmax_le.
+ by rewrite size_map size_enum_ord //=.
+ intros.
  rewrite seq_equiv. rewrite nth_mkseq.
  - rewrite /row_sum.
    apply Rle_trans with
    (\sum_(j < n.+1) Rabs (A (inord i) j) +
     \sum_(j < n.+1) Rabs (B (inord i) j))%Re.
    * assert (\sum_(j < n.+1) Rabs ((A + B)%Ri (inord i) j) =
              \sum_(j < n.+1) Rabs (A (inord i) j + B (inord i) j)).
      { apply eq_big. by []. intros. rewrite !mxE. by rewrite -RplusE. }
      rewrite H0. apply sum_abs_le .
    * apply Rplus_le_compat.
      ++ assert (\sum_(j < n.+1) Rabs (A (inord i) j) =
                  nth 0 [seq \sum_(j < n.+1) Rabs (A i0 j)
                            | i0 <- enum 'I_n.+1] i).
         { rewrite seq_equiv. rewrite nth_mkseq.
           + by [].
           + by rewrite size_map size_enum_ord in H.
         } rewrite H0. apply /RleP.
         apply (@bigmaxr_ler _ 0 [seq \sum_(j < n.+1) Rabs (A i0 j)
                                      | i0 <- enum 'I_n.+1] i).
         rewrite size_map size_enum_ord in H.
         by rewrite size_map size_enum_ord.
      ++ assert (\sum_(j < n.+1) Rabs (B (inord i) j) =
                  nth 0 [seq \sum_(j < n.+1) Rabs (B i0 j)
                            | i0 <- enum 'I_n.+1] i).
         { rewrite seq_equiv. rewrite nth_mkseq.
           + by [].
           + by rewrite size_map size_enum_ord in H.
         } rewrite H0. apply /RleP.
         apply (@bigmaxr_ler _ 0 [seq \sum_(j < n.+1) Rabs (B i0 j)
                                      | i0 <- enum 'I_n.+1] i).
         rewrite size_map size_enum_ord in H.
         by rewrite size_map size_enum_ord.
  - by rewrite size_map size_enum_ord in H.
Qed.

Lemma matrix_norm_sum {n:nat} (f : nat -> 'M[R]_n.+1) (k:nat):
  matrix_inf_norm
   (\sum_(j < k.+1) f j) <=
  \sum_(j < k.+1) (matrix_inf_norm (f j)).
Proof.
induction k.
+ rewrite !big_ord_recr //= !big_ord0 !add0r. by apply /RleP; nra.
+ rewrite big_ord_recr //=.
  assert (\sum_(j < k.+2) matrix_inf_norm (f j) =
          \sum_(j < k.+1) matrix_inf_norm (f j) + matrix_inf_norm (f k.+1)).
  { by rewrite big_ord_recr //=. } rewrite H.
  apply /RleP.
  apply Rle_trans with
  (matrix_inf_norm (\sum_(i < k.+1) f i) + matrix_inf_norm (f k.+1))%Re.
  - apply /RleP. apply matrix_norm_add.
  - rewrite -RplusE.
    apply Rplus_le_compat_r.
    by apply /RleP.
Qed.

Lemma matrix_inf_norm_1 {n:nat}:
  @matrix_inf_norm n.+1 1 = 1%Re.
Proof.
rewrite /matrix_inf_norm. rewrite seq_equiv.
assert (mkseq (fun i : nat => row_sum 1 (@inord n i)) n.+1 =
          mkseq (fun i : nat => 1%Re) n.+1).
{ apply eq_map. unfold eqfun. intros.
  rewrite /row_sum.
  rewrite (bigD1 (inord x)) //=.
  assert (\sum_(i < n.+1 | i != inord x) Rabs ((1%:M : 'M[R]_n.+1) (inord x) i) = 0%Re).
  { rewrite big_0_ex_abstract.
    + by [].
    + intros. rewrite !mxE.
      assert (inord x == i = false).
      { rewrite eq_sym. apply /eqP. by apply /eqP. } rewrite H0 //=.
      by rewrite Rabs_R0.
      } rewrite H !mxE //=.
  rewrite addr0.
  assert (@inord n x == @inord n x = true).
  { by apply /eqP. } rewrite H0 //=. by rewrite Rabs_R1.
} rewrite H.
apply bigmaxrP.
split.
+ assert (1%Re = nth 0 (mkseq (fun=> 1) n.+1) 0).
  { by rewrite nth_mkseq. } rewrite H0. rewrite inE //=.
  apply /orP. by left.
+ intros. rewrite nth_mkseq.
  - apply /RleP. apply Rle_refl.
  - assert (mkseq (fun i : nat => 1%Re) n.+1 =
             [seq 1%Re | i <- enum 'I_n.+1]).
    { by rewrite seq_equiv. } rewrite H1 in H0.
    rewrite size_map size_enum_ord //= in H0.
Qed.

Lemma matrix_inf_norm_pow {n:nat}:
  forall (A: 'M[R]_n.+1) (i: nat),
  (matrix_inf_norm (A ^+ i) <= (matrix_inf_norm A)^+i)%Re.
Proof.
intros.
induction i.
+ rewrite !expr0. rewrite matrix_inf_norm_1 . apply Rle_refl.
+ rewrite !exprS.
  apply Rle_trans with
  (matrix_inf_norm A * matrix_inf_norm (A ^+ i))%Re.
  - apply /RleP. apply matrix_norm_le .
  - rewrite -RmultE. apply Rmult_le_compat_l.
    * apply /RleP. apply matrix_norm_pd.
    * apply IHi.
Qed.


Require Import Arith List.
Require Import BellantoniCook.Lib BellantoniCook.Cobham.

Definition Zero_e (n:nat) : Cobham :=
  Comp n Zero nil.

Lemma arity_Zero n : arity (Zero_e n) = ok_arity n.
Proof.
  trivial.
Qed.

Lemma rec_bounded_Zero n :
  rec_bounded (Zero_e n).
Proof.
simpl; tauto.
Qed.

Definition One_e (n:nat) : Cobham :=
  Comp n (Comp 0 (Succ true) [Zero]) nil.

Lemma arity_One n : arity (One_e n) = ok_arity n.
Proof.
  trivial.
Qed.

Lemma rec_bounded_One n :
  rec_bounded (One_e n).
Proof.
simpl; tauto.
Qed.

(** Def 12 of (Rose) *)

Definition App_e : Cobham :=
  Rec (Proj 1 0)
  (Comp 3 (Succ false) [Proj 3 1])
  (Comp 3 (Succ true) [Proj 3 1])
  (Comp 2 Smash [Comp 2 (Succ true) [Proj 2 0]; Comp 2 (Succ true) [Proj 2 1] ]).

Lemma arity_App : arity App_e = ok_arity 2.
Proof.
  trivial.
Qed.

Lemma rec_bounded_App : rec_bounded App_e.
Proof.
simpl.
intuition.
destruct l as [ | u [ | v l] ]; simpl.
omega.
rewrite length_smash, mult_1_r; simpl.
induction u as [ | [ | ] u IH]; simpl; omega.
rewrite length_smash', length_smash; simpl.
induction u as [ | [ | ] u IH]; simpl; omega.
Qed.

Lemma App_correct : forall l,
  Sem App_e l = hd nil l ++ hd nil (tl l).
Proof.
  intros; simpl.
  destruct l; simpl; trivial.
  induction l; simpl.
  destruct l0; simpl; trivial.
  rewrite IHl; case a; trivial.
Qed.

Opaque App_e.

Definition Rev_e : Cobham :=
  Rec
    Zero
    (Comp 2 App_e [Proj 2 1; Comp 2 (Succ false) [Zero_e 2]])
    (Comp 2 App_e [Proj 2 1; Comp 2 (Succ true) [Zero_e 2]])
    (Proj 1 0).

Lemma arity_Rev :
  arity Rev_e = ok_arity 1.
Proof.
trivial.
Qed.

Lemma rec_bounded_Rev :
  rec_bounded Rev_e.
Proof.
simpl.
intuition.
apply rec_bounded_App.
apply rec_bounded_App.
destruct l as [ | v l].
trivial.
simpl.
induction v as [ | [ | ] v IH].
trivial.
simpl.
rewrite App_correct.
simpl.
rewrite app_length.
simpl; omega.
simpl.
rewrite App_correct.
simpl.
rewrite app_length.
simpl; omega.
Qed.

Lemma Rev_correct l :
  Sem Rev_e l = List.rev (hd nil l).
Proof.
destruct l as [ | v l].
trivial.
simpl.
induction v as [ | [ | ] v IH].
trivial.
simpl.
rewrite App_correct.
simpl; congruence.
simpl.
rewrite App_correct.
simpl; congruence.
Qed.

Definition RemoveLSZ_e : Cobham :=
  Rec
    Zero
    (Proj 2 1)
    (Comp 2 (Succ true) [Proj 2 0])
    (Proj 1 0).

Lemma arity_RemoveLSZ :
  arity RemoveLSZ_e = ok_arity 1.
Proof.
trivial.
Qed.

Lemma rec_bounded_RemoveLSZ :
  rec_bounded RemoveLSZ_e.
Proof.
simpl.
intuition.
destruct l as [ | v l].
trivial.
simpl.
induction v as [ | [ | ] v IH].
trivial.
trivial.
simpl; omega.
Qed.

Lemma RemoveLSZ_app u v l :
  Sem RemoveLSZ_e ((u++v)::l) =
  match Sem RemoveLSZ_e (u::l) with
  | nil => Sem RemoveLSZ_e (v::l)
  | u' => u'++v
  end.
Proof.
simpl.
induction u as [ | [ | ] u IH]; trivial.
Qed.

Definition Cond : Cobham :=
  Rec (Proj 3 0) (Proj 5 4) (Proj 5 3) (
    Comp 4 Smash [
      Comp 4 (Succ true) [Proj 4 1];
      Comp 4 Smash [
        Comp 4 (Succ true) [Proj 4 2];
        Comp 4 (Succ true) [Proj 4 3]
      ]
    ]
  ).

Lemma arity_Cond : arity Cond = ok_arity 4.
Proof.
trivial.
Qed.

Lemma rec_bounded_Cond : rec_bounded' Cond.
Proof.
  simpl; repeat (split; auto);  intros.
  repeat (rewrite length_smash'; simpl).
  repeat (rewrite length_smash; simpl).
  repeat (rewrite length_smash'; simpl).
  repeat (rewrite length_smash; simpl).

  destruct (hd nil l); simpl; repeat rewrite nth_S_tl.

  rewrite plus_n_Sm.
  rewrite plus_comm.
  apply le_plus_trans.
  apply le_trans with ( S (S (length (nth 1 l nil)) * 1)).
  omega.
  apply le_n_S.
  apply le_n_S.
  apply mult_le_compat.
  trivial.
  apply le_n_S.
  auto with arith.

  apply le_trans with ( S (length (if b then nth 2 l nil else nth 3 l nil)) * 1).
  rewrite mult_1_r; auto with arith.

  apply le_trans with (S (S (length (nth 2 l nil)) * S (length (nth 3 l nil)))).
  case b.
  rewrite mult_1_r.
  apply le_n_S.
  rewrite <- mult_1_r at 1.
  apply mult_le_compat; auto with arith.
  rewrite mult_1_r.
  apply le_n_S.
  rewrite <- mult_1_l at 1.
  apply mult_le_compat; auto with arith.
  set (R1 := length (nth 1 l nil)).
  set (R2 := length (nth 2 l nil)).
  set (R3 := length (nth 3 l nil)).
  set (R4 := length (nth 4 l nil)).
  ring_simplify.
  cutrewrite (R2 * R3 * R1 + R2 * R3 + R2 * R1 + R2 + R3 * R1 + R3 + 2 * R1 + 3 =
    (R2 * R3 + R2 + R3 + 2) + (R2 * R3 * R1 + R2 * R1 + R3 * R1 + 2 * R1 + 1)).
  auto with arith.
  ring.
Qed.

Lemma Cond_correct : forall l,
  Sem Cond l =
  match hd nil l with
  | nil => hd nil (tl l)
  | true::_ => hd nil (tl (tl l))
  | false::_ => hd nil (tl (tl (tl l)))
  end.
Proof.
destruct l as [ | [ | [ | ] v1] [ | v2 [ | v3 [ | v4 l] ] ] ]; trivial.
Qed.


Require Coq.Logic.Classical_Prop.
Require Import ProofCheckingEuclid.euclidean_axioms.
Require Import ProofCheckingEuclid.euclidean_defs.
Require Import ProofCheckingEuclid.lemma_equalitysymmetric.
Require Import ProofCheckingEuclid.lemma_orderofpoints_ABC_ACD_BCD.
Require Import ProofCheckingEuclid.lemma_orderofpoints_ABC_BCD_ACD.
Require Import ProofCheckingEuclid.lemma_outerconnectivity.
Require Import ProofCheckingEuclid.lemma_s_onray.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma lemma_onray_shared_initial_point :
	forall B C D V,
	OnRay B C D ->
	OnRay B C V ->
	OnRay B D V.
Proof.
	intros B C D V.
	intros OnRay_BC_D.
	intros OnRay_BC_V.

	destruct OnRay_BC_D as (E & BetS_E_B_D & BetS_E_B_C).
	destruct OnRay_BC_V as (H & BetS_H_B_V & BetS_H_B_C).

	assert (~ ~ BetS E B V) as BetS_E_B_V.
	{
		intros nBetS_E_B_V.

		assert (~ BetS B E H) as nBetS_B_E_H.
		{
			intros BetS_B_E_H.

			pose proof (axiom_betweennesssymmetry _ _ _ BetS_B_E_H) as BetS_H_E_B.
			pose proof (lemma_orderofpoints_ABC_ACD_BCD _ _ _ _ BetS_H_E_B BetS_H_B_V) as BetS_E_B_V.

			contradict BetS_E_B_V.
			exact nBetS_E_B_V.
		}

		assert (~ BetS B H E) as nBetS_B_H_E.
		{
			intros BetS_B_H_E.

			pose proof (axiom_betweennesssymmetry _ _ _ BetS_B_H_E) as BetS_E_H_B.
			pose proof (lemma_orderofpoints_ABC_BCD_ACD _ _ _ _ BetS_E_H_B BetS_H_B_V) as BetS_E_B_V.

			contradict BetS_E_B_V.
			exact nBetS_E_B_V.
		}

		pose proof (axiom_betweennesssymmetry _ _ _ BetS_E_B_C) as BetS_C_B_E.
		pose proof (axiom_betweennesssymmetry _ _ _ BetS_H_B_C) as BetS_C_B_H.
		pose proof (lemma_outerconnectivity _ _ _ _ BetS_C_B_H BetS_C_B_E nBetS_B_H_E nBetS_B_E_H) as eq_H_E.

		pose proof (lemma_equalitysymmetric _ _ eq_H_E) as eq_E_H.
		assert (BetS E B V) as BetS_E_B_V by (rewrite eq_E_H; exact BetS_H_B_V).

		contradict BetS_E_B_V.
		exact nBetS_E_B_V.
	}
	apply Classical_Prop.NNPP in BetS_E_B_V.

	pose proof (lemma_s_onray _ _ _ _ BetS_E_B_D BetS_E_B_V) as OnRay_BD_V.
	exact OnRay_BD_V.
Qed.

End Euclid.


Require Import decideq.

(**********************************************************************)

(*Definining a dependent destruct from decideq:*)

Ltac dep_destruct H := depdestruct H; dep_destruct_cleanup; try discriminate.

Ltac dde := dependent decide equality.
Notation defeq := (ltac:(dde)) (only parsing).

Require PeanoNat.
Existing Instance PeanoNat.Nat.eq_dec.

(* Require Eqdep. *)
(* Ltac UIP_alias ::= Eqdep.EqdepTheory.UIP. *)
(* Ltac inj_pair2_alias ::= Eqdep.EqdepTheory.inj_pair2. *)

Require Eqdep_dec.
Ltac UIP_alias ::= Eqdep_dec.UIP_dec.
Ltac inj_pair2_alias ::= Eqdep_dec.inj_pair2_eq_dec.

(* Require Eqdep_em. *)
(* Ltac UIP_alias ::= Eqdep_em.UIP_em. *)
(* Ltac inj_pair2_alias ::= Eqdep_em.inj_pair2_eqem. *)

(**********************************************************************)

(* example from James Wilcox - see:
http://homes.cs.washington.edu/~jrw12/dep-destruct.html*)

Inductive Fin : nat -> Set :=
| F1 : forall n : nat, Fin (S n)
| FS : forall n : nat, Fin n -> Fin (S n).

Instance Fin_eqdec : eqdec Fin := defeq.
Print Assumptions Fin_eqdec.

Definition cardinality (n : nat) (A : Type) : Prop :=
  exists (f : A -> Fin n) (g : Fin n -> A),
    (forall x, g (f x) = x) /\
    (forall y, f (g y) = y).

Definition bool_to_Fin_2 (x : bool) : Fin 2 :=
  if x then FS _ (F1 _) else F1 _.

Definition Fin_2_to_bool (y : Fin 2) : bool :=
  match y with
  | F1 _ => false
  | FS _ (F1 _) => true
  | _ => false (* bogus! *)
  end.

Theorem bool_cardinality_2 : cardinality 2 bool.
Proof.
  unfold cardinality.
  exists bool_to_Fin_2.
  exists Fin_2_to_bool.
  split; intros.
  - destruct x; reflexivity.
  - dep_destruct y; try reflexivity.
    dep_destruct y; try reflexivity.
    dep_destruct y.
Qed.
Print Assumptions bool_cardinality_2.

Lemma fin_case :
  forall n (P : Fin (S n) -> Type),
    (P (F1 _)) ->
    (forall x, P (FS _ x)) ->
    (forall x, P x).
Proof.
  intros n P X X0 x.
  dep_destruct x.
  all:auto with nocore.
Qed.
Print Assumptions fin_case.

(**********************************************************************)

Lemma le_minus : forall n:nat, n < 1 -> n = 0.
Proof.
  intros n H.
  dep_destruct H. (*not enough generalizing*)
  Undo.
  solve [dep_destruct H; inversion H]. (*but backtracking forces it*)
  Undo.
  Ltac sigTgen.sigT_generalize_as_needed ::= false.
  dep_destruct H. (*now have enough without backtracking*)
  inversion H.
Qed.
Print Assumptions le_minus.

Ltac sigTgen.sigT_generalize_as_needed ::= true.

Inductive vect A : nat -> Type :=
| vnil : vect A 0
| vcons : forall (h:A) (n:nat), vect A n -> vect A (S n).

Lemma vect_break: forall A n, forall v : vect A (S n), exists v' : vect A n, exists a : A, v = vcons A a _ v'.
Proof.
  intros A n v.
  dep_destruct v.
  do 2 eexists.
  reflexivity.
Qed.
Print Assumptions vect_break.

(*from /test-suite/success/dependentind.v:*)
(** Example by Andrew Kenedy, uses simplification of the first component of dependent pairs. *)

Set Implicit Arguments.

Inductive Ty :=
 | Nat : Ty
 | Prod : Ty -> Ty -> Ty.

Instance Ty_eqdec : eqdec Ty := defeq.
Print Assumptions Ty_eqdec.

Inductive Exp : Ty -> Type :=
| Const : nat -> Exp Nat
| Pair : forall t1 t2, Exp t1 -> Exp t2 -> Exp (Prod t1 t2)
| Fst : forall t1 t2, Exp (Prod t1 t2) -> Exp t1.

Instance Exp_eqdec : eqdec Exp := defeq.
Print Assumptions Exp_eqdec.

Inductive Ev : forall t, Exp t -> Exp t -> Prop :=
| EvConst   : forall n, Ev (Const n) (Const n)
| EvPair    : forall t1 t2 (e1:Exp t1) (e2:Exp t2) e1' e2',
               Ev e1 e1' -> Ev e2 e2' -> Ev (Pair e1 e2) (Pair e1' e2')
| EvFst     : forall t1 t2 (e:Exp (Prod t1 t2)) e1 e2,
               Ev e (Pair e1 e2) ->
               Ev (Fst e) e1.

Lemma EvFst_inversion : forall t1 t2 (e:Exp (Prod t1 t2)) e1, Ev (Fst e) e1 -> exists e2, Ev e (Pair e1 e2).
  intros t1 t2 e e1 ev.
  dep_destruct ev.
  Fail eexists; eassumption.
  Undo 2.
  (*backtrack to generalize enough works:*)
  dep_destruct ev; eexists; eassumption.
  Undo.
  (*or, turn off as_needed mode:*)
  Ltac sigTgen.sigT_generalize_as_needed ::= false.
  dep_destruct ev.
  eexists; eassumption.
Qed.
Print Assumptions EvFst_inversion. (*closed now, was using eq_rect_eq*)