(** * Poly: Polymorphism and Higher-Order Functions *)

(* Final reminder: Please do not put solutions to the exercises in
   publicly accessible places.  Thank you!! *)

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

(*** Polymorphism *)

(** In this chapter we continue our development of basic
    concepts of functional programming.  The critical new ideas are
    _polymorphism_ (abstracting functions over the types of the data
    they manipulate) and _higher-order functions_ (treating functions
    as data).  We begin with polymorphism. *)

(* ================================================================= *)
(** ** Polymorphic Lists *)

(** For the last couple of chapters, we've been working just
    with lists of numbers.  Obviously, interesting programs also need
    to be able to manipulate lists with elements from other types --
    lists of strings, lists of booleans, lists of lists, etc.  We
    _could_ just define a new inductive datatype for each of these,
    for example... *)

Inductive boollist : Type :=
  | bool_nil : boollist
  | bool_cons : bool -> boollist -> boollist.

(** ... but this would quickly become tedious, partly because we
    have to make up different constructor names for each datatype, but
    mostly because we would also need to define new versions of all
    our list manipulating functions ([length], [rev], etc.) for each
    new datatype definition. *)

(** To avoid all this repetition, Coq supports _polymorphic_
    inductive type definitions.  For example, here is a _polymorphic
    list_ datatype. *)

Inductive list (X:Type) : Type :=
  | nil : list X
  | cons : X -> list X -> list X.

(** This is exactly like the definition of [natlist] from the
    previous chapter, except that the [nat] argument to the [cons]
    constructor has been replaced by an arbitrary type [X], a binding
    for [X] has been added to the header, and the occurrences of
    [natlist] in the types of the constructors have been replaced by
    [list X].  (We can re-use the constructor names [nil] and [cons]
    because the earlier definition of [natlist] was inside of a
    [Module] definition that is now out of scope.)

    What sort of thing is [list] itself?  One good way to think
    about it is that [list] is a _function_ from [Type]s to
    [Inductive] definitions; or, to put it another way, [list] is a
    function from [Type]s to [Type]s.  For any particular type [X],
    the type [list X] is an [Inductive]ly defined set of lists whose
    elements are of type [X]. *)

Check list.
(* ===> list : Type -> Type *)

(** The parameter [X] in the definition of [list] becomes a parameter
    to the constructors [nil] and [cons] -- that is, [nil] and [cons]
    are now polymorphic constructors, that need to be supplied with
    the type of the list they are building. As an example, [nil nat]
    constructs the empty list of type [nat]. *)

Check (nil nat).
(* ===> nil nat : list nat *)

(** Similarly, [cons nat] adds an element of type [nat] to a list of
    type [list nat]. Here is an example of forming a list containing
    just the natural number 3.*)

Check (cons nat 3 (nil nat)).
(* ===> cons nat 3 (nil nat) : list nat *)

(** What might the type of [nil] be? We can read off the type [list X]
    from the definition, but this omits the binding for [X] which is
    the parameter to [list]. [Type -> list X] does not explain the
    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's
    notation for this situation is [forall X : Type, list X]. *)

Check nil.
(* ===> nil : forall X : Type, list X *)

(** Similarly, the type of [cons] from the definition looks like
    [X -> list X -> list X], but using this convention to explain the
    meaning of [X] results in the type [forall X, X -> list X -> list
    X]. *)

Check cons.
(* ===> cons : forall X : Type, X -> list X -> list X *)

(** (Side note on notation: In .v files, the "forall" quantifier
    is spelled out in letters.  In the generated HTML files and in the
    way various IDEs show .v files (with certain settings of their
    display controls), [forall] is usually typeset as the usual
    mathematical "upside down A," but you'll still see the spelled-out
    "forall" in a few places.  This is just a quirk of typesetting:
    there is no difference in meaning.) *)

(** Having to supply a type argument for each use of a list
    constructor may seem an awkward burden, but we will soon see
    ways of reducing that burden. *)

Check (cons nat 2 (cons nat 1 (nil nat))).

(** (We've written [nil] and [cons] explicitly here because we haven't
    yet defined the [ [] ] and [::] notations for the new version of
    lists.  We'll do that in a bit.) *)

(** We can now go back and make polymorphic versions of all the
    list-processing functions that we wrote before.  Here is [repeat],
    for example: *)

Fixpoint repeat (X : Type) (x : X) (count : nat) : list X :=
  match count with
  | 0 => nil X
  | S count' => cons X x (repeat X x count')
  end.

(** As with [nil] and [cons], we can use [repeat] by applying it
    first to a type and then to an element of this type (and a number): *)

Example test_repeat1 :
  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).
Proof. reflexivity.  Qed.

(** To use [repeat] to build other kinds of lists, we simply
    instantiate it with an appropriate type parameter: *)

Example test_repeat2 :
  repeat bool false 1 = cons bool false (nil bool).
Proof. reflexivity.  Qed.

Module MumbleGrumble.

(** **** Exercise: 2 stars (mumble_grumble)  *)
(** Consider the following two inductively defined types. *)

Inductive mumble : Type :=
  | a : mumble
  | b : mumble -> nat -> mumble
  | c : mumble.

Inductive grumble (X:Type) : Type :=
  | d : mumble -> grumble X
  | e : X -> grumble X.

(** Which of the following are well-typed elements of [grumble X] for
    some type [X]?
      - [d (b a 5)]
      - [d mumble (b a 5)]
      - [d bool (b a 5)]
      - [e bool true]
      - [e mumble (b c 0)]
      - [e bool (b c 0)]
      - [c]
(* FILL IN HERE *)
*)
(** [] *)

End MumbleGrumble.

(* ----------------------------------------------------------------- *)
(** *** Type Annotation Inference *)

(** Let's write the definition of [repeat] again, but this time we
    won't specify the types of any of the arguments.  Will Coq still
    accept it? *)

Fixpoint repeat' X x count : list X :=
  match count with
  | 0        => nil X
  | S count' => cons X x (repeat' X x count')
  end.

(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)

Check repeat'.
(* ===> forall X : Type, X -> nat -> list X *)
Check repeat.
(* ===> forall X : Type, X -> nat -> list X *)

(** It has exactly the same type type as [repeat].  Coq was able
    to use _type inference_ to deduce what the types of [X], [x], and
    [count] must be, based on how they are used.  For example, since
    [X] is used as an argument to [cons], it must be a [Type], since
    [cons] expects a [Type] as its first argument; matching [count]
    with [0] and [S] means it must be a [nat]; and so on.

    This powerful facility means we don't always have to write
    explicit type annotations everywhere, although explicit type
    annotations are still quite useful as documentation and sanity
    checks, so we will continue to use them most of the time.  You
    should try to find a balance in your own code between too many
    type annotations (which can clutter and distract) and too
    few (which forces readers to perform type inference in their heads
    in order to understand your code). *)

(* ----------------------------------------------------------------- *)
(** *** Type Argument Synthesis *)

(** To use a polymorphic function, we need to pass it one or
    more types in addition to its other arguments.  For example, the
    recursive call in the body of the [repeat] function above must
    pass along the type [X].  But since the second argument to
    [repeat] is an element of [X], it seems entirely obvious that the
    first argument can only be [X] -- why should we have to write it
    explicitly?

    Fortunately, Coq permits us to avoid this kind of redundancy.  In
    place of any type argument we can write the "implicit argument"
    [_], which can be read as "Please try to figure out for yourself
    what belongs here."  More precisely, when Coq encounters a [_], it
    will attempt to _unify_ all locally available information -- the
    type of the function being applied, the types of the other
    arguments, and the type expected by the context in which the
    application appears -- to determine what concrete type should
    replace the [_].

    This may sound similar to type annotation inference -- indeed, the
    two procedures rely on the same underlying mechanisms.  Instead of
    simply omitting the types of some arguments to a function, like

      repeat' X x count : list X :=

    we can also replace the types with [_]

      repeat' (X : _) (x : _) (count : _) : list X :=

    to tell Coq to attempt to infer the missing information.

    Using implicit arguments, the [repeat] function can be written like
    this: *)

Fixpoint repeat'' X x count : list X :=
  match count with
  | 0        => nil _
  | S count' => cons _ x (repeat'' _ x count')
  end.

(** In this instance, we don't save much by writing [_] instead of
    [X].  But in many cases the difference in both keystrokes and
    readability is nontrivial.  For example, suppose we want to write
    down a list containing the numbers [1], [2], and [3].  Instead of
    writing this... *)

Definition list123 :=
  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).

(** ...we can use argument synthesis to write this: *)

Definition list123' :=
  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).

(* ----------------------------------------------------------------- *)
(** *** Implicit Arguments *)

(** We can go further and even avoid writing [_]'s in most cases by
    telling Coq _always_ to infer the type argument(s) of a given
    function.

    The [Arguments] directive specifies the name of the function (or
    constructor) and then lists its argument names, with curly braces
    around any arguments to be treated as implicit.  (If some
    arguments of a definition don't have a name, as is often the case
    for constructors, they can be marked with a wildcard pattern
    [_].) *)

Arguments nil {X}.
Arguments cons {X} _ _.
Arguments repeat {X} x count.

(** Now, we don't have to supply type arguments at all: *)

Definition list123'' := cons 1 (cons 2 (cons 3 nil)).

(** Alternatively, we can declare an argument to be implicit
    when defining the function itself, by surrounding it in curly
    braces instead of parens.  For example: *)

Fixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=
  match count with
  | 0        => nil
  | S count' => cons x (repeat''' x count')
  end.

(** (Note that we didn't even have to provide a type argument to the
    recursive call to [repeat''']; indeed, it would be invalid to
    provide one!)

    We will use the latter style whenever possible, but we will
    continue to use explicit [Argument] declarations for [Inductive]
    constructors.  The reason for this is that marking the parameter
    of an inductive type as implicit causes it to become implicit for
    the type itself, not just for its constructors.  For instance,
    consider the following alternative definition of the [list]
    type: *)

Inductive list' {X:Type} : Type :=
  | nil' : list'
  | cons' : X -> list' -> list'.

(** Because [X] is declared as implicit for the _entire_ inductive
    definition including [list'] itself, we now have to write just
    [list'] whether we are talking about lists of numbers or booleans
    or anything else, rather than [list' nat] or [list' bool] or
    whatever; this is a step too far. *)

(** Let's finish by re-implementing a few other standard list
    functions on our new polymorphic lists... *)

Fixpoint app {X : Type} (l1 l2 : list X)
             : (list X) :=
  match l1 with
  | nil      => l2
  | cons h t => cons h (app t l2)
  end.

Fixpoint rev {X:Type} (l:list X) : list X :=
  match l with
  | nil      => nil
  | cons h t => app (rev t) (cons h nil)
  end.

Fixpoint length {X : Type} (l : list X) : nat :=
  match l with
  | nil => 0
  | cons _ l' => S (length l')
  end.

Example test_rev1 :
  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).
Proof. reflexivity.  Qed.

Example test_rev2:
  rev (cons true nil) = cons true nil.
Proof. reflexivity.  Qed.

Example test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.
Proof. reflexivity.  Qed.

(* ----------------------------------------------------------------- *)
(** *** Supplying Type Arguments Explicitly *)

(** One small problem with declaring arguments [Implicit] is
    that, occasionally, Coq does not have enough local information to
    determine a type argument; in such cases, we need to tell Coq that
    we want to give the argument explicitly just this time.  For
    example, suppose we write this: *)

Fail Definition mynil := nil.

(** (The [Fail] qualifier that appears before [Definition] can be
    used with _any_ command, and is used to ensure that that command
    indeed fails when executed. If the command does fail, Coq prints
    the corresponding error message, but continues processing the rest
    of the file.)

    Here, Coq gives us an error because it doesn't know what type
    argument to supply to [nil].  We can help it by providing an
    explicit type declaration (so that Coq has more information
    available when it gets to the "application" of [nil]): *)

Definition mynil : list nat := nil.

(** Alternatively, we can force the implicit arguments to be explicit by
   prefixing the function name with [@]. *)

Check @nil.

Definition mynil' := @nil nat.

(** Using argument synthesis and implicit arguments, we can
    define convenient notation for lists, as before.  Since we have
    made the constructor type arguments implicit, Coq will know to
    automatically infer these when we use the notations. *)

Notation "x :: y" := (cons x y)
                     (at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y []) ..).
Notation "x ++ y" := (app x y)
                     (at level 60, right associativity).

(** Now lists can be written just the way we'd hope: *)

Definition list123''' := [1; 2; 3].

(* ----------------------------------------------------------------- *)
(** *** Exercises *)

(** **** Exercise: 2 stars, optional (poly_exercises)  *)
(** Here are a few simple exercises, just like ones in the [Lists]
    chapter, for practice with polymorphism.  Complete the proofs below. *)

Theorem app_nil_r : forall (X:Type), forall l:list X,
  l ++ [] = l.
Proof.
  intros X l.
  induction l.
  reflexivity.
  simpl.
  rewrite -> IHl.
  reflexivity.
Qed.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  intros X l m n.
  induction l.
  reflexivity.
  simpl.
  rewrite <- IHl.
  reflexivity.
Qed.

Lemma app_length : forall (X:Type) (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  intros X l1 l2.
  induction l1.
  reflexivity.
  simpl.
  rewrite -> IHl1.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)
(** Here are some slightly more interesting ones... *)

Theorem rev_app_distr: forall X (l1 l2 : list X),
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  intros X l1 l2.
  induction l1.
  simpl. rewrite -> app_nil_r. reflexivity.
  simpl.
  rewrite -> IHl1.
  rewrite -> app_assoc.
  reflexivity.
Qed.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  intros X l.
  induction l.
  reflexivity.
  simpl.
Admitted.
(** [] *)

(* ================================================================= *)
(** ** Polymorphic Pairs *)

(** Following the same pattern, the type definition we gave in
    the last chapter for pairs of numbers can be generalized to
    _polymorphic pairs_, often called _products_: *)

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

Arguments pair {X} {Y} _ _.

(** As with lists, we make the type arguments implicit and define the
    familiar concrete notation. *)

Notation "( x , y )" := (pair x y).

(** We can also use the [Notation] mechanism to define the standard
    notation for product _types_: *)

Notation "X * Y" := (prod X Y) : type_scope.

(** (The annotation [: type_scope] tells Coq that this abbreviation
    should only be used when parsing types.  This avoids a clash with
    the multiplication symbol.) *)

(** It is easy at first to get [(x,y)] and [X*Y] confused.
    Remember that [(x,y)] is a _value_ built from two other values,
    while [X*Y] is a _type_ built from two other types.  If [x] has
    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)

(** The first and second projection functions now look pretty
    much as they would in any functional programming language. *)

Definition fst {X Y : Type} (p : X * Y) : X :=
  match p with
  | (x, y) => x
  end.

Definition snd {X Y : Type} (p : X * Y) : Y :=
  match p with
  | (x, y) => y
  end.

(** The following function takes two lists and combines them
    into a list of pairs.  In other functional languages, it is often
    called [zip]; we call it [combine] for consistency with Coq's
    standard library. *)

Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)
           : list (X*Y) :=
  match lx, ly with
  | [], _ => []
  | _, [] => []
  | x :: tx, y :: ty => (x, y) :: (combine tx ty)
  end.

(** **** Exercise: 1 star, optional (combine_checks)  *)
(** Try answering the following questions on paper and
    checking your answers in coq:
    - What is the type of [combine] (i.e., what does [Check
      @combine] print?)
    - What does

        Compute (combine [1;2] [false;false;true;true]).

      print? *)
(** [] *)

(** **** Exercise: 2 stars, recommended (split)  *)
(** The function [split] is the right inverse of [combine]: it takes a
    list of pairs and returns a pair of lists.  In many functional
    languages, it is called [unzip].

    Fill in the definition of [split] below.  Make sure it passes the
    given unit test. *)

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

Example test_split:
  split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
reflexivity. Qed.
(** [] *)

(* ================================================================= *)
(** ** Polymorphic Options *)

(** One last polymorphic type for now: _polymorphic options_,
    which generalize [natoption] from the previous chapter: *)

Inductive option (X:Type) : Type :=
  | Some : X -> option X
  | None : option X.

Arguments Some {X} _.
Arguments None {X}.

(** We can now rewrite the [nth_error] function so that it works
    with any type of lists. *)

Fixpoint nth_error {X : Type} (l : list X) (n : nat)
                   : option X :=
  match l with
  | [] => None
  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)
  end.

Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.
Proof. reflexivity. Qed.
Example test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].
Proof. reflexivity. Qed.
Example test_nth_error3 : nth_error [true] 2 = None.
Proof. reflexivity. Qed.

(** **** Exercise: 1 star, optional (hd_error_poly)  *)
(** Complete the definition of a polymorphic version of the
    [hd_error] function from the last chapter. Be sure that it
    passes the unit tests below. *)

Definition hd_error {X : Type} (l : list X) : option X :=
  match l with
  | [] => None
  | x :: xs => Some x
end.

(** Once again, to force the implicit arguments to be explicit,
    we can use [@] before the name of the function. *)

Check @hd_error.

Example test_hd_error1 : hd_error [1;2] = Some 1.
 reflexivity. Qed.
Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].
 reflexivity. Qed.
