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

(** 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 functiofns_ (treating functions
    as data).
*)

Require Export Lists.

(* ###################################################### *)
(** * 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 things of type [X]. *)

(** With this definition, when we use the constructors [nil] and
    [cons] to build lists, we need to tell Coq the type of the
    elements in the lists we are building -- that is, [nil] and [cons]
    are now _polymorphic constructors_.  Observe the types of these
    constructors: *)

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

(** The "[forall X]" in these types can be read as an additional
    argument to the constructors that determines the expected types of
    the arguments that follow.  When [nil] and [cons] are used, these
    arguments are supplied in the same way as the others.  For
    example, the list containing [2] and [1] is written like this: *)

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

(** (We've gone back to writing [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 (or "generic")
    versions of all the list-processing functions that we wrote
    before.  Here is [length], for example: *)

(** *** *)

Fixpoint length (X:Type) (l:list X) : nat :=
  match l with
  | nil      => 0
  | cons h t => S (length X t)
  end.

(** Note that the uses of [nil] and [cons] in [match] patterns
    do not require any type annotations: Coq already knows that the list
    [l] contains elements of type [X], so there's no reason to include
    [X] in the pattern.  (More precisely, the type [X] is a parameter
    of the whole definition of [list], not of the individual
    constructors.  We'll come back to this point later.)

    As with [nil] and [cons], we can use [length] by applying it first
    to a type and then to its list argument: *)

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

(** To use our length with other kinds of lists, we simply
    instantiate it with an appropriate type parameter: *)

Example test_length2 :
    length bool (cons bool true (nil bool)) = 1.
Proof. reflexivity.  Qed.

(** *** *)
(** Let's close this subsection 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 X h (app X t l2)
  end.

Fixpoint snoc (X:Type) (l:list X) (v:X) : (list X) :=
  match l with
  | nil      => cons X v (nil X)
  | cons h t => cons X h (snoc X t v)
  end.

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

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

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

Module MumbleBaz.
(** **** 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.
(* Chan *)
(** 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]

*)
(*  Eval compute in (d (b a 5)). *)
Eval compute in (d mumble (b a 5)).
Eval compute in c.
(** [] *)

(** **** Exercise: 2 stars (baz_num_elts)  *)
(** Consider the following inductive definition: *)

Inductive baz : Type :=
   | x : baz -> baz
   | y : baz -> bool -> baz.

(** How _many_ elements does the type [baz] have?
(* FILL IN HERE *)
*)
(** [] *)

End MumbleBaz.

(* ###################################################### *)
(** *** Type Annotation Inference *)

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

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

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

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

(** It has exactly the same type type as [app].  Coq was able to
    use a process called _type inference_ to deduce what the types of
    [X], [l1], and [l2] 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 [l1] with [nil] and [cons] means it must be a [list]; 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.  You should try to find a balance in your own code between
    too many type annotations (so many that they 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 *)

(** Whenever we 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 [length] function
    above must pass along the type [X].  But just like providing
    explicit type annotations everywhere, this is heavy and verbose.
    Since the second argument to [length] is a list of [X]s, 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 figure out for yourself what
    type 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 -- and,
    indeed, the two procedures rely on the same underlying mechanisms.
    Instead of simply omitting the types of some arguments to a
    function, like
      app' X l1 l2 : list X :=
    we can also replace the types with [_], like
      app' (X : _) (l1 l2 : _) : list X :=
    which tells Coq to attempt to infer the missing information, just
    as with argument synthesis.

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

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

(** In this instance, we don't save much by writing [_] instead of
    [X].  But in many cases the difference can be significant.  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 *)

(** In fact, we can go further.  To avoid having to sprinkle [_]'s
    throughout our programs, we can tell 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.
    *)

Arguments nil {X}.
Arguments cons {X} _ _.  (* use underscore for argument position that has no name *)
Arguments length {X} l.
Arguments app {X} l1 l2.
Arguments rev {X} l.
Arguments snoc {X} l v.

(* note: no _ arguments required... *)
Definition list123'' := cons 1 (cons 2 (cons 3 nil)).
Check (length list123'').

(** *** *)

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

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

(** (Note that we didn't even have to provide a type argument to
    the recursive call to [length'']; indeed, it is invalid to provide
    one.)  We will use this style whenever possible, although we will
    continue to use use explicit [Argument] declarations for
    [Inductive] constructors. *)

(** *** *)

(** 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 this time, even though
    we've globally declared it to be [Implicit].  For example, suppose we
    write this: *)

(* Definition mynil := nil.  *)

(** If we uncomment this definition, Coq will give 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: Polymorphic Lists *)

(** **** Exercise: 2 stars, optional (poly_exercises)  *)
(** Here are a few simple exercises, just like ones in the [Lists]
    chapter, for practice with polymorphism.  Fill in the definitions
    and complete the proofs below. *)
(* TODO BC *)
Fixpoint repeat {X : Type} (n : X) (count : nat) : list X :=
  match count with
    | O => []
    | S count' => n::(repeat n count')
                   end.

Example test_repeat1:
  repeat true 2 = cons true (cons true nil).
 Proof. reflexivity. Qed.
(* BC *)
Theorem nil_app : forall X:Type, forall l:list X,
  app [] l = l.
Proof.
  intros. reflexivity.
Qed.
(* TODO BC *)
Theorem rev_snoc : forall X : Type,
                     forall v : X,
                     forall s : list X,
  rev (snoc s v) = v :: (rev s).
Proof.
  intros X v s. induction s as [| h t].
  Case "s = []". reflexivity.
  Case "s = h::t". simpl. rewrite -> IHt. simpl. reflexivity. Qed.

(* TODO AM *)
Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  intros. induction l as [| h t].
  Case "l = []". reflexivity.
  Case "l = h :: t ". simpl. rewrite -> rev_snoc. rewrite -> IHt. reflexivity.
Qed.
(* TODO BC *)
Theorem snoc_with_append : forall X : Type,
                         forall l1 l2 : list X,
                         forall v : X,
  snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).
Proof.
  intros X l1 l2 v. induction l1 as [ | h t].
  Case "l1 = []". reflexivity.
  Case "l1 = h::t". simpl. rewrite -> IHt. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** ** 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_ (or _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 pair _types_: *)

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

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

(** *** *)
(** A note of caution: 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; [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 many functional programming languages,
    it is called [zip].  We call it [combine] for consistency with
    Coq's standard library. *)
(** Note that the pair notation can be used both in expressions and in
    patterns... *)

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?)
      it prints out list (X*Y)
    - What does
        Eval compute in (combine [1;2] [false;false;true;true]).
      print?   [(1, false); (2, false)]
*)

Eval compute in (combine [1;2] [false; false; true; true]).

(** **** Exercise: 2 stars (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
    programing languages, this function is called [unzip].

    Uncomment the material below and fill in the definition of
    [split].  Make sure it passes the given unit tests. *)
(* BC *)
Fixpoint split
           {X Y : Type} (l : list (X*Y))
           : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | h :: t => match h with (hx, hy) => match (split t) with (tx, ty) =>
            ((hx :: tx), (hy :: ty)) end end
  end.

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

(* ###################################################### *)
(** ** Polymorphic Options *)

(** One last polymorphic type for now: _polymorphic options_.
    The type declaration generalizes the one for [natoption] in 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 [index] function so that it works
    with any type of lists. *)

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

Example test_index1 :    index 0 [4;5;6;7]  = Some 4.
Proof. reflexivity.  Qed.
Example test_index2 :    index  1 [[1];[2]]  = Some [2].
Proof. reflexivity.  Qed.
Example test_index3 :    index  2 [true]  = None.
Proof. reflexivity.  Qed.

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

Definition hd_opt {X : Type} (l : list X)  : option X :=
  index 0 l.

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

Check @hd_opt.

Example test_hd_opt1 :  hd_opt [1;2] = Some 1.
Proof. reflexivity. Qed.
Example test_hd_opt2 :   hd_opt  [[1];[2]]  = Some [1].
Proof. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** * Functions as Data *)
(* ###################################################### *)
(** ** Higher-Order Functions *)

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

    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.

(* ###################################################### *)
(** ** Partial Application *)

(** 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 is the same as saying that Coq primitively
    supports only one-argument functions -- do you see why?)  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.

(* ###################################################### *)
(** ** Digression: Currying *)

(** **** 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. *)
(* TODO BC *)
Definition prod_uncurry {X Y Z : Type}
  (f : X -> Y -> Z) (p : X * Y) : Z :=
  f (fst p) (snd p).

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

Check @prod_curry.
Check @prod_uncurry.

(* Chan *)
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.
  reflexivity.
Qed.

(* TODO BC *)
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. destruct p as []. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** ** Filter *)

(** Here is a useful higher-order function, which takes a list
    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])
    and "filters" 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 a little annoying 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. It is also possible to
    construct a function "on the fly" without declaring it at the top
    level or giving it a name; this is analogous to the notation we've
    been using for writing down constant lists, natural numbers, and
    so on. *)

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

(** Here is the motivating example from before, 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. *)
(* TODO BC *)

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

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

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
Proof. 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.
*)
(* Chan *)
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]).
Proof. reflexivity. Qed.
Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).
Proof. 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 (plus 3) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

(** The element types of the input and output lists need not be
    the same ([map] takes _two_ type arguments, [X] and [Y]).  This
    version of [map] 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.

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

(* TODO BC *)

Lemma map_snoc : forall (X Y : Type) (f: X -> Y) (l : list X) (x : X),
  map f (snoc l x) = snoc (map f l) (f x).
Proof.
  intros. induction l as [| h l'].
  Case "l = []". reflexivity.
  Case "l = h :: t". simpl. rewrite -> IHl'. reflexivity.
Qed.

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  intros. induction l as [| h t].
  Case "l = []". reflexivity.
  Case "l = h :: t". simpl. rewrite -> map_snoc. rewrite -> IHt. reflexivity.
Qed.

(** [] *)

(** **** Exercise: 2 stars (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].
*)
(* TODO AM *)
Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)
                   : (list Y) :=
  match l with
  | [] => []
  | h :: t => app (f h) (flat_map f t)
  end.

Example test_flat_map1:
  flat_map (fun n => [n;n;n]) [1;5;4]
  = [1; 1; 1; 5; 5; 5; 4; 4; 4].
Proof. 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))).
    Here are 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? *)

(*   Maybe counting the number of occurrences of a certain string in a list? Like
counting how many times the string "test" appears in the given list. Then
X would be of type string while Y would be an integer. *)

