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

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

Require Export Lists.

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

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

(* ###################################################### *)
(** ** Polymorphic Lists *)

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

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

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

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

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

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

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

(** (Side note on notation: In .v files, the "forall" quantifier is
    spelled out in letters.  In the generated HTML files, [forall] is
    usually typeset as the usual mathematical "upside down A," but
    you'll see the spelled-out "forall" in a few places, as in the
    above comments.  This is just a quirk of typesetting: there is no
    difference in meaning.) *)

(** 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 written [nil] and [cons] explicitly here because we haven't
    yet defined the [ [] ] and [::] notations for the new version of
    lists.  We'll do that in a bit.) *)

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

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

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

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

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

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

Module MumbleGrumble.

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

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

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

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

End MumbleGrumble.

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

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

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

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

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

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

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

(* ###################################################### *)
(** *** Type Argument Synthesis *)

(** To 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 [repeat] function above must
    pass along the type [X].  But since the second argument to
    [repeat] is an element of [X], it seems entirely obvious that the
    first argument can only be [X] -- why should we have to write it
    explicitly?

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

    This may sound similar to type annotation inference -- indeed, the
    two procedures rely on the same underlying mechanisms.  Instead of
    simply omitting the types of some arguments to a function, like
      repeat' X x count : list X :=
    we can also replace the types with [_]
      repeat' (X : _) (x : _) (count : _) : list X :=
    to tell Coq to attempt to infer the missing information.

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

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

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

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

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

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

(* ###################################################### *)
(** *** Implicit Arguments *)

(** We can go further and even avoid writing [_]'s in most cases by
    telling Coq _always_ to infer the type argument(s) of a given
    function.  The [Arguments] directive specifies the name of the
    function (or constructor) and then lists its argument names, with
    curly braces around any arguments to be treated as implicit.  (If
    some arguments of a definition don't have a name, as is often the
    case for constructors, they can be marked with a wildcard pattern
    [_].) *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fail Definition mynil := nil.

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

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

Definition mynil : list nat := nil.

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

Check @nil.

Definition mynil' := @nil nat.

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

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

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

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

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

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

Theorem app_nil_r : forall (X:Type), forall l:list X,
  l ++ [] = l.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
  (* FILL IN HERE *) Admitted.

Lemma app_length : forall (X:Type) (l1 l2 : list X),
  length (l1 ++ l2) = length l1 + length l2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

Theorem rev_app_distr: forall X (l1 l2 : list X),
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** ** Polymorphic Pairs *)

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

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

Arguments pair {X} {Y} _ _.

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

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

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

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

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

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

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

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

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

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

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

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

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

    Uncomment the material below and fill in the definition of
    [split].  Make sure it passes the given unit test. *)

Fixpoint split {X Y : Type} (l : list (X*Y))
               : (list X) * (list Y) :=
(* FILL IN HERE *) admit.

Example test_split:
  split [(1,false);(2,false)] = ([1;2],[false;false]).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

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

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

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

Definition hd_error {X : Type} (l : list X) : option X :=
  (* FILL IN HERE *) admit.

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

Check @hd_error.

Example test_hd_error1 : hd_error [1;2] = Some 1.
 (* FILL IN HERE *) Admitted.
Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].
 (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(* ###################################################### *)
(** ** Anonymous Functions *)

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

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

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

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

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

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

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

Definition filter_even_gt7 (l : list nat) : list nat :=
  (* FILL IN HERE *) admit.

Example test_filter_even_gt7_1 :
  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].
 (* FILL IN HERE *) Admitted.

Example test_filter_even_gt7_2 :
  filter_even_gt7 [5;2;6;19;129] = [].
 (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (partition)  *)
(** Use [filter] to write a Coq function [partition]:
  partition : forall X : Type,
              (X -> bool) -> list X -> list X * list X
   Given a set [X], a test function of type [X -> bool] and a [list
   X], [partition] should return a pair of lists.  The first member of
   the pair is the sublist of the original list containing the
   elements that satisfy the test, and the second is the sublist
   containing those that fail the test.  The order of elements in the
   two sublists should be the same as their order in the original
   list.
*)

Definition partition {X : Type}
                     (test : X -> bool)
                     (l : list X)
                   : list X * list X :=
(* FILL IN HERE *) admit.

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

(* ###################################################### *)
(** ** 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, since [map] takes _two_ type arguments, [X] and [Y]; it
    can thus be applied to a list of numbers and a function from
    numbers to booleans to yield a list of booleans: *)

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

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

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

(** *** Exercises *)

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

Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),
  map f (rev l) = rev (map f l).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, recommended (flat_map)  *)
(** The function [map] maps a [list X] to a [list Y] using a function
    of type [X -> Y].  We can define a similar function, [flat_map],
    which maps a [list X] to a [list Y] using a function [f] of type
    [X -> list Y].  Your definition should work by 'flattening' the
    results of [f], like so:
        flat_map (fun n => [n;n+1;n+2]) [1;5;10]
      = [1; 2; 3; 5; 6; 7; 10; 11; 12].
*)

Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)
                   : (list Y) :=
  (* FILL IN HERE *) admit.

Example test_flat_map1:
  flat_map (fun n => [n;n;n]) [1;5;4]
  = [1; 1; 1; 5; 5; 5; 4; 4; 4].
 (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

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

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

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

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

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

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

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

(* ###################################################### *)
(** ** Functions That Construct Functions *)

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

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

Definition ftrue := constfun true.

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

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

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

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

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

Definition plus3 := plus 3.
Check plus3.

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

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

Module Exercises.

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

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

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

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

Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
(* FILL IN HERE *) Admitted.
(** [] *)

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

Definition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=
(* FILL IN HERE *) admit.

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

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

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

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

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

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

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

Definition prod_uncurry {X Y Z : Type}
  (f : X -> Y -> Z) (p : X * Y) : Z :=
  (* FILL IN HERE *) admit.

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

Check @prod_curry.
Check @prod_uncurry.

Theorem uncurry_curry : forall (X Y Z : Type)
                        (f : X -> Y -> Z)
                        x y,
  prod_curry (prod_uncurry f) x y = f x y.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem curry_uncurry : forall (X Y Z : Type)
                        (f : (X * Y) -> Z) (p : X * Y),
  prod_uncurry (prod_curry f) p = f p.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)
(** Recall the definition of the [nth_error] function:
   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=
     match l with
     | [] => None
     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)
     end.
   Write an informal proof of the following theorem:
   forall X n l, length l = n -> @nth_error X l n
(* FILL IN HERE *)
*)
(** [] *)

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

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

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

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

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

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

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

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

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

Definition three : nat := @doit3times.

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

(** Successor of a natural number: *)

Definition succ (n : nat) : nat :=
  (* FILL IN HERE *) admit.

Example succ_1 : succ zero = one.
Proof. (* FILL IN HERE *) Admitted.

Example succ_2 : succ one = two.
Proof. (* FILL IN HERE *) Admitted.

Example succ_3 : succ two = three.
Proof. (* FILL IN HERE *) Admitted.

(** Addition of two natural numbers: *)

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

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

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

End Exercises.

(** $Date: 2016-01-28 15:02:07 -0500 (Thu, 28 Jan 2016) $ *)


(**************************************************************)
(*   Copyright Dominique Larchey-Wendling [*]                 *)
(*                                                            *)
(*                             [*] Affiliation LORIA -- CNRS  *)
(**************************************************************)
(*      This file is distributed under the terms of the       *)
(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)
(**************************************************************)

Require Import List Arith Lia Eqdep_dec Bool.

From Undecidability.Shared.Libs.DLW.Utils
  Require Import utils_tac utils_list finite.

From Undecidability.Shared.Libs.DLW.Vec
  Require Import pos vec.

From Undecidability.FOL.TRAKHTENBROT
  Require Import notations decidable fol_ops membership hfs.

Set Implicit Arguments.

(* * Construction of the Hereditary Finite Sets model *)

Section bt_model_n.

  (*  This discussion briefly describes how we encode finite and discrete
      model X with a decidable nt-ary relation R into an hereditary finite
      set (hfs) with two elements l and r, l representing the points in X
      and r representing the n-tuples in R.

      Because X is finite and discrete, one can compute a bijection X <~> pos n
      where n is the cardinal of X. Hence we assume that X = pos n and the
      nt-art relation is R : vec (pos n) nt -> Prop

      1) We find a transitive hfs l such that (pos n) bijects with the elements
         of l (transitive means ∀x, x∈l -> x⊆l). Hence

                            pos n <-> { x | x ∈ l }

         For this, we use the encoding of natural numbers into sets,
         ie 0 := ø and 1+i := {i} U i and choose l to be the encoding
         of n (the cardinal of X = pos n above).

         Notice that since l is transitive then so is P(l) (powerset)
         and hence P^i(l) for any i.

      2) forall x,y ∈ l, both {x} and {x,y} belong to P(l)
         hence (x,y) = {{x},{x,y}} ∈ P(P(l))=P^2(l)

      3) l contains the empty set (cardinal > 0)

      4) Hence P^2nt(l) contains all nt-tuples build
         from the elements of l by induction on n

      5) So we can encode R as hfs r ∈ p := P^(2nt+1)(l) = P(P^2nt(l)) and
         p serves as our model, ie

                      Y := { x : hfs | x ∈b p }

         where x ∈b p is the Boolean encoding of x ∈ p to ensure
         uniqueness of witnesses/proofs.

      6) In the logic, we replace any

               R v by [v] ∈ r

         encoded according to the above description.

      *)

  Variable (X : Type) (Xfin : finite_t X) (Xdiscr : discrete X) (x0 : X) (nt : nat).

  Notation "∅" := hfs_empty.
  Infix "∈" := hfs_mem.
  Notation "x ⊆ y" := (forall u, u ∈ x -> u ∈ y).
  Notation "⟬ x , y ⟭" := (hfs_opair x y).

  (* First we compute a bijection with the cardinal of X *)

  Section the_model.

    Local Definition X_surj_hfs : { d : hfs &
                     { f : hfs -> X &
                     { g : X -> hfs |
                        hfs_transitive d
                     /\ ∅ ∈ d
                     /\ (forall p, g p ∈ d)
                     /\ (forall x, x ∈ d -> exists p, x = g p)
                     /\ (forall p, f (g p) = p)
                     }}}.
    Proof using x0 Xfin Xdiscr.
      destruct (finite_t_discrete_bij_t_pos Xfin)
        as ([ | n ] & Hn); auto.
      1: { exfalso; destruct Hn as (f & g & H1 & H2).
           generalize (f x0); intro p; invert pos p. }
      destruct Hn as (f & g & H1 & H2).
      destruct (hfs_pos_n_transitive n)
        as (l & g' & f' & G1 & G0 & G2 & G3 & G4).
      exists l, (fun x => g (g' x)), (fun x => f' (f x)); msplit 4; auto.
      + intros x Hx.
        destruct (G3 x Hx) as (p & Hp).
        exists (g p); rewrite H2; auto.
      + intros p; rewrite G4; auto.
    Qed.

    (* First a surjective map from some transitive set d to X *)

    Local Definition d := projT1 X_surj_hfs.
    Local Definition s := projT1 (projT2 X_surj_hfs).
    Local Definition i := proj1_sig (projT2 (projT2 (X_surj_hfs))).

    Let Hd : hfs_transitive d.       Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.
    Let Hempty : ∅ ∈ d.              Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.

    Local Fact Hs : forall x, s (i x) = x.
    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.

    Local Fact Hi : forall x, i x ∈ d.
    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.

    Local Fact Hi' : forall s, s ∈ d -> exists x, s = i x.
    Proof. apply (proj2_sig (projT2 (projT2 (X_surj_hfs)))). Qed.

    (* Now we build P^(1+2nt) d that contains all the sets of nt-tuples of d *)

    Local Definition p := iter hfs_pow d (1+(2*nt)).

    Local Fact Hp1 : hfs_transitive p.
    Proof. apply hfs_iter_pow_trans; auto. Qed.

    Local Fact Hp2 : d ∈ p.
    Proof.
      apply hfs_iter_pow_le with (n := 1); simpl; auto; try lia.
      apply hfs_pow_spec; auto.
    Qed.

    Local Fact Hp5 n v : (forall p, vec_pos v p ∈ d) -> @hfs_tuple n v ∈ iter hfs_pow d (2*n).
    Proof. apply hfs_tuple_pow; auto. Qed.

    Local Fact Hp6 n v : n <= nt -> (forall p, vec_pos v p ∈ d) -> @hfs_tuple n v ∈ p.
    Proof.
      intros L H; apply Hp5 in H.
      revert H; apply hfs_iter_pow_le; try lia; auto.
    Qed.

  End the_model.

  Variable (R : vec X nt -> Prop).
  Hypothesis HR : forall v, { R v } + { ~ R v }.

  Hint Resolve finite_t_prod hfs_mem_fin_t : core.
  Hint Resolve Hp1 Hp2 Hp5 Hp6 Hs Hi Hi' : core.

  Section the_relation.

    (* We encode R as a subset of tuples of elements of d in p *)

    Let encode_R : { r | r ∈ p
                      /\ (forall v, @hfs_tuple nt v ∈ r -> forall q, vec_pos v q ∈ d)
                      /\ forall v, R v <-> hfs_tuple (vec_map i v) ∈ r }.
    Proof.
      set (P v := R (vec_map s v) /\ forall q, vec_pos v q ∈ d).
      set (f := @hfs_tuple nt).
      destruct hfs_comprehension with (P := P) (f := f) as (r & Hr).
      + apply fin_t_dec.
        * intros; apply HR.
        * apply fin_t_vec with (P := fun t => t ∈ d).
          apply hfs_mem_fin_t.
      + exists r; msplit 2.
        * unfold p; rewrite Nat.add_comm, iter_plus with (b := 1).
          apply hfs_pow_spec; intros x; rewrite Hr.
          intros (v & H1 & <-).
          apply Hp5, H1.
        * unfold f; intros v.
          rewrite Hr.
          intros (w & H1 & H2).
          apply hfs_tuple_spec in H2; subst w.
          apply H1.
        * intros v.
          rewrite Hr.
          split.
          - exists (vec_map i v); split; auto.
            split; auto.
            ++ rewrite vec_map_map.
               revert H; apply fol_equiv_ext.
               f_equal; apply vec_pos_ext; intro; rew vec.
            ++ intro; rew vec.
          - intros (w & (H1 & _) & H2).
            apply hfs_tuple_spec in H2.
            revert H1; subst w; apply fol_equiv_ext.
            f_equal; apply vec_pos_ext; intro; rew vec.
    Qed.

    Local Definition r := proj1_sig encode_R.

    Local Fact Hr1 : r ∈ p.
    Proof. apply (proj2_sig encode_R). Qed.

    Local Fact Hr2 v : @hfs_tuple nt v ∈ r -> forall q, vec_pos v q ∈ d.
    Proof. apply (proj2_sig encode_R). Qed.

    Local Fact Hr3 v : R v <-> hfs_tuple (vec_map i v) ∈ r.
    Proof. apply (proj2_sig encode_R). Qed.

  End the_relation.

  Hint Resolve Hr1 Hr2 Hr3 : core.

  (* The Boolean encoding of x ∈ p *)

  Local Definition p_bool x := if hfs_mem_dec x p then true else false.

  Local Fact p_bool_spec x : x ∈ p <-> p_bool x = true.
  Proof.
    unfold p_bool.
    destruct (hfs_mem_dec x p); split; try tauto; discriminate.
  Qed.

  Local Fact p_bool_spec1 x : x ∈ p -> p_bool x = true.
  Proof. apply p_bool_spec. Qed.

  Local Fact p_bool_spec2 x : p_bool x = true -> x ∈ p.
  Proof. apply p_bool_spec. Qed.

  Local Definition Y := sig (fun x => p_bool x = true).

  Notation π1 := (@proj1_sig _ (fun x => p_bool x = true)).

  Hint Resolve p_bool_spec p_bool_spec1 p_bool_spec2 : core.

  Local Fact eqY : forall x y : Y, π1 x = π1 y -> x = y.
  Proof.
    intros (x & Hx) (y & Hy); simpl.
    intros; subst; f_equal; apply UIP_dec, bool_dec.
  Qed.

  Local Fact HY : finite_t Y.
  Proof.
    apply fin_t_finite_t.
    + intros; apply UIP_dec, bool_dec.
    + generalize (hfs_mem_fin_t p); apply fin_t_equiv.
      intros x; auto.
  Qed.

  (* This one is not needed anymore *)

  Local Fact discrY : discrete Y.
  Proof.
    intros (x & Hx) (y & Hy).
    destruct (hfs_eq_dec x y) as [ -> | D ].
    + left; f_equal; apply UIP_dec, bool_dec.
    + right; contradict D; inversion D; auto.
  Qed.

  Local Definition mem (x y : Y) := π1 x ∈ π1 y.

  Local Fact mem_dec : forall x y, { mem x y } + { ~ mem x y }.
  Proof.
    intros (a & ?) (b & ?); unfold mem; simpl; apply hfs_mem_dec.
  Qed.

  Local Definition yd : Y := exist _ _ (p_bool_spec1 Hp2).
  Local Definition yr : Y := exist _ _ (p_bool_spec1 Hr1).

  Local Fact fa_mem_Y (P : _ -> Prop) :
                           (forall a, a ∈ p -> P a)
                       <-> (forall a, P (π1 a)).
  Proof.
    split.
    + intros H (a & Ha); simpl; auto.
    + intros H a Ha.
      apply (H (exist _ _ (p_bool_spec1 Ha))).
  Qed.

  Local Fact ex_mem_Y (P : _ -> Prop) :
                           (exists a, a ∈ p /\ P a)
                       <-> (exists a, P (π1 a)).
  Proof.
    split.
    + intros (a & H & Ha).
      exists (exist _ a (p_bool_spec1 H)); auto.
    + intros ((a & Ha) & H); simpl in *; eauto.
  Qed.

  Local Fact mem_fa_Y (P : _ -> Prop) k : k ∈ p -> (forall a, P a -> a ∈ p)
                       -> (forall a, a ∈ k <-> P a)
                       <-> (forall a, π1 a ∈ k <-> P (π1 a)).
  Proof.
    intros H1 H2.
    rewrite <- fa_mem_Y with (P := fun a => a ∈ k <-> P a).
    split.
    + intros H ? _; auto.
    + intros H a; split.
      * intros Ha; apply H; auto.
        apply (Hp1 Ha); auto.
      * intros Ha; apply H; auto.
  Qed.

  (* Membership equivalence is identity in the model *)

  Local Fact mem_equiv_Y u v :
                        u ∈ p
                     -> v ∈ p
                     -> (forall y : Y, π1 y ∈ u <-> π1 y ∈ v)
                    <-> (forall x : hfs, x ∈ u <-> x ∈ v).
  Proof.
    intros Hu Hv.
    symmetry; apply mem_fa_Y; auto.
    intros s Hs; apply (Hp1 Hs); auto.
  Qed.

  Local Fact is_equiv : forall x y, mb_equiv mem x y <-> π1 x = π1 y.
  Proof.
    intros (x & Hx) (y & Hy); simpl.
    unfold mb_equiv, mem; simpl; split.
    2: { intros []; tauto. }
    rewrite mem_equiv_Y; auto; apply hfs_mem_ext.
  Qed.

  Local Fact mem_ext_Y x y : x ∈ p -> y ∈ p -> (forall a, π1 a ∈ x <-> π1 a ∈ y) <-> x = y.
  Proof.
    intros H1 H2; split.
    + intros H; apply hfs_mem_ext.
      rewrite mem_fa_Y; auto.
      intros z Hz; apply (Hp1 Hz); auto.
    + intros ->; tauto.
  Qed.

  Hint Resolve mem_ext_Y : core.

  Local Fact is_pair : forall x y k, mb_is_pair mem k x y
                                 <-> π1 k = hfs_pair (π1 x) (π1 y).
  Proof.
    intros (x & Hx) (y & Hy) (k & Hk); simpl.
    unfold mb_is_pair; simpl.
    unfold mb_equiv, mem; simpl.
    rewrite hfs_pair_spec'.
    rewrite mem_fa_Y; auto.
    2: intros ? [ -> | -> ]; auto.
    fol equiv; intros (a & Ha); simpl.
    fol equiv; try tauto.
    fol equiv; auto.
  Qed.

  Local Fact is_opair : forall x y k, mb_is_opair mem k x y
                                  <-> π1 k = ⟬π1 x,π1 y⟭.
  Proof.
    intros (x & Hx) (y & Hy) (k & Hk); simpl.
    unfold mb_is_opair; simpl.
    split.
    + intros ((a & Ha) & (b & Hb) & H); revert H.
      repeat rewrite is_pair; simpl.
      intros (-> & -> & ->); auto.
    + intros ->.
      generalize Hx Hy Hk; revert Hx Hy Hk.
      do 3 rewrite <- p_bool_spec at 1.
      intros Hx' Hy' Hk' Hx Hy Hk.
      apply hfs_trans_opair_inv in Hk'; auto.
      do 2 rewrite p_bool_spec in Hk'.
      destruct Hk' as (H1 & H2).
      exists (exist _ (hfs_pair x x) H1).
      exists (exist _ (hfs_pair x y) H2).
      repeat rewrite is_pair; simpl; auto.
  Qed.

  Local Fact is_tuple n : forall v t, @mb_is_tuple _ mem t n v
                                  <-> π1 t = hfs_tuple (vec_map π1 v).
  Proof.
    induction n as [ | n IHn ]; intros v (t & Ht).
    + vec nil v; clear v; simpl; split.
      * intros H; apply hfs_mem_ext.
        intros z; split.
        - intros Hz.
          assert (Hz' : p_bool z = true).
          { apply p_bool_spec.
            apply Hp1 with (1 := Hz), p_bool_spec; auto. }
          destruct (H (exist _ z Hz')); auto.
        - rewrite hfs_empty_spec; tauto.
      * intros -> (z & ?); unfold mem; simpl.
        rewrite hfs_empty_spec; tauto.
    + vec split v with x; simpl; split.
      * intros (t' & H1 & H2).
        rewrite IHn in H2; try lia.
        rewrite <- H2.
        apply is_opair with (k := exist _ t Ht); auto.
      * intros ->.
        assert (H1 : p_bool (hfs_tuple (vec_map π1 v)) = true).
        { apply p_bool_spec.
          apply p_bool_spec in Ht.
          apply hfs_trans_opair_inv, proj2, hfs_trans_pair_inv in Ht; auto; tauto. }
        exists (exist _ (hfs_tuple (vec_map π1 v)) H1); split.
        - rewrite is_opair; simpl; auto.
        - rewrite IHn; simpl; auto.
  Qed.

  Local Fact has_tuples : mb_has_tuples mem yd nt.
  Proof.
    intros v Hv.
    set (t := hfs_tuple (vec_map (proj1_sig (P:=fun x : hfs => p_bool x = true)) v)).
    assert (H1 : p_bool t = true).
    { apply p_bool_spec, Hp6; auto; intro; rew vec; apply Hv. }
    exists (exist _ t H1).
    apply is_tuple; simpl; reflexivity.
  Qed.

  Local Definition i' x : Y := exist _ _ (p_bool_spec1 (Hp1 (Hi x) Hp2)).

  Local Fact Hi'' x : mem (i' x) yd.
  Proof. unfold i', yd, mem; simpl; auto. Qed.

  Hint Resolve Hi'' : core.

  Local Definition s' (y : Y) : X := s (π1 y).

  (*
    For finite and discrete type X, non empty (as witnessed by a given element)
    equipped with a Boolean ternary relation R, one can compute a type Y, finite
    (and discrete), equipped with a Boolean binary membership predicate ∈ (which is
    extensional). Y is a finite (set like) model which contains two sets yd and
    yr and there is a bijection between X and (the elements of) yd. All ordered
    nt-tuples build from elements of yd exist in Y, and yr encodes R in the set
    of (ordered) nt-tuples it contains.
    (Finally, membership equivalence (≈) is the same as identity (=) in Y).

    Membership equivalence : x ≈ y := ∀z, z∈x <-> z∈y
    Membership extensional : x ≈ y -> ∀z, x∈z -> y∈z

    Tuples are build the usual way (in set theory)
      - z ∈ {x,y} := z ≈ x \/ z ≈ y
      - ordered pairs: (x,y) is {{x},{x,y}}
      - ordered triples: (x,y,z) is ((x,y),z), etc

    Non-emptyness is not really necessary but then the bijection between X=ø
    and yl has to be implemented with dependent functions, more cumbersome to work
    with. And first order models can never be empty because one has to be able
    to interpret variables.

    Maybe a discussion on the case of empty models could help, but then
    the FO logic been reduced to True/False in that case.
    Any ∀ formula is True, any ∃ is False and no atomic formula can ever
    be evaluated (because it contains terms that cannot be interpreted).
    Only closed formula have a meaning in the empty model
  *)

  Theorem reln_hfs : { Y : Type &
                     { _ : finite_t Y &
                     { mem : Y -> Y -> Prop &
                     { _ : forall u v, { mem u v } + { ~ mem u v } &
                     { yd : Y &
                     { yr : Y &
                     { i : X -> Y &
                     { s : Y -> X &
                             (forall x, mem (i x) yd)
                          /\ (forall y, mem y yd -> exists x, y = i x)
                          /\ (forall v, R v <-> mb_is_tuple_in mem yr (vec_map i v))
                      }}}}}}}}.
  Proof using x0 Xfin Xdiscr HR.
    exists Y, HY, mem, mem_dec, yd, yr, i', s'.
    msplit 2; auto.
    + intros y Hy; unfold i'.
      destruct (Hi' Hy) as (x & Hx).
      exists x; apply eqY; simpl; auto.
    + intros v; rewrite Hr3; split.
      * intros Hv.
        red.
        assert (H1 : p_bool (hfs_tuple (vec_map i v)) = true).
        { apply p_bool_spec, Hp1 with (1 := Hv); auto. }
        exists (exist _ (hfs_tuple (vec_map i v)) H1); split.
        - apply is_tuple; simpl; rewrite vec_map_map; auto.
        - unfold yr; red; simpl; auto.
      * intros ((t & Ht) & H1 & H2).
        rewrite is_tuple in H1.
        simpl in H1, H2.
        rewrite vec_map_map in H1; subst t; auto.
  Qed.

End bt_model_n.


Require Export LL.Misc.Utils.
Require Export LL.FOLL.Syntax.

Export ListNotations.
Set Implicit Arguments.

Section LL2Sequent.
  Context `{OLS: OLSig}.
  Definition multiset := list.

  Reserved Notation "n '|--' B ';' L " (at level 80).

  Inductive LL2N:  nat -> multiset oo -> multiset oo -> Prop :=
  (* axioms *)
  | ll2_init : forall B A L n, Permutation L [atom A; perp A] -> n |-- B ; L
  | ll2_one : forall B n, n |-- B ; [One]
  | ll2_top : forall B M L n, Permutation L (Top :: M) ->
      n |-- B ; L
  (* additives *)
  | ll2_plus1 : forall B M F G L n, Permutation L ((AOr F G)::M) ->
      n |-- B ; F::M -> S n |-- B ; L
  | ll2_plus2 : forall B M F G L n, Permutation L ((AOr F G)::M) ->
      n |-- B ; G::M -> S n |-- B ; L
  | ll2_with : forall B M F G L n, Permutation L ((AAnd F G)::M) ->
      n |-- B ; F :: M ->
      n |-- B ; G :: M -> S n |-- B ; L
  (* multiplicatives *)
  | ll2_bot : forall B M L n, Permutation L (Bot :: M) ->
      n |-- B ; M -> S n |-- B ; L
  | ll2_par : forall B M F G L n, Permutation L ((MOr F G) :: M) ->
      n |-- B ; F::G::M -> S n |-- B ; L
  | ll2_tensor : forall B M N F G L n, Permutation L ((MAnd F G)::(M ++ N)) ->
                                        (n |-- B ; F::M) ->
                                        (n |-- B ; G::N) ->
                                        (S n) |-- B ; L
   (* exponentials *)
  | ll2_quest : forall B M F L n, Permutation L ((Quest F) :: M) ->
      n |-- F::B ; M -> S n |-- B ; L
  | ll2_bang : forall B F n,
      n |-- B ; [F] -> S n |-- B ; [Bang F]
  (* quantifiers *)
  | ll2_ex  : forall B FX M L t n,  Permutation L ((Some  FX)::M) ->
      uniform_oo FX -> proper t -> n |-- B; (FX t)::M -> S n|-- B; L
  | ll2_fx  : forall B FX M L n, Permutation L ((All  FX)::M) ->
      uniform_oo FX -> (forall x, proper x -> n |-- B ; (FX x) ::  M) ->
      S n |-- B ; L
  (* structurals *)
  | ll2_abs : forall B L F n,
     In F B -> n |-- B ; F::L -> S n |-- B ; L

  where "n '|--' B ';' L " := (LL2N n B L).

  Reserved Notation "'|--' B ';' L" (at level 80).

  Inductive LL2S:  multiset oo -> multiset oo -> Prop :=
  (* axioms *)
  | ll2_init' : forall B A L, Permutation L [atom A; perp A] -> |-- B ; L
  | ll2_one' : forall B, |-- B ; [One]
  | ll2_top' : forall B M L, Permutation L (Top :: M) ->
      |-- B ; L
  (* additives *)
  | ll2_plus1' : forall B M F G L, Permutation L ((AOr F G)::M) ->
      |-- B ; F::M -> |-- B ; L
  | ll2_plus2' : forall B M F G L, Permutation L ((AOr F G)::M) ->
      |-- B ; G::M -> |-- B ; L
  | ll2_with' : forall B M F G L, Permutation L ((AAnd F G)::M) ->
      |-- B ; F :: M ->
      |-- B ; G :: M -> |-- B ; L
  (* multiplicatives *)
  | ll2_bot' : forall B M L, Permutation L (Bot :: M) ->
      |-- B ; M -> |-- B ; L
  | ll2_par' : forall B M F G L, Permutation L ((MOr F G) :: M) ->
      |-- B ; F::G::M -> |-- B ; L
  | ll2_tensor' : forall B M N F G L, Permutation L ((MAnd F G)::(M ++ N)) ->
                                        |-- B ; F::M ->
                                        |-- B ; G::N ->
                                        |-- B ; L
  (* exponentials *)
  | ll2_quest' : forall B M F L, Permutation L ((Quest F) :: M) ->
      |-- F::B ; M -> |-- B ; L
  | ll2_bang' : forall B F,
      |-- B ; [F] -> |-- B ; [Bang F]
  (* quantifiers *)
  | ll2_ex'  : forall B FX M L t,  Permutation L ((Some  FX)::M) ->
      uniform_oo FX -> proper t -> |-- B; (FX t)::M -> |-- B; L
  | ll2_fx'  : forall B FX M L, Permutation L ((All  FX)::M) ->
      uniform_oo FX -> (forall x, proper x -> |-- B ; (FX x) ::  M) ->
      |-- B ; L
  (* structurals *)
  | ll2_abs' : forall B L F,
     In F B -> |-- B ; F::L -> |-- B ; L
  where "'|--' B ';' L " := (LL2S B L).

 End LL2Sequent .

Global Hint Constructors LL2N : core .
Global Hint Constructors LL2S : core.

Notation "'LL2' n '|--' B ';' L " := (LL2N n B L)  (at level 80).
Notation "'LL2' '|--' B ';' L " := (LL2S B L)  (at level 80).


From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq tuple.
From mathcomp Require Import choice path bigop finfun fintype.

(* IPDL only needs a simple, terminating model for distributions. A probability distribution is a program that depends on a finite number of coin flips. *)

Inductive Dist A :=
  | DRet : A -> Dist A
  | Flip : (bool -> Dist A) -> Dist A.

Arguments DRet [A].
Arguments Flip [A].

Fixpoint dbind {A B} (d : Dist A) (k : A -> Dist B) : Dist B :=
  match d with
    | DRet x => k x
    | Flip f =>
      Flip (fun b => dbind (f b) k)
  end.

(* Distributions are given semantics by simply counting the number of occurences of return values. *)

Fixpoint interpDist {A} (d : Dist A) : list A :=
  match d with
  | DRet y => [:: y]
  | Flip k =>
    interpDist (k false) ++ interpDist (k true) end.

Lemma interp_dbind {A B} (d : Dist A) (k : A -> Dist B) :
  interpDist (dbind d k) = flatten (map (fun x => interpDist (k x)) (interpDist d)).
    induction d; rewrite //=.
    rewrite cats0 //=.
    rewrite !H.
    rewrite map_cat //= flatten_cat //=.
Qed.

(* A distribution is uniform if every return value appears the same amount of times in the interpretation. *)
Definition uniform {A : finType} (d : Dist A) :=
  exists n,
    forall x, \sum_(j <- interpDist d) (j == x) = n.

Class unif (A : finType) :=
  {
    Unif : Dist A;
    is_unif : uniform Unif }.

Fixpoint Unif_bv (n : nat) : Dist (n.-tuple bool) :=
  match n with
    | 0%nat => DRet [tuple]
    | S n' =>
      Flip (fun x =>
              dbind (Unif_bv n') (fun t => DRet [tuple of x :: t])) end.

Lemma uniform_Unif n : uniform (Unif_bv n).
    exists 1.
    induction n.
    intro.
    simpl.
    rewrite big_cons big_nil //=.
    have -> : x = [tuple] by apply tuple0.
    done.
    intro; rewrite //= !big_cat //= !interp_dbind !big_flatten //= !big_map //=.
    under eq_bigr => m do rewrite !big_cons big_nil addn0.
    rewrite addnC.
    under eq_bigr => m do rewrite !big_cons big_nil addn0.
    destruct (tupleP x); simpl.
    under eq_bigr => m do rewrite eqE //=.
    rewrite addnC.
    under eq_bigr => m do rewrite eqE //=.
    destruct x; simpl.

    rewrite big_const_seq //=.
    rewrite iter_addn_0 mul0n //=.
    under eq_bigr => m do rewrite eqE //=.
                          rewrite IHn //=.

    rewrite big_const_seq //=.
    rewrite iter_addn_0 mul0n //=.
    under eq_bigr => m do rewrite eqE //=.
                          rewrite IHn //=.
Qed.

#[export]
Instance unif_bv (n : nat) : unif [finType of n.-tuple bool] :=
  {
  Unif := Unif_bv n;
  is_unif := (uniform_Unif n) }.

Definition uniform_bool : Dist bool := Flip (fun b => DRet b).
Lemma uniform_boolP : uniform uniform_bool.
  exists 1.
  intro.
  simpl.
  rewrite !big_cons big_nil; destruct x; rewrite //=.
Qed.

#[export]
Instance unif_bool : unif [finType of bool] :=
  {
  Unif := uniform_bool;
  is_unif := uniform_boolP
             }.

Definition Unif_pair X Y `{unif X} `{unif Y} : Dist (X * Y) :=
  dbind Unif (fun x => dbind Unif (fun y => DRet (x, y))).
Lemma Unif_pair_unif X Y `{unif X} `{unif Y} :
    uniform (Unif_pair X Y).
    destruct H.
    destruct H0.
    destruct is_unif0.
    destruct is_unif1.
    exists (x * x0).
    intro.
    rewrite interp_dbind.
    rewrite big_flatten //=.
    rewrite big_map //=.
    etransitivity.
    apply eq_bigr; intros.
    rewrite interp_dbind.
    rewrite big_flatten //=.
    simpl.
    etransitivity.
    apply eq_bigr; intros.
    rewrite big_map.
    simpl.
    etransitivity.
    apply eq_bigr; intros.
    rewrite big_cons big_nil addn0 //=.
    done.
    simpl.
    destruct x1; simpl.
    etransitivity.
    apply eq_bigr; intros.
    have -> :
      \sum_(i0 <- interpDist Unif1) ((i, i0) == (s, s0)) =
      (i == s) * \sum_(i0 <- interpDist Unif1) (i0 == s0).
      rewrite big_distrr //=; apply eq_bigr; intros.
      rewrite eqE //= mulnb //=.
    rewrite e0.
    done.
    simpl.
    have -> :
      \sum_(i <- interpDist Unif0) ((i == s) * x0) =
      x0 * \sum_(i <- interpDist Unif0) ((i == s)).
      rewrite big_distrr //=; apply eq_bigr; intros.
      rewrite mulnC //=.
    rewrite e mulnC //=.
Qed.

#[export]
Instance unif_pair X Y `{unif X} `{unif Y} : unif [finType of X * Y] :=
  {|
    Unif := Unif_pair X Y;
    is_unif := Unif_pair_unif X Y
  |}.


Require Export Arith.
Require Export ArithRing.
Require Export Omega.

Fixpoint two_power (n : nat) : nat :=
 match n with 0 => 1 | S p => 2 * two_power p end.

Theorem div2_rec:
 forall (P : nat ->  Set),
 P 0 -> P 1 -> (forall n, P n ->  P (S (S n))) -> forall (n : nat),  P n.
Proof.
intros P H0 H1 Hrec n; assert (P n * P (S n))%type.
elim n; intuition.
intuition.
Qed.

Theorem div2_spec:
 forall n,  ({x : nat | 2 * x = n}) + ({x : nat | 2 * x + 1 = n}).
intros n; elim n  using div2_rec.
left; exists 0; trivial.
right; exists 0; trivial.
intros p [[x Heq]|[x Heq]].
left; exists (S x); rewrite <- Heq; ring.
right; exists (S x); rewrite <- Heq; ring.
Qed.

Theorem half_smaller0: forall n x, 2 * x = S n ->  (x < S n).
Proof.
intros; omega.
Qed.

Theorem half_smaller1: forall n x, 2 * x + 1 = n ->  (x < n).
Proof.
intros; omega.
Qed.

Definition log2_F:
 forall (n : nat),
 (forall (y : nat),
  y < n -> y <> 0 ->  ({p : nat | two_power p <= y /\ y < two_power (p + 1)})) ->
 n <> 0 ->  ({p : nat | two_power p <= n /\ n < two_power (p + 1)}).
intros n; case n.
intros log2 Hn0; elim Hn0; trivial.
intros n' log2 _.
elim (div2_spec (S n')).
intros [x]; case x.
simpl; intros; discriminate.
intros x' Heqx'; assert (Hn0: S x' <> 0).
auto with arith.
destruct (log2 (S x') (half_smaller0 _ _ Heqx') Hn0) as [v Heqv].
exists (S v); simpl.
rewrite <- Heqx'.
omega.
intros [x]; case x.
simpl.
intros Heq; rewrite <- Heq; exists 0.
simpl; auto with arith.
intros x' Heqx'; assert (Hn0: S x' <> 0).
auto with arith.
destruct (log2 (S x') (half_smaller1 _ _ Heqx') Hn0) as [v Heqv].
exists (S v); rewrite <- Heqx'.
simpl; omega.
Qed.


Require Import GeoCoq.Axioms.parallel_postulates.
Require Import GeoCoq.Tarski_dev.Ch12_parallel.

Section proclus_SPP.

Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.

Lemma proclus_s_postulate_implies_strong_parallel_postulate :
  proclus_postulate -> strong_parallel_postulate.
Proof.
intros HP P Q R S T U HPTQ HRTS HNC1 HCop HCong1 Hcong2.
unfold BetS in *; spliter.
elim (col_dec P Q R); [exists P; split; ColR|intro HNC2].
destruct (HP P R Q S P U) as [I [HCol1 HCol2]]; [..|exists I; split]; Col.
apply l12_17 with T; [assert_diffs|split..]; Cong.
assert (Coplanar P Q R S) by (exists T; left; split; Col).
CopR.
Qed.

End proclus_SPP.


(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

(* This file is generated by Why3's Coq-realize driver *)
(* Beware! Only edit allowed sections below    *)
Require Import BuiltIn.
Require Reals.Rfunctions.
Require BuiltIn.
Require int.Int.
Require real.Real.
Require real.RealInfix.

Require Import Exponentiation.
Import Rfunctions.

(* Why3 comment *)
(* power is replaced with (Reals.Rfunctions.powerRZ x x1) by the coq driver *)

Lemma power_is_exponentiation :
  forall x n, (0 <= n)%Z -> powerRZ x n = Exponentiation.power _ R1 Rmult x n.
Proof.
intros x [|n|n] H.
easy.
2: now elim H.
unfold Exponentiation.power, powerRZ.
simpl.
induction (nat_of_P n).
easy.
simpl.
now rewrite IHn0.
Qed.

(* Why3 goal *)
Lemma Power_0 :
forall (x:R), ((Reals.Rfunctions.powerRZ x 0%Z) = 1%R).
Proof.
intros x.
easy.
Qed.

(* Why3 goal *)
Lemma Power_s :
forall (x:R) (n:Z),
 (0%Z <= n)%Z ->
 ((Reals.Rfunctions.powerRZ x (n + 1%Z)%Z) = (x * (Reals.Rfunctions.powerRZ x n))%R).
Proof.
intros x n h1.
rewrite 2!power_is_exponentiation by auto with zarith.
now apply Power_s.
Qed.

(* Why3 goal *)
Lemma Power_s_alt :
forall (x:R) (n:Z),
 (0%Z < n)%Z ->
 ((Reals.Rfunctions.powerRZ x n) = (x * (Reals.Rfunctions.powerRZ x (n - 1%Z)%Z))%R).
intros x n h1.
rewrite <- Power_s.
f_equal; omega.
omega.
Qed.

(* Why3 goal *)
Lemma Power_1 :
forall (x:R), ((Reals.Rfunctions.powerRZ x 1%Z) = x).
Proof.
exact Rmult_1_r.
Qed.

(* Why3 goal *)
Lemma Power_sum :
forall (x:R) (n:Z) (m:Z),
 (0%Z <= n)%Z ->
 ((0%Z <= m)%Z ->
  ((Reals.Rfunctions.powerRZ x (n + m)%Z) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ x m))%R)).
Proof.
intros x n m h1 h2.
rewrite 3!power_is_exponentiation by auto with zarith.
apply Power_sum ; auto with real.
Qed.

(* Why3 goal *)
Lemma Power_mult :
forall (x:R) (n:Z) (m:Z),
 (0%Z <= n)%Z ->
 ((0%Z <= m)%Z ->
  ((Reals.Rfunctions.powerRZ x (n * m)%Z) = (Reals.Rfunctions.powerRZ (Reals.Rfunctions.powerRZ x n) m))).
Proof.
intros x n m h1 h2.
rewrite 3!power_is_exponentiation by auto with zarith.
apply Power_mult ; auto with real.
Qed.

(* Why3 goal *)
Lemma Power_comm1 :
forall (x:R) (y:R),
 ((x * y)%R = (y * x)%R) ->
 forall (n:Z),
  (0%Z <= n)%Z ->
  (((Reals.Rfunctions.powerRZ x n) * y)%R = (y * (Reals.Rfunctions.powerRZ x n))%R).
intros x y h1 n h2.
apply Rmult_comm.
Qed.

(* Why3 goal *)
Lemma Power_comm2 :
forall (x:R) (y:R),
 ((x * y)%R = (y * x)%R) ->
 forall (n:Z),
  (0%Z <= n)%Z ->
  ((Reals.Rfunctions.powerRZ (x * y)%R n) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ y n))%R).
Proof.
intros x y h1 n h2.
rewrite 3!power_is_exponentiation by auto with zarith.
apply Power_comm2 ; auto with real.
Qed.

(* Why3 goal *)
Lemma Pow_ge_one :
forall (x:R) (n:Z),
 ((0%Z <= n)%Z /\ (1%R <= x)%R) -> (1%R <= (Reals.Rfunctions.powerRZ x n))%R.
intros x n (h1,h2).
generalize h1.
pattern n; apply Z_lt_induction; auto.
clear n h1; intros n Hind h1.
assert (h: (n = 0 \/ 0 < n)%Z) by omega.
destruct h.
subst n; rewrite Power_0; auto with *.
replace n with ((n-1)+1)%Z by omega.
rewrite Power_s; auto with zarith.
assert (h : (1 <= powerRZ x (n-1))%R).
apply Hind; omega.
replace 1%R with (1*1)%R by auto with real.
apply Rmult_le_compat; auto with real.
Qed.