(** [] *)

(* ################################################################# *)
(** * Functions as Data *)

(** Like many other modern programming languages -- including
    all functional languages (ML, Haskell, Scheme, Scala, Clojure,
    etc.) -- Coq treats functions as first-class citizens, allowing
    them to be passed as arguments to other functions, returned as
    results, stored in data structures, etc.*)

(* ================================================================= *)
(** ** Higher-Order Functions *)

(** Functions that manipulate other functions are often called
    _higher-order_ functions.  Here's a simple one: *)

Definition doit3times {X:Type} (f:X->X) (n:X) : X :=
  f (f (f n)).

(** The argument [f] here is itself a function (from [X] to
    [X]); the body of [doit3times] applies [f] three times to some
    value [n]. *)

Check @doit3times.
(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)

Example test_doit3times: doit3times minustwo 9 = 3.
Proof. reflexivity.  Qed.

Example test_doit3times': doit3times negb true = false.
Proof. reflexivity.  Qed.

(* ================================================================= *)
(** ** Filter *)

(** Here is a more useful higher-order function, taking a list
    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])
    and "filtering" the list, returning a new list containing just
    those elements for which the predicate returns [true]. *)

Fixpoint filter {X:Type} (test: X->bool) (l:list X)
                : (list X) :=
  match l with
  | []     => []
  | h :: t => if test h then h :: (filter test t)
                        else       filter test t
  end.

(** For example, if we apply [filter] to the predicate [evenb]
    and a list of numbers [l], it returns a list containing just the
    even members of [l]. *)

Example test_filter1: filter evenb [1;2;3;4] = [2;4].
Proof. reflexivity.  Qed.

Definition length_is_1 {X : Type} (l : list X) : bool :=
  beq_nat (length l) 1.

Example test_filter2:
    filter length_is_1
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity.  Qed.

(** We can use [filter] to give a concise version of the
    [countoddmembers] function from the [Lists] chapter. *)

Definition countoddmembers' (l:list nat) : nat :=
  length (filter oddb l).

Example test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.
Proof. reflexivity.  Qed.
Example test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.
Proof. reflexivity.  Qed.
Example test_countoddmembers'3:   countoddmembers' nil = 0.
Proof. reflexivity.  Qed.

(* ================================================================= *)
(** ** Anonymous Functions *)

(** It is arguably a little sad, in the example just above, to
    be forced to define the function [length_is_1] and give it a name
    just to be able to pass it as an argument to [filter], since we
    will probably never use it again.  Moreover, this is not an
    isolated example: when using higher-order functions, we often want
    to pass as arguments "one-off" functions that we will never use
    again; having to give each of these functions a name would be
    tedious.

    Fortunately, there is a better way.  We can construct a function
    "on the fly" without declaring it at the top level or giving it a
    name. *)

Example test_anon_fun':
  doit3times (fun n => n * n) 2 = 256.
Proof. reflexivity.  Qed.

(** The expression [(fun n => n * n)] can be read as "the function
    that, given a number [n], yields [n * n]." *)

(** Here is the [filter] example, rewritten to use an anonymous
    function. *)

Example test_filter2':
    filter (fun l => beq_nat (length l) 1)
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (filter_even_gt7)  *)
(** Use [filter] (instead of [Fixpoint]) to write a Coq function
    [filter_even_gt7] that takes a list of natural numbers as input
    and returns a list of just those that are even and greater than
    7. *)

Definition filter_even_gt7 (l : list nat) : list nat :=
  filter (fun x => andb (evenb x) (blt_nat 7 x)) l.

Example test_filter_even_gt7_1 :
  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
 reflexivity. Qed.

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
 reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars (partition)  *)
(** Use [filter] to write a Coq function [partition]:

      partition : forall X : Type,
                  (X -> bool) -> list X -> list X * list X

   Given a set [X], a test function of type [X -> bool] and a [list
   X], [partition] should return a pair of lists.  The first member of
   the pair is the sublist of the original list containing the
   elements that satisfy the test, and the second is the sublist
   containing those that fail the test.  The order of elements in the
   two sublists should be the same as their order in the original
   list. *)

Definition partition {X : Type}
                     (test : X -> bool)
                     (l : list X)
                   : list X * list X :=
  (filter test l, filter (fun x => negb (test x)) l).

Example test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).
  reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
  reflexivity. Qed.
(** [] *)

(* ================================================================= *)
(** ** Map *)

(** Another handy higher-order function is called [map]. *)

Fixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=
  match l with
  | []     => []
  | h :: t => (f h) :: (map f t)
  end.

(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]
    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has
    been applied to each element of [l] in turn.  For example: *)

Example test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

(** The element types of the input and output lists need not be
    the same, since [map] takes _two_ type arguments, [X] and [Y]; it
    can thus be applied to a list of numbers and a function from
    numbers to booleans to yield a list of booleans: *)

Example test_map2:
  map oddb [2;1;2;5] = [false;true;false;true].
Proof. reflexivity.  Qed.

(** It can even be applied to a list of numbers and
    a function from numbers to _lists_ of booleans to
    yield a _list of lists_ of booleans: *)

Example test_map3:
    map (fun n => [evenb n;oddb n]) [2;1;2;5]
  = [[true;false];[false;true];[true;false];[false;true]].
Proof. reflexivity.  Qed.

(* ----------------------------------------------------------------- *)
(** *** Exercises *)

(** **** Exercise: 3 stars (map_rev)  *)
(** Show that [map] and [rev] commute.  You may need to define an
    auxiliary lemma. *)

Lemma map_app : forall (X Y : Type) (f : X -> Y) (l : list X) (x : X),
  map f (rev l ++ [x]) = map f (rev l) ++ [f x].
Proof.
  intros X Y f l x.
  induction l.
  reflexivity.
  simpl.
Admitted.

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  intros X Y f l.
  induction l.
  reflexivity.
  simpl.
  rewrite <- IHl.
  rewrite <- map_app.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, recommended (flat_map)  *)
(** The function [map] maps a [list X] to a [list Y] using a function
    of type [X -> Y].  We can define a similar function, [flat_map],
    which maps a [list X] to a [list Y] using a function [f] of type
    [X -> list Y].  Your definition should work by 'flattening' the
    results of [f], like so:

        flat_map (fun n => [n;n+1;n+2]) [1;5;10]
      = [1; 2; 3; 5; 6; 7; 10; 11; 12].
*)

Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)
                   : (list Y) :=
  match l with
  | [] => []
  | x :: xs => (f x) ++ (flat_map f xs)
  end.

Example test_flat_map1:
  flat_map (fun n => [n;n;n]) [1;5;4]
  = [1; 1; 1; 5; 5; 5; 4; 4; 4].
 reflexivity. Qed.
(** [] *)

(** Lists are not the only inductive type that we can write a
    [map] function for.  Here is the definition of [map] for the
    [option] type: *)

Definition option_map {X Y : Type} (f : X -> Y) (xo : option X)
                      : option Y :=
  match xo with
    | None => None
    | Some x => Some (f x)
  end.

(** **** Exercise: 2 stars, optional (implicit_args)  *)
(** The definitions and uses of [filter] and [map] use implicit
    arguments in many places.  Replace the curly braces around the
    implicit arguments with parentheses, and then fill in explicit
    type parameters where necessary and use Coq to check that you've
    done so correctly.  (This exercise is not to be turned in; it is
    probably easiest to do it on a _copy_ of this file that you can
    throw away afterwards.)
*)
(** [] *)

(* ================================================================= *)
(** ** Fold *)

(** An even more powerful higher-order function is called
    [fold].  This function is the inspiration for the "[reduce]"
    operation that lies at the heart of Google's map/reduce
    distributed programming framework. *)

Fixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)
                         : Y :=
  match l with
  | nil => b
  | h :: t => f h (fold f t b)
  end.

(** Intuitively, the behavior of the [fold] operation is to
    insert a given binary operator [f] between every pair of elements
    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively
    means [1+2+3+4].  To make this precise, we also need a "starting
    element" that serves as the initial second input to [f].  So, for
    example,

       fold plus [1;2;3;4] 0

    yields

       1 + (2 + (3 + (4 + 0))).

    Some more examples: *)

Check (fold andb).
(* ===> fold andb : list bool -> bool -> bool *)

Example fold_example1 :
  fold mult [1;2;3;4] 1 = 24.
Proof. reflexivity. Qed.

Example fold_example2 :
  fold andb [true;true;false;true] true = false.
Proof. reflexivity. Qed.

Example fold_example3 :
  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].
Proof. reflexivity. Qed.

(** **** Exercise: 1 star, advanced (fold_types_different)  *)
(** Observe that the type of [fold] is parameterized by _two_ type
    variables, [X] and [Y], and the parameter [f] is a binary operator
    that takes an [X] and a [Y] and returns a [Y].  Can you think of a
    situation where it would be useful for [X] and [Y] to be
    different? *)

(** Un caso podría ser cuando queremos obtener la suma de la parte entera
de una lista de elementos representados en punto flotante.*)
(** [] *)

(* ================================================================= *)
(** ** Functions That Construct Functions *)

(** Most of the higher-order functions we have talked about so
    far take functions as arguments.  Let's look at some examples that
    involve _returning_ functions as the results of other functions.
    To begin, here is a function that takes a value [x] (drawn from
    some type [X]) and returns a function from [nat] to [X] that
    yields [x] whenever it is called, ignoring its [nat] argument. *)

Definition constfun {X: Type} (x: X) : nat->X :=
  fun (k:nat) => x.

Definition ftrue := constfun true.

Example constfun_example1 : ftrue 0 = true.
Proof. reflexivity. Qed.

Example constfun_example2 : (constfun 5) 99 = 5.
Proof. reflexivity. Qed.

(** In fact, the multiple-argument functions we have already
    seen are also examples of passing functions as data.  To see why,
    recall the type of [plus]. *)

Check plus.
(* ==> nat -> nat -> nat *)