(* ###################################################### *)
(** ** Functions For Constructing Functions *)

(** Most of the higher-order functions we have talked about so
    far take functions as _arguments_.  Now let's look at some
    examples involving _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.

(** *** *)
(** Similarly, but a bit more interestingly, here is a function
    that takes a function [f] from numbers to some type [X], a number
    [k], and a value [x], and constructs a function that behaves
    exactly like [f] except that, when called with the argument [k],
    it returns [x]. *)

Definition override {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=
  fun (k':nat) => if beq_nat k k' then x else f k'.

(** For example, we can apply [override] twice to obtain a
    function from numbers to booleans that returns [false] on [1] and
    [3] and returns [true] on all other arguments. *)

Definition fmostlytrue := override (override ftrue 1 false) 3 false.

(** *** *)

Example override_example1 : fmostlytrue 0 = true.
Proof. reflexivity. Qed.

Example override_example2 : fmostlytrue 1 = false.
Proof. reflexivity. Qed.

Example override_example3 : fmostlytrue 2 = true.
Proof. reflexivity. Qed.

Example override_example4 : fmostlytrue 3 = false.
Proof. reflexivity. Qed.

(** *** *)

(** **** Exercise: 1 star (override_example)  *)
(** Before starting to work on the following proof, make sure you
    understand exactly what the theorem is saying and can paraphrase
    it in your own words.  The proof itself is straightforward. *)
(* TODO BC *)
Theorem override_example : forall (b:bool),
  (override (constfun b) 3 true) 2 = b.
Proof.
  intros. reflexivity.
Qed.

(** [] *)

(** We'll use function overriding heavily in parts of the rest of the
    course, and we will end up needing to know quite a bit about its
    properties.  To prove these properties, though, we need to know
    about a few more of Coq's tactics; developing these is the main
    topic of the next chapter.  For now, though, let's introduce just
    one very useful tactic that will also help us with proving
    properties of some of the other functions we have introduced in
    this chapter. *)

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

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

(** Sometimes, a proof will get stuck because Coq doesn't
    automatically expand a function call into its definition.  (This
    is a feature, not a bug: if Coq automatically expanded everything
    possible, our proof goals would quickly become enormous -- hard to
    read and slow for Coq to manipulate!) *)

Theorem unfold_example_bad : forall m n,
  3 + n = m ->
  plus3 n + 1 = m + 1.
Proof.
  intros m n H.
(* At This point, we'd like to do [rewrite -> H], since
     [plus3 n] is definitionally equal to [3 + n].  However,
     Coq doesn't automatically expand [plus3 n] to its
     definition. *)
  Abort.

(** The [unfold] tactic can be used to explicitly replace a
    defined name by the right-hand side of its definition.  *)

Theorem unfold_example : forall m n,
  3 + n = m ->
  plus3 n + 1 = m + 1.
Proof.
  intros m n H.
  unfold plus3.
  rewrite -> H.
  reflexivity.  Qed.

(** Now we can prove a first property of [override]: If we
    override a function at some argument [k] and then look up [k], we
    get back the overridden value. *)

Theorem override_eq : forall {X:Type} x k (f:nat->X),
  (override f k x) k = x.
Proof.
  intros X x k f.
  unfold override.
  rewrite <- beq_nat_refl.
  reflexivity.  Qed.

(** This proof was straightforward, but note that it requires
    [unfold] to expand the definition of [override]. *)
(* TODO AM *)
(** **** Exercise: 2 stars (override_neq)  *)
Theorem override_neq : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  f k1 = x1 ->
  beq_nat k2 k1 = false ->
  (override f k2 x2) k1 = x1.
Proof.
  intros.
  unfold override.
  rewrite -> H0. rewrite -> H.
  reflexivity.
Qed.
(** [] *)

(** As the inverse of [unfold], Coq also provides a tactic
    [fold], which can be used to "unexpand" a definition.  It is used
    much less often. *)

(* ##################################################### *)
(** * Additional 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]. *)
(* TODO BC *)
Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
Proof.
  intros X l. induction l as [ | h t].
  reflexivity. simpl. rewrite <- IHt. reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars (fold_map)  *)
(** We can also define [map] in terms of [fold].  Finish [fold_map]
    below. *)
(* TODO AM *)
Definition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=
  fold (fun x l => (f x) :: 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. unfold fold_map. induction l as [| h t].
  Case "l = []".
    reflexivity.
  Case "l = h :: t".
    simpl. rewrite IHt. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (index_informal)  *)
(** Recall the definition of the [index] function:
   Fixpoint index {X : Type} (n : nat) (l : list X) : option X :=
     match l with
     | [] => None
     | a :: l' => if beq_nat n O then Some a else index (pred n) l'
     end.
   Write an informal proof of the following theorem:
   forall X n l, length l = n -> @index X n l = None.
  essentially we will run out of the elements to pattern match
  and the first case of the pattern match gets returned
  as a result.
*)
(** [] *)

(** **** Exercise: 4 stars, advanced (church_numerals)  *)

Module Church.

(** In this exercise, we will explore 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. More formally, *)

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

(** Let's see how to write some numbers with this notation. Any
    function [f] iterated once shouldn't change. Thus, *)

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

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

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

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

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

(** More generally, a number [n] will 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 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 *)
(* TODO BC *)

(* idk how to do this Ben *)

Definition succ (n : nat) : nat :=
  admit.

Example succ_1 : succ zero = one.
Proof. Admitted.

Example succ_2 : succ one = two.
Proof. Admitted.

Example succ_3 : succ two = three.
Proof. Admitted.

(** Addition of two natural numbers *)
(* TODO AM *)
Definition plus (n m : nat) : nat :=
  (* FILL IN HERE *) admit.

Example plus_1 : plus zero one = one.
Proof. (* FILL IN HERE *) Admitted.

Example plus_2 : plus two three = plus three two.
Proof. (* FILL IN HERE *) Admitted.

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

(** Multiplication *)
(* TODO BC *)
Definition mult (n m : nat) : nat :=
  (* FILL IN HERE *) admit.

Example mult_1 : mult one one = one.
Proof. (* FILL IN HERE *) Admitted.

Example mult_2 : mult zero (plus three three) = zero.
Proof. (* FILL IN HERE *) Admitted.

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

(** 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. *)
(* TODO AM *)
Definition exp (n m : nat) : nat :=
  (* FILL IN HERE *) admit.

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.

(** [] *)

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


(**
This file is part of the Coq.Interval library for proving bounds of
real-valued expressions in Coq: http://coq-interval.gforge.inria.fr/

Copyright (C) 2015-2016, Inria

This library is governed by the CeCILL-C license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/or redistribute the library under the terms of the CeCILL-C
license as circulated by CEA, CNRS and Inria at the following URL:
http://www.cecill.info/

As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided
only with a limited warranty and the library's author, the holder of
the economic rights, and the successive licensors have only limited
liability. See the COPYING file for more details.
*)

From Coq Require Import Reals List Psatz.
From Coquelicot Require Import Coquelicot.
From mathcomp.ssreflect Require Import ssreflect ssrfun ssrbool.

Require Import Stdlib.
From Coquelicot Require Import Hierarchy.
Require Import Coquelicot.
Require Import Xreal.
Require Import Sig.
Require Import Interval.
Require Import Taylor_model.
Require Import Interval_compl.

Delimit Scope nat_scope with N.

Section Missing.

Lemma filter_prod_at_point_infty :
  forall a (P : R -> R -> Prop),
  (forall x y, a <= x <= y -> P x y) ->
  filter_prod (at_point a) (Rbar_locally p_infty)
  (fun ab : R * R => P ab.1 ab.2).
Proof.
intros a P HP.
apply (Filter_prod _ _ _ (fun x => x = a) (fun x => a < x)).
- easy.
- now exists a.
- move => x y -> /= H.
  apply HP.
  split.
  apply Rle_refl.
  now apply Rlt_le.
Qed.

Lemma filter_prod_at_point :
  forall {T F} { FF : Filter F} a (P : R -> T -> Prop) Q,
  F Q ->
  (forall y, Q y -> P a y) ->
  filter_prod (at_point a) F
  (fun ab : R * T => P ab.1 ab.2).
Proof.
intros T F FF a P Q FQ HQ.
apply: (Filter_prod _ _ _ (fun x => x = a) Q) => // .
- move => x y -> /= H.
  exact: HQ.
Qed.

Lemma filter_prod_at_point_l :
  forall {T F} { FF : Filter F} a (P : T -> R -> Prop) Q,
  F Q ->
  (forall y, Q y -> P y a) ->
  filter_prod F (at_point a)
  (fun ab : T * R => P ab.1 ab.2).
Proof.
intros T F FF a P Q FQ HQ.
apply: (Filter_prod _ _ _ Q (fun x => x = a)) => // .
- move => x y /= H ->.
  exact: HQ.
Qed.

Lemma at_point_filter_prod :
  forall {T F} { FF : Filter F} a (P : R -> T -> Prop),
  filter_prod (at_point a) F
              (fun ab : R * T => P ab.1 ab.2) ->
  F (P a).
Proof.
move => T F FF a P [Q R inQ inR H].
apply: filter_imp inR.
move => x; exact: H.
Qed.

Lemma at_point_filter_prod_l :
  forall {T F} { FF : Filter F} a (P : T -> R -> Prop),
  filter_prod F (at_point a)
              (fun ab : T * R => P ab.1 ab.2) ->
  F (fun y => P y a).
Proof.
move => T F FF a P [Q R inQ inR H].
apply: filter_imp inQ.
move => x /= HQ; apply: H => // .
Qed.

Lemma filterlimi_const_loc {T} {U : UniformSpace}
  {F : (T -> Prop) -> Prop} {FF : Filter F} :
  forall (f : T -> U -> Prop) (a : U),
  F (fun x => f x a) ->
  filterlimi f F (locally a).
Proof.
intros f a Hf P HP.
rewrite /filtermapi /=.
apply: filter_imp Hf => x H.
exists a.
apply (conj H).
exact: locally_singleton.
Qed.

Lemma filterlimi_const {T} {U : UniformSpace}
  {F : (T -> Prop) -> Prop} {FF : Filter F} :
  forall (f : T -> U -> Prop) (a : U),
  (forall x, f x a) ->
  filterlimi f F (locally a).
Proof.
intros f a Hf.
apply filterlimi_const_loc.
exact: filter_forall.
Qed.

Lemma is_RInt_gen_0 {Fa Fb : (R -> Prop) -> Prop}
  {FFa : Filter Fa} {FFb : Filter Fb} :
  is_RInt_gen (fun y => 0) Fa Fb zero.
Proof.
apply: filterlimi_const.
intros [a b].
rewrite -(scal_zero_r (b - a)).
exact: is_RInt_const.
Qed.

(* TODO: find better name *)
Lemma is_RInt_gen_filterlim {V : CompleteNormedModule R_AbsRing}
  {Fa Fb : (R -> Prop) -> Prop}
  {FFa : ProperFilter Fa} {FFb : ProperFilter Fb} (f : R -> V) (lf : V) :
  is_RInt_gen f Fa Fb lf ->
  filterlim (fun x => RInt f x.1 x.2) (filter_prod Fa Fb) (locally lf).
Proof.
move => Hlf P HlfP.
have := (Hlf P HlfP).
case => Q R HFa HFb.
econstructor.
exact: HFa.
exact: HFb.
move => x y HQx HRy.
case : (p x y HQx HRy) => x0 [HRInt HP].
by move: (is_RInt_unique f x y _ HRInt ) => ->.
Qed.

(* very inelegant *)
Lemma ex_RInt_ex_RInt_gen {V : CompleteNormedModule R_AbsRing}
  {Fa Fb : (R -> Prop) -> Prop}
  {FFa : ProperFilter Fa} {FFb : ProperFilter Fb} (f : R -> V) :
  ex_RInt_gen f Fa Fb ->
  (filter_prod Fa Fb (fun ab => ex_RInt f ab.1 ab.2)).
Proof.
intros [lf Hlf].
have := (Hlf (fun _ => True)).
case. now exists (mkposreal _ Rlt_0_1).
move => Q R HFaQ HFbR His_RInt.
apply: Filter_prod HFaQ HFbR _.
move => x y HQx HRy.
case: (His_RInt x y HQx HRy) => I [H _].
now exists I.
Qed.

(* very inelegant again *)
(* we probably want a more general lemma linking filterlim and filterlimi *)
Lemma RInt_gen_le {Fa Fb : (R -> Prop) -> Prop}
  {FFa : ProperFilter Fa} {FFb : ProperFilter Fb} (f : R -> R) (g : R -> R) (lf : R) (lg : R) :
  filter_prod Fa Fb (fun ab => fst ab <= snd ab)
  -> filter_prod Fa Fb (fun ab => forall x, fst ab <= x <= snd ab -> f x <= g x)
  -> is_RInt_gen f Fa Fb lf -> is_RInt_gen g Fa Fb lg
    -> lf <= lg.
Proof.
move => Hab Hle.
move => Hlf Hlg.
apply (filterlim_le (F := filter_prod Fa Fb) (fun x => RInt f x.1 x.2) (fun x => RInt g x.1 x.2) lf lg).
apply: (filter_imp (fun x => ex_RInt f x.1 x.2 /\ ex_RInt g x.1 x.2 /\ (forall y, x.1 <= y <= x.2 -> f y <= g y) /\ x.1 <= x.2)).
move => x [H1 [H2 [H3 H4]]].
apply: RInt_le => // .
move => x0 Hx0. have:= H3 x0. apply.
by split; now apply Rlt_le.
apply: filter_and.
apply: ex_RInt_ex_RInt_gen.
now exists lf.
apply: filter_and.
apply: ex_RInt_ex_RInt_gen.
now exists lg.
apply: filter_and => // .
exact: is_RInt_gen_filterlim.
exact: is_RInt_gen_filterlim.
Qed.

Lemma ex_RInt_gen_cauchy {V : CompleteNormedModule R_AbsRing}
  {Fb : (R -> Prop) -> Prop} {FFb : ProperFilter Fb}
  (a : R) (f : R -> V) :
  ex_RInt_gen f (at_point a) Fb <->
  (filter_prod (at_point a) Fb (fun ab => ex_RInt f ab.1 ab.2) /\
   forall eps : posreal, exists P,
     Fb P /\
     (forall u v,
        P u -> P v ->
        forall I, is_RInt f u v I -> norm I <= eps)).
Proof.
split.
- intros [If HIf].
  split.
  apply ex_RInt_ex_RInt_gen.
  now exists If.
  move => eps.
  exists (fun x => ex_RInt f a x /\ forall I, is_RInt f a x I -> ball_norm If (pos_div_2 eps) I).
  split.
    - assert (Hb: locally If (ball_norm If (pos_div_2 eps))).
      exact: locally_ball_norm.
      have toto := (HIf _ Hb).
      rewrite /filtermapi in toto.
      pose K x1 x2 :=
        exists y : V, is_RInt f x1 x2 y /\
                      ball_norm If (pos_div_2 eps) y.
      assert (titi := at_point_filter_prod a K toto).
      + apply: filter_and.
        apply: filter_imp titi => x.
        rewrite /K; case => y [Hy _].
        by eexists; exact Hy.
      apply: filter_imp titi => x [y [Hy1 Hy2]] I HI.
      rewrite -(is_RInt_unique _ _ _ _ HI).
      by rewrite  (is_RInt_unique _ _ _ _ Hy1).
    - move => u v [Hau Hu] [Hvu Hv] I HI.
      suff Hfau : is_RInt f a u (RInt f a u).
      suff Hfav : is_RInt f a v (RInt f a v).
      suff -> : (I = plus (minus If (RInt f a u)) (minus (RInt f a v) If))%R.
      rewrite /ball_norm.
      rewrite /minus.
      suff -> : (pos eps%R = (pos (pos_div_2 eps)) + (pos (pos_div_2 eps)))%R.
      apply :Rle_trans. apply: (norm_triangle).
      apply: Rle_trans.
        apply: Rplus_le_compat_l.
        move: (Hv _ Hfav). rewrite /ball_norm /minus.
        exact: Rlt_le.
      apply: Rplus_le_compat_r.
      move: (Hu _ Hfau). rewrite /ball_norm /minus.
      rewrite -{2}[If]opp_opp -opp_plus norm_opp plus_comm.
      exact: Rlt_le.
      rewrite /pos_div_2 /=; lra.
      rewrite -opp_minus -[minus (RInt f a v) If]opp_minus. rewrite -opp_plus.
      rewrite -minus_trans /minus -opp_RInt_swap. rewrite opp_plus !opp_opp.
      rewrite RInt_Chasles. symmetry; apply: is_RInt_unique => // .
      apply: ex_RInt_swap; eexists; exact: Hfau.
      eexists; exact: Hfav.
      apply: ex_RInt_swap; eexists; exact: Hfau.
      apply: RInt_correct => // .
      apply: RInt_correct => // .
- intros [Hab Hb].
  refine (proj1 (filterlimi_locally_cauchy _ _) _).
    apply: filter_imp Hab.
    move => /= [a' b'] /= HIf.
    apply (conj HIf).
    intros y1 y2 H1 H2.
    rewrite -(is_RInt_unique _ _ _ _ H1).
    exact: is_RInt_unique.
  intros eps.
  destruct (Hb (pos_div_2 eps)) as [Qb [FbQb H]].
  exists (fun ab => ab.1 = a /\ Qb ab.2).
  split.
    eexists (fun x => x = a) _.
    easy.
    exact: FbQb.
    easy.
  intros [u1 u2] [v1 v2] [-> Qbu2] [-> Qbv2] I1 I2 HI1 HI2.
  apply: norm_compat1.
  unfold minus.
  apply is_RInt_swap in HI1.
  have HC := (is_RInt_Chasles _ _ _ _ _ _ HI1 HI2).
  rewrite plus_comm.
  move: (H _ _ Qbu2 Qbv2) => /= .
  move => /(_ _ HC) Hle.
  apply: Rle_lt_trans Hle _.
  move: (cond_pos eps); lra.
Qed.

(* this proof should be much shorter *)
Lemma ex_RInt_gen_cauchy_left {V : CompleteNormedModule R_AbsRing}
  {Fb : (R -> Prop) -> Prop} {FFb : ProperFilter Fb}
  (a : R) (f : R -> V) :
  ex_RInt_gen f Fb (at_point a) <->
  (filter_prod Fb (at_point a) (fun ab => ex_RInt f ab.1 ab.2) /\
   forall eps : posreal, exists P,
     Fb P /\
     (forall u v,
        P u -> P v ->
        forall I, is_RInt f u v I -> norm I <= eps)).
Proof.
split.
- move => [I HI].
  have Hswap : ex_RInt_gen (fun x => opp (f x)) (at_point a) Fb.
    apply is_RInt_gen_swap,is_RInt_gen_opp in HI.
    by eexists; exact: HI.
  case ((proj1 (ex_RInt_gen_cauchy a (fun x => opp (f x)))) Hswap) => Hprod Hint.
  split.
  + case: Hprod => Q R HQ HR H.
    econstructor.
    * exact: HR.
    * exact: HQ.
    * move => x y Hx Hy /= .
      case: (H y x Hy Hx) => /= I1 HI1.
      eexists; apply: is_RInt_swap.
      apply: is_RInt_ext => [x1 Hx1|]; first by rewrite -[f x1]opp_opp.
      by apply: is_RInt_opp; exact: HI1.
  + move => eps; case: (Hint eps) => Peps [HFeps HRInt].
    exists Peps; split => // .
    move => u v Hu Hv I0 HI0.
    case: (HRInt u v Hu Hv (opp I0)).
    exact: is_RInt_opp.
    by rewrite norm_opp; lra.
    by rewrite norm_opp; lra.
- move => [Hfilter HInt].
  eexists.
  apply: is_RInt_gen_swap.
  case: (proj2 (ex_RInt_gen_cauchy a f)).
  split.
  + case: Hfilter => Q R HQ HR Hex.
    apply: (Filter_prod).
      * exact: HR.
      * exact: HQ.
      * move => x y Rx Qy; apply: ex_RInt_swap; exact: Hex.
  + move => eps; case: (HInt eps) => Peps [HFPeps His_RInt].
    exists Peps ;split => // .
  + move => x Hx. apply RInt_gen_correct.
    eexists. exact: Hx.
Qed.

Lemma at_right_le_at_point a b (Hab : a < b) : (filter_prod (at_right a) (at_point b) (fun x => x.1 <= x.2)).
Proof.
pose Q x := a < x < b.
pose R x := x = b.
apply: (Filter_prod _ _ _ Q R) => // .
rewrite /at_right /within /locally.
pose epsilon := (b - a).
have Hepspos : 0 < epsilon by rewrite /epsilon; lra.
pose eps := mkposreal epsilon Hepspos.
exists (pos_div_2 eps) => y.
by move/ball_to_lra; rewrite /Q; rewrite  /= /epsilon; lra.
move => x y . rewrite /Q /R /=.  lra.
Qed.

Lemma RInt_gen_pos (* {V : CompleteNormedModule R_AbsRing} *)
  {Fa : (R -> Prop) -> Prop} {FFa : ProperFilter Fa}
  {Fb : (R -> Prop) -> Prop} {FFb : ProperFilter Fb}
  (P Q : R -> Prop) (f : R -> R) (If : R) :
  (Fa P) ->
  (Fb Q) ->
  (forall x y z, P x -> Q y -> x <= z <= y -> 0 <= f z) ->
  filter_prod Fa Fb (fun ab : R * R => ab.1 <= ab.2) ->
  is_RInt_gen f Fa Fb If ->
  0 <= If.
Proof.
  move => HFa HFb Hfx Hle Hint.
  have -> : 0 = norm 0 by rewrite norm_zero.
  apply: (RInt_gen_norm (fun _ => 0) f 0 If _ _ _ Hint) => // .
  apply: (Filter_prod _ _ _ P Q HFa HFb) => x y HPx HQy x0 /= Hx0.
  rewrite norm_zero; apply: (Hfx _ _ _ HPx HQy) => // .
  exact: is_RInt_gen_0.
Qed.

Lemma RInt_gen_neg (* {V : CompleteNormedModule R_AbsRing} *)
  {Fa : (R -> Prop) -> Prop} {FFa : ProperFilter Fa}
  {Fb : (R -> Prop) -> Prop} {FFb : ProperFilter Fb}
  (P Q : R -> Prop) (f : R -> R) (If : R) :
  (Fa P) ->
  (Fb Q) ->
  (forall x y z, P x -> Q y -> x <= z <= y -> f z <= 0) ->
  filter_prod Fa Fb (fun ab : R * R => ab.1 <= ab.2) ->
  is_RInt_gen f Fa Fb If ->
  If <= 0.
Proof.
  move => HFa HFb Hfx Hle Hint.
  (* have -> : 0 = norm 0 by rewrite norm_zero. *)
  apply is_RInt_gen_opp in Hint.
  suff: 0 <= opp If.
    by rewrite /opp /=; lra.
  apply: (@RInt_gen_pos Fa FFa Fb FFb P Q (fun x => opp (f x)) (opp If)) => // .
  move => x y z HPx HQy Hxzy; move: (Hfx x y z HPx HQy Hxzy).
  by rewrite /opp /=; lra.
Qed.

End Missing.

Module IntegralTactic (F : FloatOps with Definition sensible_format := true) (I : IntervalOps with Definition bound_type := F.type with Definition precision := F.precision with Definition convert_bound := F.toX).

Module J := IntervalExt I.
Module F' := FloatExt F.

Section IntervalIntegral.

(* A fixed precision *)
Variable prec : F.precision.

Variables (f : R -> R) (iF : I.type -> I.type).

Hypothesis HiFIntExt : forall xi x, contains (I.convert xi) (Xreal x) -> contains (I.convert (iF xi)) (Xreal (f x)).

Definition integralEstimatorCorrect (estimator : I.type) ia ib :=
  forall a b,
  contains (I.convert ia) (Xreal a) ->
  contains (I.convert ib) (Xreal b) ->
  I.convert estimator <> IInan ->
  exists I : R,
  is_RInt f a b I /\
  contains (I.convert estimator) (Xreal I).

Definition integralEstimatorCorrect_infty (estimator : I.type) ia:=
  forall a,
  contains (I.convert ia) (Xreal a) ->
  I.convert estimator <> IInan ->
  exists I : R,
  is_RInt_gen f (at_point a) (Rbar_locally p_infty) I /\
  contains (I.convert estimator) (Xreal I).

Definition integralEstimatorCorrect_atsing (estimator : I.type) ia sing:=
  forall a,
  contains (I.convert ia) (Xreal a) ->
  I.convert estimator <> IInan ->
  exists I : R,
  is_RInt_gen f (at_right sing) (at_point a) I /\
  contains (I.convert estimator) (Xreal I).

Section Functions.

Variable est : I.type -> I.type -> I.type.

Definition diam x := F.sub_UP prec (I.upper x) (I.lower x).

Fixpoint integral_interval_absolute (depth : nat) (ia ib : I.type) (epsilon : F.type) :=
  let int := I.join ia ib in
  let m := I.midpoint' int in
  match I.bounded m with
    | false => I.nai
    | true =>
      match depth with
        | O => I.add prec (est ia m) (est m ib)
        | S n => let m := I.midpoint' int in
                 let halfeps := F.div2 epsilon in
                 let roughEstimate_1 := est ia m in
                 let roughEstimate_2 := est m ib in
                 match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
                   | true,true => I.add prec roughEstimate_1 roughEstimate_2
                   | true,false => let int2 := integral_interval_absolute n m ib (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
                   | false,true => let int1 := integral_interval_absolute n ia m (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
                   | false,false =>
                     let i1 := integral_interval_absolute n ia m halfeps in
                     let i2 := integral_interval_absolute n m ib halfeps in
                     I.add prec i1 i2
                 end
      end
  end.

Variable est_infty : I.type -> I.type.

Fixpoint integral_interval_absolute_infty (depth : nat) (ia: I.type) (epsilon : F.type) :=
  let int := I.upper_extent ia in
  let m := I.midpoint' int in
  match I.bounded m with
    | false => I.nai
    | true =>
      match depth with
        | O => I.add prec (est ia m) (est_infty m)
        | S n => let m := I.midpoint' int in
                 let halfeps := F.div2 epsilon in
                 let roughEstimate_1 := est ia m in
                 let roughEstimate_2 := est_infty m in
                 match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
                   | true,true => I.add prec roughEstimate_1 roughEstimate_2
                   | true,false => let int2 := integral_interval_absolute_infty n m (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
                   | false,true => let int1 := integral_interval_absolute n ia m (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
                   | false,false =>
                     let i1 := integral_interval_absolute n ia m halfeps in
                     let i2 := integral_interval_absolute_infty n m halfeps in
                     I.add prec i1 i2
                 end
      end
  end.

(* morally, est_sing ia estimates the integral from sing to a \in ia *)
Variable est_sing : I.type -> I.type.

Fixpoint integral_interval_absolute_sing (depth : nat) (ia: I.type) (iSing: I.type) (epsilon : F.type) :=
  let int := I.join iSing ia in
  let m := I.midpoint' int in
  match I.bounded m with
    | false => I.nai
    | true =>
      match depth with
        | O => I.add prec (est_sing m) (est m ia)
        | S n => let m := I.midpoint' int in
                 let halfeps := F.div2 epsilon in
                 let roughEstimate_1 := est_sing m in
                 let roughEstimate_2 := est m ia in
                 match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
                   | true,true => I.add prec roughEstimate_1 roughEstimate_2
                   | true,false => let int2 := integral_interval_absolute n m ia (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
                   | false,true => let int1 := integral_interval_absolute_sing n m iSing (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
                   | false,false =>
                     let i1 := integral_interval_absolute_sing n m iSing halfeps in
                     let i2 := integral_interval_absolute n m ia halfeps in
                     I.add prec i1 i2
                 end
      end
  end.

Definition integral_interval' (depth : nat)
    (epsilon : F.type + F.type)
    (est : unit -> I.type) (f : nat -> F.type -> I.type) :=
  let roughEst := est tt in
  match depth, epsilon with
  | O, _ => roughEst
  | S depth, inl eps =>
    if F'.le (diam roughEst) eps then roughEst
    else f depth eps
  | S depth, inr eps =>
    if I.bounded roughEst then
      let eps := F.mul_UP prec eps (I.upper (I.abs roughEst)) in
      if F'.le (diam roughEst) eps then roughEst
      else f depth eps
    else roughEst
  end.

Definition integral_interval (depth : nat) (ia ib : I.type) epsilon :=
  if I.bounded ia && I.bounded ib then
    integral_interval' depth epsilon (fun _ => est ia ib)
      (fun d => integral_interval_absolute d ia ib)
  else I.nai.

Definition integral_interval_infty (depth : nat) (ia : I.type) epsilon :=
  if I.bounded ia then
    integral_interval' depth epsilon (fun _ => est_infty ia)
      (fun d => integral_interval_absolute_infty d ia)
  else I.nai.

Definition integral_interval_sing (depth : nat) (ia : I.type) iSing epsilon :=
  if I.bounded ia then
    integral_interval' depth epsilon (fun _ => est_sing ia)
      (fun d => integral_interval_absolute_sing d ia iSing)
  else I.nai.

Lemma integral_interval_absolute_Sn {n ia ib epsilon} :
  let int := I.join ia ib in
  let m := I.midpoint' int in
  let halfeps := F.div2 epsilon in
  let roughEstimate_1 := est ia m in
  let roughEstimate_2 := est m ib in
  I.bounded m ->
  integral_interval_absolute (S n) ia ib epsilon =
  match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
    | true,true => I.add prec roughEstimate_1 roughEstimate_2
    | true,false => let int2 := integral_interval_absolute n m ib (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
    | false,true => let int1 := integral_interval_absolute n ia m (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
    | false,false =>
      let i1 := integral_interval_absolute n ia m halfeps in
      let i2 := integral_interval_absolute n m ib halfeps in
      I.add prec i1 i2
  end.
Proof.
rewrite /=.
move ->.
by [].
Qed.

Lemma integral_interval_absolute_infty_Sn {n ia epsilon} :
  let int := I.upper_extent ia in
  let m := I.midpoint' int in
  let halfeps := F.div2 epsilon in
  let roughEstimate_1 := est ia m in
  let roughEstimate_2 := est_infty m in
  I.bounded m ->
  integral_interval_absolute_infty (S n) ia epsilon =
  match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
    | true,true => I.add prec roughEstimate_1 roughEstimate_2
    | true,false => let int2 := integral_interval_absolute_infty n m (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
    | false,true => let int1 := integral_interval_absolute n ia m (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
    | false,false =>
      let i1 := integral_interval_absolute n ia m halfeps in
      let i2 := integral_interval_absolute_infty n m halfeps in
      I.add prec i1 i2
  end.
Proof.
(* rewrite /integral_interval_absolute. *)
rewrite /=.
move ->.
by [].
Qed.

Lemma integral_interval_absolute_sing_Sn {n ia iSing epsilon} :
  let int := I.join iSing ia in
  let m := I.midpoint' int in
  let halfeps := F.div2 epsilon in
  let roughEstimate_1 := est_sing m in
  let roughEstimate_2 := est m ia in
  I.bounded m ->
  integral_interval_absolute_sing (S n) ia iSing epsilon =
                 match F'.le (diam roughEstimate_1) halfeps, F'.le (diam roughEstimate_2) halfeps with
                   | true,true => I.add prec roughEstimate_1 roughEstimate_2
                   | true,false => let int2 := integral_interval_absolute n m ia (F.sub_UP prec epsilon (diam roughEstimate_1)) in I.add prec roughEstimate_1 int2
                   | false,true => let int1 := integral_interval_absolute_sing n m iSing (F.sub_UP prec epsilon (diam roughEstimate_2)) in I.add prec int1 roughEstimate_2
                   | false,false =>
                     let i1 := integral_interval_absolute_sing n m iSing halfeps in
                     let i2 := integral_interval_absolute n m ia halfeps in
                     I.add prec i1 i2
                 end.
Proof.
(* rewrite /integral_interval_absolute. *)
rewrite /=.
move ->.
by [].
Qed.

Definition naive_integral (ia ib : I.type) :=
  I.mul prec (I.sub prec ib ia) (iF (I.join ia ib)).

End Functions.

Section Proofs.

Variable estimator : I.type -> I.type -> I.type.
Variable estimator_infty : I.type -> I.type.
Variable estimator_sing : I.type -> I.type.

Lemma integral_interval_absolute_correct (depth : nat) ia ib epsilon :
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  I.bounded ia ->
  I.bounded ib ->
  integralEstimatorCorrect (integral_interval_absolute estimator depth ia ib epsilon) ia ib.
Proof.
move => base_case Hboundia Hboundib.
elim: depth epsilon ia ib Hboundia Hboundib =>
[|d Hd] epsilon ia ib Hboundia Hboundib a b Hia Hib HnotInan.
- move: HnotInan.
  set iab := (I.join ia ib).
  rewrite /integral_interval_absolute.
  set m' := I.midpoint' iab.
  case: (I.bounded m'); last by rewrite I.nai_correct.
  have [m Hm]:  (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    by apply: H2; exists a; apply: I.join_correct; left.
  move => HnotInan.
  case: (base_case ia m' a m) => // [M|Iam [Ham Cam]].
    apply: HnotInan.
    exact: I.add_propagate_l.
  case: (base_case m' ib m b) => // [M|Imb [Hmb Cmb]].
    apply: HnotInan.
    exact: I.add_propagate_r.
  exists (Iam + Imb).
  split.
  exact: is_RInt_Chasles Ham Hmb.
  exact: J.add_correct.
- set iab := (I.join ia ib).
  set m' := I.midpoint' iab.
  case Hbnded: (I.bounded m'); last first.
    by rewrite /integral_interval_absolute Hbnded I.nai_correct in HnotInan.
  rewrite (integral_interval_absolute_Sn _ Hbnded) in HnotInan |- *.
  have [m Hm]: (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    by apply: H2; exists a; apply: I.join_correct; left.
  have K: (forall i1 i2,
      I.convert i1 <> Inan ->
      I.convert i2 <> Inan ->
      integralEstimatorCorrect i1 ia m' ->
      integralEstimatorCorrect i2 m' ib ->
      exists I : R, is_RInt f a b I /\ contains (I.convert (I.add prec i1 i2)) (Xreal I)).
    move => i1 i2 N1 N2 H1 H2.
    case: (H1 a m) => {H1} // [I1 [H1 C1]].
    case: (H2 m b) => {H2} // [I2 [H2 C2]].
    exists (I1 + I2).
    split.
    exact: is_RInt_Chasles H1 H2.
    exact: J.add_correct.
  move: HnotInan.
  set b1 := (X in if X then _ else _).
  case: b1.
  + set b2 := (X in if X then _ else _).
    case Hb2 : b2 => HnotInan.
    * apply: K => // [L|L] ; apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
  + set b2 := (X in if X then _ else _).
    case: b2 => HnotInan.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
    * apply: K => // [L|L||] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
      exact: Hd.
Qed.

Lemma integral_interval_absolute_infty_correct (depth : nat) ia epsilon :
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  (forall ia, integralEstimatorCorrect_infty (estimator_infty ia) ia) ->
  I.bounded ia ->
  integralEstimatorCorrect_infty (integral_interval_absolute_infty estimator estimator_infty depth ia epsilon) ia.
Proof.
move => base_case base_case_infty Hboundia.
elim: depth epsilon ia Hboundia =>
[|d Hd] epsilon ia Hboundia a Hia HnotInan.
- move: HnotInan.
  set iab := (I.upper_extent ia).
  rewrite /integral_interval_absolute_infty.
  set m' := I.midpoint' iab.
  case: (I.bounded m'); last by rewrite I.nai_correct.
  have [m Hm]:  (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    apply: H2; exists a.
    apply: I.upper_extent_correct; first exact : Hia.
    exact: Rle_refl.
  move => HnotInan.
  case: (base_case ia m' a m) => // [M|Iam [Ham Cam]].
    apply: HnotInan.
    exact: I.add_propagate_l.
  case: (base_case_infty m' m) => // [M|Imb [Hmb Cmb]].
    apply: HnotInan.
    exact: I.add_propagate_r.
  exists (Iam + Imb).
  split.
  apply: is_RInt_gen_Chasles Hmb.
  by rewrite is_RInt_gen_at_point.
  exact: J.add_correct.
- set iab := (I.upper_extent ia).
  set m' := I.midpoint' iab.
  case Hbnded: (I.bounded m'); last first.
    by rewrite /integral_interval_absolute_infty Hbnded I.nai_correct in HnotInan.
  rewrite (integral_interval_absolute_infty_Sn _ _ Hbnded) in HnotInan |- *.
  have [m Hm]:  (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    apply: H2; exists a.
    apply: I.upper_extent_correct; first exact : Hia.
    exact: Rle_refl.
  have K: (forall i1 i2,
      I.convert i1 <> Inan ->
      I.convert i2 <> Inan ->
      integralEstimatorCorrect i1 ia m' ->
      integralEstimatorCorrect_infty i2 m' ->
      exists I : R, is_RInt_gen f (at_point a) (Rbar_locally p_infty) I /\ contains (I.convert (I.add prec i1 i2)) (Xreal I)).
    move => i1 i2 N1 N2 H1 H2.
    case: (H1 a m) => {H1} // [I1 [H1 C1]].
    case: (H2 m) => {H2} // [I2 [H2 C2]].
    exists (I1 + I2).
    split.
    apply: is_RInt_gen_Chasles H2.
    by rewrite is_RInt_gen_at_point.
    exact: J.add_correct.
  move: HnotInan.
  set b1 := (X in if X then _ else _).
  case: b1.
  + set b2 := (X in if X then _ else _).
    case Hb2 : b2 => HnotInan.
    * apply: K => // [L|L] ; apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
  + set b2 := (X in if X then _ else _).
    case: b2 => HnotInan.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: integral_interval_absolute_correct.
    * apply: K => // [L|L||] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: integral_interval_absolute_correct.
      exact: Hd.
Qed.

Lemma integral_interval_absolute_sing_correct (depth : nat) ia epsilon sing iSing :
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  (forall ia, integralEstimatorCorrect_atsing (estimator_sing ia) ia sing) ->
  I.bounded ia ->
  integralEstimatorCorrect_atsing (integral_interval_absolute_sing estimator estimator_sing depth ia iSing epsilon) ia sing.
Proof.
move => base_case base_case_sing Hboundia.
elim: depth epsilon ia Hboundia =>
[|d Hd] epsilon ia Hboundia a Hia HnotInan.
- move: HnotInan.
  set iab := (I.join iSing ia).
  rewrite /integral_interval_absolute_sing.
  set m' := I.midpoint' iab.
  case: (I.bounded m'); last by rewrite I.nai_correct.
  have [m Hm]:  (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    apply: H2; exists a.
    by apply: I.join_correct; first (right; exact : Hia).
  move => HnotInan.
  case: (base_case m' ia m a) => // [M|Iam [Ham Cam]].
    apply: HnotInan.
    exact: I.add_propagate_r.
  case: (base_case_sing m' m) => // [M|Imb [Hmb Cmb]].
    apply: HnotInan.
    exact: I.add_propagate_l.
  exists (Imb + Iam).
  split.
  apply: is_RInt_gen_Chasles; first exact: Hmb.
  by rewrite is_RInt_gen_at_point.
  exact: J.add_correct.
- set iab := (I.join iSing ia).
  set m' := I.midpoint' iab.
  case Hbnded: (I.bounded m'); last first.
    by rewrite /integral_interval_absolute_sing Hbnded I.nai_correct in HnotInan.
  rewrite (integral_interval_absolute_sing_Sn _ _ Hbnded) in HnotInan |- *.
  have [m Hm]:  (not_empty (I.convert m')).
    move: (I.midpoint'_correct iab) => [H1 H2].
    apply: H2; exists a.
    by apply: I.join_correct; first (right; exact : Hia).
  have K: (forall i1 i2,
      I.convert i1 <> Inan ->
      I.convert i2 <> Inan ->
      integralEstimatorCorrect_atsing i1 m' sing ->
      integralEstimatorCorrect i2 m' ia ->
      exists I : R, is_RInt_gen f (at_right sing) (at_point a) I /\ contains (I.convert (I.add prec i1 i2)) (Xreal I)).
    move => i1 i2 N1 N2 H1 H2.
    case: (H1 m) => {H1} // [I1 [H1 C1]].
    case: (H2 m a) => {H2} // [I2 [H2 C2]].
    exists (I1 + I2).
    split.
    apply: is_RInt_gen_Chasles; first exact: H1.
    by rewrite is_RInt_gen_at_point.
    exact: J.add_correct.
  move: HnotInan.
  set b1 := (X in if X then _ else _).
  case: b1.
  + set b2 := (X in if X then _ else _).
    case Hb2 : b2 => HnotInan.
    * apply: K => // [L|L]; apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: integral_interval_absolute_correct.
  + set b2 := (X in if X then _ else _).
    case: b2 => HnotInan.
    * apply: K => // [L|L|] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
    * apply: K => // [L|L||] ; try apply: HnotInan.
      exact: I.add_propagate_l.
      exact: I.add_propagate_r.
      exact: Hd.
      exact: integral_interval_absolute_correct.
Qed.

Lemma integral_interval_correct (depth : nat) ia ib epsilon :
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  integralEstimatorCorrect (integral_interval estimator depth ia ib epsilon) ia ib.
Proof.
move => base_case.
rewrite /integral_interval /integral_interval'.
case Hiab: (I.bounded ia);
  case Hibb: (I.bounded ib) => /=;
  try (move => a b _ _ ; by rewrite I.nai_correct).
case: depth => [|depth].
exact: base_case.
case: epsilon => [abs|rel].
set b1 := (X in if X then _ else _).
case Hb1 : b1.
exact: base_case.
exact: integral_interval_absolute_correct.
set b1 := (X in if X then _ else _).
case Hb1 : b1.
set b2 := (X in if X then _ else _).
case Hb2 : b2.
exact: base_case.
exact: integral_interval_absolute_correct.
exact: base_case.
Qed.

Lemma integral_interval_infty_correct (depth : nat) ia epsilon :
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  (forall ia, integralEstimatorCorrect_infty (estimator_infty ia) ia) ->
  integralEstimatorCorrect_infty (integral_interval_infty estimator estimator_infty depth ia epsilon) ia.
Proof.
move => base_case base_case_infty.
rewrite /integral_interval_infty /integral_interval'.
case Hiab: (I.bounded ia); last by move => a _ ; rewrite I.nai_correct.
case: depth => [|depth].
exact: base_case_infty.
case: epsilon => [abs|rel].
set b1 := (X in if X then _ else _).
case Hb1 : b1.
exact: base_case_infty.
exact: integral_interval_absolute_infty_correct.
set b1 := (X in if X then _ else _).
case Hb1 : b1.
set b2 := (X in if X then _ else _).
case Hb2 : b2.
exact: base_case_infty.
exact: integral_interval_absolute_infty_correct.
exact: base_case_infty.
Qed.

Lemma integral_interval_sing_correct (depth : nat) ia epsilon sing (iSing : I.type) :
  (forall ia, integralEstimatorCorrect_atsing (estimator_sing ia) ia sing) ->
  (forall ia ib, integralEstimatorCorrect (estimator ia ib) ia ib) ->
  integralEstimatorCorrect_atsing (integral_interval_sing estimator estimator_sing depth ia iSing epsilon) ia sing.
Proof.
move => base_case_sing base_case.
rewrite /integral_interval_sing /integral_interval'.
case Hiab: (I.bounded ia); last by move => a _ ; rewrite I.nai_correct.
case: depth => [|depth].
exact: base_case_sing.
case: epsilon => [abs|rel].
set b1 := (X in if X then _ else _).
case Hb1 : b1.
exact: base_case_sing.
exact: integral_interval_absolute_sing_correct.
set b1 := (X in if X then _ else _).
case Hb1 : b1.
set b2 := (X in if X then _ else _).
case Hb2 : b2.
exact: base_case_sing.
exact: integral_interval_absolute_sing_correct.
exact: base_case_sing.
Qed.

Lemma naive_integral_correct (ia ib: I.type) (a b : R) :
  contains (I.convert ia) (Xreal a) ->
  contains (I.convert ib) (Xreal b) ->
  ex_RInt f a b ->
  contains (I.convert (naive_integral ia ib)) (Xreal (RInt f a b)).
Proof.
move => Hcont1 Hcont2 Hfint.
rewrite /naive_integral.
apply: J.contains_RInt => //.
intros x Hx.
apply: HiFIntExt.
apply: contains_connected Hx; apply: I.join_correct.
now apply Rmin_case ; [left|right].
now apply Rmax_case ; [left|right].
Qed.

End Proofs.

End IntervalIntegral.

(* this can probably be significantly shortened *)
Lemma bounded_ex {xi} (Hne : not_empty (I.convert xi)) (Hbnded : I.bounded xi) :
  (exists l u : R, I.convert xi = Ibnd (Xreal l) (Xreal u)).
Proof.
exists (proj_val (I.convert_bound (I.lower xi))).
exists (proj_val (I.convert_bound (I.upper xi))).
have := (I.bounded_correct xi).
rewrite Hbnded; case => // .
move => Hlb Hub.
case: (I.lower_bounded_correct xi Hlb) => <- => /= HbndedProp.
case: (I.upper_bounded_correct xi Hub) => <-.
by rewrite /I.bounded_prop; apply.
Qed.

Lemma at_right_open_interval a lb : (lb < a) -> at_right lb (fun x : R => lb < x < a).
Proof.
move => Hlba. rewrite /at_right /within /locally.
pose epsilon := (a - lb).
have Hepspos : 0 < epsilon by rewrite /epsilon; lra.
pose eps := mkposreal epsilon Hepspos.
exists (pos_div_2 eps) => y.
by move/ball_to_lra; rewrite /= /epsilon; lra.
Qed.

Lemma at_right_semi_open_interval a lb : (lb < a) -> at_right lb (fun x : R => lb < x <= a).
Proof.
move => Hlba. rewrite /at_right /within /locally.
pose epsilon := (a - lb).
have Hepspos : 0 < epsilon by rewrite /epsilon; lra.
pose eps := mkposreal epsilon Hepspos.
exists (pos_div_2 eps) => y.
by move/ball_to_lra; rewrite /= /epsilon; lra.
Qed.

Definition constant_sign (S : R -> Prop) (f : R -> R) :=
  (forall x, S x -> 0 <= f x) \/ (forall x, S x -> f x <= 0).

Lemma is_RInt_le_0 :
forall (f : R -> R) (a b If : R),
a <= b ->
is_RInt f a b If -> (forall x : R, a < x < b -> f x <= 0) -> If <= 0.
Proof.
move => f a b If leab fint fneg.
suff: (0 <= -If) by lra.
apply: (is_RInt_ge_0 (fun x => - (f x)) a b _ leab).
  exact: is_RInt_opp.
by move => x Hx; move: (fneg x Hx); lra.
Qed.

Lemma is_RInt_const_sign (f : R -> R) (If : R) a b (le_ab : a <= b) :
  constant_sign (fun x => Rmin a b <= x <= Rmax a b) f ->
  is_RInt f a b If ->
  is_RInt (fun x => Rabs (f x)) a b (Rabs If).
Proof.
move => cst_sgn fint.
case: cst_sgn => [f_pos|f_neg].
- have Habs : forall x , Rmin a b < x < Rmax a b -> f x = Rabs (f x).
    by move => x Hx; rewrite Rabs_pos_eq //; apply: f_pos; lra.
  apply: (is_RInt_ext f _ _ _ _ Habs).
  rewrite Rabs_pos_eq // .
    apply: (is_RInt_ge_0 f a b If le_ab fint).
      by move => x Hx; apply: f_pos; rewrite Rmin_left ?Rmax_right; lra.
- have Habs : forall x , Rmin a b < x < Rmax a b -> - (f x) = Rabs (f x).
    by move => x Hx; rewrite Rabs_left1 //; apply: f_neg; lra.
  apply: (is_RInt_ext _ _ _ _ _ Habs).
  rewrite Rabs_left1.
  apply: is_RInt_opp => // .
  apply: (is_RInt_le_0 _ a b _ le_ab) => // .
    exact: fint.
    move => x Hx. apply: f_neg. rewrite Rmin_left ?Rmax_right; lra.
Qed.

Lemma integral_interval_mul_sing :
  forall prec sing a ia f fi g Ig Igi,
  (sing < a) ->
  contains (I.convert ia) (Xreal a) ->
  (forall x, sing <= x <= a -> contains (I.convert fi) (Xreal (f x))) ->
  I.bounded fi ->
  (forall x, sing <= x <= a -> continuous f x) ->
  (forall x, sing < x <= a -> continuous g x) ->
  constant_sign (fun x => sing < x <= a) g ->
  is_RInt_gen g (at_right sing) (at_point a) Ig ->
  contains (I.convert Igi) (Xreal Ig) ->
  exists Ifg,
  is_RInt_gen (fun t => f t * g t) (at_right sing) (at_point a) Ifg /\
  contains (I.convert (I.mul prec fi Igi)) (Xreal Ifg).
Proof.
move => prec sing a ia f fi g Ig Igi H0a Hia Hf Hfi Cf Cg Hg HIg HIg'.

have Hnefi : not_empty (I.convert fi).
{ now exists (f sing); apply Hf; split; [right|left]. }

move: (bounded_ex Hnefi Hfi) => [] l [] u HiFia.
have Hgoodorder_bis : forall x, sing <= x <= a -> l <= f x <= u.
  move => x0 Hax0.
  move: (Hf _ Hax0).
  by rewrite HiFia.
suff [Ifg HIfg]: ex_RInt_gen (fun t => f t * g t) (at_right sing) (at_point a).
  exists Ifg.
  have HIntl : is_RInt_gen (fun x => scal l (g x)) (at_right sing) (at_point a)  (scal l Ig).
    exact: is_RInt_gen_scal.
  have HIntu : is_RInt_gen (fun x => scal u (g x)) (at_right sing) (at_point a) (scal u Ig).
    exact: is_RInt_gen_scal.
  have Hgoodorder : l <= u.
    by case: (Hgoodorder_bis a); try lra.
  apply: (conj HIfg).

  case: Hg => [Hg|Hg]; last first.

  apply: (contains_connected _ (scal u Ig) (scal l Ig)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: (conj _ (Rle_refl _)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: (conj (Rle_refl _)).
  split.
    apply: (@RInt_gen_le (at_right sing) (at_point a) _ _ (fun x => scal u (g x)) (fun x => scal (f x) (g x))  _ _) => // .
      exact: at_right_le_at_point.
    apply: (filter_prod_at_point_l a (fun x y => forall z, x <= z <= y -> _ <= _) (fun z => sing < z < a)).
      exact: at_right_open_interval.
    by move => y Hy z Hz; apply: Rmult_le_compat_neg_r; case: (Hg z) (Hgoodorder_bis z); lra.

    apply: (@RInt_gen_le (at_right sing) (at_point a) _ _ (fun x => scal (f x) (g x)) (fun x => scal l (g x))  _ _) => // .
      exact: at_right_le_at_point.
    apply: (filter_prod_at_point_l a (fun x y => forall z, x <= z <= y -> _ <= _) (fun z => sing < z < a)).
      exact: at_right_open_interval.
    by move => y Hy z Hz; apply: Rmult_le_compat_neg_r; case: (Hg z) (Hgoodorder_bis z); lra.

  (* second case: 0 <= g x *)
      apply: (contains_connected _ (scal l Ig) (scal u Ig)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: (conj (Rle_refl _)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: (conj _ (Rle_refl _)).
  split.
    apply: (@RInt_gen_le (at_right sing) (at_point a) _ _ (fun x => scal l (g x)) (fun x => scal (f x) (g x))  _ _) => // .
      exact: at_right_le_at_point.
    apply: (filter_prod_at_point_l a (fun x y => forall z, x <= z <= y -> _ <= _) (fun z => sing < z < a)).
      exact: at_right_open_interval.
    by move => y Hy z Hz; apply: Rmult_le_compat_r; case: (Hg z) (Hgoodorder_bis z); lra.

    apply: (@RInt_gen_le (at_right sing) (at_point a) _ _ (fun x => scal (f x) (g x)) (fun x => scal u (g x))  _ _) => // .
      exact: at_right_le_at_point.
    apply: (filter_prod_at_point_l a (fun x y => forall z, x <= z <= y -> _ <= _) (fun z => sing < z < a)).
      exact: at_right_open_interval.
    by move => y Hy z Hz; apply: Rmult_le_compat_r; case: (Hg z) (Hgoodorder_bis z); lra.

refine (proj2 (ex_RInt_gen_cauchy_left _ _) _).
split.
- apply: filter_prod_at_point_l; first exact: (at_right_open_interval a).
  move => y Hxay; apply: ex_RInt_continuous => z Hz.
  rewrite Rmin_left in Hz; last by lra.
  rewrite Rmax_right in Hz; last by lra.
  apply: continuous_mult.
    by apply: Cf; lra.
    by apply: Cg; lra.
- move => eps.
  set eps1 := eps / (1 + Rmax (Rabs l) (Rabs u)).
  have Hmaxpos : 1 + Rmax (Rabs l) (Rabs u) > 0.
    by rewrite /Rmax; case: Rle_dec; move: (Rabs_pos u) (Rabs_pos l); lra.
  have eps1_pos : 0 < eps1.
    by apply: RIneq.Rdiv_lt_0_compat => // ; first apply: cond_pos eps.
  set pos_eps1 := mkposreal eps1 eps1_pos.
  case: (proj1 (ex_RInt_gen_cauchy_left _ _) (ex_intro _ _  HIg)) => Hexg Heps.
  case: (Heps (pos_eps1)) => Peps1 [HPinf HPint].
  have HPge : at_right sing (fun x => sing < x < a).
    exact: at_right_open_interval.
  assert(Hand := filter_and _ _ (at_point_filter_prod_l _ _ Hexg) HPinf).
  assert(Hand1 := filter_and _ _ Hand HPge).
  eexists; split. exact: Hand1.
  move => u0 v0 [[Hu1 Hu2] Hule] [[Hv1 Hv2] Hvle] I HisInt.
  wlog : I u0 v0 Hv1 Hv2 Hvle HisInt Hu1 Hu2 Hule / (u0 <= v0).
    move => Hwlog.
    case: (Rle_dec v0 u0) => Huv; last first.
      by apply: (Hwlog _ u0 v0 Hv1) => // ; lra.
    rewrite -norm_opp.
    apply: (Hwlog (opp I) v0 u0) => // .
    exact: is_RInt_swap.
  move => Hu0v0.

  have [Ig' HIg'']: ex_RInt g u0 v0.
    apply: ex_RInt_Chasles. exact: Hu1.
    exact: ex_RInt_swap.
  move: (HPint u0 v0 Hu2 Hv2 Ig' HIg'') => {HPint} HPint.
  suff Hineq: norm I <= (1 + Rmax (Rabs l) (Rabs u)) * norm Ig'.
    apply: Rle_trans Hineq _.
    rewrite /pos_eps1 /eps1 /=  in HPint.
    have ->: eps = (1 + Rmax (Rabs l) (Rabs u)) * (eps / (1 + Rmax (Rabs l) (Rabs u))) :> R .
      by field; lra.
    by apply: Rmult_le_compat_l HPint; lra.
  apply: norm_RInt_le HisInt _; first lra.
    move => x Hx.
    2: {
      apply: is_RInt_scal.
      apply: (is_RInt_const_sign g) => // .
        case: Hg => [gpos | gneg]; [left|right] => x Hx.
          by apply: gpos; move: Hx; rewrite Rmin_left ?Rmax_right; lra.
        by apply: gneg; move: Hx; rewrite Rmin_left ?Rmax_right; lra.
    }
  rewrite /=.
  eapply Rle_trans.
    exact: norm_scal.
  rewrite /norm /= /abs /= .
  apply: Rmult_le_compat_r; first exact: Rabs_pos.
  have Hax : sing <= x <= a by lra.
  suff: Rabs (f x) <= Rmax (Rabs l) (Rabs u) by lra.
    by apply: RmaxAbs; move: (Hgoodorder_bis x Hax) ;lra.
Qed.

Lemma integral_interval_mul_zero :
  forall prec a ia f fi g Ig Igi,
  (0 < a) ->
  contains (I.convert ia) (Xreal a) ->
  (forall x, 0 <= x <= a -> contains (I.convert fi) (Xreal (f x))) ->
  I.bounded fi ->
  (forall x, 0 <= x <= a -> continuous f x) ->
  (forall x, 0 < x <= a -> continuous g x) ->
  constant_sign (fun x => 0 < x <= a) g ->
  is_RInt_gen g (at_right 0) (at_point a) Ig ->
  contains (I.convert Igi) (Xreal Ig) ->
  exists Ifg,
  is_RInt_gen (fun t => f t * g t) (at_right 0) (at_point a) Ifg /\
  contains (I.convert (I.mul prec fi Igi)) (Xreal Ifg).
Proof.
move => prec a ia f fi g Ig Igi H0a Hia Hf Hfi Cf Cg Hg HIg HIg'.
apply: (integral_interval_mul_sing) => // ; last exact: HIg'; last exact: HIg.
exact: Hia.
Qed.

Lemma integral_interval_mul_infty :
  forall prec a ia f fi g Ig Igi,
  contains (I.convert ia) (Xreal a) ->
  (forall x, a <= x -> contains (I.convert fi) (Xreal (f x))) ->
  I.bounded fi ->
  (forall x, a <= x -> continuous f x) ->
  (forall x, a <= x -> continuous g x) ->
  (forall x, a <= x -> 0 <= g x) ->
  is_RInt_gen g (at_point a) (Rbar_locally p_infty) Ig ->
  contains (I.convert Igi) (Xreal Ig) ->
  exists Ifg,
  is_RInt_gen (fun t => f t * g t) (at_point a) (Rbar_locally p_infty) Ifg /\
  contains (I.convert (I.mul prec fi Igi)) (Xreal Ifg).
Proof.
move => prec a ia f fi g Ig Igi Hia Hf Hfi Cf Cg Hg HIg HIg'.
have Hnefi : not_empty (I.convert fi).
{ now exists (f a); apply Hf; right. }
move: (bounded_ex Hnefi Hfi) => [] l [] u HiFia.
have Hgoodorder_bis : forall x, a <= x -> l <= f x <= u.
  move => x0 Hax0.
  move: (Hf _ Hax0).
  by rewrite HiFia.
suff [Ifg HIfg]: ex_RInt_gen (fun t => f t * g t) (at_point a) (Rbar_locally p_infty).
  exists Ifg.
  have HIntl : is_RInt_gen (fun x => scal l (g x)) (at_point a) (Rbar_locally p_infty) (scal l Ig).
    by apply: is_RInt_gen_scal.
  have HIntu : is_RInt_gen (fun x => scal u (g x)) (at_point a) (Rbar_locally p_infty) (scal u Ig).
    by apply: is_RInt_gen_scal.
  have Hgoodorder : l <= u.
    move: (Hgoodorder_bis a (Rle_refl a)).
    move => [H1 H2].
    exact: Rle_trans H1 H2.
  have intgpos : 0 <= Ig.
    apply: (@RInt_gen_pos (at_point a) _ (Rbar_locally p_infty) _ (fun x => x = a) (fun y => y > a) g) => // .
      by rewrite /= ; exists a => x; lra.
    by move => x y z Hxa Hya Hxz; apply: Hg; lra.
    now apply filter_prod_at_point_infty.
  apply: (conj HIfg).
  apply: (contains_connected _ (scal l Ig) (scal u Ig)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: (conj (Rle_refl _)).
  + apply: J.mul_correct => // .
    rewrite HiFia.
    exact: conj (Rle_refl _).
  split.
    apply: (@RInt_gen_le (at_point a) (Rbar_locally p_infty) _ _ (fun x => scal l (g x)) (fun x => scal (f x) (g x)) _ _) => // .
      now apply filter_prod_at_point_infty. (* now and by behave differently here *)
    apply (filter_prod_at_point_infty a (fun x y => forall z, x <= z <= y -> _ <= _)).
    move => m n [Hm _] o [Ho _].
    rewrite /scal /= /mult /= .
    apply: Rmult_le_compat_r => // .
      apply Hg.
      now apply Rle_trans with m.
    apply Hgoodorder_bis.
    now apply Rle_trans with m.
  apply: (@RInt_gen_le (at_point a) (Rbar_locally p_infty) _ _ (fun x => scal (f x) (g x)) (fun x => scal u (g x)) _ _) => // .
    now apply filter_prod_at_point_infty.
  apply (filter_prod_at_point_infty a (fun x y => forall z, x <= z <= y -> _ <= _)).
  move => m n [Hm _] o [Ho _].
  rewrite /scal /= /mult /= .
  apply: Rmult_le_compat_r => // .
    apply Hg.
    now apply Rle_trans with m.
  apply Hgoodorder_bis.
  now apply Rle_trans with m.
refine (proj2 (ex_RInt_gen_cauchy _ _) _).
split.
- apply: filter_prod_at_point_infty.
  move => x y Hxay; apply: ex_RInt_continuous => z Hz.
  rewrite Rmin_left in Hz; last by lra.
  rewrite Rmax_right in Hz; last by lra.
  apply: continuous_mult.
    by apply: Cf; lra.
    by apply: Cg; lra.
- move => eps.
  set eps1 := eps / (1 + Rmax (Rabs l) (Rabs u)).
  have Hmaxpos : 1 + Rmax (Rabs l) (Rabs u) > 0.
    by rewrite /Rmax; case: Rle_dec; move: (Rabs_pos u) (Rabs_pos l); lra.
  have eps1_pos : 0 < eps1.
    by apply: RIneq.Rdiv_lt_0_compat => // ; first apply: cond_pos eps.
  set pos_eps1 := mkposreal eps1 eps1_pos.
  case: (proj1 (ex_RInt_gen_cauchy _ _) (ex_intro _ _  HIg)) => Hexg Heps.
  case: (Heps (pos_eps1)) => Peps1 [HPinf HPint].
  have HPge : Rbar_locally p_infty (fun x => a <= x).
    by exists a => x; lra.
  assert(Hand := filter_and _ _ (at_point_filter_prod _ _ Hexg) HPinf).
  assert(Hand1 := filter_and _ _ Hand HPge).
  eexists; split. exact: Hand1.
  move => u0 v0 [[Hu1 Hu2] Hule] [[Hv1 Hv2] Hvle] I HisInt.
  wlog : I u0 v0 Hv1 Hv2 Hvle HisInt Hu1 Hu2 Hule / (u0 <= v0).
    move => Hwlog.
    case: (Rle_dec v0 u0) => Huv; last first.
      by apply: (Hwlog _ u0 v0 Hv1) => // ; lra.
    rewrite -norm_opp.
    apply: (Hwlog (opp I) v0 u0) => // .
    exact: is_RInt_swap.
  move => Hu0v0.

  have [Ig' HIg'']: ex_RInt g u0 v0.
    apply: ex_RInt_Chasles Hv1.
    exact: ex_RInt_swap.
  have Ig'pos : 0 <= Ig'.
    apply: (is_RInt_le (fun _ => zero) g) Hu0v0 _ HIg'' _.
    have -> : 0 = scal (v0 - u0) zero by rewrite scal_zero_r.
    by apply: is_RInt_const.
    by move => x Hx; apply: Hg; lra.
  move: (HPint u0 v0 Hu2 Hv2 Ig' HIg'') => {HPint} HPint.
  suff Hineq: norm I <= (1 + Rmax (Rabs l) (Rabs u)) * norm Ig'.
    apply: Rle_trans Hineq _.
    rewrite /pos_eps1 /eps1 /=  in HPint.
    have ->: eps = (1 + Rmax (Rabs l) (Rabs u)) * (eps / (1 + Rmax (Rabs l) (Rabs u))) :> R .
      by field; lra.
    by apply: Rmult_le_compat_l HPint; lra.
  apply: norm_RInt_le HisInt _; first lra.
    move => x Hx.
    2: {
    apply: is_RInt_scal.
      suff -> : norm Ig' = Ig'.
        exact: HIg''.
      by rewrite /norm /= /abs /=; rewrite Rabs_right //; lra.
    }
  rewrite /=.
  eapply Rle_trans.
    exact: norm_scal.
  rewrite /norm /= /abs /= .
  rewrite (Rabs_pos_eq (g x)).
  apply: Rmult_le_compat_r; first by (apply: Hg; lra).
  have Hax : a <= x by lra.
  suff: Rabs (f x) <= Rmax (Rabs l) (Rabs u) by lra.
    by apply: RmaxAbs; move: (Hgoodorder_bis x Hax) ;lra.
  by apply: Hg; lra.
Qed.

End IntegralTactic.

Module IntegralTaylor (I : IntervalOps).

Module J := IntervalExt I.
Module TM := TM I.

Section DepthZeroPol.

(* A fixed precision *)
Variable prec : I.precision.

Variables (f : R -> R) (iF : I.type -> I.type).

Hypothesis HiFIntExt : forall xi x, contains (I.convert xi) (Xreal x) -> contains (I.convert (iF xi)) (Xreal (f x)).

Variable Mf : TM.TMI.rpa.
Variables X : I.type.
Definition x0 := proj_val (I.convert_bound (I.midpoint X)).
Definition X0 := I.bnd (I.midpoint X) (I.midpoint X).
Definition iX := I.convert X.
Definition iX0 := I.convert X0.

Hypothesis validMf : TM.TMI.i_validTM x0 iX Mf (fun x => Xreal (f x)).

Variables (a b : R).

(* f is integrable on [a, b]*)
Hypothesis Hintegrable : ex_RInt f a b.

Variables ia ib : I.type.

Hypothesis Hconta : contains (I.convert ia) (Xreal a).
Hypothesis Hcontb : contains (I.convert ib) (Xreal b).
Hypothesis Hcontxa : contains iX (Xreal a).
Hypothesis Hcontxb : contains iX (Xreal b).

Definition taylor_integral :=
  TM.TMI.integralEnclosure prec X0 Mf ia ib.

(* now we take the intersection of a naive and intelligent way of computing the integral *)
Definition taylor_integral_naive_intersection :=
  let temp := I.mul prec (I.sub prec ib ia) (iF (I.join ia ib)) in
  if I.real temp then I.meet temp taylor_integral else temp.

Lemma taylor_integral_correct :
  contains
    (I.convert taylor_integral)
    (Xreal (RInt f a b)).
Proof.
rewrite /taylor_integral.
apply: (@TM.TMI.integralEnclosure_correct prec X0 X (fun x => Xreal (f x)) Mf (proj_val (I.convert_bound (I.midpoint X)))) => //.
assert (Hex : exists x : ExtendedR, contains (I.convert X) x).
{ eexists.
  exact: Hcontxa. }
rewrite /X0 I.bnd_correct.
{ now rewrite (proj1 (I.midpoint_correct X _)); [split ; apply Rle_refl|]. }
{ now apply I.valid_lb_real, I.midpoint_correct. }
now apply I.valid_ub_real, I.midpoint_correct.
Qed.

Lemma taylor_integral_naive_intersection_correct :
  contains
    (I.convert taylor_integral_naive_intersection)
    (Xreal (RInt f a b)).
Proof.
rewrite /taylor_integral_naive_intersection.
set tmp := I.mul prec (I.sub prec ib ia) (iF (I.join ia ib)).
generalize (I.real_correct tmp).
case I.real ; intros Hr.
2: now destruct (I.convert tmp).
apply I.meet_correct.
apply J.contains_RInt => //.
intros x Hx.
apply HiFIntExt.
assert (H := I.join_correct ia ib).
apply: contains_connected Hx.
apply H.
now apply Rmin_case ; [left|right].
apply H.
now apply Rmax_case ; [left|right].
exact: taylor_integral_correct.
Qed.

End DepthZeroPol.

End IntegralTaylor.


From Hammer Require Import Hammer.

Require Import Sumbool.

Require Import BinInt.
Require Import Zorder.
Require Import Zcompare.
Local Open Scope Z_scope.

Lemma Dcompare_inf : forall r:comparison, {r = Eq} + {r = Lt} + {r = Gt}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Dcompare_inf".
induction r; auto.
Defined.

Lemma Zcompare_rect (P:Type) (n m:Z) :
((n ?= m) = Eq -> P) -> ((n ?= m) = Lt -> P) -> ((n ?= m) = Gt -> P) -> P.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Zcompare_rect".
intros H1 H2 H3.
destruct (n ?= m); auto.
Defined.

Lemma Zcompare_rec (P:Set) (n m:Z) :
((n ?= m) = Eq -> P) -> ((n ?= m) = Lt -> P) -> ((n ?= m) = Gt -> P) -> P.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Zcompare_rec".   apply Zcompare_rect. Defined.

Notation Z_eq_dec := Z.eq_dec (compat "8.3").

Section decidability.

Variables x y : Z.

Definition Z_lt_dec : {x < y} + {~ x < y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_lt_dec".
unfold Z.lt; case Z.compare; (now left) || (now right).
Defined.

Definition Z_le_dec : {x <= y} + {~ x <= y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_le_dec".
unfold Z.le; case Z.compare; (now left) || (right; tauto).
Defined.

Definition Z_gt_dec : {x > y} + {~ x > y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_gt_dec".
unfold Z.gt; case Z.compare; (now left) || (now right).
Defined.

Definition Z_ge_dec : {x >= y} + {~ x >= y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_ge_dec".
unfold Z.ge; case Z.compare; (now left) || (right; tauto).
Defined.

Definition Z_lt_ge_dec : {x < y} + {x >= y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_lt_ge_dec".
exact Z_lt_dec.
Defined.

Lemma Z_lt_le_dec : {x < y} + {y <= x}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_lt_le_dec".
elim Z_lt_ge_dec.
* now left.
* right; now apply Z.ge_le.
Defined.

Definition Z_le_gt_dec : {x <= y} + {x > y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_le_gt_dec".
elim Z_le_dec; auto with arith.
intro. right. Z.swap_greater. now apply Z.nle_gt.
Defined.

Definition Z_gt_le_dec : {x > y} + {x <= y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_gt_le_dec".
exact Z_gt_dec.
Defined.

Definition Z_ge_lt_dec : {x >= y} + {x < y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_ge_lt_dec".
elim Z_ge_dec; auto with arith.
intro. right. Z.swap_greater. now apply Z.lt_nge.
Defined.

Definition Z_le_lt_eq_dec : x <= y -> {x < y} + {x = y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_le_lt_eq_dec".
intro H.
apply Zcompare_rec with (n := x) (m := y).
intro. right. elim (Z.compare_eq_iff x y); auto with arith.
intro. left. elim (Z.compare_eq_iff x y); auto with arith.
intro H1. absurd (x > y); auto with arith.
Defined.

End decidability.

Lemma Zlt_cotrans : forall n m:Z, n < m -> forall p:Z, {n < p} + {p < m}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Zlt_cotrans".
intros x y H z.
case (Z_lt_ge_dec x z).
intro.
left.
assumption.
intro.
right.
apply Z.le_lt_trans with (m := x).
apply Z.ge_le.
assumption.
assumption.
Defined.

Lemma Zlt_cotrans_pos : forall n m:Z, 0 < n + m -> {0 < n} + {0 < m}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Zlt_cotrans_pos".
intros x y H.
case (Zlt_cotrans 0 (x + y) H x).
- now left.
- right.
apply Z.add_lt_mono_l with (p := x).
now rewrite Z.add_0_r.
Defined.

Lemma Zlt_cotrans_neg : forall n m:Z, n + m < 0 -> {n < 0} + {m < 0}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Zlt_cotrans_neg".
intros x y H; case (Zlt_cotrans (x + y) 0 H x); intro Hxy;
[ right; apply Z.add_lt_mono_l with (p := x); rewrite Z.add_0_r | left ];
assumption.
Defined.

Lemma not_Zeq_inf : forall n m:Z, n <> m -> {n < m} + {m < n}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.not_Zeq_inf".
intros x y H.
case Z_lt_ge_dec with x y.
intro.
left.
assumption.
intro H0.
generalize (Z.ge_le _ _ H0).
intro.
case (Z_le_lt_eq_dec _ _ H1).
intro.
right.
assumption.
intro.
apply False_rec.
apply H.
symmetry .
assumption.
Defined.

Lemma Z_dec : forall n m:Z, {n < m} + {n > m} + {n = m}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_dec".
intros x y.
case (Z_lt_ge_dec x y).
intro H.
left.
left.
assumption.
intro H.
generalize (Z.ge_le _ _ H).
intro H0.
case (Z_le_lt_eq_dec y x H0).
intro H1.
left.
right.
apply Z.lt_gt.
assumption.
intro.
right.
symmetry .
assumption.
Defined.

Lemma Z_dec' : forall n m:Z, {n < m} + {m < n} + {n = m}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_dec'".
intros x y.
case (Z.eq_dec x y); intro H;
[ right; assumption | left; apply (not_Zeq_inf _ _ H) ].
Defined.

Corollary Z_zerop : forall x:Z, {x = 0} + {x <> 0}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_zerop".
exact (fun x:Z => Z.eq_dec x 0).
Defined.

Corollary Z_notzerop : forall (x:Z), {x <> 0} + {x = 0}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_notzerop".  exact ((fun x => sumbool_not _ _ (Z_zerop x))). Qed.

Corollary Z_noteq_dec : forall (x y:Z), {x <> y} + {x = y}.
Proof. hammer_hook "ZArith_dec" "ZArith_dec.Z_noteq_dec".  exact ((fun x y => sumbool_not _ _ (Z.eq_dec x y))). Qed.