Require Import Coq.PArith.BinPosDef.
Require Import Crypto.Util.Decidable Crypto.Util.Notations.
Require Import Crypto.Algebra.Ring Crypto.Algebra.Field.

Module _fsatz_test.
  Section _test.
    Context {F eq zero one opp add sub mul inv div}
            {fld:@Hierarchy.field F eq zero one opp add sub mul inv div}
            {eq_dec:DecidableRel eq}.
    Local Infix "=" := eq. Local Notation "a <> b" := (not (a = b)).
    Local Infix "=" := eq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope.
    Local Notation "0" := zero.  Local Notation "1" := one.
    Local Infix "+" := add. Local Infix "*" := mul.
    Local Infix "-" := sub. Local Infix "/" := div.

    Lemma inv_hyp a b c d (H:a*inv b=inv d*c) (bnz:b<>0) (dnz:d<>0) : a*d = b*c.
    Proof using Type*. fsatz. Qed.

    Lemma inv_goal a b c d (H:a=b+c) (anz:a<>0) : inv a*d + 1 = (d+b+c)*inv(b+c).
    Proof using Type*. fsatz. Qed.

    Lemma div_hyp a b c d (H:a/b=c/d) (bnz:b<>0) (dnz:d<>0) : a*d = b*c.
    Proof using Type*. fsatz. Qed.

    Lemma div_goal a b c d (H:a=b+c) (anz:a<>0) : d/a + 1 = (d+b+c)/(b+c).
    Proof using Type*. fsatz. Qed.

    Lemma inv_inv x (H:x <> 0) : 1/(1/x) = x.
    Proof using Type*. fsatz. Qed.

    Lemma zero_neq_one : 0 <> 1.
    Proof using Type*. fsatz. Qed.

    Lemma only_two_square_roots x y : x * x = y * y -> x <> opp y -> x = y.
    Proof using Type*. intros; fsatz. Qed.

    Lemma transitivity_contradiction a b c (ab:a=b) (bc:b=c) (X:a<>c) : False.
    Proof using Type*. fsatz. Qed.

    Lemma algebraic_contradiction a b c (A:a+b=c) (B:a-b=c) (X:a*a - b*b <> c*c) : False.
    Proof using Type*. fsatz. Qed.

    Lemma division_by_zero_in_hyps (bad:1/0 + 1 = (1+1)/0): 1 = 1.
    Proof using Type*. fsatz. Qed.
    Lemma division_by_zero_in_hyps_eq_neq (bad:1/0 + 1 = (1+1)/0): 1 <> 0.
    Proof using Type*.
 fsatz. Qed.
    Lemma division_by_zero_in_hyps_neq_neq (bad:1/0 <> (1+1)/0): 1 <> 0.
    Proof using Type*.
 fsatz. Qed.
    Import BinNums.

    Context {char_ge_16:@Ring.char_ge F eq zero one opp add sub mul 16}.

    Local Notation two := (one+one) (only parsing).
    Local Notation three := (one+one+one) (only parsing).
    Local Notation seven := (three+three+one) (only parsing).
    Local Notation nine := (three+three+three) (only parsing).

    Lemma fractional_equation_solution x (A:x<>1) (B:x<>opp two) (C:x*x+x <> two) (X:nine/(x*x + x - two) = three/(x+two) + seven*inv(x-1)) : x = opp one / (three+two).
    Proof using Type*. fsatz. Qed.

    Lemma fractional_equation_no_solution x (A:x<>1) (B:x<>opp two) (C:x*x+x <> two) (X:nine/(x*x + x - two) = opp three/(x+two) + seven*inv(x-1)) : False.
    Proof using Type*. fsatz. Qed.

    Local Notation "x ^ 2" := (x*x).
    Lemma recursive_nonzero_solving
          (a sqrt_a d x y : F)
          (Hpoly : a * x^2 + y^2 = one + d * x^2 * y^2)
          (Hsqrt : sqrt_a^2 = a)
          (Hfrac : (sqrt_a / y)^2 <> d)
      : x^2 = (y^2 - one) / (d * y^2 - a).
    Proof using eq_dec fld. fsatz. Qed.

    Local Notation "x ^ 3" := (x^2*x).
    Lemma weierstrass_associativity_main a b x1 y1 x2 y2 x4 y4
          (A: y1^2=x1^3+a*x1+b)
          (B: y2^2=x2^3+a*x2+b)
          (C: y4^2=x4^3+a*x4+b)
          (Hi3: x2 <> x1)
          λ3 (Hλ3: λ3 = (y2-y1)/(x2-x1))
          x3 (Hx3: x3 = λ3^2-x1-x2)
          y3 (Hy3: y3 = λ3*(x1-x3)-y1)
          (Hi7: x4 <> x3)
          λ7 (Hλ7: λ7 = (y4-y3)/(x4-x3))
          x7 (Hx7: x7 = λ7^2-x3-x4)
          y7 (Hy7: y7 = λ7*(x3-x7)-y3)
          (Hi6: x4 <> x2)
          λ6 (Hλ6: λ6 = (y4-y2)/(x4-x2))
          x6 (Hx6: x6 = λ6^2-x2-x4)
          y6 (Hy6: y6 = λ6*(x2-x6)-y2)
          (Hi9: x6 <> x1)
          λ9 (Hλ9: λ9 = (y6-y1)/(x6-x1))
          x9 (Hx9: x9 = λ9^2-x1-x6)
          y9 (Hy9: y9 = λ9*(x1-x9)-y1)
      : x7 = x9 /\ y7 = y9.
    Proof using Type*. fsatz_prepare_hyps; split; fsatz. Qed.
  End _test.
End _fsatz_test.


Require Export Arith.EqNat.
Require Export Arith.Le.
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.