(** Each [->] in this expression is actually a _binary_ operator
    on types.  This operator is _right-associative_, so the type of
    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it
    can be read as saying that "[plus] is a one-argument function that
    takes a [nat] and returns a one-argument function that takes
    another [nat] and returns a [nat]."  In the examples above, we
    have always applied [plus] to both of its arguments at once, but
    if we like we can supply just the first.  This is called _partial
    application_. *)

Definition plus3 := plus 3.
Check plus3.

Example test_plus3 :    plus3 4 = 7.
Proof. reflexivity.  Qed.
Example test_plus3' :   doit3times plus3 0 = 9.
Proof. reflexivity.  Qed.
Example test_plus3'' :  doit3times (plus 3) 0 = 9.
Proof. reflexivity.  Qed.

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

Module Exercises.

(** **** Exercise: 2 stars (fold_length)  *)
(** Many common functions on lists can be implemented in terms of
   [fold].  For example, here is an alternative definition of [length]: *)

Definition fold_length {X : Type} (l : list X) : nat :=
  fold (fun _ n => S n) l 0.

Example test_fold_length1 : fold_length [4;7;0] = 3.
Proof. reflexivity. Qed.

(** Prove the correctness of [fold_length]. *)

Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
Proof.
  intros X l.
  induction l.
  reflexivity.
  simpl.
  rewrite <- IHl.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars (fold_map)  *)
(** We can also define [map] in terms of [fold].  Finish [fold_map]
    below. *)

Definition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=
  fold (fun n l => f n :: l) l [].

(** Write down a theorem [fold_map_correct] in Coq stating that
   [fold_map] is correct, and prove it. *)

Theorem fold_map_correct : forall (X Y : Type) (l : list X) (f : X -> Y),
  fold_map f l = map f l.
Proof.
  intros X Y l f.
  induction l.
  reflexivity.
  simpl.
  rewrite <- IHl.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (currying)  *)
(** In Coq, a function [f : A -> B -> C] really has the type [A
    -> (B -> C)].  That is, if you give [f] a value of type [A], it
    will give you function [f' : B -> C].  If you then give [f'] a
    value of type [B], it will return a value of type [C].  This
    allows for partial application, as in [plus3].  Processing a list
    of arguments with functions that return functions is called
    _currying_, in honor of the logician Haskell Curry.

    Conversely, we can reinterpret the type [A -> B -> C] as [(A *
    B) -> C].  This is called _uncurrying_.  With an uncurried binary
    function, both arguments must be given at once as a pair; there is
    no partial application. *)

(** We can define currying as follows: *)

Definition prod_curry {X Y Z : Type}
  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).

(** As an exercise, define its inverse, [prod_uncurry].  Then prove
    the theorems below to show that the two are inverses. *)

Definition prod_uncurry {X Y Z : Type}
  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).

(** As a (trivial) example of the usefulness of currying, we can use it
    to shorten one of the examples that we saw above: *)

Example test_map1': map (plus 3) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

(** Thought exercise: before running the following commands, can you
    calculate the types of [prod_curry] and [prod_uncurry]? *)

Check @prod_curry.
Check @prod_uncurry.

Theorem uncurry_curry : forall (X Y Z : Type)
                        (f : X -> Y -> Z)
                        x y,
  prod_curry (prod_uncurry f) x y = f x y.
Proof.
  intros X Y Z f x y.
  reflexivity.
Qed.

Theorem curry_uncurry : forall (X Y Z : Type)
                        (f : (X * Y) -> Z) (p : X * Y),
  prod_uncurry (prod_curry f) p = f p.
Proof.
  intros X Y Z f p.
  induction p.
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)
(** Recall the definition of the [nth_error] function:

   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=
     match l with
     | [] => None
     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)
     end.

   Write an informal proof of the following theorem:

   forall X n l, length l = n -> @nth_error X l n = None

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

(** **** Exercise: 4 stars, advanced (church_numerals)  *)
(** This exercise explores an alternative way of defining natural
    numbers, using the so-called _Church numerals_, named after
    mathematician Alonzo Church.  We can represent a natural number
    [n] as a function that takes a function [f] as a parameter and
    returns [f] iterated [n] times. *)

Module Church.
Definition nat := forall X : Type, (X -> X) -> X -> X.

(** Let's see how to write some numbers with this notation. Iterating
    a function once should be the same as just applying it.  Thus: *)

Definition one : nat :=
  fun (X : Type) (f : X -> X) (x : X) => f x.

(** Similarly, [two] should apply [f] twice to its argument: *)

Definition two : nat :=
  fun (X : Type) (f : X -> X) (x : X) => f (f x).

(** Defining [zero] is somewhat trickier: how can we "apply a function
    zero times"?  The answer is actually simple: just return the
    argument untouched. *)

Definition zero : nat :=
  fun (X : Type) (f : X -> X) (x : X) => x.

(** More generally, a number [n] can be written as [fun X f x => f (f
    ... (f x) ...)], with [n] occurrences of [f].  Notice in
    particular how the [doit3times] function we've defined previously
    is actually just the Church representation of [3]. *)

Definition three : nat := @doit3times.

(** Complete the definitions of the following functions. Make sure
    that the corresponding unit tests pass by proving them with
    [reflexivity]. *)

(** Successor of a natural number: *)

Definition succ (n : nat) : nat :=
  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).

Example succ_1 : succ zero = one.
Proof. reflexivity. Qed.

Example succ_2 : succ one = two.
Proof. reflexivity. Qed.

Example succ_3 : succ two = three.
Proof. reflexivity. Qed.

(** Addition of two natural numbers: *)

Definition plus (n m : nat) : nat :=
  fun (X : Type) (f : X -> X) (x : X) => m X f (n X f x).

Example plus_1 : plus zero one = one.
Proof. reflexivity. Qed.

Example plus_2 : plus two three = plus three two.
Proof. reflexivity. Qed.

Example plus_3 :
  plus (plus two two) three = plus one (plus three three).
Proof. reflexivity. Qed.

(** Multiplication: *)

Definition mult (n m : nat) : nat :=
  fun (X : Type) (f : X -> X) (x : X) => m X (n X f) x.

Example mult_1 : mult one one = one.
Proof. reflexivity. Qed.

Example mult_2 : mult zero (plus three three) = zero.
Proof. reflexivity. Qed.

Example mult_3 : mult two three = plus three three.
Proof. reflexivity. Qed.

(** Exponentiation: *)

(** (_Hint_: Polymorphism plays a crucial role here.  However,
    choosing the right type to iterate over can be tricky.  If you hit
    a "Universe inconsistency" error, try iterating over a different
    type: [nat] itself is usually problematic.) *)

Definition exp (n m : nat) : nat (**:=
  fun (X : Type) (f : X -> X) (x : X) => *). Admitted.

(** Sé que tengo que multiplicar m veces a n (n * n * ... * n), pero no me
doy cuenta de cómo expresarlo en Coq. *)

Example exp_1 : exp two two = plus two two.
Proof. (* FILL IN HERE *) Admitted.

Example exp_2 : exp three two = plus (mult two (mult two two)) one.
Proof. (* FILL IN HERE *) Admitted.

Example exp_3 : exp three zero = one.
Proof. (* FILL IN HERE *) Admitted.

End Church.
(** [] *)

End Exercises.

(** $Date: 2018-01-23 21:16:07 -0500 (Tue, 23 Jan 2018) $ *)


Require Import VST.msl.base.
Require Import VST.msl.sepalg.
Require Import VST.msl.predicates_sa.

Definition covariant {B A : Type} (F: (B -> pred A) -> (B -> pred A)) : Prop :=
forall (P Q: B -> pred A), (forall x, P x |-- Q x) -> (forall x, F P x |-- F Q x).

Definition corec {B A: Type}  (F: (B -> pred A) -> (B -> pred A)) : B -> pred A :=
fun x w => forall P: B -> pred A, (forall x, F P x |-- P x) -> P x w.

Lemma corec_fold_unfold {B A}:
forall {F: (B -> pred A) -> (B -> pred A)},
       covariant F ->
        corec F = F (corec F).
Proof.
intros.
assert (forall x, F (corec F) x |-- corec F x).
Focus 2.
extensionality x.
apply pred_ext; intros w ?.
apply H1. intros x' ? ?.
eapply H.  eapply H0.
replace (F (corec F)) with (fun (x : B) (w : A) => F (corec F) x w); auto;
  (extensionality z z'; auto).  (* this line for compatibility with Coq 8.3 *)
apply H0; auto.
intros x ? ?.
intros ? ?.
specialize (H (corec F) P).
apply H1. apply H; auto.
intros x' ? ?.
apply H2; auto;
  (replace (fun (x'0 : B) (a1 : A) => P x'0 a1) with P; auto; (* compability with Coq 8.3 *)
   extensionality z z'; auto).  (* compability with Coq 8.3 *)
Qed.

Lemma corec_least_fixpoint {B A}:
forall {F: (B -> pred A) -> (B -> pred A)}, forall {P : B -> pred A},
  P = F P ->
  forall b, corec F b |-- P b.
Proof.
  intros. do 2 intro.
  apply H0 with (P := P). intros b' ? ?.
  rewrite H. apply H1.
Qed.

Lemma covariant_sepcon {B}{A} {JA: Join A}{PA: Perm_alg A}:
   forall P Q : (B -> pred A) -> (B -> pred A),
    covariant P -> covariant Q ->
    covariant (fun (x : B -> pred A) b => P x b * Q x b)%pred.
Proof.
intros. intros R S ? ?.
eapply sepcon_derives; auto.
Qed.

Lemma covariant_const {B A}:    forall P : B -> pred A, covariant (fun _ => P).
Proof.
intros. intros R S ?. auto.
Qed.

Lemma covariant_orp {B A}:  forall P Q: (B -> pred A)-> (B -> pred A),
      covariant P -> covariant Q -> covariant (fun x b => P x b || Q x b)%pred.
Proof.
intros. intros R S ? ?.
intros w [H2|H2]; [left; eapply H | right; eapply H0]; try apply H1; eauto.
Qed.

Lemma covariant_andp {B A}:  forall P Q: (B -> pred A) -> (B -> pred A),
      covariant P -> covariant Q -> covariant (fun x b => P x b && Q x b)%pred.
Proof.
intros. intros R S ? ?.
apply andp_derives; auto.
Qed.

Lemma covariant_exp {C B A}: forall F: C -> (B -> pred A) -> (B -> pred A),
  (forall c, covariant (F c)) ->
   covariant (fun P b => EX c:C, F c P b)%pred.
Proof.
intros.
repeat intro.
destruct H1 as [b ?].
exists b. specialize (H b).
unfold covariant in H.
apply (H P Q H0). auto.
Qed.

Lemma covariant_id {B A}: covariant (fun F: B -> pred A => F).
Proof.
unfold covariant; auto.
Qed.

Lemma covariant_const' {B A}:
  forall c:B,  covariant (fun (P: B -> pred A) _ => P c).
Proof.
repeat intro.
apply H; auto.
Qed.


(* Prototype implementation of a source language without types built into compiler *)

Require Import oeuf.Common.
Require Vector.
(*Require VecVec.*)

(* an index used to construct a type from the global environment *)
(* Needed to construct arrow types before we mention them *)
(* This allows arrow types as args to constructors *)
Inductive type_index (n : nat) :=
| dt : Fin.t n -> type_index n
| arrow : type_index n -> type_index n -> type_index n.

Inductive type (n : nat) :=
| datatype :
    forall
      (typ : Fin.t n)
      (ctor_args : list (list (type_index n * bool))),
      (* length (ctor_args) is num of constrs *)
      (* length (ctor_args[0]) is args to constr 0 *)
      (* The type_index is a tree which can be used to create constr arg types *)
      (* The bool is whether the argument is recursive *)
      type n
| arrowtype :
    type n -> type n -> type n.

(* type_index and type are syntax for types *)
(* We can denote them within an environment to get an actual coq Type *)

(* The global env contains the types of the program *)
(*Definition env := list Type.*)
Definition env (n : nat) := Vector.t Type n.

Fixpoint denote_type_index {n} (e : env n) (t : type_index n) : Type :=
  match t with
  | dt _ fn =>
    Vector.nth e fn
  | arrow _ t1 t2 =>
    (denote_type_index e t1) -> (denote_type_index e t2)
  end.

Fixpoint denote_type {n} (e : env n) (t : type n) : Type :=
  match t with
  | arrowtype _ t1 t2 =>
    (denote_type e t1) -> (denote_type e t2)
  | datatype _ fn _ =>
    Vector.nth e fn
  end.

(* given a return type, and a list of arguments, make the arrow type *)
Fixpoint build_application_type (ret : Type) (args : list Type) : Type :=
  match args with
  | nil => ret
  | f :: r => f -> (build_application_type ret r)
  end.

Record constructr :=
  { arg_tys : list Type;
    ret_ty : Type;
    ctor : build_application_type ret_ty arg_tys
  }.

(* TODO: maybe use symbolic rep of types to build generic version? *)
Fixpoint build_generic_application_type
         (num_type_params : nat)
         (ret_ty : Type)
         (arg_tys : list Type) : Type :=
  match num_type_params with
  | O => build_application_type ret_ty arg_tys
  | S n => Type -> (build_generic_application_type n ret_ty arg_tys)
  end.

(* TODO: is it possible to represent  *)
(*Record generic_constructr :=
  { num_type_params : nat;
    gen_arg_tys : build_application_type (list Type) (repeat Type num_type_params);
    gen_ret_ty : build_application_type Type (repeat Type num_type_params);
    ctor : build_generic_application_type num_type_params ret_ty arg_tys
  }.*)

(* TODO: we need something like a vector *)
(* except that instead of indexed by a nat *)
(* It's indexed by a vector of nats *)
Definition constr_env := list (list constructr).

Definition get_constr
           (ce : constr_env)
           (type_idx : nat) (ctor_idx : nat) : option constructr :=
  match nth_error ce type_idx with
  | Some cts =>
    nth_error cts ctor_idx
  | _ => None
  end.

Definition denote_constr_type (ct : constructr) : Type :=
  build_application_type (ret_ty ct) (arg_tys ct).

(* Denote for constructors *)
Definition denote_constr (ct : constructr) : denote_constr_type ct :=
  ctor ct.

(* example *)
Definition nil_constr (A : Type) : constructr :=
  Build_constructr (nil) (@list A) (nil).
Definition cons_constr (A : Type) : constructr :=
  Build_constructr (A :: list A :: nil) (list A) cons.

Definition list_of_bool_env : constr_env := (nil_constr bool :: cons_constr bool :: nil) :: nil.

Eval cbv in (denote_constr (nil_constr bool)).
Eval cbv in (denote_constr (cons_constr bool)).

Inductive my_type :=
| c1 : my_type
| c2 : nat -> bool -> nat -> my_type
| c3 : my_type
| c4 : my_type -> my_type.

Definition c1_constr : constructr :=
  Build_constructr nil my_type c1.
Definition c2_constr : constructr :=
  Build_constructr ((nat : Type) :: (bool : Type) :: (nat : Type) :: nil) my_type c2.
Definition c3_constr : constructr :=
  Build_constructr nil my_type c3.
Definition c4_constr : constructr :=
  Build_constructr ((my_type : Type) :: nil) my_type c4.

Eval cbv in (denote_constr c1_constr).
Eval cbv in (denote_constr c2_constr).
Eval cbv in (denote_constr c3_constr).
Eval cbv in (denote_constr c4_constr).

Record anything :=
  { T : Type;
    payload : T
  }.

Definition my_t := Build_anything _ my_type.
Definition my_c2 := Build_anything _ c2.
Definition my_t_elim := Build_anything _ my_type_rect.

Definition denote_anything (x : anything) := payload x.

Eval cbv in (denote_anything my_c2).

Eval cbv in (T my_c2).

(* TODO: how do we do eliminators? *)

(* New approach: *)
(* Expressions are very plain, don't contain types *)
(* Everywhere they would contain a type, they contain an index *)
(* denotation can now fail, when indices go out of range *)
Inductive expr :=
| constr (type_idx : nat) (* which type out of global list of types *)
         (ctor_idx : nat) (* which constructor within list of constrs for type *)
         (args : list expr) (* arguments to the constructor *)
| eliminator (type_idx : nat) (* which type out of global list of types *)
             (args : list expr) (* arguments to the eliminator *)
| var (idx : nat) (* which variable, basically debruijn index *)
| abs (e : expr) (* abstraction *)
| app (f a : expr) (* application *)
(* TODO: values? *)
.


(* The following development formalizes hard-core bits for a trapdoor permutation. This is used in the TrapdoorOT proof. *)

Require Import List.
From mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq tuple ssrfun.
From mathcomp Require Import choice path bigop fintype.
Require Import Lib.Base Ipdl.Exp Ipdl.Core String Ipdl.Lems Lib.TupleLems Ipdl.Tacs Lib.Dist Lib.Base Lib.SeqOps Pars Ipdl.Approx.

Require Import Typ Lib.SeqOps.
Module Type HCBit.

  (* We assume the trapdoor permutation is given by:
   - a length, D, of its domain;
   - a length, ek, for its evaluation keys;
   - a length, tk, for its trapdoor keys;
   - along with appropriate algorithms for sampling the trapdoor key, creating evaluation keys out of trapdoor keys, and evaluating the trapdoor permutation. *)

  Parameters (D ek tk: nat)
             (evalKey : tk.-bv -> ek.-bv)
             (sampK : Dist tk.-bv)
             (eval : ek.-bv -> D.-bv -> D.-bv)
             (evalInv : tk.-bv -> D.-bv -> D.-bv)
             (eval_cancel : forall tk, cancel (eval (evalKey tk)) (evalInv tk))
             (B : D.-bv -> bool).

  (* The real experiment for HCBit returns the tuple
    (ek, y, b),
  where ek is the evaluation key,
  y is an evaluation under ek of a random element, w; and
  b is the hard-core predicate for w. *)
  Definition HCBitReal {chan} (c_ek : chan ek.-bv) (y : chan D.-bv) (b : chan bool) :=
    c_tk <- new tk.-bv ;;
    w <- new D.-bv ;;
    pars [::
                c_tk ::= (Samp sampK);
                c_ek ::= (x <-- Read c_tk ;; Ret (evalKey x));
                w ::= (Samp (Unif ));
                y ::= (e <-- Read c_ek ;; w <-- Read w ;; Ret (eval e w));
                b ::= (x <-- Read w ;; Ret (B x : bool)) ].

  (* The 'ideal' experiment is the same shape of tuple, but uniformly random. *)
  Definition HCBitIdeal {chan} (c_ek : chan ek.-bv) (y : chan D.-bv) (b : chan bool) :=
              pars [::
                    c_ek ::= (x <-- Samp sampK;; Ret (evalKey x));
                    y ::= (Samp (Unif ));
                    b ::= (Samp (Unif ))
                        ].

  Parameter (lambda : nat).
  Parameter HCBitSecurity :
    (forall {chan : Type -> Type} (c_ek : chan ek.-bv) y b, (HCBitReal c_ek y b) =a_(lambda, err1) (HCBitIdeal c_ek y b)).

End HCBit.

Module HCBitPair (Export P : HCBit).

  (* HC Bit pair security:
   we prove that if the above two protocols are approximately equivalent, then the distribution
   (ek, y1, y2, b1, b2) is approximately equivalent to uniform. *)

  Definition HCBitPairReal {chan} (c_ek : chan ek.-bv) (y1 y2 : chan D.-bv) (b1 b2 : chan bool) :=
    c_tk <- new tk.-bv ;;
    w1 <- new D.-bv ;;
    w2 <- new D.-bv ;;
    pars [::
                c_tk ::= (Samp sampK);
                c_ek ::= (x <-- Read c_tk ;; Ret (evalKey x));
                w1 ::= (Samp (Unif ));
                w2 ::= (Samp Unif );
                y1 ::= (e <-- Read c_ek ;; w <-- Read w1 ;; Ret (eval e w));
                y2 ::= (e <-- Read c_ek ;; w <-- Read w2 ;; Ret (eval e w));
                b1 ::= (x <-- Read w1 ;; Ret (B x));
                b2 ::= (x <-- Read w2 ;; Ret (B x))
           ] .

  Definition HCBitPairIdeal {chan} (c_ek : chan ek.-bv) (y1 y2 : chan D.-bv) (b1 b2 : chan bool) :=
              pars [::
                         c_ek ::= (x <-- Samp sampK ;; Ret (evalKey x));
                         y1 ::= (Samp Unif );
                         y2 ::= (Samp Unif );
                         b1 ::= (Samp Unif);
                         b2 ::= (Samp Unif) ].

  Lemma HCBitPair_security {chan} c_ek :
    forall y1 y2 b1 b2,
      (@HCBitPairReal chan c_ek y1 y2 b1 b2) =a_(lambda, err1 +e (comp_err err1 3)) (HCBitPairIdeal c_ek y1 y2 b1 b2).
    intros.
    rewrite /HCBitPairReal.
    swap_tac 3 4.
    swap_tac 4 6.
    setoid_rewrite (pars_split 5); simpl.
    setoid_rewrite <- newComp_r.
    setoid_rewrite <- newComp.
    setoid_rewrite <- newComp.
    arewrite (HCBitSecurity c_ek y1 b1).
    rewrite /HCBitIdeal.
    rewrite newComp_r.
    setoid_rewrite <- pars_cat; simpl.
    setoid_rewrite <- pars_fold.
    rewrite EqNewExch.
    swap_tac 0 1.
    swap_tac 2 5.
    swap_tac 3 4.
    swap_tac 4 6.
    setoid_rewrite (pars_split 5); simpl.
    setoid_rewrite <- newComp.
    setoid_rewrite <- newComp.
    arewrite (HCBitSecurity c_ek y2 b2).
    rewrite /HCBitIdeal.
    rewrite pars_pars; simpl.
    symmetry.
    setoid_rewrite pars_fold.
    rewrite <- pars_cat; simpl.
    apply AEq_zero.
    align.
    done.
    rewrite add_err0.
    rewrite /comp_err /add_err //=.
    apply _.
  Qed.

  Definition withHCBitPairReal {chan} (f : chan ek.-bv -> chan D.-bv -> chan D.-bv -> chan bool -> chan bool -> ipdl) :=
    c1 <- new ek.-bv ;;
    y1 <- new D.-bv ;;
    y2 <- new D.-bv ;;
    b1 <- new bool ;;
    b2 <- new bool ;;
    pars [::
            HCBitPairReal c1 y1 y2 b1 b2;
            f c1 y1 y2 b1 b2] .

  Definition withHCBitPairIdeal {chan} (f : chan ek.-bv -> chan D.-bv -> chan D.-bv -> chan bool -> chan bool -> ipdl) :=
    c1 <- new ek.-bv ;;
    y1 <- new D.-bv ;;
    y2 <- new D.-bv ;;
    b1 <- new bool ;;
    b2 <- new bool ;;
    pars [::
            HCBitPairIdeal c1 y1 y2 b1 b2;
            f c1 y1 y2 b1 b2].

  Lemma withHCBitPairRealP {chan} f bnd `{forall c1 y1 y2 b1 b2, IPDLBnd (f c1 y1 y2 b1 b2) bnd} :
    withHCBitPairReal f =a_(lambda, comp_err (err1 +e comp_err err1 3) bnd) @withHCBitPairIdeal chan f.
    intros.
    apply AEq_new; intros.
    apply AEq_new; intros.
    apply AEq_new; intros.
    apply AEq_new; intros.
    apply AEq_new; intros.
    eapply AEq_tr.
    arewrite (HCBitPair_security c c0 c1 c2 c3).
    done.
    rewrite add_err0 addn0.
    done.
    reflexivity.
    rewrite add_err0 //=.
  Qed.

  Lemma HCBitReal_t {chan} c y b :
    @ipdl_t chan [:: tag c; tag y; tag b] (HCBitReal c y b).
    rewrite /HCBitReal; repeat type_tac.
    perm_match.
  Qed.

End HCBitPair.


Add LoadPath "C:\Users\21692\ParcoursRecherche\dossier_final\coq_parcours_recherche\znaidi22\dev\final" as lp.

Require Import  String.

Load Verbose vecteurs.

Load Verbose alphabets.

(* Bibliothèque standard pour les chaînes de caractères : voir la section
"Strings Implementation of string as list of ascii characters" de
https://coq.inria.fr/distrib/current/stdlib/
- Ascii.ascii : type inductif avec un constructeur acceptant huit booléeens
 *)

(* Front end : un plongement, un isomorphisme
 - plongement : string -> {n : nat & Vecteur Ascii n}
                          // (type existentiel ou union dépendante)
 - isomorphisme : Vecteur Ascii n -> Vecteur (Modulo MA) n
   // MA : max des codes ascii (255)
- D'après 'typeExistentiel.v', on déduit un isomorphisme entre
  {n : nat & Vecteur Ascii n} et {n : nat & Vecteur (Modulo MA) n}.
*)
Print existT.

Fixpoint ascii_traduction_String_VecteurAscii(s : string) : Vecteur Ascii.ascii (String.length s).
Proof.
  case s as [ | t r].
  - exact (vecteur_vide _) .
  - apply vecteur_cons.
    -- exact t.
    -- exact (ascii_traduction_String_VecteurAscii r).
Defined.

Definition ascii_traduction_String_UnionVecteursAscii(s : string)
  : {n : nat & Vecteur Ascii.ascii n}.
Proof.
  exists (String.length s).
  exact (ascii_traduction_String_VecteurAscii s).
Defined.

Fixpoint ascii_traduction_VecteurAscii_String{n : nat}(v : Vecteur Ascii.ascii n)
  : string.
Proof.
  case v as [ | pn tv rv].
  - exact String.EmptyString.
  - apply String.
    -- exact tv.
    -- exact (ascii_traduction_VecteurAscii_String _ rv).
Defined.

Definition ascii_traduction_UnionVecteursAscii_String
  (ve : {n : nat & Vecteur Ascii.ascii n}) : string.
Proof.
  case ve as [n v].
  exact (ascii_traduction_VecteurAscii_String v).
Defined.

Proposition ascii_plongement_String_UnionVecteursAscii :
  @fonction_egalite string string
    (ascii_traduction_String_UnionVecteursAscii
     ;; ascii_traduction_UnionVecteursAscii_String)
    id.
Proof.
  unfold fonction_egalite.
  fix HR 1.
  intro s.
  case s as [ | t r].
  - cbn.
    reflexivity.
  - unfold fonction_sequence.
    cbn.
    unfold id.
    f_equal.
    apply HR.
Qed.

(* Il n'y a pas d'isomorphisme mais seulement un plongement.
- (v : Vecteur A n) --> (s : string) --> (v' : Vecteur A (length s))
                                     --> (v : Vecteur A n) ??

Même si (length s = n), on ne peut convertir v' en (Vecteur A n).
En effet, la règle de subsomption suivante n'est pas vailde en Coq.

x : A   A = B
-------------
   x : B

Si elle l'était, la relation de typage ne serait plus décidable. *)

Definition ascii_traduction_VecteurAscii_VecteurModulo{n : nat} :
  (Vecteur Ascii.ascii n) -> (Vecteur (Modulo MAX_ASCII) n) :=
    vecteur_application (Ascii.nat_of_ascii ;; (modulo_morphismeNat MAX_ASCII)).

Definition ascii_traduction_VecteurModulo_VecteurAscii{n : nat} :
  (Vecteur (Modulo MAX_ASCII) n) -> (Vecteur Ascii.ascii n) :=
  vecteur_application ( modulo_valeur ;; Ascii.ascii_of_nat).

Proposition ascii_isomorphisme_VecteurModulo_VecteurAscii :
  forall (n : nat),
    @fonction_egalite (Vecteur (Modulo MAX_ASCII) n) (Vecteur (Modulo MAX_ASCII) n)
      (ascii_traduction_VecteurModulo_VecteurAscii
       ;; ascii_traduction_VecteurAscii_VecteurModulo)
      id.
Proof.
  unfold ascii_traduction_VecteurAscii_VecteurModulo.
  unfold ascii_traduction_VecteurModulo_VecteurAscii.
  intro n.
  Check vecteur_application_preservationSequence.
  eapply fonction_egalite_transitivite.
  apply fonction_egalite_symetrie.
  apply vecteur_application_preservationSequence.
  apply fonction_egalite_transitivite with (vecteur_application id).
  apply vecteur_application_compatibiliteEgaliteFonctionnelle.
  intro x.
  unfold fonction_sequence.
  rewrite (Ascii.nat_ascii_embedding (modulo_valeur x)
             (modulo_valeur_majoration _ x)).
  apply modulo_morphismeNat_inversibiliteAnterieure.
  apply vecteur_application_preservationIdentite.
Qed.

  (* Theorem ascii_nat_embedding :
  forall a : ascii, ascii_of_nat (nat_of_ascii a) = a.

Theorem nat_ascii_embedding :
  forall n : nat, n < 256 -> nat_of_ascii (ascii_of_nat n) = n.

Theorem nat_ascii_bounded :
  forall a : ascii, nat_of_ascii a < 256.

Proposition divEuclidienne_caracterisationReste :
  forall d, (0 < d) ->
       forall n q r, (n = q * d + r) -> (r < d)
                -> (reste n d = r).
   *)

Proposition ascii_isomorphisme_VecteurAscii_VecteurModulo :
  forall (n : nat),
    @fonction_egalite (Vecteur Ascii.ascii n) (Vecteur Ascii.ascii n)
      (ascii_traduction_VecteurAscii_VecteurModulo
       ;; ascii_traduction_VecteurModulo_VecteurAscii)
      id.
Proof.
  unfold ascii_traduction_VecteurAscii_VecteurModulo.
  unfold ascii_traduction_VecteurModulo_VecteurAscii.
  intro n.
  Check vecteur_application_preservationSequence.
  eapply fonction_egalite_transitivite.
  apply fonction_egalite_symetrie.
  apply vecteur_application_preservationSequence.
  apply fonction_egalite_transitivite with (vecteur_application id).
  apply vecteur_application_compatibiliteEgaliteFonctionnelle.
  intro x.
  unfold fonction_sequence.
  rewrite modulo_morphismeNat_valeur.
  assert(reste (Ascii.nat_of_ascii x) (S MAX_ASCII) = Ascii.nat_of_ascii x) as egR.
  {
    apply divEuclidienne_caracterisationReste with 0.
    Search(0 < S _).
    apply PeanoNat.Nat.lt_0_succ.
    reflexivity.
    apply Ascii.nat_ascii_bounded.
  }
  rewrite egR.
  apply Ascii.ascii_nat_embedding.
  apply vecteur_application_preservationIdentite.
Qed.


Require Export Relations.
Require Export List.

Module Type DEC_ORDER.
  Parameter A : Set.
  Parameter le : A -> A -> Prop.
  Parameter lt : A -> A -> Prop.
  Axiom ordered : order A le.
  Axiom lt_le_weak : forall a b:A, lt a b -> le a b.
  Axiom lt_diff : forall a b:A, lt a b -> a <> b.
  Axiom le_lt_or_eq : forall a b:A, le a b -> lt a b \/ a = b.
  Parameter lt_eq_lt_dec : forall a b:A, {lt a b} + {a = b} + {lt b a}.
End DEC_ORDER.

Module Type MORE_DEC_ORDERS.
  Parameter A : Set.
  Parameter le : A -> A -> Prop.
  Parameter lt : A -> A -> Prop.
  Axiom le_trans : transitive A le.
  Axiom le_refl : reflexive A le.
  Axiom le_antisym : antisymmetric A le.
  Axiom lt_irreflexive : forall a:A, ~ lt a a.
  Axiom lt_trans : transitive A lt.
  Axiom lt_not_le : forall a b:A, lt a b -> ~ le b a.
  Axiom le_not_lt : forall a b:A, le a b -> ~ lt b a.
  Axiom lt_intro : forall a b:A, le a b -> a <> b -> lt a b.
  Parameter le_lt_dec : forall a b:A, {le a b} + {lt b a}.
  Parameter le_lt_eq_dec : forall a b:A, le a b -> {lt a b} + {a = b}.
End MORE_DEC_ORDERS.

Module More_Dec_Orders (D: DEC_ORDER) : MORE_DEC_ORDERS with Definition
  A := D.A with Definition le := D.le with Definition lt := D.lt.
  Definition A := D.A.
  Definition le := D.le.
  Definition lt := D.lt.
  Theorem le_trans : transitive A le.
    case D.ordered.
    auto.
  Qed.

  Theorem le_refl : reflexive A le.
    case D.ordered.
    auto.
  Qed.

  Theorem le_antisym : antisymmetric A le.
    case D.ordered.
    auto.
  Qed.

  Theorem lt_intro : forall a b:A, le a b -> a <> b -> lt a b.
    intros a b H diff.
    case (D.le_lt_or_eq a b H); tauto.
  Qed.

  Theorem lt_irreflexive : forall a:A, ~ lt a a.
    intuition.
    case (D.lt_diff _ _ H); trivial.
  Qed.

  Theorem lt_not_le : forall a b:A, lt a b -> ~ le b a.
    intros a b H H0.
    absurd (a = b).
    apply D.lt_diff; trivial.
    apply le_antisym; auto; apply D.lt_le_weak; assumption.
  Qed.

  Theorem le_not_lt : forall a b:A, le a b -> ~ lt b a.
    intros a b H H0; apply (lt_not_le b a); auto.
  Qed.

  Theorem lt_trans : transitive A lt.
    unfold A, transitive in |- *.
    intros x y z H H0.
    apply (lt_intro x z).
    apply le_trans with y; apply D.lt_le_weak; assumption.
    intro e; rewrite e in H.
    absurd (y = z).
    intro e'; rewrite e' in H.
    apply (lt_irreflexive _ H).
    apply le_antisym; apply D.lt_le_weak; trivial.
  Qed.

  Definition le_lt_dec : forall a b:A, {le a b} + {lt b a}.
    intros a b; case (D.lt_eq_lt_dec a b).
    intro d; case d; auto.
    left; apply D.lt_le_weak; trivial.
    simple induction 1; left; apply le_refl.
    right; trivial.
  Defined.

  Definition le_lt_eq_dec : forall a b:A, le a b -> {lt a b} + {a = b}.
    intros a b H.
    case (D.lt_eq_lt_dec a b).
    trivial.
    intro H0; case (le_not_lt a b H H0).
  Defined.

End More_Dec_Orders.

Module List_Order (D: DEC_ORDER) <: DEC_ORDER with Definition
  A := list D.A .
  Definition A := list D.A .
  Fixpoint lt (l r : A) : Prop :=
    match l,r with
    | nil, nil => False
    | nil, _ => True
    | _, nil => False
    | el :: ll, er :: lr => (D.lt el er) \/ ((el = er)/\(lt ll lr))
    end.
  Fixpoint le (l r : A) : Prop :=
    match l,r with
    | nil, nil => True
    | nil, _ => True
    | _, nil => False
    | el :: ll, er :: lr => (D.lt el er) \/ ((el = er)/\(le ll lr))
    end.
  Module M := More_Dec_Orders D.
  Lemma ordered : order A le.
    intuition.
    unfold reflexive.
    intuition.
    induction x.
    auto with *.
    simpl.
    tauto.
    unfold transitive.
    induction x.
    simpl.
    destruct z; auto.
    simpl in *.
    destruct y.
    tauto.
    destruct z;auto.
    intros.
    intuition.
    simpl in *.
    intuition.
    left.
    eapply M.lt_trans;
    eauto.
    subst.
    tauto.
    subst.
    simpl in *.
    intuition.
    subst.
    right.
    intuition.
    eauto.
    unfold antisymmetric.
    induction x.
    destruct y.
    trivial.
    simpl in *.
    intuition.
    intuition.
    destruct y.
    simpl in *.
    tauto.
    simpl in *.
    intuition.
    apply M.lt_not_le in H1.
    intuition.
    elim H1.
    apply D.lt_le_weak.
    auto.
    subst.
    apply D.lt_diff in H1.
    tauto.
    subst.
    apply D.lt_diff in H1.
    tauto.
    clear H.
    subst.
    f_equal.
    auto.
  Qed.

  Lemma lt_diff : forall a b:A, lt a b -> a <> b.
    induction a.
    simpl in *.
    destruct b;auto.
    intuition.
    assert(nil<>a::b).
    auto with *.
    tauto.
    intros.
    simpl in *.
    destruct b;auto.
    destruct H.
    assert(a <> a1).
    apply D.lt_diff in H.
    trivial.
    intuition.
    apply H0.
    injection H1.
    trivial.
    destruct H.
    subst.
    assert(a0<>b).
    auto.
    intuition.
    apply H.
    injection H1.
    trivial.
  Qed.

  Lemma lt_le_weak : forall a b:A, lt a b -> le a b.
    induction a.
    induction b.
    auto with *.
    trivial.
    destruct b.
    trivial.
    simpl.
    intuition.
  Qed.

  Lemma le_lt_or_eq : forall a b:A, le a b -> lt a b \/ a = b.
    induction a.
    destruct b;
    tauto.
    destruct b;simpl in *.
    tauto.
    intuition.
    subst.
    ecase IHa.
    eauto.
    tauto.
    intuition.
    subst.
    tauto.
  Qed.

  Definition lt_eq_lt_dec : forall a b:A, {lt a b} + {a = b} + {lt b a}.
    induction a.
    destruct b.
    tauto.
    constructor 1.
    constructor 1.
    simpl.
    trivial.
    destruct b.
    simpl in *.
    constructor 2.
    trivial.
    simpl in *.
    assert({D.lt a a1} + {a = a1} + {D.lt a1 a}).
    apply D.lt_eq_lt_dec.
    destruct H.
    destruct s.
    tauto.
    subst.
    assert({lt a0 b} + {a0 = b} + {lt b a0}).
    apply IHa.
    destruct H.
    destruct s.
    tauto.
    subst.
    tauto.
    tauto.
    tauto.
  Defined.

End List_Order.


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

(** We prove that the following lemma ("injective pairing") is inconsistent with univalence: *)
Definition injective_pairing_statement :=
  ∏ A (B : A → UU) a (b b' : B a),
  a ,, b = a ,, b' →
  b = b'.

(** Proof sketch by Folkmar Frederik Ramcke. Formalisation by Jannis Limperg with help from Joj
   Helfer. *)

(** * Preliminaries *)

Lemma univalence_pathsinv0 {A B : UU} (p : A = B) :
  univalence _ _ (!p) = invweq (univalence _ _ p).
Proof.
  apply eqweqmap_pathsinv0.
Defined.

(** Inverting the path obtained from an equivalence is the same as inverting the equivalence. *)
Lemma pathsinv0_weqtopaths {A B : UU} (eq : A ≃ B) :
  ! (weqtopaths eq) = weqtopaths (invweq eq).
Proof.
  type_induction eq e.
  symmetry.
  refine (maponpaths _ (! univalence_pathsinv0 e) @ _).
  refine (homotinvweqweq _ _ @ _).
  refine (maponpaths _ (! homotinvweqweq _ _)).
Defined.

(** * Refutation of Injective Pairing *)

(** Boolean negation is a weak equivalence. *)
Definition negb_weq : bool ≃ bool.
Proof.
  exists negb.
  cbv. intros.
  use tpair.
  - use tpair.
    + exact (negb y).
    + induction y; apply idpath.
  - cbn. intro t.
    induction t as [b eq].
    induction b; induction eq; apply idpath.
Defined.

(** Thus, we can construct two equal pairs whose second components are different: *)
Definition negb_weq_pair
  : @paths (∑ A : UU, A → bool) (bool ,, idfun bool) (bool ,, negb).
Proof.
  refine (
    total2_paths_f (B := λ A, A → bool) (s := bool ,, idfun bool) (s' := bool ,, negb)
      (weqtopaths negb_weq) _
  ).
  refine (transportf_fun (idfun UU) (weqtopaths negb_weq) (idfun (idfun UU bool)) @ _).
  change (transportb (idfun UU) (weqtopaths negb_weq) = negb).
  refine (maponpaths _ (pathsinv0_weqtopaths _ ) @ _).
  apply weqpath_transport.
Defined.

(** By injective pairing, we get [idfun bool = negb], a contradiction. *)
Theorem no_injective_pairing :
  injective_pairing_statement -> ∅.
Proof.
  intro contra.
  specialize (contra _ _ _ _ _ negb_weq_pair).
  apply toforallpaths in contra.
  exact (nopathstruetofalse (contra true)).
Defined.

(** * Injective Pairing <-> Uniqueness of Identity Proofs *)

(** Another way to see why injective pairing cannot hold: It is logically equivalent to uniqueness
    of identity proofs, which is in turn equivalent to the K axiom and incompatible with univalence. *)

Definition uip_statement :=
  ∏ A (x y : A) (p q : x = y), p = q.

(** Injective pairing implies uniqueness of identity proofs. *)
Theorem injective_pairing_uip :
  injective_pairing_statement → uip_statement.
Proof.
  intros injpair A x y p q.
  assert (eqpair : @paths (∑ x, x = y) (x ,, p) (x ,, q)).
    { induction p. induction q. use total2_paths_f; apply idpath. }
  unfold injective_pairing_statement in injpair.
  exact (injpair _ (λ x, x = y) x p q eqpair).
Defined.

(** Uniqueness of identity proofs implies injective pairing. *)
Theorem uip_injective_pairing :
  uip_statement → injective_pairing_statement.
Proof.
  intros uip A B a b b' eqpair.
  set (eqa := base_paths _ _ eqpair).
  assert (eqb : transportf _ eqa b = b').
    { apply (fiber_paths eqpair). }
  assert (eqa_idpath : eqa = idpath _).
    { apply uip. }
  symmetry.
  etrans.
  { exact (! eqb). }
  exact (maponpaths (λ p, transportf B p b) eqa_idpath).
Defined.


From Categories Require Import Essentials.Notations.
From Categories Require Import Essentials.Types.
From Categories Require Import Essentials.Facts_Tactics.
From Categories Require Import Category.Main.
From Categories Require Import Functor.Main.
From Categories Require Import Basic_Cons.Terminal.
From Categories Require Import Ext_Cons.Arrow.
From Categories Require Import Coq_Cats.Type_Cat.Card_Restriction.
From Categories Require Export NatTrans.NatTrans NatTrans.Operations.
From Categories Require Export KanExt.Local KanExt.Global KanExt.GlobalDuality
        KanExt.GlobaltoLocal KanExt.LocaltoGlobal KanExt.LocalFacts.Main.
From Categories Require Export Cat.Terminal.

Local Open Scope functor_scope.

(** Definition of limits and colimits using right and left kan extensions
    along the functor to the terminal category. *)
Section Limit.
  Context {J C : Category} (D : J --> C).

  Definition Cone := LoKan_Cone (Functor_To_1_Cat J) D.

  Definition Cone_Morph Cn Cn' :=
    @LoKan_Cone_Morph _ _ (Functor_To_1_Cat J) _ D Cn Cn'.

  Definition Limit : Type := Local_Right_KanExt (Functor_To_1_Cat J) D.

  Definition limit_to_cone (l : Limit) : Cone := (LRKE l).

  Coercion limit_to_cone : Limit >-> Cone.

  Definition cone_to_obj (cn : Cone) : C := (cone_apex cn) _o tt.

  Coercion cone_to_obj : Cone >-> Obj.

  Definition is_Limit (Cn : Cone) :=
    is_Cone_Local_Right_KanExt (Functor_To_1_Cat J) D Cn.

  Definition is_Limit_Limit {Cn : Cone} (il : is_Limit Cn) : Limit :=
    is_Cone_Local_Right_KanExt_Local_Right_KanExt (Functor_To_1_Cat J) D il.

  Definition Limit_is_Limit {L : Limit} : is_Limit L :=
    Local_Right_KanExt_is_Cone_Local_Right_KanExt (Functor_To_1_Cat J) D L.

End Limit.

(** Limits are unique up to isomorphism. *)
Program Definition Limit_Iso {J C : Category} {D : J --> C} (l l' : Limit D) :
  (l ≃≃ l' ::> C)%isomorphism :=
  {|
    iso_morphism :=
      Trans
        (cone_morph (iso_morphism (Local_Right_KanExt_unique _ _ l l')))
        tt;
    inverse_morphism :=
      Trans
        (cone_morph (inverse_morphism (Local_Right_KanExt_unique _ _ l l')))
        tt
  |}.

Next Obligation.
Proof (
    f_equal
      (fun x : LoKan_Cone_Morph l l => Trans (cone_morph x) tt)
      (left_inverse (Local_Right_KanExt_unique _ _ l l'))
  ).

Next Obligation.
Proof (
    f_equal
      (fun x : LoKan_Cone_Morph l' l' => Trans (cone_morph x) tt)
      (right_inverse (Local_Right_KanExt_unique _ _ l l'))
  ).

(** Proposition stating that category C has all limits of cardinality
    specified by P *)
Definition Has_Restr_Limits (C : Category) (P : Card_Restriction) :=
  ∀ (J : Category) (D : J --> C), P J → P (Arrow J) → Limit D.

(** A complete category has all limits – here it has global
    right kan extension *)
Definition Complete (C : Category) :=
  ∀ J : Category, Right_KanExt (Functor_To_1_Cat J) C.

Existing Class Complete.

(** If a category is complete, we can produce all limits. *)
Definition LimitOf {C D : Category} {H : Complete D} (F : C --> D) : Limit F :=
  Global_to_Local_Right _ _ (H _) F.

(** A category having restricted limitis where the restriction always holds
is just complete. *)
Section Restricted_Limits_to_Complete.
  Context {C : Category} {P : Card_Restriction} (HRL : Has_Restr_Limits C P).

  Definition No_Restriction_Complete : (∀ t, P t) → Complete C :=
    fun All_Ps J => Local_to_Global_Right
                   _ _ (fun D => HRL _ D (All_Ps J) (All_Ps (Arrow J))).

End Restricted_Limits_to_Complete.

(** A complete category has restricted limits for any restriction. *)
Section Complete_to_Restricted_Limits.
  Context (C : Category) {CC : Complete C} (P : Card_Restriction).

  Definition Complete_Has_Restricted_Limits : Has_Restr_Limits C P :=
    fun J D _ _ => Global_to_Local_Right _ _ (CC _) D.

End Complete_to_Restricted_Limits.

(** A functor is continuous if it preserces all limits. *)
Section Continuous.
  Context
    {C D : Category}
    (CC : Complete C)
    (G : (C --> D)%functor).

  Section Cone_Conv.
    Context
      {J : Category}
      {F : (J --> C)%functor}
      (Cn : Cone F).

    Program Definition Cone_Conv : Cone (G ∘ F)%functor
      :=
        {|
          cone_apex :=
            (G ∘ (cone_apex Cn))%functor;
          cone_edge :=
            (((NatTrans_id G)
                ∘_h (cone_edge Cn)) ∘ (NatTrans_Functor_assoc _ _ _))%nattrans
        |}.

  End Cone_Conv.

  Definition Continuous :=
    ∀ (J : Category) (F : (J --> C)%functor),
      is_Cone_Local_Right_KanExt _ _ (Cone_Conv (LRKE (LimitOf F))).

End Continuous.

(** CoLimits *)

Section CoLimit.
  Context {J C : Category} (D : J --> C).

  Definition CoCone :=
    LoKan_Cone (Functor_To_1_Cat J^op) (D^op).

  Definition CoCone_Morph Cn Cn' :=
    @LoKan_Cone_Morph _ _ (Functor_To_1_Cat J^op) _ (D^op) Cn Cn'.

  Definition CoLimit := Local_Left_KanExt (Functor_To_1_Cat J) D.

  Definition is_CoLimit (Cn : CoCone) :=
    is_Cone_Local_Right_KanExt (Functor_To_1_Cat (J^op)) (D^op) Cn.

  Definition is_CoLimit_CoLimit {Cn : CoCone} (il : is_CoLimit Cn) : CoLimit :=
    is_Cone_Local_Right_KanExt_Local_Right_KanExt
      (Functor_To_1_Cat (J^op)) (D^op) il.

  Definition CoLimit_is_CoLimit {L : CoLimit} : is_CoLimit L :=
    Local_Right_KanExt_is_Cone_Local_Right_KanExt
      (Functor_To_1_Cat (J^op)) (D^op) L.

End CoLimit.

(** Proposition stating that category C has all colimits of
    cardinality specified by P *)
Definition Has_Restr_CoLimits (C : Category) (P : Card_Restriction) :=
  ∀ (J : Category) (D : J --> C), P J → P (Arrow J) → CoLimit D.

(** A cocomplete category has all colimits – here it has global
    left kan extension *)
Definition CoComplete (C : Category) :=
  ∀ J : Category, Left_KanExt (Functor_To_1_Cat J) C.

Existing Class CoComplete.

(** If a category is cocomplete, we can produce all colimits. *)
Definition CoLimitOf {C D : Category} {H : CoComplete D} (F : C --> D) :
  CoLimit F := Global_to_Local_Left _ _ (H _) F.

(** If a category is complete, its dual is cocomplete *)
Definition Complete_to_CoComplete_Op {C : Category} {CC : Complete C}
  : CoComplete (C ^op) :=
fun D => KanExt_Right_to_Left (Functor_To_1_Cat D ^op) C (CC (D ^op)%category).

(** If a category is cocomplete, its dual is complete *)
Definition CoComplete_to_Complete_Op {C : Category} {CC : CoComplete C}
  : Complete (C ^op) :=
    fun D => KanExt_Left_to_Right (Functor_To_1_Cat D ^op) C (CC (D ^op)%category).

(** A category having restricted colimitis where the restriction always holds
is just cocomplete. *)
Section Restricted_CoLimits_to_CoComplete.
  Context {C : Category} {P : Card_Restriction} (HRL : Has_Restr_CoLimits C P).

  Definition No_Restriction_CoComplete : (∀ t, P t) → CoComplete C :=
    fun All_Ps J =>
      Local_to_Global_Left _ _ (fun D => HRL _ D (All_Ps J) (All_Ps (Arrow J))).

End Restricted_CoLimits_to_CoComplete.

(** A cocomplete category has restricted colimits for any restriction. *)
Section CoComplete_to_Restricted_CoLimits.
  Context (C : Category) {CC : CoComplete C} (P : Card_Restriction).

  Definition CoComplete_Has_Restricted_CoLimits : Has_Restr_CoLimits C P :=
    fun J D _ _ => Global_to_Local_Left _ _ (CC _) D.

End CoComplete_to_Restricted_CoLimits.

(** If a category has restricted limits, its dual has restricted colomits *)
Definition Has_Restr_Limits_to_Has_Restr_CoLimits_Op
        {C : Category} {P : Card_Restriction}
        (HRL : Has_Restr_Limits C P) :
  Has_Restr_CoLimits (C ^op) P :=
  (fun (D : Category)
       (F : D --> C ^op)
       (H1 : P D)
       (H2 : P (Arrow D)) =>
     HRL
       (D ^op)%category
       (F ^op)%functor H1
       (Card_Rest_Respect P (Arrow D) (Arrow (D^op)) (Arrow_OP_Iso D) H2)).

(** If a category has restricted colimits, its dual has restricted lomits *)
Definition Has_Restr_CoLimits_to_Has_Restr_Limits_Op
        {C : Category}
        {P : Card_Restriction}
        (HRL : Has_Restr_CoLimits C P) :
  Has_Restr_Limits (C ^op) P :=
  (fun (D : Category)
       (F : D --> C ^op)
       (H1 : P D)
       (H2 : P (Arrow D)) =>
     HRL
       (D ^op)%category
       (F ^op)%functor
       H1
       (Card_Rest_Respect P (Arrow D) (Arrow (D^op)) (Arrow_OP_Iso D) H2)).

(** A functor is co-continuous if it preserces all co-limits. *)
Section CoContinuous.
  Context
    {C D : Category}
    (CC : CoComplete C)
    (G : (C --> D)%functor).

  Section CoCone_Conv.
    Context
      {J : Category}
      {F : (J --> C)%functor}
      (Cn : CoCone F).

    Program Definition CoCone_Conv : CoCone (G ∘ F)%functor
      :=
        {|
          cone_apex :=
            ((G ^op) ∘ (cone_apex Cn))%functor;
          cone_edge := _
                         (((NatTrans_id (G ^op)) ∘_h (cone_edge Cn))
                            ∘ (NatTrans_Functor_assoc _ _ _))%nattrans
        |}.

  End CoCone_Conv.

  Definition CoContinuous :=
    ∀ (J : Category) (F : (J --> C)%functor),
      is_Cone_Local_Right_KanExt _ _ (CoCone_Conv (LRKE (CoLimitOf F))).

End CoContinuous.


Require Export Coq.Unicode.Utf8.
Require Export FSub.

(******************************************************************************)
(* Subtyping relation                                                         *)
(******************************************************************************)

Inductive Sub (Γ: Env) : Ty → Ty → Prop :=
  | SA_Top {S} (wf_S: wfTy (domainEnv Γ) S) :
      Sub Γ S top
  | SA_Refl_TVar {X} :
      wfindex (domainEnv Γ) X → Sub Γ (tvar X) (tvar X)
  | SA_Trans_TVar {X T U} :
      lookup_etvar Γ X U → Sub Γ U T → Sub Γ (tvar X) T
  | SA_Arrow {T1 T2 S1 S2} :
      Sub Γ T1 S1 → Sub Γ S2 T2 → Sub Γ (tarr S1 S2) (tarr T1 T2)
  | SA_All {T1 T2 S1 S2} :
      Sub Γ T1 S1 → Sub (etvar Γ T1) S2 T2 → Sub Γ (tall S1 S2) (tall T1 T2).

(******************************************************************************)
(* Typing relation.                                                           *)
(******************************************************************************)

Inductive Typing (Γ: Env) : Tm → Ty → Prop :=
  | T_Var {y T} :
      lookup_evar Γ y T → Typing Γ (var y) T
  | T_Abs {t T1 T2} (wf_T1: wfTy (domainEnv Γ) T1) :
      Typing (evar Γ T1) t T2 →
      Typing Γ (abs T1 t) (tarr T1 T2)
  | T_App {t1 t2 T11 T12} :
      Typing Γ t1 (tarr T11 T12) → Typing Γ t2 T11 →
      Typing Γ (app t1 t2) T12
  | T_Tabs {t T1 T2} (wf_T1: wfTy (domainEnv Γ) T1) :
      Typing (etvar Γ T1) t T2 →
      Typing Γ (tabs T1 t) (tall T1 T2)
  | T_Tapp {t1 T11 T12 T2} :
      Typing Γ t1 (tall T11 T12) → Sub Γ T2 T11 →
      Typing Γ (tapp t1 T2) (tsubstTy X0 T2 T12)
  | T_Sub {t T1 T2} :
      Typing Γ t T1 → Sub Γ T1 T2 →
      Typing Γ t T2.


Require Import  month.

Definition is_January : month -> Prop :=
 month_rect (fun m => Prop)
  True
  False
  False
  False
  False
  False
  False
  False
  False
  False
  False
  False.

Eval compute in (is_January February).

Eval compute in (is_January January).

(* alternate solution *)
Reset is_January.

Definition is_January (m : month) : Prop :=
 match m with
 | January => True
 | other_month => False
 end.

Print is_January.


Require Import Reals.Rbase.
Require Import Reals.Rfunctions.
Require Import Ranalysis_reg.
Require Import Reals.Integration.
Require Import Rtrigo_def.
Require Import SeqProp.
Require Import Coquelicot.Coquelicot.

Require Import Lra Omega.
Require Import Utils.

Set Bullet Behavior "Strict Subproofs".

Local Open Scope R_scope.
Implicit Type f : R -> R.

Lemma RiemannInt_p1 f (a:R) (pr1:Riemann_integrable f a (a+1)) :
    (forall x y :R, a <= x -> y <= a+1 -> x<=y -> f y <= f x)
    -> RiemannInt pr1 <= f a .
Proof.
  intros.
  assert (pr2:Riemann_integrable (fun _ : R => f a) a (a + 1)).
  { apply continuity_implies_RiemannInt.
    - lra.
    - intros.
      apply continuity_pt_const.
      red; trivial.
  }
  generalize (@RiemannInt_P19 f (fun x => f a) a (a+1) pr1 pr2); intros HH.
  cut_to HH.
  - generalize (RiemannInt_P15 pr2).
    unfold fct_cte; intros eqq; rewrite eqq in HH; clear eqq.
    replace (f a * (a + 1 - a)) with (f a) in HH by lra.
    trivial.
  - lra.
  - intros.
    apply H; lra.
Qed.

Lemma RiemannInt_p2 f (a:R) (pr1:Riemann_integrable f a (a+1)) :
    (forall x y :R, a <= x -> y <= a+1 -> x<=y -> f y <= f x)
    -> RiemannInt pr1 >= f (a+1).
Proof.
  intros.
  assert (pr2:Riemann_integrable (fun _ : R => f (a+1)) a (a + 1)).
  { apply continuity_implies_RiemannInt.
    - lra.
    - intros.
      apply continuity_pt_const.
      red; trivial.
  }
  generalize (RiemannInt_P19 pr2 pr1); intros HH.
  cut_to HH.
  - generalize (RiemannInt_P15 pr2).
    unfold fct_cte; intros eqq; rewrite eqq in HH; clear eqq.
    replace (f (a+1) * (a + 1 - a)) with (f (a+1)) in HH by lra.
    lra.
  - lra.
  - intros.
    apply H; lra.
Qed.

Lemma RiemannInt_pn1 f (n:nat) (pr1:Riemann_integrable f 1 (2 + INR n)) :
    (forall x y :R, 1 <= x -> y <= 2 + (INR n) -> x<=y -> f y <= f x)
    -> RiemannInt pr1 <= sum_f 1 (n+1) (fun j:nat => f (INR j)).
Proof.
  revert pr1.
  induction n; simpl.
  - assert (eqq:(2 + 0)=2) by (compute; lra).
    rewrite eqq.
    intros.
    generalize (RiemannInt_p1 _ _ pr1); intros.
    cut_to H0.
    + auto.
    + intros.
      apply H; lra.
  - intros.
    replace (match n with
                                    | 0%nat => 1
                                    | S _ => INR n + 1
             end) with (INR n + 1) in *
      by repeat (destruct n; simpl; try lra).
    assert (leqs:1 <= (2 + INR n) <= (2 + match n with
                                    | 0%nat => 1
                                    | S _ => INR n + 1
                      end)).
    { destruct n.
      - simpl; split; intros; lra.
      - rewrite <- Rplus_assoc.
        split; intros; [ | lra].
        replace 1 with (1+0) by lra.
        apply Rplus_le_compat; [lra | ].
        apply pos_INR.
    }
    generalize (RiemannInt_P22 pr1 leqs); intros pr2.
    specialize (IHn pr2).
    cut_to IHn.
    + unfold sum_f in *.
      replace ((S (n + 1) - 1)%nat) with ((S n)%nat) by omega.
      replace ((n + 1 - 1)%nat) with (n%nat) in IHn by omega.
      simpl.
      assert (eqn:match n with
                  | 0%nat => 1
                  | S _ => INR n + 1
                  end = INR n + 1).
      { destruct n; trivial; simpl; lra. }
      assert (pr3:Riemann_integrable f (2 + INR n)
        (2 + match n with
             | 0%nat => 1
             | S _ => INR n + 1
             end)).
      {
        apply (@RiemannInt_P23 f 1  (2 + match n with
                                        | 0%nat => 1
                                        | S _ => INR n + 1
                                         end)); trivial.
      }
      generalize (RiemannInt_P26 pr2 pr3 pr1); intros eqr.
      rewrite <- eqr.
      clear pr1 eqr.
      apply Rplus_le_compat; trivial.
      revert pr3 H; clear.
      assert (eqn:2 + match n with
                  | 0%nat => 1
                  | S _ => INR n + 1
                  end = (2 + INR n) + 1).
      { destruct n.
        - simpl; lra.
        - lra.
      }
      rewrite eqn.
      intros pr3 H.
      replace (match (n + 1)%nat with
                      | 0%nat => 1
                      | S _ => INR (n + 1) + 1
               end) with (2 + INR n).
      * apply (RiemannInt_p1 _ _ pr3).
        intros.
        apply H; try lra.
        eapply Rle_trans; [| eapply H0].
        replace 1 with (1 + 0) by lra.
        apply Rplus_le_compat; try lra.
        apply pos_INR.
      * { assert (forall x, match x%nat with
              | 0%nat => 1
              | S _ => INR x + 1
                            end = INR x+1).
          { destruct x; [simpl | ]; lra. }
          rewrite H0.
          rewrite plus_INR.
          simpl; lra.
        }
    + intros.
      apply H; lra.
Qed.

Lemma RiemannInt_pn2 f (n:nat) (pr1:Riemann_integrable f 1 (2 + INR n)) :
    (forall x y :R, 1 <= x -> y <= (2 + INR n) -> x<=y -> f y <= f x)
    -> RiemannInt pr1 >= sum_f 2 (2+n) (fun j:nat => f (INR j)).
Proof.
  revert pr1.
  induction n; simpl.
  - assert (eqq:(2 + 0)=2) by (compute; lra).
    rewrite eqq.
    intros.
    generalize (RiemannInt_p2 _ _ pr1); intros.
    cut_to H0.
    + auto.
    + intros.
      apply H; trivial.
  - intros.
    replace (match n with
                                    | 0%nat => 1
                                    | S _ => INR n + 1
             end) with (INR n + 1) in *
      by repeat (destruct n; simpl; try lra).
    assert (leqs:1 <= (2 + INR n) <= (2 + match n with
                                    | 0%nat => 1
                                    | S _ => INR n + 1
                      end)).
    { destruct n.
      - simpl; split; intros; lra.
      - rewrite <- Rplus_assoc.
        split; intros; [ | lra].
        replace 1 with (1+0) by lra.
        apply Rplus_le_compat; [lra | ].
        apply pos_INR.
    }
    generalize (RiemannInt_P22 pr1 leqs); intros pr2.
    specialize (IHn pr2).
    cut_to IHn.
    + unfold sum_f in *.
      replace ( (S (S (S n)) - 2))%nat with ((S n)%nat) by omega.
      replace ((2 + n - 2)%nat) with (n%nat) in IHn by omega.
      simpl.
      assert (eqn:match (n + 2)%nat with
                  | 0%nat => 1
                  | S _ => INR (n + 2) + 1
                  end = INR (n + 2) + 1).
      { destruct n; simpl; lra. }
      assert (pr3:Riemann_integrable f (2 + INR n)
        (2 + match n with
             | 0%nat => 1
             | S _ => INR n + 1
             end)).
      {
        apply (@RiemannInt_P23 f 1  (2 + match n with
                                        | 0%nat => 1
                                        | S _ => INR n + 1
                                         end)); trivial.
      }
      generalize (RiemannInt_P26 pr2 pr3 pr1); intros eqr.
      rewrite <- eqr.
      clear pr1 eqr.
      apply Rplus_ge_compat; trivial.
      revert pr3 H; clear.
      assert (eqn:2 + match n with
                  | 0%nat => 1
                  | S _ => INR n + 1
                  end = (2 + INR n) + 1).
      { destruct n.
        - simpl; lra.
        - lra.
      }
      rewrite eqn.
      intros pr3 H.
      replace (match (n + 2)%nat with
                      | 0%nat => 1
                      | S _ => INR (n + 2) + 1
               end) with ((2 + INR n) + 1).
      * apply (RiemannInt_p2 _ _ pr3).
        intros.
        apply H; try lra.
        eapply Rle_trans; [| eapply H0].
        replace 1 with (1 + 0) by lra.
        apply Rplus_le_compat; try lra.
        apply pos_INR.
      * { assert (forall x, match x%nat with
              | 0%nat => 1
              | S _ => INR x + 1
                            end = INR x+1).
          { destruct x; [simpl | ]; lra. }
          rewrite H0.
          rewrite plus_INR.
          simpl; lra.
        }
    + intros.
      apply H; lra.
Qed.

Lemma RiemannInt_pn f (n:nat) (pr1:Riemann_integrable f 1 (2 + INR n)) :
    (forall x y :R, 1 <= x -> y <= 2 + (INR n) -> x<=y -> f y <= f x)
    -> sum_f 2 (2+n) (fun j:nat => f (INR j))
       <= RiemannInt pr1 <=
       sum_f 1 (n+1) (fun j:nat => f (INR j)).
Proof.
  split.
  - apply Rge_le.
    apply RiemannInt_pn2; trivial.
  - apply RiemannInt_pn1; trivial.
Qed.

Lemma ale21 n : 1 <= 2 + INR n.
Proof.
  generalize (pos_INR n); intros.
  lra.
Qed.

Lemma RiemannInt_cont_pn1 f (n:nat) :
  forall (C0:forall x:R, 1 <= x <= 2 + (INR n) -> continuity_pt f x),
    (forall x y :R, 1 <= x -> y <= 2 + (INR n) -> x<=y -> f y <= f x)
    -> RiemannInt (@continuity_implies_RiemannInt f 1 (2 + (INR n)) (ale21 n) C0) <=
       sum_f 1 (n+1) (fun j:nat => f (INR j)).
Proof.
  intros.
  apply RiemannInt_pn1; trivial.
Qed.

Lemma RiemannInt_cont_pn2 f (n:nat):
  forall (C0:forall x:R, 1 <= x <= 2 + (INR n) -> continuity_pt f x),
    (forall x y :R, 1 <= x -> y <= (2 + INR n) -> x<=y -> f y <= f x)
    -> RiemannInt (@continuity_implies_RiemannInt f 1 (2 + (INR n)) (ale21 n) C0) >=
       sum_f 2 (2+n) (fun j:nat => f (INR j)).
Proof.
  intros.
  apply RiemannInt_pn2; trivial.
Qed.

Lemma RiemannInt_cont_pn f (n:nat):
  forall (C0:forall x:R, 1 <= x <= 2 + (INR n) -> continuity_pt f x),
    (forall x y :R, 1 <= x -> y <= (2 + INR n) -> x<=y -> f y <= f x)
    ->  sum_f 2 (2+n) (fun j:nat => f (INR j))
        <= RiemannInt (@continuity_implies_RiemannInt f 1 (2 + (INR n)) (ale21 n) C0) <=
        sum_f 1 (n+1) (fun j:nat => f (INR j)).
Proof.
  split.
  - apply Rge_le.
    apply RiemannInt_cont_pn2; trivial.
  - apply RiemannInt_cont_pn1; trivial.
Qed.

Lemma sum_bound_22 n : 0 <= n -> 0 <= 2-1/(n+2) - (2-1/(n+1)) - 1/((n+2)*(n+2)).
Proof.
  intros.
  replace (2 - 1 / (n + 2) - (2 - 1 / (n + 1)) - 1 / ((n + 2) * (n + 2)))
                              with (1 / (n + 1) - 1 / (n + 2) - 1 / ((n + 2) * (n + 2))) by lra.
  field_simplify (1 / (n + 1) - 1 / (n + 2) - 1 / ((n + 2) * (n + 2))); try lra.
  rewrite (Fdiv_def Rfield).
  destruct H.
  - left.
      apply Rmult_lt_0_compat; [lra | ].
      apply Rinv_0_lt_compat.
      replace 0 with (0 + 0 + 0 + 0) by lra.
      repeat try apply Rplus_lt_compat.
      * simpl pow.
        repeat (apply Rmult_lt_0_compat; trivial).
        lra.
      * simpl pow.
        repeat (apply Rmult_lt_0_compat; trivial)
        ; lra.
      * lra.
      * lra.
  - subst.
    simpl pow.
    lra.
Qed.

Lemma sum_f_bound n : sum_f_R0 (fun i => 1 / Rsqr (INR i+1)) n <= 2 - 1 / (INR (n + 1)).
Proof.
  induction n.
  - simpl.
    unfold Rsqr.
    lra.
  - simpl.
    replace ((match n with
       | 0%nat => 1
       | S _ => INR n + 1
              end)) with (INR n + 1).
    + replace (match (n + 1)%nat with
          | 0%nat => 1
          | S _ => INR (n + 1) + 1
               end) with (INR (n + 1) + 1).
      * replace (2 - 1 / (INR (n + 1) + 1)) with (2 - 1 / INR (n + 1) + ((2 - 1 / (INR (n + 1) + 1)) - (2 - 1 / INR (n + 1)))) by lra.
        apply Rplus_le_compat; trivial.
        generalize (sum_bound_22 (INR n)); intros sb.
        cut_to sb; [| apply pos_INR].
        replace ((INR n + 1 + 1)²) with ((INR n + 2) * (INR n + 2)); [| unfold Rsqr; lra].
        { replace (INR (n + 1) + 1) with (INR (n+2)).
          - apply (Rplus_le_compat_r (1 / ((INR n + 2) * (INR n + 2)))) in sb.
            rewrite Rplus_0_l in sb.
            eapply Rle_trans; [eapply sb |].
            clear.
            replace ( 2 - 1 / (INR n + 2) - (2 - 1 / (INR n + 1)) - 1 / ((INR n + 2) * (INR n + 2)) +
                      1 / ((INR n + 2) * (INR n + 2)) ) with
                                  (( 2 - 1 / (INR n + 2) - (2 - 1 / (INR n + 1)))) by lra.
            unfold Rminus.
            repeat rewrite Rplus_assoc.
            apply Rplus_le_compat_l.
            repeat rewrite plus_INR.
            apply Rplus_le_compat_l.
            simpl; lra.
          - repeat rewrite plus_INR; simpl; lra.
        }
      * destruct n; simpl; trivial.
    + destruct n; simpl; trivial; lra.
Qed.

Definition f_inv := (fun x : R =>  / x).
Definition f_inv_sq := (fun x : R => / Rsqr x).

Lemma continuity_pt_inv_x a : 0 < a -> continuity_pt f_inv a.
Proof.
  intros.
  apply continuity_pt_inv.
  apply derivable_continuous_pt.
  apply derivable_pt_id.
  apply Rgt_not_eq.
  apply Rlt_gt; trivial.
Qed.

Lemma continuity_pt_inv_xsq a : 0 < a -> continuity_pt f_inv_sq a.
Proof.
  intros.
  apply continuity_pt_inv.
  apply derivable_continuous_pt.
  apply derivable_pt_Rsqr.
  apply Rmult_integral_contrapositive; lra.
Qed.

Lemma integrable_inv a : 1 <= a -> Riemann_integrable f_inv 1 a.
Proof.
  intros.
  apply continuity_implies_RiemannInt; trivial.
  intros.
  apply continuity_pt_inv_x; lra.
Qed.

Lemma integrable_inv_sq a : 1 <= a -> Riemann_integrable f_inv_sq 1 a.
Proof.
  intros.
  apply continuity_implies_RiemannInt; trivial.
  intros.
  apply continuity_pt_inv_xsq; lra.
Qed.

Lemma ub_sum_inv_sq (n:nat) :
   sum_f 2 (2+n) (fun j:nat => f_inv_sq (INR j))
        <= RiemannInt (@integrable_inv_sq (2 + (INR n)) (ale21 n)).
Proof.
   apply Rge_le.
   apply RiemannInt_pn2.
   intros.
   unfold f_inv_sq.
   apply Rinv_le_contravar; trivial.
   apply Rmult_lt_0_compat; lra.
   apply Rmult_le_compat; lra.
Qed.

Lemma lb_sum_inv (n:nat) :
   RiemannInt (@integrable_inv (2 + (INR n)) (ale21 n))
       <= sum_f 1 (n+1) (fun j:nat => f_inv (INR j)).
Proof.
   apply RiemannInt_pn1.
   intros.
   unfold f_inv.
   apply Rinv_le_contravar; lra.
Qed.

Lemma ln_int_unbounded : forall x:R, 0 < x -> { y | ln y - ln 1 > x}.
Proof.
  intros.
  exists (exp(x+1)).
  rewrite ln_1.
  rewrite ln_exp.
  rewrite <- (Rplus_0_r x) at 2.
  replace (1-0) with 1; lra.
Qed.

Lemma inv_int_bounded : forall x:R, 0 < x -> 1 - (/ x) < 1.
Proof.
  intros.
  rewrite <- (Rplus_0_r 1) at 2.
  apply Rplus_lt_compat_l.
  apply Ropp_lt_gt_0_contravar.
  apply Rinv_0_lt_compat; trivial.
Qed.

Lemma is_RInt_inv (b:R) (pr:1 <= b) :
    is_RInt Rinv 1 b ((ln b) - (ln 1)).
Proof.
  apply (@is_RInt_derive).
  rewrite Rmin_left by lra.
  rewrite Rmax_right; intuition.
  apply is_derive_Reals.
  apply derivable_pt_lim_ln; lra.
  rewrite Rmin_left by lra.
  rewrite Rmax_right; intuition.
  unfold continuous.
  apply continuity_pt_filterlim.
  apply continuity_pt_inv; try lra.
  apply continuity_pt_id.
Qed.

Lemma is_lim_RInt_inv0:
  is_lim (fun b => (ln b) - (ln 1)) p_infty p_infty.
Proof.
  apply is_lim_minus with (lf := p_infty) (lg := 0).
  apply is_lim_ln_p.
  apply (is_lim_ext (fun _ =>  0)).
  rewrite ln_1; trivial.
  apply is_lim_const.
  unfold is_Rbar_minus.
  simpl.
  replace (- 0) with (0) by lra.
  unfold is_Rbar_plus.
  now unfold Rbar_plus'.
Qed.

Lemma is_lim_RInt_inv:
  is_lim (fun b => (RInt Rinv 1 b)) p_infty p_infty.
Proof.
  apply (is_lim_ext_loc (fun b => (ln b) - (ln 1))).
  exists 2.
  intros.
  symmetry.
  apply is_RInt_unique.
  apply is_RInt_inv; lra.
  apply is_lim_RInt_inv0.
Qed.

Lemma is_RInt_inv_Rsqr (b:R) (pr:1 <= b) :
    is_RInt (fun x:R => / Rsqr x) 1 b (1 - 1 / b).
Proof.
  replace (1 - 1/b) with ((- Rinv b) - (- Rinv 1)).
  apply (@is_RInt_derive) with (f:= fun x => - Rinv x).
  rewrite Rmin_left by lra.
  rewrite Rmax_right by lra.
  intros.
  replace (/ (Rsqr x)) with (- (- 1 / x^2)).
  apply is_derive_opp with (f := fun x => / x).
  apply is_derive_inv with (f := id).
  apply (@is_derive_id).
  unfold id; lra.
  unfold Rsqr.
  field_simplify; trivial; lra.
  rewrite Rmin_left by lra.
  rewrite Rmax_right; intuition.
  unfold continuous.
  apply (continuity_pt_filterlim (fun x => / (Rsqr x))).
  apply continuity_pt_inv.
  unfold Rsqr.
  apply continuity_pt_mult.
  apply continuity_pt_id.
  apply continuity_pt_id.
  apply Rgt_not_eq.
  apply Rmult_gt_0_compat; lra.
  field_simplify; trivial; lra.
Qed.

Lemma is_lim_Rint_inv_Rsqr0 :
  is_lim (fun b => (1 - 1 / b)) p_infty 1.
Proof.
  apply is_lim_minus with (lf := 1) (lg := 0).
  apply is_lim_const.
  apply (is_lim_ext Rinv).
  intros.
  lra.
  replace (Finite 0) with (Rbar_inv p_infty).
  apply is_lim_inv.
  apply is_lim_id.
  discriminate.
  unfold Rbar_inv; trivial.
  compute.
  apply f_equal.
  replace (Rplus R1 (Ropp R0)) with (R1); trivial; lra.
Qed.

Lemma is_lim_Rint_inv_Rsqr :
  is_lim (fun b => RInt (fun x:R => / Rsqr x) 1 b) p_infty 1.
Proof.
  apply (is_lim_ext_loc (fun b => 1 - 1/b)).
  exists 2.
  intros.
  symmetry.
  apply is_RInt_unique.
  apply is_RInt_inv_Rsqr.
  lra.
  apply is_lim_Rint_inv_Rsqr0.
Qed.

Lemma is_RInt_gen_inv_Rsqr :
  is_RInt_gen (fun x:R => / Rsqr x) (at_point 1) (Rbar_locally' p_infty) 1.
Proof.
  apply (is_RInt_gen_ext (Derive (fun x => - / x))).
  - exists (fun a => a=1) (fun b => b>1000).
      now unfold at_point.
      unfold Rbar_locally'.
      now exists 1000.
      unfold fst, snd.
      intros.
      subst.
      rewrite Rmin_left in H1 by lra.
      rewrite Rmax_right in H1 by lra.
      assert (x0 <> 0).
      apply Rgt_not_eq; lra.
      rewrite Derive_opp.
      rewrite Derive_inv; try lra.
      rewrite Derive_id.
      unfold Rsqr.
      field_simplify; try lra.
      now auto_derive.
  - replace (1) with (0 - (-1)) at 2 by lra.
    apply is_RInt_gen_Derive.
    + exists (fun a => a=1) (fun b => b>1000).
      now unfold at_point.
      unfold Rbar_locally'.
      now exists 1000.
      intros.
      unfold fst, snd in H1.
      subst.
      rewrite Rmin_left in H1 by lra.
      rewrite Rmax_right in H1 by lra.
      assert (x0 <> 0).
      apply Rgt_not_eq; lra.
      auto_derive; try lra.
    + exists (fun a => a=1) (fun b => b>1000).
      now unfold at_point.
      unfold Rbar_locally'.
      now exists 1000.
      intros.
      unfold fst, snd in H1.
      subst.
      rewrite Rmin_left in H1 by lra.
      rewrite Rmax_right in H1 by lra.
      assert (x0 <> 0).
      apply Rgt_not_eq; lra.
      apply continuous_continuous_on with (D:=fun x => x>0).
      assert (0 < 1/2) by lra.
      exists (mkposreal (1/2) H2).
      intros.
      cut (Rabs (y0-x0) < 1/2).
      unfold Rabs.
      destruct (Rcase_abs (y0-x0)); lra.
      apply -> ball_Rabs; trivial.
      apply (continuous_on_ext (fun x => x > 0) (fun x => / Rsqr x)).
      * intros.
        assert (x <> 0).
        apply Rgt_not_eq; lra.
        rewrite Derive_opp.
        rewrite Derive_inv; try lra.
        rewrite Derive_id.
        unfold Rsqr.
        field_simplify; try lra.
        apply ex_derive_id.
      * apply continuous_on_forall.
        intros.
        apply (@ex_derive_continuous).
        auto_derive.
        apply Rgt_not_eq.
        now apply Rmult_gt_0_compat.
    + unfold filterlim, filter_le.
      intros.
      unfold filtermap, at_point.
      replace (- / 1) with (-1) by lra.
      now apply locally_singleton.
    + replace (filterlim (fun x : R => - / x) (Rbar_locally' p_infty) (locally 0)) with
          (is_lim (fun x : R => - / x) p_infty 0).
      replace (Finite 0) with (Rbar_opp 0).
      * apply is_lim_opp.
        replace (Finite 0) with (Rbar_inv p_infty).
        -- apply is_lim_inv.
           apply is_lim_id.
           discriminate.
        -- now compute.
      * compute; f_equal; lra.
      * unfold is_lim; trivial.
Qed.

(* this proves sum 1/i^2 converges to a finite limit  *)
Lemma sum_inv_sqr_bounded :
  ex_finite_lim_seq (fun n => sum_f_R0 (fun i => 1 / Rsqr (INR i + 1)) n).
Proof.
  apply ex_finite_lim_seq_incr with (M := 2).
  intros.
  simpl.
  cut (0 <
       1 / (match n with
       | 0%nat => 1
       | S _ => INR n + 1
       end + 1)²).
  lra.
  unfold Rdiv.
  rewrite (Rmult_1_l).
  apply Rinv_0_lt_compat.
  destruct n.
  compute; lra.
  replace (INR (S n) + 1 + 1) with (INR (S n) + 2) by lra.
  apply Rlt_0_sqr.
  apply Rgt_not_eq.
  cut (0 <= INR (S n)); try lra.
  apply pos_INR.
  intros.
  apply Rle_trans with (r2 := 2 - 1 / INR (n+1)) (r3 := 2).
  apply sum_f_bound.
  apply Rminus_le.
  ring_simplify.
  apply Rge_le.
  apply Ropp_0_le_ge_contravar.
  apply Rlt_le.
  unfold Rdiv.
  rewrite (Rmult_1_l).
  replace (n+1)%nat with (S n).
  rewrite S_INR.
  apply RinvN_pos.
  intuition.
Defined.

Lemma converges_2harmonic :
  exists sum:R, infinite_sum (fun i => 1 / Rsqr (INR i + 1)) sum.
Proof.
  assert (ex_finite_lim_seq (fun n => sum_f_R0 (fun i => 1 / Rsqr (INR i + 1)) n)).
  apply sum_inv_sqr_bounded.
  destruct H.
  exists x.
  apply infinite_sum_is_lim_seq; trivial.
Qed.