(* The bdestruct tactic is borrowed from https://softwarefoundations.cis.upenn.edu/vfa-current/Perm.html *)

Lemma beq_reflect : forall x y, reflect (x = y) (x =? y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply beq_nat_true_iff.
Qed.

Lemma blt_reflect : forall x y, reflect (x < y) (x <? y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply Nat.ltb_lt.
Qed.

Lemma ble_reflect : forall x y, reflect (x <= y) (x <=? y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply Nat.leb_le.
Qed.
#[global] Hint Resolve blt_reflect ble_reflect beq_reflect : bdestruct.

Ltac bdestruct X :=
  let H := fresh in let e := fresh "e" in
                    evar (e: Prop);
                    assert (H: reflect e X); subst e;
                    [eauto with bdestruct
                    | destruct H as [H|H];
                      [ | try first [apply not_lt in H | apply not_le in H] ] ].


Require CPidgin.Data.Maybe.

Module MList.

Import Maybe.Maybe.

(* Simple linked list of values of an optional type. *)
Inductive MList (A : Type) : Type :=
    | nil : MList A
    | cons : Maybe A -> MList A -> MList A.

(* Gather the implicit type A parameter from implicit context. *)
Arguments nil {A}.
(* The implicit type A maps to the type of the cons parameter. *)
Arguments cons {A} a _.

(* Use [] notation to indicate nil. *)
Notation "[ ]" := nil (format "[ ]").
(* Use [ x ] notation to indicate a list of one item. *)
Notation "[ x ]" := (cons x nil).
(* Use [x ; y ; .. ; z ] notation to indicate a variable length list. *)
Notation "[ x ; y ; .. ; z ]" := (cons x (cons y .. (cons z nil) ..)).
(* Use x :: y to break down a cons cell in a list. *)
Notation "x :: y" := (cons x y).

(* Get the head of a given MList. *)
Definition head {A : Type} (lst : MList A) : Maybe A :=
    match lst with
        | [] => Nothing
        | x :: xs => x
    end.

(* Get the tail of a given MList. *)
Definition tail {A : Type} (lst : MList A) : MList A :=
    match lst with
        | [] => []
        | x :: xs => xs
    end.

(* Drop n elements from a MList. *)
Fixpoint drop {A : Type} (n : nat) (lst : MList A) : MList A :=
    match n with
        | 0 => lst
        | S n' => drop n' (tail lst)
    end.

(* Append two MLists. *)
Fixpoint append {A : Type} (l1 l2 : MList A) : MList A :=
    match l1 with
        | [] => l2
        | (x :: xs) => x :: append xs l2
    end.

(* Use xs ++ ys to append these two lists. *)
Notation "xs ++ ys" := (append xs ys).

(* Get the length of an MList. *)
Fixpoint length {A : Type} (l : MList A) : nat :=
    match l with
        | [] => 0
        | (x :: xs) => S (length xs)
    end.

(* Take the first n elements in an MList. *)
Fixpoint take {A : Type} (n : nat) (l : MList A) : MList A :=
    match n with
        | 0 => []
        | S n' =>
            match l with
                | [] => []
                | (x :: xs) => x :: take n' xs
            end
    end.

(* Take the nth item from an MList. *)
Definition nth {A : Type} (n : nat) (l : MList A) : Maybe A :=
    match n with
        | 0 => head l
        | S n' => head (drop n l)
    end.

(* Remove the nth item from an MList. *)
Fixpoint removeNth {A : Type} (n : nat) (l : MList A) : MList A :=
    match n with
        | 0 => tail l
        | S n' =>
        match l with
            | [] => []
            | (x :: xs) => x :: removeNth n' xs
        end
    end.

End MList.


(* Parameterized types *)

Inductive prod (X Y : Set) : Set :=
  pair : X -> Y -> prod X Y.

Check pair.
(* : forall X Y : Set, X -> Y -> prod X Y *)

Check (pair nat nat O (S(S O))).
(* : prod nat nat *)

Arguments pair {X} {Y} _ _.

Check (pair O (S(S O))).

Inductive list (T : Set) : Set :=
| Nil : list T
| Cons : T -> list T -> list T.

Fixpoint length T (ls : list T) : nat :=
match ls with
| Nil => O
| Cons _ ls' => S (length T ls')
end.

Reset list.

Set Implicit Arguments.

Section list.
  Variable T : Set.

  Inductive list : Set :=
  | Nil : list
  | Cons : T -> list -> list.

  Fixpoint length (ls : list) : nat :=
    match ls with
      | Nil => O
      | Cons _ ls' => S (length ls')
    end.

End list.

Check length.
(*
 : forall T : Set, list T -> nat
*)

(*
Check (length nat (Nil nat)).
Check (length nat (Cons nat O (Nil nat))).
*)

Arguments Nil [T].

Check length Nil.


(** * Basics: Functional Programming in Coq *)

(*
   [Admitted] is Coq's "escape hatch" that says accept this definition
   without proof.  We use it to mark the 'holes' in the development
   that should be completed as part of your homework exercises.  In
   practice, [Admitted] is useful when you're incrementally developing
   large proofs.

   As of Coq 8.4 [admit] is in the standard library, but we include
   it here for backwards compatibility.
*)
Definition admit {T: Type} : T.  Admitted.

(* ###################################################################### *)
(** * Introduction *)

(** The functional programming style brings programming closer to
    mathematics: If a procedure or method has no side effects, then
    pretty much all you need to understand about it is how it maps
    inputs to outputs -- that is, you can think of its behavior as
    just computing a mathematical function.  This is one reason for
    the word "functional" in "functional programming."  This direct
    connection between programs and simple mathematical objects
    supports both sound informal reasoning and formal proofs of
    correctness.

    The other sense in which functional programming is "functional" is
    that it emphasizes the use of functions (or methods) as
    _first-class_ values -- i.e., values that can be passed as
    arguments to other functions, returned as results, stored in data
    structures, etc.  The recognition that functions can be treated as
    data in this way enables a host of useful idioms, as we will see.

    Other common features of functional languages include _algebraic
    data types_ and _pattern matching_, which make it easy to construct
    and manipulate rich data structures, and sophisticated
    _polymorphic type systems_ that support abstraction and code
    reuse.  Coq shares all of these features.
*)

(* ###################################################################### *)
(** * Enumerated Types *)

(** One unusual aspect of Coq is that its set of built-in
    features is _extremely_ small.  For example, instead of providing
    the usual palette of atomic data types (booleans, integers,
    strings, etc.), Coq offers an extremely powerful mechanism for
    defining new data types from scratch -- so powerful that all these
    familiar types arise as instances.

    Naturally, the Coq distribution comes with an extensive standard
    library providing definitions of booleans, numbers, and many
    common data structures like lists and hash tables.  But there is
    nothing magic or primitive about these library definitions: they
    are ordinary user code.

    To see how this works, let's start with a very simple example. *)

(* ###################################################################### *)
(** ** Days of the Week *)

(** The following declaration tells Coq that we are defining
    a new set of data values -- a _type_. *)

Inductive day : Type :=
  | monday : day
  | tuesday : day
  | wednesday : day
  | thursday : day
  | friday : day
  | saturday : day
  | sunday : day.

(** The type is called [day], and its members are [monday],
    [tuesday], etc.  The second through eighth lines of the definition
    can be read "[monday] is a [day], [tuesday] is a [day], etc."

    Having defined [day], we can write functions that operate on
    days. *)

Definition next_weekday (d:day) : day :=
  match d with
  | monday    => tuesday
  | tuesday   => wednesday
  | wednesday => thursday
  | thursday  => friday
  | friday    => monday
  | saturday  => monday
  | sunday    => monday
  end.

(** One thing to note is that the argument and return types of
    this function are explicitly declared.  Like most functional
    programming languages, Coq can often work out these types even if
    they are not given explicitly -- i.e., it performs some _type
    inference_ -- but we'll always include them to make reading
    easier. *)

(** Having defined a function, we should check that it works on
    some examples.  There are actually three different ways to do this
    in Coq.  First, we can use the command [Eval compute] to evaluate a
    compound expression involving [next_weekday].  *)

Eval compute in (next_weekday friday).
   (* ==> monday : day *)
Eval compute in (next_weekday (next_weekday saturday)).
   (* ==> tuesday : day *)

(** If you have a computer handy, now would be an excellent
    moment to fire up the Coq interpreter under your favorite IDE --
    either CoqIde or Proof General -- and try this for yourself.  Load
    this file ([Basics.v]) from the book's accompanying Coq sources,
    find the above example, submit it to Coq, and observe the
    result. *)

(** The keyword [compute] tells Coq precisely how to
    evaluate the expression we give it.  For the moment, [compute] is
    the only one we'll need; later on we'll see some alternatives that
    are sometimes useful. *)

(** Second, we can record what we _expect_ the result to be in
    the form of a Coq example: *)

Example test_next_weekday:
  (next_weekday (next_weekday saturday)) = tuesday.

(** This declaration does two things: it makes an
    assertion (that the second weekday after [saturday] is [tuesday]),
    and it gives the assertion a name that can be used to refer to it
    later. *)
(** Having made the assertion, we can also ask Coq to verify it,
    like this: *)

Proof. simpl. reflexivity.  Qed.

(** The details are not important for now (we'll come back to
    them in a bit), but essentially this can be read as "The assertion
    we've just made can be proved by observing that both sides of the
    equality evaluate to the same thing, after some simplification." *)

(** Third, we can ask Coq to "extract," from a [Definition], a
    program in some other, more conventional, programming
    language (OCaml, Scheme, or Haskell) with a high-performance
    compiler.  This facility is very interesting, since it gives us a
    way to construct _fully certified_ programs in mainstream
    languages.  Indeed, this is one of the main uses for which Coq was
    developed.  We'll come back to this topic in later chapters.
    More information can also be found in the Coq'Art book by Bertot
    and Casteran, as well as the Coq reference manual. *)

(* ###################################################################### *)
(** ** Booleans *)

(** In a similar way, we can define the type [bool] of booleans,
    with members [true] and [false]. *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

(** Although we are rolling our own booleans here for the sake
    of building up everything from scratch, Coq does, of course,
    provide a default implementation of the booleans in its standard
    library, together with a multitude of useful functions and
    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library
    documentation if you're interested.)  Whenever possible, we'll
    name our own definitions and theorems so that they exactly
    coincide with the ones in the standard library. *)

(** Functions over booleans can be defined in the same way as
    above: *)

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

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Definition orb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => true
  | false => b2
  end.

(** The last two illustrate the syntax for multi-argument
    function definitions. *)

(** The following four "unit tests" constitute a complete
    specification -- a truth table -- for the [orb] function: *)

Example test_orb1:  (orb true  false) = true.
Proof. reflexivity.  Qed.
Example test_orb2:  (orb false false) = false.
Proof. reflexivity.  Qed.
Example test_orb3:  (orb false true)  = true.
Proof. reflexivity.  Qed.
Example test_orb4:  (orb true  true)  = true.
Proof. reflexivity.  Qed.

(** (Note that we've dropped the [simpl] in the proofs.  It's not
    actually needed because [reflexivity] will automatically perform
    simplification.) *)

(** _A note on notation_: We use square brackets to delimit
    fragments of Coq code in comments in .v files; this convention,
    also used by the [coqdoc] documentation tool, keeps them visually
    separate from the surrounding text.  In the html version of the
    files, these pieces of text appear in a [different font]. *)

(** The values [Admitted] and [admit] can be used to fill
    a hole in an incomplete definition or proof.  We'll use them in the
    following exercises.  In general, your job in the exercises is
    to replace [admit] or [Admitted] with real definitions or proofs. *)

(** **** Exercise: 1 star (nandb)  *)
(** Complete the definition of the following function, then make
    sure that the [Example] assertions below can each be verified by
    Coq.  *)

(** This function should return [true] if either or both of
    its inputs are [false]. *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  negb( andb b1 b2).

(** Remove "[Admitted.]" and fill in each proof with
    "[Proof. reflexivity. Qed.]" *)

Example test_nandb1:               (nandb true false) = true.
Proof. reflexivity.  Qed.
Example test_nandb2:               (nandb false false) = true.
Proof. reflexivity.  Qed.
Example test_nandb3:               (nandb false true) = true.
Proof. reflexivity.  Qed.
Example test_nandb4:               (nandb true true) = false.
Proof. reflexivity.  Qed.
(** [] *)

(** **** Exercise: 1 star (andb3)  *)
(** Do the same for the [andb3] function below. This function should
    return [true] when all of its inputs are [true], and [false]
    otherwise. *)

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  match b1 with
|false=>false
|true=>match b2 with
|false=>false
|true=>b3
end
end.
Example test_andb31:                 (andb3 true true true) = true.
Proof. reflexivity.  Qed.
Example test_andb32:                 (andb3 false true true) = false.
Proof. reflexivity.  Qed.
Example test_andb33:                 (andb3 true false true) = false.
Proof. reflexivity.  Qed.
Example test_andb34:                 (andb3 true true false) = false.
Proof. reflexivity.  Qed.
(** [] *)

(* ###################################################################### *)
(** ** Function Types *)

(** The [Check] command causes Coq to print the type of an
    expression.  For example, the type of [negb true] is [bool]. *)

Check true.
(* ===> true : bool *)
Check (negb true).
(* ===> negb true : bool *)

(** Functions like [negb] itself are also data values, just like
    [true] and [false].  Their types are called _function types_, and
    they are written with arrows. *)

Check negb.
(* ===> negb : bool -> bool *)

(** The type of [negb], written [bool -> bool] and pronounced
    "[bool] arrow [bool]," can be read, "Given an input of type
    [bool], this function produces an output of type [bool]."
    Similarly, the type of [andb], written [bool -> bool -> bool], can
    be read, "Given two inputs, both of type [bool], this function
    produces an output of type [bool]." *)

(* ###################################################################### *)
(** ** Numbers *)

(** _Technical digression_: Coq provides a fairly sophisticated
    _module system_, to aid in organizing large developments.  In this
    course we won't need most of its features, but one is useful: If
    we enclose a collection of declarations between [Module X] and
    [End X] markers, then, in the remainder of the file after the
    [End], these definitions will be referred to by names like [X.foo]
    instead of just [foo].  Here, we use this feature to introduce the
    definition of the type [nat] in an inner module so that it does
    not shadow the one from the standard library. *)

Module Playground1.

(** The types we have defined so far are examples of "enumerated
    types": their definitions explicitly enumerate a finite set of
    elements.  A more interesting way of defining a type is to give a
    collection of "inductive rules" describing its elements.  For
    example, we can define the natural numbers as follows: *)

Inductive nat : Type :=
  | O : nat
  | S : nat -> nat.

(** The clauses of this definition can be read:
      - [O] is a natural number (note that this is the letter "[O]," not
        the numeral "[0]").
      - [S] is a "constructor" that takes a natural number and yields
        another one -- that is, if [n] is a natural number, then [S n]
        is too.

    Let's look at this in a little more detail.

    Every inductively defined set ([day], [nat], [bool], etc.) is
    actually a set of _expressions_.  The definition of [nat] says how
    expressions in the set [nat] can be constructed:

    - the expression [O] belongs to the set [nat];
    - if [n] is an expression belonging to the set [nat], then [S n]
      is also an expression belonging to the set [nat]; and
    - expressions formed in these two ways are the only ones belonging
      to the set [nat].

    The same rules apply for our definitions of [day] and [bool]. The
    annotations we used for their constructors are analogous to the
    one for the [O] constructor, and indicate that each of those
    constructors doesn't take any arguments. *)

(** These three conditions are the precise force of the
    [Inductive] declaration.  They imply that the expression [O], the
    expression [S O], the expression [S (S O)], the expression
    [S (S (S O))], and so on all belong to the set [nat], while other
    expressions like [true], [andb true false], and [S (S false)] do
    not.

    We can write simple functions that pattern match on natural
    numbers just as we did above -- for example, the predecessor
    function: *)

Definition pred (n : nat) : nat :=
  match n with
    | O => O
    | S n' => n'
  end.

(** The second branch can be read: "if [n] has the form [S n']
    for some [n'], then return [n']."  *)

End Playground1.

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

(** Because natural numbers are such a pervasive form of data,
    Coq provides a tiny bit of built-in magic for parsing and printing
    them: ordinary arabic numerals can be used as an alternative to
    the "unary" notation defined by the constructors [S] and [O].  Coq
    prints numbers in arabic form by default: *)

Check (S (S (S (S O)))).
Eval compute in (minustwo 4).

(** The constructor [S] has the type [nat -> nat], just like the
    functions [minustwo] and [pred]: *)

Check S.
Check pred.
Check minustwo.

(** These are all things that can be applied to a number to yield a
    number.  However, there is a fundamental difference: functions
    like [pred] and [minustwo] come with _computation rules_ -- e.g.,
    the definition of [pred] says that [pred 2] can be simplified to
    [1] -- while the definition of [S] has no such behavior attached.
    Although it is like a function in the sense that it can be applied
    to an argument, it does not _do_ anything at all! *)

(** For most function definitions over numbers, pure pattern
    matching is not enough: we also need recursion.  For example, to
    check that a number [n] is even, we may need to recursively check
    whether [n-2] is even.  To write such functions, we use the
    keyword [Fixpoint]. *)

Fixpoint evenb (n:nat) : bool :=
  match n with
  | O        => true
  | S O      => false
  | S (S n') => evenb n'
  end.

(** We can define [oddb] by a similar [Fixpoint] declaration, but here
    is a simpler definition that will be a bit easier to work with: *)

Definition oddb (n:nat) : bool   :=   negb (evenb n).

Example test_oddb1:    (oddb (S O)) = true.
Proof. reflexivity.  Qed.
Example test_oddb2:    (oddb (S (S (S (S O))))) = false.
Proof. reflexivity.  Qed.

(** Naturally, we can also define multi-argument functions by
    recursion.  (Once again, we use a module to avoid polluting the
    namespace.) *)

Module Playground2.

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

(** Adding three to two now gives us five, as we'd expect. *)

Eval compute in (plus (S (S (S O))) (S (S O))).

(** The simplification that Coq performs to reach this conclusion can
    be visualized as follows: *)

(*  [plus (S (S (S O))) (S (S O))]
==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]
==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]
==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]
==> [S (S (S (S (S O))))]          by the first clause of the [match]
*)

(** As a notational convenience, if two or more arguments have
    the same type, they can be written together.  In the following
    definition, [(n m : nat)] means just the same as if we had written
    [(n : nat) (m : nat)]. *)

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

Example test_mult1: (mult 3 3) = 9.
Proof. reflexivity.  Qed.

(** You can match two expressions at once by putting a comma
    between them: *)

Fixpoint minus (n m:nat) : nat :=
  match n, m with
  | O   , _    => O
  | S _ , O    => n
  | S n', S m' => minus n' m'
  end.

(** The _ in the first line is a _wildcard pattern_.  Writing _ in a
    pattern is the same as writing some variable that doesn't get used
    on the right-hand side.  This avoids the need to invent a bogus
    variable name. *)

End Playground2.

Fixpoint exp (base power : nat) : nat :=
  match power with
    | O => S O
    | S p => mult base (exp base p)
  end.

(** **** Exercise: 1 star (factorial)  *)
(** Recall the standard factorial function:
<<
    factorial(0)  =  1
    factorial(n)  =  n * factorial(n-1)     (if n>0)
>>
    Translate this into Coq. *)

Fixpoint factorial (n:nat) : nat :=
match n with
  | O => S O
  | S p=> mult n (factorial p)
end.

Example test_factorial1:          (factorial 3) = 6.
Proof. reflexivity.  Qed.
Example test_factorial2:          (factorial 5) = (mult 10 12).
Proof. reflexivity.  Qed.

(** [] *)

(** We can make numerical expressions a little easier to read and
    write by introducing "notations" for addition, multiplication, and
    subtraction. *)

Notation "x + y" := (plus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x - y" := (minus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x * y" := (mult x y)
                       (at level 40, left associativity)
                       : nat_scope.

Check ((0 + 1) + 1).

(** (The [level], [associativity], and [nat_scope] annotations
   control how these notations are treated by Coq's parser.  The
   details are not important, but interested readers can refer to the
   "More on Notation" subsection in the "Optional Material" section at
   the end of this chapter.) *)

(** Note that these do not change the definitions we've already
    made: they are simply instructions to the Coq parser to accept [x
    + y] in place of [plus x y] and, conversely, to the Coq
    pretty-printer to display [plus x y] as [x + y]. *)

(** When we say that Coq comes with nothing built-in, we really
    mean it: even equality testing for numbers is a user-defined
    operation! *)
(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,
    yielding a [b]oolean.  Note the use of nested [match]es (we could
    also have used a simultaneous match, as we did in [minus].)  *)

Fixpoint beq_nat (n m : nat) : bool :=
  match n with
  | O => match m with
         | O => true
         | S m' => false
         end
  | S n' => match m with
            | O => false
            | S m' => beq_nat n' m'
            end
  end.

(** Similarly, the [ble_nat] function tests [nat]ural numbers for
    [l]ess-or-[e]qual, yielding a [b]oolean. *)

Fixpoint ble_nat (n m : nat) : bool :=
  match n with
  | O => true
  | S n' =>
      match m with
      | O => false
      | S m' => ble_nat n' m'
      end
  end.

Example test_ble_nat1:             (ble_nat 2 2) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat2:             (ble_nat 2 4) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat3:             (ble_nat 4 2) = false.
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (blt_nat)  *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for
    this one, define it in terms of a previously defined function.

    Note: If you have trouble with the [simpl] tactic, try using
    [compute], which is like [simpl] on steroids.  However, there is a
    simple, elegant solution for which [simpl] suffices. *)

 (*beq_nat (n m) means"n=m?"*)
(*ble_nat (n m) means"n <=m?"*)
(*blt_nat(n m) means "n<m"*)
(*blt=ble-beq=(AND ble (NOT beq))*)
Definition blt_nat (n m : nat) : bool :=
(andb (ble_nat n m) (negb (beq_nat n m))).

Example test_blt_nat1:             (blt_nat 2 2) = false.
Proof. reflexivity.  Qed.
Example test_blt_nat2:             (blt_nat 2 4) = true.
Proof. reflexivity.  Qed.

Example test_blt_nat3:             (blt_nat 4 2) = false.
Proof. reflexivity.  Qed.

(** [] *)

(* ###################################################################### *)
(** * Proof by Simplification *)

(** Now that we've defined a few datatypes and functions, let's
    turn to the question of how to state and prove properties of their
    behavior.  Actually, in a sense, we've already started doing this:
    each [Example] in the previous sections makes a precise claim
    about the behavior of some function on some particular inputs.
    The proofs of these claims were always the same: use [reflexivity]
    to check that both sides of the [=] simplify to identical values.

    (By the way, it will be useful later to know that
    [reflexivity] actually does somewhat more simplification than [simpl]
    does -- for example, it tries "unfolding" defined terms, replacing them with
    their right-hand sides.  The reason for this difference is that,
    when reflexivity succeeds, the whole goal is finished and we don't
    need to look at whatever expanded expressions [reflexivity] has
    found; by contrast, [simpl] is used in situations where we may
    have to read and understand the new goal, so we would not want it
    blindly expanding definitions.)

    The same sort of "proof by simplification" can be used to prove
    more interesting properties as well.  For example, the fact that
    [0] is a "neutral element" for [+] on the left can be proved
    just by observing that [0 + n] reduces to [n] no matter what
    [n] is, a fact that can be read directly off the definition of [plus].*)

Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
  intros n. reflexivity.  Qed.

(** (_Note_: You may notice that the above statement looks
    different in the original source file and the final html output. In Coq
    files, we write the [forall] universal quantifier using the
    "_forall_" reserved identifier. This gets printed as an
    upside-down "A", the familiar symbol used in logic.)  *)

(** The form of this theorem and proof are almost exactly the
    same as the examples above; there are just a few differences.

    First, we've used the keyword [Theorem] instead of
    [Example].  Indeed, the difference is purely a matter of
    style; the keywords [Example] and [Theorem] (and a few others,
    including [Lemma], [Fact], and [Remark]) mean exactly the same
    thing to Coq.

    Secondly, we've added the quantifier [forall n:nat], so that our
    theorem talks about _all_ natural numbers [n].  In order to prove
    theorems of this form, we need to to be able to reason by
    _assuming_ the existence of an arbitrary natural number [n].  This
    is achieved in the proof by [intros n], which moves the quantifier
    from the goal to a "context" of current assumptions. In effect, we
    start the proof by saying "OK, suppose [n] is some arbitrary number."

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to tell Coq how it should check the correctness of some
    claim we are making.  We will see several more tactics in the rest
    of this lecture, and yet more in future lectures. *)

(** Step through these proofs in Coq and notice how the goal and
    context change. *)

Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
  intros n. reflexivity.  Qed.

Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
  intros n. reflexivity.  Qed.

(** The [_l] suffix in the names of these theorems is
    pronounced "on the left." *)

(* ###################################################################### *)
(** * Proof by Rewriting *)

(** Here is a slightly more interesting theorem: *)

Theorem plus_id_example : forall n m:nat,
  n = m ->
  n + n = m + m.

(** Instead of making a completely universal claim about all numbers
    [n] and [m], this theorem talks about a more specialized property
    that only holds when [n = m].  The arrow symbol is pronounced
    "implies."

    As before, we need to be able to reason by assuming the existence
    of some numbers [n] and [m].  We also need to assume the hypothesis
    [n = m]. The [intros] tactic will serve to move all three of these
    from the goal into assumptions in the current context.

    Since [n] and [m] are arbitrary numbers, we can't just use
    simplification to prove this theorem.  Instead, we prove it by
    observing that, if we are assuming [n = m], then we can replace
    [n] with [m] in the goal statement and obtain an equality with the
    same expression on both sides.  The tactic that tells Coq to
    perform this replacement is called [rewrite]. *)

Proof.
  intros n m.   (* move both quantifiers into the context *)
  intros H.     (* move the hypothesis into the context *)
  rewrite -> H. (* Rewrite the goal using the hypothesis *)
  reflexivity.  Qed.

(** The first line of the proof moves the universally quantified
    variables [n] and [m] into the context.  The second moves the
    hypothesis [n = m] into the context and gives it the (arbitrary)
    name [H].  The third tells Coq to rewrite the current goal ([n + n
    = m + m]) by replacing the left side of the equality hypothesis
    [H] with the right side.

    (The arrow symbol in the [rewrite] has nothing to do with
    implication: it tells Coq to apply the rewrite from left to right.
    To rewrite from right to left, you can use [rewrite <-].  Try
    making this change in the above proof and see what difference it
    makes in Coq's behavior.) *)

(** **** Exercise: 1 star (plus_id_exercise)  *)
(** Remove "[Admitted.]" and fill in the proof. *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.

  intros n m o.
(*universally quantified variables n,m,o*)
  intros H H0 .
(*hypothesis [n = m,m=o] into the context and gives it the (arbitrary)
    name [H,H0]*)
 (*n : nat
m : nat
o : nat
H : n = m
H0 : m = o
n + m = m + o*)
 rewrite-> H.
(*m + m = m + o*)
 rewrite ->H0.
(*o + o = o + o*)
reflexivity.
Qed.

(** [] *)

(** As we've seen in earlier examples, the [Admitted] command
    tells Coq that we want to skip trying to prove this theorem and
    just accept it as a given.  This can be useful for developing
    longer proofs, since we can state subsidiary facts that we believe
    will be useful for making some larger argument, use [Admitted] to
    accept them on faith for the moment, and continue thinking about
    the larger argument until we are sure it makes sense; then we can
    go back and fill in the proofs we skipped.  Be careful, though:
    every time you say [Admitted] (or [admit]) you are leaving a door
    open for total nonsense to enter Coq's nice, rigorous, formally
    checked world! *)

(** We can also use the [rewrite] tactic with a previously proved
    theorem instead of a hypothesis from the context. *)

Theorem mult_0_plus : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_O_n.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (mult_S_1)  *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  intros n m H.
(*n : nat
m : nat
H : m = S n
m * (1 + n) = m * m*)
  rewrite H.
(*S n * (1 + n) = S n * S n*)
  (*simpl.*)
  reflexivity.
Qed.

(** [] *)

(* ###################################################################### *)
(** * Proof by Case Analysis *)

(** Of course, not everything can be proved by simple
    calculation: In general, unknown, hypothetical values (arbitrary
    numbers, booleans, lists, etc.) can block the calculation.
    For example, if we try to prove the following fact using the
    [simpl] tactic as above, we get stuck. *)

Theorem plus_1_neq_0_firsttry : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n.
  simpl.  (* does nothing! *)
Abort.

(** The reason for this is that the definitions of both
    [beq_nat] and [+] begin by performing a [match] on their first
    argument.  But here, the first argument to [+] is the unknown
    number [n] and the argument to [beq_nat] is the compound
    expression [n + 1]; neither can be simplified.

    What we need is to be able to consider the possible forms of [n]
    separately.  If [n] is [O], then we can calculate the final result
    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].
    And if [n = S n'] for some [n'], then, although we don't know
    exactly what number [n + 1] yields, we can calculate that, at
    least, it will begin with one [S], and this is enough to calculate
    that, again, [beq_nat (n + 1) 0] will yield [false].

    The tactic that tells Coq to consider, separately, the cases where
    [n = O] and where [n = S n'] is called [destruct]. *)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem as
    proved.  (No special command is needed for moving from one subgoal
    to the other.  When the first subgoal has been proved, it just
    disappears and we are left with the other "in focus.")  In this
    proof, each of the subgoals is easily proved by a single use of
    [reflexivity].

    The annotation "[as [| n']]" is called an _intro pattern_.  It
    tells Coq what variable names to introduce in each subgoal.  In
    general, what goes between the square brackets is a _list_ of
    lists of names, separated by [|].  Here, the first component is
    empty, since the [O] constructor is nullary (it doesn't carry any
    data).  The second component gives a single name, [n'], since [S]
    is a unary constructor.

    The [destruct] tactic can be used with any inductively defined
    datatype.  For example, we use it here to prove that boolean
    negation is involutive -- i.e., that negation is its own
    inverse. *)

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b. destruct b.
    reflexivity.
    reflexivity.  Qed.

(** Note that the [destruct] here has no [as] clause because
    none of the subcases of the [destruct] need to bind any variables,
    so there is no need to specify any names.  (We could also have
    written [as [|]], or [as []].)  In fact, we can omit the [as]
    clause from _any_ [destruct] and Coq will fill in variable names
    automatically.  Although this is convenient, it is arguably bad
    style, since Coq often makes confusing choices of names when left
    to its own devices. *)

(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  intros n.
  destruct n as [| n'].
    reflexivity.
(*beq_nat 0 (S n' + 1) = false*)
    reflexivity.
Qed.

(** [] *)

(* ###################################################################### *)
(** * More Exercises *)

(** **** Exercise: 2 stars (boolean_functions)  *)
(** Use the tactics you have learned so far to prove the following
    theorem about boolean functions. *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  (* FILL IN HERE *) Admitted.

(** Now state and prove a theorem [negation_fn_applied_twice] similar
    to the previous one but where the second hypothesis says that the
    function [f] has the property that [f x = negb x].*)

(* FILL IN HERE *)

(** [] *)

(** **** Exercise: 2 stars (andb_eq_orb)  *)
(** Prove the following theorem.  (You may want to first prove a
    subsidiary lemma or two. Alternatively, remember that you do
    not have to introduce all hypotheses at the same time.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (binary)  *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

      - zero,
      - twice a binary number, or
      - one more than twice a binary number.

    (a) First, write an inductive definition of the type [bin]
        corresponding to this description of binary numbers.

    (Hint: Recall that the definition of [nat] from class,
    Inductive nat : Type :=
      | O : nat
      | S : nat -> nat.
    says nothing about what [O] and [S] "mean."  It just says "[O] is
    in the set called [nat], and if [n] is in the set then so is [S
    n]."  The interpretation of [O] as zero and [S] as successor/plus
    one comes from the way that we _use_ [nat] values, by writing
    functions to do things with them, proving things about them, and
    so on.  Your definition of [bin] should be correspondingly simple;
    it is the functions you will write next that will give it
    mathematical meaning.)

    (b) Next, write an increment function for binary numbers, and a
        function to convert binary numbers to unary numbers.

    (c) Write some unit tests for your increment and binary-to-unary
        functions. Notice that incrementing a binary number and
        then converting it to unary should yield the same result as first
        converting it to unary and then incrementing.
*)

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

(* ###################################################################### *)
(** * Optional Material *)

(** ** More on Notation *)

Notation "x + y" := (plus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x * y" := (mult x y)
                       (at level 40, left associativity)
                       : nat_scope.

(** For each notation-symbol in Coq we can specify its _precedence level_
    and its _associativity_. The precedence level n can be specified by the
    keywords [at level n] and it is helpful to disambiguate
    expressions containing different symbols. The associativity is helpful
    to disambiguate expressions containing more occurrences of the same
    symbol. For example, the parameters specified above for [+] and [*]
    say that the expression [1+2*3*4] is a shorthand for the expression
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.

    Each notation-symbol in Coq is also active in a _notation scope_.
    Coq tries to guess what scope you mean, so when you write [S(O*O)]
    it guesses [nat_scope], but when you write the cartesian
    product (tuple) type [bool*bool] it guesses [type_scope].
    Occasionally you have to help it out with percent-notation by
    writing [(x*y)%nat], and sometimes in Coq's feedback to you it
    will use [%nat] to indicate what scope a notation is in.

    Notation scopes also apply to numeral notation (3,4,5, etc.), so you
    may sometimes see [0%nat] which means [O], or [0%Z] which means the
    Integer zero.
*)

(** ** [Fixpoint]s and Structural Recursion *)

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

(** When Coq checks this definition, it notes that [plus'] is
    "decreasing on 1st argument."  What this means is that we are
    performing a _structural recursion_ over the argument [n] -- i.e.,
    that we make recursive calls only on strictly smaller values of
    [n].  This implies that all calls to [plus'] will eventually
    terminate.  Coq demands that some argument of _every_ [Fixpoint]
    definition is "decreasing".

    This requirement is a fundamental feature of Coq's design: In
    particular, it guarantees that every function that can be defined
    in Coq will terminate on all inputs.  However, because Coq's
    "decreasing analysis" is not very sophisticated, it is sometimes
    necessary to write functions in slightly unnatural ways. *)

(** **** Exercise: 2 stars, optional (decreasing)  *)
(** To get a concrete sense of this, find a way to write a sensible
    [Fixpoint] definition (of a simple function on numbers, say) that
    _does_ terminate on all inputs, but that Coq will _not_ accept
    because of this restriction. *)

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

(* $Date: 2014-10-02 09:22:16 +0900 (2014年10月02日 (木)) $ *)


(************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

(** This module defines type constructors for types in [Type]
    ([Datatypes.v] and [Logic.v] defined them for types in [Set]) *)

Set Implicit Arguments.

Require Import Datatypes.
Require Export Logic.

(** Negation of a type in [Type] *)

Definition notT (A:Type) := A -> False.

(** Properties of [identity] *)

Section identity_is_a_congruence.

 Variables A B : Type.
 Variable f : A -> B.

 Variables x y z : A.

 Lemma identity_sym : identity x y -> identity y x.
 Proof.
  destruct 1; trivial.
 Defined.

 Lemma identity_trans : identity x y -> identity y z -> identity x z.
 Proof.
  destruct 2; trivial.
 Defined.

 Lemma identity_congr : identity x y -> identity (f x) (f y).
 Proof.
  destruct 1; trivial.
 Defined.

 Lemma not_identity_sym : notT (identity x y) -> notT (identity y x).
 Proof.
  red in |- *; intros H H'; apply H; destruct H'; trivial.
 Qed.

End identity_is_a_congruence.

Definition identity_ind_r :
  forall (A:Type) (a:A) (P:A -> Prop), P a -> forall y:A, identity y a -> P y.
 intros A x P H y H0; case identity_sym with (1 := H0); trivial.
Defined.

Definition identity_rec_r :
  forall (A:Type) (a:A) (P:A -> Set), P a -> forall y:A, identity y a -> P y.
 intros A x P H y H0; case identity_sym with (1 := H0); trivial.
Defined.

Definition identity_rect_r :
  forall (A:Type) (a:A) (P:A -> Type), P a -> forall y:A, identity y a -> P y.
 intros A x P H y H0; case identity_sym with (1 := H0); trivial.
Defined.

Hint Immediate identity_sym not_identity_sym: core v62.

Notation refl_id := identity_refl (only parsing).
Notation sym_id := identity_sym (only parsing).
Notation trans_id := identity_trans (only parsing).
Notation sym_not_id := not_identity_sym (only parsing).


From Hammer Require Import Hammer.

Require Import QArith_base Orders QOrderedType GenericMinMax.

Local Open Scope Q_scope.

Definition Qmax := gmax Qcompare.
Definition Qmin := gmin Qcompare.

Module QHasMinMax <: HasMinMax Q_as_OT.
Module QMM := GenericMinMax Q_as_OT.
Definition max := Qmax.
Definition min := Qmin.
Definition max_l := QMM.max_l.
Definition max_r := QMM.max_r.
Definition min_l := QMM.min_l.
Definition min_r := QMM.min_r.
End QHasMinMax.

Module Q.

Include MinMaxProperties Q_as_OT QHasMinMax.

Lemma plus_max_distr_l : forall n m p, Qmax (p + n) (p + m) == p + Qmax n m.
Proof. hammer_hook "Qminmax" "Qminmax.Q.plus_max_distr_l".
intros. apply max_monotone.
intros x x' Hx; rewrite Hx; auto with qarith.
intros x x' Hx. apply Qplus_le_compat; q_order.
Qed.

Lemma plus_max_distr_r : forall n m p, Qmax (n + p) (m + p) == Qmax n m + p.
Proof. hammer_hook "Qminmax" "Qminmax.Q.plus_max_distr_r".
intros. rewrite (Qplus_comm n p), (Qplus_comm m p), (Qplus_comm _ p).
apply plus_max_distr_l.
Qed.

Lemma plus_min_distr_l : forall n m p, Qmin (p + n) (p + m) == p + Qmin n m.
Proof. hammer_hook "Qminmax" "Qminmax.Q.plus_min_distr_l".
intros. apply min_monotone.
intros x x' Hx; rewrite Hx; auto with qarith.
intros x x' Hx. apply Qplus_le_compat; q_order.
Qed.

Lemma plus_min_distr_r : forall n m p, Qmin (n + p) (m + p) == Qmin n m + p.
Proof. hammer_hook "Qminmax" "Qminmax.Q.plus_min_distr_r".
intros. rewrite (Qplus_comm n p), (Qplus_comm m p), (Qplus_comm _ p).
apply plus_min_distr_l.
Qed.

End Q.


Require Export Iron.Language.SystemF2Data.Kind.
Require Export Iron.Language.SystemF2Data.Type.Exp.
Require Export Iron.Language.SystemF2Data.Type.Operator.LiftTT.
Require Export Iron.Language.SystemF2Data.Type.Operator.SubstTT.

(********************************************************************)
(* Kinds judgement assigns a kind to a type *)
Inductive KIND : kienv -> ty -> ki -> Prop :=
 | KIConFun
   :  forall ke
   ,  KIND ke (TCon TyConFun) (KFun KStar (KFun KStar KStar))

 | KIConData
   :  forall ke i k
   ,  KIND ke (TCon (TyConData i k)) k

 | KIVar
   :  forall ke i k
   ,  get i ke = Some k
   -> KIND ke (TVar i) k

 | KIForall
   :  forall ke t
   ,  KIND (ke :> KStar) t           KStar
   -> KIND ke            (TForall t) KStar

 | KIApp
   :  forall ke t1 t2 k11 k12
   ,  KIND ke t1 (KFun k11 k12)
   -> KIND ke t2 k11
   -> KIND ke (TApp t1 t2) k12.
Hint Constructors KIND.

(********************************************************************)
(* Invert all hypothesis that are compound kinding statements. *)
Ltac inverts_kind :=
 repeat
  (match goal with
   | [ H: KIND _ (TCon _)    _  |- _ ] => inverts H
   | [ H: KIND _ (TVar _)    _  |- _ ] => inverts H
   | [ H: KIND _ (TForall _) _  |- _ ] => inverts H
   | [ H: KIND _ (TApp _ _) _   |- _ ] => inverts H
   end).

(********************************************************************)
(* A well kinded type is well formed *)
Lemma kind_wfT
 :  forall ke t k
 ,  KIND ke t k
 -> wfT  (length ke) t.
Proof.
 intros ke t k HK. gen ke k.
 induction t; intros; inverts_kind; burn.
 - eapply WfT_TForall.
   rrwrite (S (length ke) = length (ke :> KStar)).
   eauto.
Qed.
Hint Resolve kind_wfT.

Lemma kind_wfT_Forall
 :  forall ks ts
 ,  Forall (fun t => KIND ks t KStar) ts
 -> Forall (wfT (length ks)) ts.
Proof. snorm; eauto. Qed.
Hint Resolve kind_wfT_Forall.

Lemma kind_wfT_Forall2
 :  forall (ke: kienv) ts ks
 ,  Forall2 (KIND ke) ts ks
 -> Forall (wfT (length ke)) ts.
Proof.
 intros.
 eapply (Forall2_Forall_left (KIND ke)); snorm; eauto.
Qed.
Hint Resolve kind_wfT_Forall2.

(* If a type is well kinded in an empty environment,
   then that type is closed. *)
Lemma kind_empty_is_closed
 :  forall t k
 ,  KIND nil t k
 -> closedT t.
Proof.
 intros. unfold closedT.
 have (@length ki nil = 0).
 rewrite <- H0.
 eapply kind_wfT. eauto.
Qed.
Hint Resolve kind_empty_is_closed.

(********************************************************************)
(* Weakening kind environments. *)
Lemma kind_kienv_insert
 :  forall ke ix t k1 k2
 ,  KIND ke t k1
 -> KIND (insert ix k2 ke) (liftTT 1 ix t) k1.
Proof.
 intros. gen ix ke k1.
 induction t; intros; simpl; inverts_kind; eauto.

 - Case "TVar".
   lift_cases; intros; repeat nnat; auto.

 - Case "TForall".
   apply KIForall.
   rewrite insert_rewind. auto.
Qed.

Lemma kind_kienv_weaken
 :  forall ke t k1 k2
 ,  KIND  ke         t             k1
 -> KIND (ke :> k2) (liftTT 1 0 t) k1.
Proof.
 intros.
 assert (ke :> k2 = insert 0 k2 ke). simpl.
   destruct ke; auto.
 rewrite H0. apply kind_kienv_insert. auto.
Qed.

(********************************************************************)
(* Substitution of types in types preserves kinding.
   Must also subst new new type into types in env higher than ix
   otherwise indices that reference subst type are broken, and
   the resulting type env would not be well formed *)
Theorem subst_type_type_ix
 :  forall ix ke t1 k1 t2 k2
 ,  get ix ke = Some k2
 -> KIND ke t1 k1
 -> KIND (delete ix ke) t2 k2
 -> KIND (delete ix ke) (substTT ix t2 t1) k1.
Proof.
 intros. gen ix ke t2 k1 k2.
 induction t1; intros; simpl; inverts_kind; eauto.

 - Case "TVar".
   fbreak_nat_compare.
   SCase "n = ix".
    rewrite H in H4.
    inverts H4. auto.

   SCase "n < ix".
    apply KIVar. rewrite <- H4.
    apply get_delete_above; auto.

   SCase "n > ix".
    apply KIVar. rewrite <- H4.
    destruct n.
     burn.
     simpl. nnat. apply get_delete_below. omega.

 - Case "TForall".
   apply KIForall.
   rewrite delete_rewind.
   eapply IHt1; eauto.
    apply kind_kienv_weaken; auto.
Qed.

Theorem subst_type_type_ix_forall2
 :  forall ix ke t2 k2 ts ks
 ,  get ix ke = Some k2
 -> Forall2 (KIND ke) ts ks
 ->          KIND (delete ix ke) t2 k2
 -> Forall2 (KIND (delete ix ke)) (map (substTT ix t2) ts) ks.
Proof.
 intros.
 eapply Forall2_map_left.
 apply (Forall2_impl
            (fun t k => KIND ke t k)
            (fun t k => KIND (delete ix ke) (substTT ix t2 t) k)
            ts ks).
  intros. eapply subst_type_type_ix; eauto.
  eauto.
Qed.

Theorem subst_type_type
 :  forall ke t1 k1 t2 k2
 ,  KIND (ke :> k2) t1 k1
 -> KIND ke         t2 k2
 -> KIND ke (substTT 0 t2 t1) k1.
Proof.
 intros.
 unfold substTT.
 rrwrite (ke = delete 0 (ke :> k2)).
 eapply subst_type_type_ix; burn.
Qed.


Require Import Coq.Vectors.Vector.
Require Import IList.

Generalizable All Variables.

(** This code is borrowed from the Fiat code base. *)

Section ilist2.

  (* Lists of elements whose types depend on an indexing set (CPDT's hlists).
     These lists are a convenient way to implement finite maps
     whose elements depend on their keys. The data structures used
     by our ADT notations uses these to implement notation-friendly
     method lookups.  *)

  Import Vectors.VectorDef.VectorNotations.

  Context {A : Type}. (* The indexing type. *)
  Context {B : A -> Type}. (* The type of indexed elements. *)

  Fixpoint ilist2 {n} (l : Vector.t A n) : Type :=
    match l with
      | [] => unit
      | a :: l => @prim_prod (B a) (ilist2 l)
    end.

  Definition icons2
             (a : A)
             {n}
             {l : Vector.t A n}
             (b : B a)
             (il : ilist2 l)
  : ilist2 (a :: l)
    := {| prim_fst := b; prim_snd := il |}.

  Definition inil2 : ilist2 [] := tt.

  (* Get the car of an ilist2. *)
  Definition ilist2_hd {n} {As : Vector.t A n} (il : ilist2 As) :
    match As return ilist2 As -> Type with
      | a :: As' => fun il => B a
      | [] => fun _ => unit
    end il :=
    match As return
          forall (il : ilist2 As),
            match As return ilist2 As -> Type with
              | a :: As' => fun il => B a
              | [] => fun _ => unit
            end il with
      | a :: As => fun il => prim_fst _ _ il
      | [] => fun il => tt
    end il.

  Definition ilist2_hd' {n} {As : Vector.t A (S n)} (il : ilist2 As) :
    B (Vector.hd As)
    := Vector.caseS (fun n As => ilist2 As -> B (Vector.hd As))
                           (fun a As m => ilist2_hd) As il.

  (* Get the cdr of an ilist2. *)
  Definition ilist2_tl {n} {As : Vector.t A n} (il : ilist2 As) :
    match As return ilist2 As -> Type with
      | a :: As' => fun il => ilist2 As'
      | [] => fun _ => unit
    end il :=
    match As return
          forall (il : ilist2 As),
            match As return ilist2 As -> Type with
              | a :: As' => fun il => ilist2 As'
              | [] => fun _ => unit
            end il with
      | a :: As => fun il => prim_snd _ _ il
      | [] => fun il => tt
    end il.

  Definition ilist2_tl'
             {n} {As : Vector.t A (S n)} (il : ilist2 As)
    : ilist2 (Vector.tl As) :=
    Vector.caseS (fun n As => ilist2 As -> ilist2 (Vector.tl As))
                 (fun a As m => ilist2_tl) As il.

  Infix "++" := Vector.append : vector_scope.

  (* Appending ilist2s *)
  Fixpoint ilist2_app {n} {As : Vector.t A n}
    : forall {n'} {As' : Vector.t A n'},  ilist2 As -> ilist2 As' -> ilist2 (As ++ As') :=
      match As return
            forall {n'} (As' : Vector.t A n'),
              ilist2 As -> ilist2 As' -> ilist2 (As ++ As') with
        | [] =>
          fun n' As' il il' => il'
        | a :: As'' =>
          fun n' As' il il' =>
            {| prim_fst := ilist2_hd il;
               prim_snd := ilist2_app (ilist2_tl il) il' |}
      end.

  (* Membership in an indexed list. *)

  Inductive ilist2_In {a : A} (b : B a)
  : forall {n} {As : Vector.t A n} (il : ilist2 As), Prop :=
  | In_hd : forall n' As' (il : ilist2 (n := n') As'),
              ilist2_In b (icons2 _ b il)
  | In_tl : forall {n'} a' (b' : B a') As' (il : ilist2 (n := n') As'),
              ilist2_In b il ->
              ilist2_In b (icons2 _ b' il).

  (* Looking up the ith value, returning None for indices not in the Vector.t *)

  Fixpoint ith2
           {m : nat}
           {As : Vector.t A m}
           (il : ilist2 As)
           (n : Fin.t m)
           {struct n}
    : B (Vector.nth As n) :=
    match n in Fin.t m return
          forall (As : Vector.t A m),
            ilist2 As
            -> B (Vector.nth As n) with
    | Fin.F1 =>
      fun As =>
        Vector.caseS (fun n As => ilist2 As
                                  -> B (Vector.nth As (@Fin.F1 n)))
                     (fun h n t => ilist2_hd) As
    | Fin.FS n' =>
      fun As =>
        Vector_caseS' Fin.t
                      (fun n As n' =>
                         ilist2 As
                          -> B (Vector.nth As (@Fin.FS n n')))
                     (fun h n t m il => ith2 (ilist2_tl il) m)
                     As n'
    end As il.

  Lemma ilist2_invert {n} (As : Vector.t A n) (il : ilist2 As) :
    match As as As' return ilist2 As' -> Prop with
      | a :: As' => fun il => exists b il', il = icons2 _ b il'
      | [] => fun il => il = inil2
    end il.
  Proof.
    destruct As; destruct il; simpl; unfold icons2; eauto.
  Qed.

  Lemma ilist2_invert' {n} (As : Vector.t A n) (il : ilist2 As) :
    match As as As' return ilist2 As' -> Type with
      | a :: As' => fun il => sigT (fun b => sigT (fun il' => il = icons2 _ b il'))
      | [] => fun il => il = inil2
    end il.
  Proof.
    destruct As; destruct il; unfold icons2; eauto.
  Qed.

End ilist2.

(** ** Mapping a function over a(n i)[list], in two non-dependent ways *)
Section ilist2_map.
  Context {A} (B : A -> Type).

  Import Vectors.VectorDef.VectorNotations.

  Fixpoint imap2_list (f : forall a : A, B a) {n} (As : Vector.t A n) : ilist2 As
    := match As with
         | [] => inil2
         | x :: xs => @icons2 _ B x _ _ (f x) (imap2_list f xs)
       end.

End ilist2_map.

Ltac icons2_invert :=
  repeat match goal with
           | [il : ilist2 _ (cons _ _) |- _]
             => let il' := fresh "il" in
                let b' := fresh "b" in
                let il'_eq := fresh "il_eq" in
                generalize (ilist2_invert il);
                  intros il'; destruct il' as [b' [il' il'_eq]]; subst
         end.

Section ilist2_imap.

  (* Mapping a function over an indexed Vector.t. *)

  Import Vectors.VectorDef.VectorNotations.

  Variable A : Type. (* The indexing type. *)
  Variable B B' : A -> Type. (* The two types of indexed elements. *)
  Variable f : forall a, B a -> B' a. (* The function to map over the Vector.t. *)

  Fixpoint imap2 {n} (As : Vector.t A n)
    : ilist2 As -> ilist2 As :=
    match As return ilist2 As -> ilist2 As with
    | [] => fun il => inil2
    | a :: As' => fun il => icons2 _ (@f a (ilist2_hd il)) (imap2 As' (ilist2_tl il))
    end.

  (* [imap] behaves as expected with the [ith2_default] lookup
     function. *)
(*
  Lemma ith_imap2 :
    forall {n}
           (m : Fin.t n)
           (As : Vector.t A n)
           (il : ilist2 As),
      f (ith2 il m) = ith2 (imap2 As il) m.
  Proof.
    induction m; intro.
    - eapply Vector.caseS with (v := As); intros; simpl in *; destruct il; reflexivity.
    - revert m IHm.
      pattern n, As.
      match goal with
        |- ?P n As =>
        simpl; eapply (@Vector.rectS _ P); intros
      end.
      inversion m.
      eapply IHm.
  Qed.
*)

End ilist2_imap.

Section ilist2_replace.

  Import Vectors.VectorDef.VectorNotations.

  (* Replacing an element of an indexed Vector.t. *)
  Context {A : Type}. (* The indexing type. *)
  Context {B : A -> Type}. (* The two types of indexed elements. *)

  Fixpoint replace_Index2
             {m}
             (As : Vector.t A m)
             (il : ilist2 As)
             (n : Fin.t m)
             (new_b : B (Vector.nth As n))
             {struct n}
    : ilist2 As :=
    match n in Fin.t m return
          forall (As : Vector.t A m),
            @ilist2 _ B _ As
            -> B (Vector.nth As n)
            -> ilist2 As with
    | Fin.F1 =>
      fun As =>
        Vector.caseS (fun n As => ilist2 As
                                  -> B (Vector.nth As (@Fin.F1 n))
                                  -> ilist2 As)
                     (fun h n t il new_b => icons2 _ new_b (ilist2_tl il) ) As
    | Fin.FS n' =>
      fun As =>
        Vector_caseS' Fin.t
                      (fun n As n' =>
                          ilist2 As
                          -> B (Vector.nth As (@Fin.FS n n'))
                          -> ilist2 As)
                     (fun h n t m il new_b => icons2 _ (ilist2_hd il)
                                                    (@replace_Index2 _ _ (ilist2_tl il) _ new_b))
                     As n'
    end As il new_b.

  Lemma ith_replace2_Index_neq {m}
    : forall
      (n n' : Fin.t m)
      (As : Vector.t A m)
      (il : ilist2 As)
      (new_b : B (Vector.nth As n')),
      n <> n'
      -> ith2 (replace_Index2 As il n' new_b) n = ith2 il n.
  Proof.
    intros n n'; pattern m, n, n'.
    match goal with
      |- ?P m n n' => simpl; eapply (Fin.rect2 P); intros
    end.
    - congruence.
    - generalize il f new_b; clear f new_b il H.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.rectS _ P); intros; reflexivity
      end.
    - generalize il f new_b; clear f new_b il H.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.rectS _ P); intros; reflexivity
      end.
    - assert (f <> g) by congruence.
      generalize il f g new_b H H1; clear f g new_b il H H1 H0.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.caseS _ P); intros;
        eapply (H _ (prim_snd _ _ il) new_b); eauto
      end.
  Qed.

  Lemma ith_replace2_Index_eq {m}
    : forall
      (n : Fin.t m)
      (As : Vector.t A m)
      (il : ilist2 As)
      (new_b : B (Vector.nth As n)),
      ith2 (replace_Index2 As il n new_b) n = new_b.
  Proof.
    induction n; simpl.
    - intro As; pattern n, As.
      match goal with
        |- ?P n As =>
        simpl; apply (@Vector.caseS _ P); intros; reflexivity
      end.
    - intro As; revert n0 IHn; pattern n, As.
      match goal with
        |- ?P n As =>
        simpl; apply (@Vector.caseS _ P); simpl; eauto
      end.
  Qed.

End ilist2_replace.

Lemma imap_replace2_Index
      {A}
      {m}
      {B B' : A -> Type}
  : forall (f : forall idx'', B idx'' -> B' idx'')
           (idx : Fin.t m )
           (Bound : Vector.t A m)
           (il : ilist2 Bound)
           b,
    imap2 _ B B' f Bound (replace_Index2 Bound il idx b) =
    replace_Index2 Bound (imap2 _ B B' f Bound il) idx (f _ b).
Proof.
  induction idx.
  - intro Bound; pattern n, Bound.
    match goal with
      |- ?P n Bound =>
      simpl; apply (@Vector.caseS _ P); intros; reflexivity
    end.
  - intro Bound; revert idx IHidx; pattern n, Bound.
    match goal with
      |- ?P n Bound =>
      simpl; apply (@Vector.caseS _ P); intros; simpl; f_equal; eauto
    end.
Qed.

Section ilist2_update.

  Import Vectors.VectorDef.VectorNotations.

  (* Replacing an element of an indexed Vector.t. *)
  Context {A : Type}. (* The indexing type. *)
  Context {B : A -> Type}. (* The two types of indexed elements. *)

  Fixpoint update_Index2
             {m}
             (As : Vector.t A m)
             (il : ilist2 As)
             (n : Fin.t m)
             (update_b : B (Vector.nth As n) -> B (Vector.nth As n))
             {struct n}
    : ilist2 As :=
    match n in Fin.t m return
          forall (As : Vector.t A m),
            @ilist2 _ B _ As
            -> (B (Vector.nth As n) -> B (Vector.nth As n))
            -> ilist2 As with
    | Fin.F1 =>
      fun As =>
        Vector.caseS (fun n As => ilist2 As
                                  -> (B (Vector.nth As (@Fin.F1 n)) -> B (Vector.nth As (@Fin.F1 n)))
                                  -> ilist2 As)
                     (fun h n t il update_b => icons2 _ (update_b (ilist2_hd il)) (ilist2_tl il) ) As
    | Fin.FS n' =>
      fun As =>
        Vector_caseS' Fin.t
                      (fun n As n' =>
                          ilist2 As
                          -> (B (Vector.nth As (@Fin.FS n n')) -> B (Vector.nth As (@Fin.FS n n')))
                          -> ilist2 As)
                      (fun h n t m il update_b => icons2 _ (ilist2_hd il)
                                                    (@update_Index2 _ _ (ilist2_tl il) _ update_b))
                      As n'
    end As il update_b.

  Lemma ith_update_Index2_neq {m}
    : forall
      (n n' : Fin.t m)
      (As : Vector.t A m)
      (il : ilist2 As)
      (update_b : B (Vector.nth As n') -> B (Vector.nth As n')),
      n <> n'
      -> ith2 (update_Index2 As il n' update_b) n = ith2 il n.
  Proof.
    intros n n'; pattern m, n, n'.
    match goal with
      |- ?P m n n' => simpl; eapply (Fin.rect2 P); intros
    end.
    - congruence.
    - generalize il f update_b; clear f update_b il H.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.rectS _ P); intros; reflexivity
      end.
    - generalize il f update_b; clear f update_b il H.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.rectS _ P); intros; reflexivity
      end.
    - assert (f <> g) by congruence.
      generalize il f g update_b H H1; clear f g update_b il H H1 H0.
      pattern n0, As.
      match goal with
        |- ?P n0 As =>
        simpl; apply (@Vector.caseS _ P); intros;
        eapply (H _ (prim_snd _ _ il) update_b); eauto
      end.
  Qed.
  Set Printing All.

  Lemma ith_update_Index2_eq {m}
    : forall
      (n : Fin.t m)
      (As : Vector.t A m)
      (il : ilist2 As)
      (update_b : B (Vector.nth As n) -> B (Vector.nth As n)),
      ith2 (update_Index2 As il n update_b) n = update_b (ith2 il n).
  Proof.
    induction n; simpl.
    - intro As; pattern n, As.
      match goal with
        |- ?P n As =>
        simpl; apply (@Vector.caseS _ P); intros; reflexivity
      end.
    - intro As; revert n0 IHn; pattern n, As.
      match goal with
        |- ?P n As =>
        simpl; apply (@Vector.caseS _ P); simpl; eauto
      end.
  Qed.

End ilist2_update.


From Hammer Require Import Hammer.

From hahn Require Import HahnBase HahnSets HahnList HahnRelationsBasic HahnWf HahnMinElt.
From hahn Require Import HahnEquational HahnSorted.

Set Implicit Arguments.

Lemma fsupp_immediate_pred A (R: relation A)
(FS: fsupp R) (IRR: irreflexive R) (TRANS: transitive R)
x (NMIN: ~ min_elt R x):
exists x', immediate R x' x.
Proof. hammer_hook "HahnSegment" "HahnSegment.fsupp_immediate_pred".
clarify_not.
apply fsupp_imm_t, ct_end in NMIN; eauto.
destruct NMIN; desf; eauto.
Qed.

Section Segments.

Variable A : Type.
Variable cond : A -> Prop.
Variable r : relation A.
Variable STO : strict_total_order cond r.
Variable FSUPP: fsupp r.

Lemma starting_segment_exists x (Cx: cond x):
exists l, << SORTED: StronglySorted r l >> /\
<< INIT: forall x', cond x' /\ r^* x' x <->  In x' l >>.
Proof. hammer_hook "HahnSegment" "HahnSegment.starting_segment_exists".
destruct STO as [[IRR T] TOT].
assert (WF: well_founded (restr_rel cond r)).
by eauto using wf_restr, fsupp_well_founded.
apply fsupp_restr with (cond:=cond) in FSUPP.
induction x using (well_founded_induction WF).
destruct (classic (min_elt (restr_rel cond r) x)).
* exists (x :: nil); repeat split; ins; desf; vauto.
rewrite clos_refl_transE in H2; desf; eauto.
apply clos_trans_of_transitiveD in H2; eauto; firstorder.
* forward eapply fsupp_immediate_pred as [y [M N]];
eauto using fsupp_restr, irreflexive_restr, transitive_restr.
specialize_full H; eauto; red in M; desf.
exists (l ++ x :: nil); splits; ins.
rewrite StronglySorted_app_iff, StronglySorted_cons_iff; splits; ins; desf; vauto.
apply INIT in IN1; desf.
apply ct_of_trans, ct_end; vauto.
rewrite in_app_iff, <- INIT; ins.
intuition; desf; eauto using clos_refl_trans.
tertium_non_datur (y = x') as [|NEQ]; desf; eauto using clos_refl_trans.
apply TOT in NEQ; desf; eauto using clos_refl_trans.
apply rt_of_trans in H2; ins; red in H2; desf; eauto.
destruct (N x'); vauto.
Qed.

Lemma starting_segment_exists_unique x (Cx: cond x):
exists! l, << SORTED: StronglySorted r l >> /\
<< INIT: forall x', cond x' /\ r^* x' x <->  In x' l >>.
Proof. hammer_hook "HahnSegment" "HahnSegment.starting_segment_exists_unique".
assert (X:=starting_segment_exists Cx); desc.
destruct STO.
exists l; split; ins; desc.
eapply StronglySorted_eq; eauto.
by ins; rewrite <- INIT, INIT0.
Qed.

Definition starting_segment x Cx :=
proj1_sig (constructive_definite_description _
(@starting_segment_exists_unique x Cx)).

Lemma starting_segment_property x (Cx: cond x) :
<< SORTED: StronglySorted r (starting_segment Cx) >> /\
<< INIT: forall x', cond x' /\ r^* x' x <->  In x' (starting_segment Cx) >>.
Proof. hammer_hook "HahnSegment" "HahnSegment.starting_segment_property".
unfold starting_segment; match goal with [ |- context[proj1_sig ?t] ] => destruct t end;
eauto.
Qed.

Lemma in_starting_segment_iff x (Cx: cond x) z :
In z (starting_segment Cx) <-> cond z /\ r＊ z x.
Proof. hammer_hook "HahnSegment" "HahnSegment.in_starting_segment_iff".
symmetry; apply starting_segment_property.
Qed.

Lemma starting_segment_contains_endpoint x (Cx: cond x) :
In x (starting_segment Cx).
Proof. hammer_hook "HahnSegment" "HahnSegment.starting_segment_contains_endpoint".
apply in_starting_segment_iff; vauto.
Qed.

Lemma start_of_starting_endpoint x (Cx: cond x) :
exists l, starting_segment Cx = l ++ x :: nil.
Proof. hammer_hook "HahnSegment" "HahnSegment.start_of_starting_endpoint".
assert (X:=starting_segment_contains_endpoint Cx).
apply in_split in X; desf.
enough (l2 = nil) by (desf; eauto).
assert (Y:=starting_segment_property Cx); desf.
rewrite X in *; clear X.
apply StronglySorted_app_iff, proj2, proj1 in SORTED.
apply StronglySorted_cons_iff, proj2 in SORTED.
destruct l2; ins.
rewrite Forall_cons in *.
assert (r^* a x) by (apply INIT; eauto with hahn).
destruct STO as [[IRR T] TOT].
exfalso; eapply IRR, ct_of_trans, t_rt_step; desf; vauto.
Qed.

Lemma NoDup_starting_segment x (Cx: cond x) :
NoDup (starting_segment Cx).
Proof. hammer_hook "HahnSegment" "HahnSegment.NoDup_starting_segment".
destruct STO as [[IRR T] TOT].
eapply NoDup_StronglySorted; eauto.
apply starting_segment_property.
Qed.

Lemma not_in_starting_segment x (Cx: cond x) y (Cy: cond y):
~ In y (starting_segment Cx) -> r x y.
Proof. hammer_hook "HahnSegment" "HahnSegment.not_in_starting_segment".
ins; apply NNPP; intro.
destruct H; apply starting_segment_property.
split; ins.
destruct STO as [[IRR T] TOT].
specialize (TOT _ Cx _ Cy).
apply imply_to_or in TOT; desf; clarify_not; vauto.
Qed.

Lemma start_of_starting_segment x (Cx : cond x) y (Cy : cond y) l l':
starting_segment Cx = l ++ y :: l'
-> starting_segment Cy = l ++ y :: nil.
Proof. hammer_hook "HahnSegment" "HahnSegment.start_of_starting_segment".
assert (T := STO); do 2 (red in T; desc).
ins; eapply StronglySorted_eq; vauto.
* by apply starting_segment_property.
* eapply StronglySorted_app_l.
rewrite <- app_assoc; ins.
rewrite <- H.
by apply starting_segment_property.
* split; ins.
+ apply starting_segment_property in H0; desc.
specialize (starting_segment_property Cx); ins; desf; rewrite H in *.
forward apply (proj1 (INIT x0)) as X.
{ split; ins.
eapply rt_trans; eauto.
eapply starting_segment_property.
rewrite H; eauto with hahn. }
rewrite in_app_iff in X; ins; desf; eauto with hahn.
exfalso.
apply StronglySorted_app_r, StronglySorted_inv in SORTED; desf.
rewrite Forall_forall in SORTED0.
apply SORTED0 in X.
rewrite clos_refl_transE in H1; desf.
eby eapply T.
apply (ct_of_trans T1) in H1.
eby eapply T, T1.
+ apply starting_segment_property.
specialize (starting_segment_property Cx); ins; desf; rewrite H in *.
forward apply (proj2 (INIT x0)) as X.
by rewrite in_app_iff in H0; ins; desf; eauto with hahn.
split; desf.
clear - H0 SORTED.
rewrite in_app_iff in *; ins; desf; vauto.
apply StronglySorted_app_iff in SORTED; desf.
apply rt_step; eauto with hahn.
Qed.

Definition segment x (Cx : cond x) y (Cy : cond y) :=
filterP (fun e => ~ In e (starting_segment Cx)) (starting_segment Cy).

Lemma segment_property x (Cx: cond x) y (Cy: cond y):
⟪SORTED: StronglySorted r (segment Cx Cy)⟫ /\
⟪SEGMENT: forall z, cond z /\ r x z /\ r＊ z y <-> In z (segment Cx Cy)⟫.
Proof. hammer_hook "HahnSegment" "HahnSegment.segment_property".
ins; splits.
by apply StronglySorted_filterP, starting_segment_property.
split; ins; desf.
* apply in_filterP_iff; split.
by apply starting_segment_property.
intro N; apply starting_segment_property in N; desf.
destruct STO as [[IRR T] TOT].
apply clos_refl_transE in N0; desf; eauto.
apply clos_trans_of_transitiveD in N0; eauto.
* unfold segment in H; apply in_filterP_iff in H; desf.
apply starting_segment_property in H; desf; splits; try done.
eby eapply not_in_starting_segment.
Qed.

Lemma in_segment_iff x (Cx: cond x) y (Cy: cond y) z :
In z (segment Cx Cy) <-> cond z /\ r x z /\ r^* z y.
Proof. hammer_hook "HahnSegment" "HahnSegment.in_segment_iff".
symmetry; apply segment_property.
Qed.

Lemma starting_segment_decomp x (Cx: cond x) y (Cy: cond y) (Rxy: r^* x y):
starting_segment Cy = starting_segment Cx ++ segment Cx Cy.
Proof. hammer_hook "HahnSegment" "HahnSegment.starting_segment_decomp".
destruct STO as [[IRR T] TOT].
eapply StronglySorted_eq; eauto.
* by red; eauto.
* by apply starting_segment_property.
* apply StronglySorted_app; ins.
by apply starting_segment_property.
by apply segment_property.
apply starting_segment_property in IN1; apply segment_property in IN2; desf.
rewrite clos_refl_transE in *; desf; eauto.
all: repeat match goal with H : _⁺ _ _ |- _ => apply (ct_of_trans T) in H end; eauto.
* ins; rewrite in_app_iff, !in_starting_segment_iff, in_segment_iff.
intuition; eauto using clos_refl_trans.
tertium_non_datur (x0 = x) as [->|NEQ]; eauto using clos_refl_trans.
eapply TOT in NEQ; desf; eauto using clos_refl_trans.
Qed.

End Segments.


Definition pred: forall n:nat, {p:nat | n = S p}+{n = 0}.
  intros n. case n.
  right. reflexivity.
  intros p. left. exists p. reflexivity.
Defined.

Definition pred_partial: forall n:nat, n <> 0 -> nat.
  intros n. case n. intros H. elim H. reflexivity. (* don't get this *)
  intros p H'. exact p.
Defined.


Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.

Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.opp_precat.
Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.Core.NaturalTransformations.

Require Import UniMath.CategoryTheory.Adjunctions.Core.

Require Import UniMath.CategoryTheory.OppositeCategory.Core.

Section OppositeAdjunction.

  Context {C D : category} {F : functor C D} {G : functor D C}
          (a : are_adjoints F G).

  Local Definition a_adjunction : adjunction C D := make_adjunction _ (pr2 a).

  Definition adjunction_data_opposite : adjunction_data (opp_cat D) (opp_cat C).
  Proof.
    refine (functor_op G ,, functor_op F ,, _ ,, _).
    - exists (λ d, counit_from_are_adjoints a d).
      exact (λ d1 d2 f, ! pr2 (counit_from_are_adjoints a) d2 d1 f).
    - exists (λ d, unit_from_are_adjoints a d).
      exact (λ d1 d2 f, ! pr2 (unit_from_are_adjoints a) d2 d1 f).
  Defined.

  Definition form_adjunction'_opposite : form_adjunction' adjunction_data_opposite.
  Proof.
    exists (λ d, triangle_2_statement_from_adjunction a_adjunction d).
    exact (λ c, triangle_1_statement_from_adjunction a_adjunction c).
  Qed.

  Definition adjunction_opposite : adjunction (opp_cat D) (opp_cat C).
  Proof.
    exists adjunction_data_opposite.
    exact form_adjunction'_opposite.
  Defined.

  Definition are_adjoints_opposite : are_adjoints (functor_op G) (functor_op F)
    := are_adjoints_from_adjunction adjunction_opposite.

End OppositeAdjunction.

Lemma is_right_adjoint_opposite {C D : category} (F : functor C D)
  : is_left_adjoint F -> is_right_adjoint (functor_op F).
Proof.
  intro ila.
  set (adj := make_adjunction _ (pr22 ila)).
  exists (functor_op (pr121 adj)).
  exact (are_adjoints_opposite adj).
Defined.

Lemma is_right_adjoint_opposite' {C D : category} (F : functor C D)
  : is_left_adjoint (functor_op F) -> is_right_adjoint F.
Proof.
  intro ila.
  apply (is_right_adjoint_opposite (functor_op F) ila).
Defined.


Require Import Coq.Program.Basics.
Require Import FunctionalExtensionality.
Require Import List.
Require Export functor.
Require Import monad monoid.

(** list is a covariant functor. *)
Instance Fmap_list : Fmap list := map.

Instance Functor_list : Functor list.
Proof.
  constructor; unfold fmap, Fmap_list; intros; extensionality l;
    induction l; auto; simpl; rewrite IHl; auto.
Qed.

(** list is a Jmonad. *)
Instance Return_list : Return list := fun _ x => x :: nil.

Instance Join_list : Join list := concat.

Instance Jmonad_list : Jmonad list.
Proof.
  constructor.
  - apply app_nil_r.
  - unfold fmap, Fmap_list, join, Join_list.
    intros ? l; induction l; auto; simpl; rewrite IHl; auto.
  - intros A l. induction l; auto.
    unfold join, Join_list in *. simpl.
    unfold fmap, Fmap_list in *.
    rewrite <- IHl.
    apply concat_app.
  - firstorder.
  - intros A B f.
    unfold fmap, Fmap_list, join, Join_list, compose; simpl.
    extensionality l; induction l; simpl; auto.
    rewrite <- IHl, map_app; auto.
Qed.

Instance Mappend_list A : Mappend (list A) := @app _.

Instance Semigroup_list A : Semigroup (list A).
Proof. constructor; apply app_assoc_reverse. Qed.

Instance Mempty_list A : Mempty (list A) := nil.

Instance Monoid_list A : Monoid (list A).
Proof. constructor; auto; apply app_nil_r. Qed.


(* Exercise 2 *)

Require Import BenB.

Variables A B C D : Prop.

Theorem exercise_002 : (~A -> A) -> A.
Proof.
imp_i Sigma.
neg_e' A first.
hyp first.
imp_e (~A).
hyp Sigma.
hyp first.
Qed.


Require Import Classical_Prop.

(*Copied from exercise 1,2 from uebung07*)
Section Fallunterscheidung.
Variables x y: Prop. (* x = psi; y = phi *)
Lemma FU: ((x -> y) /\ (~x -> y)) -> y.
Proof.
    intro A.
    destruct A as [A B].
    (*Widerspruchsbeweis*)
    apply NNPP.
    intro C.
    assert (~x) as D.
    intro E.
        assert (y).
        apply A.
        exact E.
    contradiction. (*y and ~y*)
        assert (y).
        apply B.
        exact D.
    contradiction. (*y and ~y*)
Qed.
End Fallunterscheidung.

Section drinker.

  Variable T : Set.             (* "Datentyp" fÃ¼r die Personen in der Kneipe. *)
  Variable x : T.               (* Sicherstellung, dass Ã¼berhaupt jemand in der Kneipe ist. *)
  Variable drinks : T -> Prop.  (* PrÃ¤dikat, dass jemand in der Kneipe trinkt. *)

  Theorem Paradox: exists x, drinks x -> forall y, drinks y.
  Proof.
    apply FU with (x := exists z, ~ drinks z).
    split.
      intro ExistsNonDrinker.
      destruct ExistsNonDrinker as [z ZDoesntDrink].
      exists z.
      intro ZDoesDrink.
      contradiction.

      intro DoesntExistNonDrinker.
      exists x.
      assert (forall y, ~~drinks y) as EverybodyDoesntNotDrink.
        intro y.
        intro YDoesntDrink.
        unfold not at 1 in DoesntExistNonDrinker.
        apply DoesntExistNonDrinker.
        exists y.
        apply YDoesntDrink.
      intro xDrinks.
      intro y.
      apply NNPP.
      apply EverybodyDoesntNotDrink.
  Qed.

End drinker.

Section zoll.

  Variable T : Set.

  Variable E : T -> Prop.       (* reist ein *)
  Variable I : T -> Prop.       (* genieÃŸt ImmunitÃ¤t *)
  Variable S : T -> T -> Prop.  (* S x y meint "x durchsucht y" *)
  Variable Z : T -> Prop.       (* Ist Zollbeamter/-in *)
  Variable D : T -> Prop.       (* Betreibt Drogenschmuggel *)

  Theorem Drogenschmuggel: ((forall x, ~I x -> exists y, Z y /\ S y x) /\ (exists x, E x /\ D x /\ (forall y, S y x -> D y)) /\ (forall x, I x -> ~ D x) -> (exists x, Z x /\ D x)).
  Proof.
    intro Conjunction.
    destruct Conjunction as [Phi1 [Phi2 Phi3]].
    destruct Phi2 as [x [xEntered [xSmuggles onlySmugglersSearchedX]]].
    assert (~ I x) as xNotImmune.
      intro xImmune.
      assert (~ D x) as xDoesntSmuggle.
        apply Phi3.
        exact xImmune.
      contradiction.
    assert (exists y, Z y /\ S y x) as [y [yZoll ySearchedx]].
      apply Phi1.
      exact xNotImmune.
    assert (D y) as ySmuggles.
      apply onlySmugglersSearchedX.
      exact ySearchedx.
    exists y.
    split.
    exact yZoll.
    exact ySmuggles.
  Qed.

End zoll.

Section eq.

  Variable f : Set -> Set -> Set.
  Variables x y : Set.

  Hypothesis A1 : forall x y, f y (f x y) = x.

  Theorem T2 : f (f x y) x = y.
  Proof.
    (*TODO: Hier Beweis ergÃ¤nzen.*)
  Admitted. (*TODO: Nach erfolgreichem Beweis diese Zeile durch "Qed."  ersetzen. *)

End eq.


Set Implicit Arguments.

Module Fun.

Definition f {X} (h:nat->X)(g:X->nat) := g (h 0).

Definition f_set := f S S.
Definition f_prop := f (fun _ => I) (fun _ => 1).
Definition f_type := f (fun _ => nat) (fun _ => 1).

End Fun.

Recursive Extraction Fun.

Module Ind.

Inductive t (X:Type) : Type := T : (nat->X)->(X->nat)-> t X.

Definition f {X} (x : t X) := match x with T h g => g (h 0) end.

Definition f_set := f (T S S).
Definition f_prop := f (T (fun _ => I) (fun _ => 1)).
Definition f_type := f (T (fun _ => nat) (fun _ => 1)).

End Ind.

Recursive Extraction Ind.

Module Match.

Definition t (b:bool) := if b then nat else True.

Definition f (b:bool)(h:nat->t b)(g:t b ->nat) := g (h 0).

Definition f_true := f true S S.
Definition f_false := f false (fun _ => I) (fun _ => 1).

End Match.

Recursive Extraction Match.

Module Poly.

Definition f {X} (p : (nat -> X) * True) : X * nat :=
  (fst p 0, 0).

Definition f_set := f (S,I).
Definition f_prop := f ((fun _ => I),I).
Definition f_type := f ((fun _ => nat),I).

End Poly.

Recursive Extraction Poly.

(* !! le polyprop warning est H.S. en 8.5 !! *)

Module Fix.

Fixpoint arity (X:Type) n : Type := match n with
 | 0 => nat
 | S n => (nat->X)->arity X n
end.

Fixpoint f {X} n (g:X->nat) acc : arity X n := match n with
 | 0 => acc
 | S n => fun (h:nat->X) => f n g (g (h acc))
end.

Definition f_nat := f 2 S 0 S S.
Definition f_prop := f 2 (fun _=>3) 0 (fun _=>I) (fun _=>I).

End Fix.

Recursive Extraction Fix.


Require Import HoTT.Basics HoTT.Utf8.
Require Import InductiveTypes.

(*
Here we demonstrate that InductiveTypes allows for the construction of
various inductive types internally.
*)

Local Notation "'convertible' x y" := (idpath x : x = y)
  (at level 0, x, y at next level).

(* We can handle multiple constructors: *)
Module Example_N.

Definition N_spec : OpSpec@{Set} Unit
  := op_prod (el tt) (ind_arg (single_argument tt) (el tt)).

Definition N : Type0 := Initial.sorts N_spec tt.

Definition N_ops : N * (N → N) := Initial.operations N_spec.
Definition O : N := fst N_ops.
Definition S : N → N := snd N_ops.

Section eliminator.
Universe j.
Context (P : N → Type@{j}) (ISO : P O) (ISS : ∀ n, P n → P (S n)).

Definition N_rect@{} : ∀ n, P n
  := Initial.eliminators N_spec (λ 'tt, P) (ISO, ISS) tt.

Check convertible (N_rect O) ISO.
Check λ n, convertible (N_rect (S n)) (ISS n (N_rect n)).

End eliminator.
End Example_N.

(* And infinitary arguments: *)
Module Example_W.
Section W.
Universe i.
Context (A : Type@{i}) (B : A → Type@{i}).

Definition W_spec@{} : OpSpec@{i} Unit
  := nonind_arg A (λ a,
     ind_arg (infinitary_argument (B a) (λ b, tt))
     (el@{i} tt)).

Definition W@{} : Type@{i} := Initial.sorts W_spec tt.

Definition sup@{} : ∀ a, (B a → W) → W := Initial.operations W_spec.

Section eliminator.
Universe j.
Context (P : W → Type@{j}) (IS : ∀ a f, (∀ b, P (f b)) → P (sup a f)).

Definition W_rect@{} : ∀ x, P x
  := Initial.eliminators@{i j} W_spec (λ 'tt, P) IS tt.

Check λ a f, convertible (W_rect (sup a f)) (IS a f (λ b, W_rect (f b))).
End eliminator.
End W.
End Example_W.

Module Example_Enum.
Definition Enum_spec : OpSpec@{Set} Unit
  := op_prod (op_prod (op_prod (op_prod (op_prod
     (el tt) (el tt)) (el tt)) (el tt)) (el tt)) (el tt).

Definition Enum : Type0 := Initial.sorts Enum_spec tt.
Definition Enum_ops : ((((Enum * Enum) * Enum) * Enum) * Enum) * Enum
  := Initial.operations Enum_spec.
Definition e0 : Enum := Enum_ops.(fst).(fst).(fst).(fst).(fst).

Definition foo@{} : Enum → trunc_index
  := Initial.eliminators@{Set Set} Enum_spec (λ 'tt _, trunc_index)
     (0, 1, 2, 3, 4, 5)tt.
Check convertible (foo e0) 0.

End Example_Enum.


From discprob.basic Require Import base order nify exp_ext.
From discprob.prob Require Import prob countable finite stochastic_order.
From discprob.rec Require Import karp quickselect_rec.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.
From mathcomp Require Import tuple finfun bigop prime binomial finset.
From Coquelicot Require Import Derive.
From Coquelicot Require AutoDerive.
Require Import Reals Fourier ProofIrrelevance FunctionalExtensionality.
Require Import Psatz.
Require Import Coq.omega.Omega.
Require Import Ranalysis5.

Module Type rec_factor.
  Parameter alpha : R.
  Parameter alpha_range: 1/2 < alpha < 1.
  Parameter ln_alpha: -/ln alpha > 1/alpha.
End rec_factor.

Module recurrence_log (ALPHA: rec_factor).
  Import ALPHA.
  Definition d := 1.
  Definition umin := 1.

  Definition a x :=
    match Rle_dec x 1 with
      | left _ => 0
      | _ =>
        match Rlt_dec x 2 with
        | left _ => (x - 1)
        | _ => 1
        end
    end.

  Definition m x :=
    match Rlt_dec x (1/alpha) with
      | left _ => 0
      | _ => x * alpha
    end.

  Definition k := -/ ln(alpha).

  Definition u x :=
    match Rle_dec x 1 with
      | left _ => 1
      | _ => ((k * ln x + 1))
    end.

  Definition u' x :=
    match Rle_dec x 1 with
      | left _ => 1
      | _ => exp ((x - 1) / k)
    end.

  Lemma umin_non_neg: 0 ≤ umin.
  Proof. rewrite /umin; fourier. Qed.

  Lemma Rlt_0_ln x: 1 < x → 0 < ln x.
  Proof.
    intros Hlt; rewrite -ln_1; apply ln_increasing; fourier.
  Qed.

  Lemma one_lt_inv_alpha:
    1 < / alpha.
  Proof.
    generalize (alpha_range), ln_alpha; intros.
    apply (Rmult_lt_reg_l alpha); first nra. field_simplify; nra.
  Qed.

  Lemma kgt1: 1 < k.
  Proof.
    generalize (alpha_range), ln_alpha; intros.
    rewrite /k.
    transitivity (/ alpha); last auto; try nra.
    apply one_lt_inv_alpha.
  Qed.

  Lemma kgt0: 0 < k.
  Proof.
    etransitivity; last apply kgt1. fourier.
  Qed.

  Lemma u_mono x y: x ≤ y → u x ≤ u y.
  Proof.
    rewrite /u/a/m/d => Hle.
    destruct (Rle_dec) as [Hle'|Hnle']; try nra;
    destruct (Rle_dec) as [Hle''|Hnle'']; try nra.
    -
      cut (0 ≤ ln y).
      {
        intros. generalize kgt1 => ?.
        assert (k * ln y ≥ 0).
        { transitivity (1 * ln y); last fourier.
          apply Rle_ge, Rmult_le_compat; try fourier.
        }
        fourier.
      }
      left. apply Rlt_0_ln; nra.
    - specialize (kgt0) => Hk.
      apply Rplus_le_compat; last nra.
      cut (ln x ≤ ln y).
      {
        specialize (kgt0); cut (0 ≤ ln x); intros; first apply Rmult_le_compat; auto; try fourier.
        rewrite -(ln_1). left; apply ln_increasing; nra.
      }
      * inversion Hle; auto; subst; last by nra. left. apply ln_increasing; intros; nra.
  Qed.

  (* This basically covers half the case for the above, so could remove some redundancy *)
  Lemma u_strict_inc x y: x ≥ d → x < y → u x < u y.
  Proof.
    rewrite /u/a/m/d => Hle Hlt.
    destruct (Rle_dec) as [Hle'|Hnle']; try nra;
    destruct (Rle_dec) as [Hle''|Hnle'']; try nra.
    - specialize (kgt0) => Hk.
      assert (0 < k * ln y).
      {
        apply Rmult_lt_0_compat; first nra.
        apply Rlt_0_ln; fourier.
      }
      rewrite ?Rmult_1_r //=; nra.
    - specialize (kgt0) => Hk.
      apply Rplus_lt_compat_r.
      cut (ln x < ln y).
      {
        specialize (kgt0); cut (0 < ln x); intros; first apply Rmult_lt_compat_l; auto; try fourier.
        rewrite -(ln_1). apply ln_increasing; nra.
      }
      apply ln_increasing; nra.
  Qed.

  Lemma u'_mono x y: x ≤ y → u' x ≤ u' y.
  Proof.
    rewrite /u'/a/m/d => Hle.
    destruct (Rle_dec) as [Hle'|Hnle']; try nra;
    destruct (Rle_dec) as [Hle''|Hnle'']; try nra.
    - rewrite -{1}exp_0.
      left; apply exp_increasing.
      rewrite /Rdiv. apply Rlt_mult_inv_pos; last apply kgt0. nra.
    - apply exp_increasing_le.
      generalize (kgt0) => Hk.
      apply Rdiv_le_compat_contra; nra.
  Qed.

  Lemma u'_pos x: u' x > 0.
  Proof.
    rewrite /u'/a/m/d.
    destruct (Rle_dec _); try nra.
    apply exp_pos.
  Qed.

  Lemma u'_inv_above x: d < x → u' (u x) = x.
  Proof.
    rewrite /u/u'/d.
    destruct (Rle_dec) as [Hc1|Hc1] => //=; try nra;
    destruct (Rle_dec) as [Hc2|Hc2] => //=; try nra.
    - intros. exfalso.
      assert (0 < ln x) by (apply Rlt_0_ln; auto).
      assert (0 < k * ln x) by (apply Rmult_lt_0_compat; auto using kgt0).
      assert (0 < (k * ln x) * (k * ln x)) by (repeat apply Rmult_lt_0_compat; auto using kgt0).
      nra.
    - rewrite -[a in _ = a]exp_ln; last nra.
      intros; do 1 f_equal.
      assert (0 < ln x) by (apply Rlt_0_ln; auto).
      assert (0 < k * ln x) by (apply Rmult_lt_0_compat; auto using kgt0).
      field. apply Rgt_not_eq, kgt0.
  Qed.

  Lemma u'u x: x ≤ u' (u x).
  Proof.
    destruct (Rlt_dec 1 x) as [Hlt|Hnlt].
    - rewrite u'_inv_above //. reflexivity.
    - rewrite /u/u'.
      apply Rnot_lt_le in Hnlt.
      destruct (Rle_dec) => //=; try nra.
      destruct (Rle_dec) => //=; try nra.
  Qed.

  Lemma u_inv_above x: umin < x → u (u' x) = x.
  Proof.
    rewrite /u/u'/umin.
    destruct (Rle_dec) as [Hc1|?] => //=; try nra;
    destruct (Rle_dec) as [?|?] => //=; try nra.
    - exfalso. rewrite -{2}exp_0 in Hc1.
      apply exp_le_embedding in Hc1.
      specialize (kgt1) => Hk.
      cut (0 < (x - 1) / k).
      { by intros ?%Rlt_not_le. }
      apply Rdiv_lt_0_compat; nra.
    - rewrite ln_exp. rewrite /Rdiv. intros.
      field. apply Rgt_not_eq, kgt0.
  Qed.

  Lemma ud_umin: u d = umin.
  Proof.
    rewrite /u/d/umin//=.
    destruct (Rle_dec); nra.
  Qed.

  Lemma u_cont: continuity u.
  Proof.
    apply piecewise_continuity' with (g := λ x, (k * ln x + 1))
                                      (f := λ x, 1) (z := 1).
    - intros; apply continuity_const => ? //.
    - intros. repeat apply continuity_pt_mult.
      * apply continuity_pt_plus.
        ** apply continuity_pt_mult.
           *** apply continuity_pt_const => ? //.
           *** apply ln_continuity_pt; fourier.
        ** apply continuity_pt_const => ? //.
    - rewrite /u => x. destruct (Rle_dec); nra.
    - rewrite /u => x.
      destruct (Rle_dec); intros.
      * assert (x = 1) as -> by (apply Rle_antisym; fourier).
        rewrite ln_1 Rmult_0_r Rplus_0_l. done.
      * done.
  Qed.

  Lemma a_cont_pt: ∀ x, d < x → continuity_pt a x.
  Proof.
    rewrite /d. intros.
    apply piecewise_continuity_pt with (P := λ x, d < x)
                                               (g := λ x,
                                                     match Rlt_dec x 2 with
                                                     | left _ => (x - 1)
                                                     | _ => 1
                                                     end)
                                               (f := λ x, 0) (z := 1).
    - intros. apply continuity_const => ??. done.
    - intros. apply piecewise_continuity_pt with (g := λ x, 1)
                                                 (f := λ x, (x - 1))
                                                 (z := 2)
                                                 (P := λ x, d < x);
                try (intros; destruct (Rlt_dec); nra); try nra.
      * rewrite /d. intros.
        ** apply continuity_minus.
           *** apply continuity_id => ??.
           *** apply continuity_const => ??. done.
      * intros. apply continuity_const => ?? //=.
    - intros x'. rewrite /a. destruct Rle_dec; try nra; destruct Rlt_dec; nra.
    - intros x'. rewrite /a. destruct Rle_dec; nra.
    - rewrite /d. intros. fourier.
    - rewrite /d. fourier.
  Qed.

  Lemma kinv: /k = ln (/alpha).
  Proof.
    rewrite /k.
    generalize (alpha_range), ln_alpha; intros.
    rewrite ln_Rinv; last by nra.
    assert (0 < ln (/alpha)).
    { rewrite -ln_1. apply ln_increasing; first nra. apply one_lt_inv_alpha. }
    rewrite Ropp_inv_permute.
    - rewrite Rinv_involutive //.
      cut (ln alpha ≠ 0); first by nra.
      apply Rlt_not_eq. rewrite -ln_1.
      apply ln_increasing; nra.
    - cut (ln alpha ≠ 0); first by nra.
      apply Rlt_not_eq. rewrite -ln_1.
      apply ln_increasing; nra.
  Qed.

  Lemma urec0 x: x > d → u x ≥ a x + u (m x).
  Proof.
    generalize (alpha_range), ln_alpha => ??.
    rewrite /u/a/m/d.
    destruct (Rle_dec) as [Hc1|Hc1] => //=; first nra.
    destruct (Rle_dec) as [Hc2|Hc2] => //=.
    - destruct (Rlt_dec) as [?|?].
      {
        destruct (Rlt_dec) as [?|?]; try nra; last first.
        { intros.
          assert (1 / alpha < 2).
          { destruct alpha_range as (Hlt&?).
            apply Rinv_lt_contravar in Hlt; last nra.
            nra.
          }
          nra.
        }
        intros.
        transitivity (x - 1 +  1); last first.
        { right. field. }
        cut (k * ln x > x - 1); first by (intros; fourier).
        cut (k * ln x - (x - 1) > 0); first by (intros; fourier).
        apply Rlt_gt.
        eapply (Rle_lt_trans _ (k * ln(1) - (1 - 1))).
        { right. rewrite ln_1 Rmult_0_r. field. }
        eapply incr_function_le with (f := λ x, k * ln x - (x - 1))
                                               (x := 1)
                                               (y := x)
                                               (a := 1)
                                               (b := /alpha)
                                               (df := λ x, k * 1/x - 1); try fourier; eauto.
        * rewrite //= => ???. AutoDerive.auto_derive; nra.
        * rewrite //=. intros x' ? ?.
          cut (k */ x' > 1).
          { intros. set (p := k */ x'). assert (p > 1) by (rewrite /p; auto).
            nra.
          }
          apply Rlt_gt, (Rmult_lt_reg_r x'); first fourier.
          rewrite Rmult_assoc Rinv_l; first (rewrite /k; nra).
          apply Rgt_not_eq; fourier.
        * rewrite //=. nra.
        * rewrite //=. nra.
      }
      assert (x = /alpha) as ->.
      {
        apply (Rmult_le_compat_r (/alpha)) in Hc2; last first.
        {
          left. transitivity 1; first nra. apply one_lt_inv_alpha.
        }
        rewrite Rmult_assoc Rinv_r in Hc2; last first.
        { apply Rgt_not_eq. nra. }
        rewrite Rmult_1_l Rmult_1_r in Hc2.
        apply Rle_antisym; nra.
      }
      destruct (Rlt_dec); last by nra.
      intros; rewrite -kinv Rinv_r; first nra.
      apply Rgt_not_eq, kgt0.
    - assert (0 < ln x) by (apply Rlt_0_ln; nra).
      destruct (Rlt_dec); first by nra; intros.
      intros; rewrite ln_mult; try nra.
      rewrite (Rmult_plus_distr_l k _).
      assert (k * ln (alpha) = -1) as ->.
      { rewrite /k. field. apply Rlt_not_eq.
        rewrite -(ln_1). apply ln_increasing; nra.
      }
      destruct Rlt_dec.
      * field_simplify; last nra.
      * rewrite /Rdiv; first fourier.
  Qed.

  Lemma alower: ∀ x, x ≤ d → a x = 0.
  Proof.
    rewrite /a => x; destruct (Rle_dec) => //=; nra.
  Qed.

  Lemma a_nonneg: ∀ x, a x ≥ 0.
  Proof.
    intros. rewrite /a. destruct (Rlt_dec); destruct (Rle_dec); nra.
  Qed.

  Lemma a_pos: ∀ x, d < x → 0 < a x.
  Proof.
    rewrite /d/a => ??. destruct (Rlt_dec); destruct (Rle_dec); nra.
  Qed.

  Lemma a_mono: Rmono a.
  Proof.
    rewrite /Rmono. intros x x' Hle.
    inversion Hle; subst; try reflexivity.
    destruct (Rle_dec d x) as [?|?%Rnot_le_gt].
    * rewrite /a. do 2 (destruct (Rle_dec); try destruct (Rlt_dec)); nra.
    * rewrite alower; auto; try fourier. apply Rge_le, a_nonneg.
  Qed.

  Lemma mnondec: ∀ y y', 0 < y → y ≤ y' → (m y / y) ≤ (m y' / y').
  Proof.
    generalize (alpha_range), ln_alpha => ??.
    intros y y' Hlt Hle.
    rewrite /m.
    destruct (Rlt_dec).
    {  destruct (Rlt_dec).
       - intros. rewrite /Rdiv ?Rmult_0_l. fourier.
       - intros. rewrite /Rdiv ?Rmult_0_l.
         rewrite Rmult_comm -Rmult_assoc Rinv_l; nra.
    }
    destruct (Rlt_dec); first by nra.
    intros. right. field. split; apply Rgt_not_eq; fourier.
  Qed.

  Lemma d_non_neg: 0 ≤ d.
  Proof.
    rewrite /d. fourier.
  Qed.

End recurrence_log.