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

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

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

Require Import Coq.Arith.EqNat.

(* ################################################################# *)
(** * 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
  | bool_cons (b : bool) (l : 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
  | cons (x : X) (l : list X).

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

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

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

(** The parameter [X] in the definition of [list] automatically
    becomes a parameter to the constructors [nil] and [cons] -- that
    is, [nil] and [cons] are now polymorphic constructors; when we use
    them, we must now provide a first argument that is the type of the
    list they are building. For example, [nil nat] constructs the
    empty list of type [nat]. *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(** **** Exercise: 2 stars, standard (mumble_grumble)

    Consider the following two inductively defined types. *)

Module MumbleGrumble.

Inductive mumble : Type :=
  | a
  | b (x : mumble) (y : nat)
  | c.

Inductive grumble (X:Type) : Type :=
  | d (m : mumble)
  | e (x : X).

(** Which of the following are well-typed elements of [grumble X] for
    some type [X]?  (Add YES or NO to each line.)
      - [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.

(* Do not modify the following line: *)
Definition manual_grade_for_mumble_grumble : option (nat*string) := None.
(** [] *)

(* ----------------------------------------------------------------- *)
(** *** 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 as [repeat].  Coq was able
    to use _type inference_ to deduce what the types of [X], [x], and
    [count] must be, based on how they are used.  For example, since
    [X] is used as an argument to [cons], it must be a [Type], since
    [cons] expects a [Type] as its first argument; matching [count]
    with [0] and [S] means it must be a [nat]; and so on.

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

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

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

    Fortunately, Coq permits us to avoid this kind of redundancy.  In
    place of any type argument we can write a "hole" [_], 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 holes, the [repeat] function can be written like this: *)

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

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

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

(** ...we can use holes to write this: *)

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

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

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

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

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

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

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

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

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

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

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

Inductive list' {X:Type} : Type :=
  | nil'
  | cons' (x : X) (l : list').

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

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

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

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

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

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

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

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

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

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

Fail Definition mynil := nil.

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

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

Definition mynil : list nat := nil.

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

Check @nil.

Definition mynil' := @nil nat.

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

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

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

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

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

(** **** Exercise: 2 stars, standard, optional (poly_exercises)

    Here are a few simple exercises, just like ones in the [Lists]
    chapter, for practice with polymorphism.  Complete the proofs below. *)

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

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

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

(** **** Exercise: 2 stars, standard, optional (more_poly_exercises)

    Here are some slightly more interesting ones... *)

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

Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
    intros.
  induction l.
  simpl. reflexivity.
  simpl.
  rewrite -> rev_app_distr .
  simpl.
  rewrite -> IHl.
  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_, often called _products_: *)

Inductive prod (X Y : Type) : Type :=
| pair (x : X) (y : 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, standard, 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, standard, recommended (split)

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

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

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

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

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

(** One last polymorphic type for now: _polymorphic options_,
    which generalize [natoption] from the previous chapter.  (We put
    the definition inside a module because the standard library
    already defines [option] and it's this one that we want to use
    below.) *)

Module OptionPlayground.

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

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

End OptionPlayground.

(** 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 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, standard, optional (hd_error_poly)

    Complete the definition of a polymorphic version of the
    [hd_error] function from the last chapter. Be sure that it
    passes the unit tests below. *)

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

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

Check @hd_error.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Definition length_is_1 {X : Type} (l : list X) : bool :=
  (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 => (length l) =? 1)
           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]
  = [ [3]; [4]; [8] ].
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars, standard (filter_even_gt7)

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

Definition filter_even_gt7 (l : list nat) : list nat :=
  filter (fun n => andb (negb (ltb n 7)) (evenb n) ) 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, standard (partition)

    Use [filter] to write a Coq function [partition]:

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

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

Definition partition {X : Type}
                     (test : X -> bool)
                     (l : list X)
                   : list X * list X :=
  (filter test l, filter (fun n => negb (test n)) 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 (fun x => plus 3 x) [2;0;2] = [5;3;5].
Proof. reflexivity.  Qed.

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

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

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

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

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

(** **** Exercise: 3 stars, standard (map_rev)

    Show that [map] and [rev] commute.  You may need to define an
    auxiliary lemma. *)

Lemma map_append : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),
  map f (l1 ++ l2) = (map f l1) ++ (map f l2).
Proof.
  intros.
  induction l1.
  {
     simpl. reflexivity.
  }
  {
     simpl.
     rewrite -> IHl1.
     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.
  {
     simpl. reflexivity.
  }
  {
     simpl.
     rewrite -> map_append.
     rewrite -> IHl.
     simpl.
     reflexivity.
}
Qed.
(** [] *)

(** **** Exercise: 2 stars, standard, recommended (flat_map)

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

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

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

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

(** Lists are not the only inductive type for which [map] makes sense.
    Here is a [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, standard, 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? *)

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_fold_types_different : option (nat*string) := None.
(** [] *)

(* ================================================================= *)
(** ** 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, standard (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].  (Hint: It may help to
    know that [reflexivity] simplifies expressions a bit more
    aggressively than [simpl] does -- i.e., you may find yourself in a
    situation where [simpl] does nothing but [reflexivity] solves the
    goal.) *)

Theorem fold_length_correct : forall X (l : list X),
  fold_length l = length l.
Proof.
   intros.
   induction l.
   {
      simpl. reflexivity.
   }
   {
      simpl.
      symmetry in IHl.
      rewrite -> IHl.
      reflexivity.
    }
Qed.

(** [] *)

(** **** Exercise: 3 stars, standard (fold_map)

    We can also define [map] in terms of [fold].  Finish [fold_map]
    below. *)

Definition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=
    fold cons (map f l) nil .

(** Write down a theorem [fold_map_correct] in Coq stating that
   [fold_map] is correct, and prove it.  (Hint: again, remember that
   [reflexivity] simplifies expressions a bit more aggressively than
   [simpl].) *)

Theorem fold_map_correct: forall X Y (l : list X) (f : X -> Y), fold_map f l = map f l .
Proof.
  intros.
  induction l.
  {
    simpl. reflexivity.
   }
  {
    simpl.
    symmetry in IHl.
      rewrite -> IHl.
      reflexivity.
   }
Qed.

(* Do not modify the following line: *)
Definition manual_grade_for_fold_map : option (nat*string) := None.
(** [] *)

(** **** Exercise: 2 stars, advanced (currying)

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

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

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

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

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

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

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

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

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

Check @prod_curry.
Check @prod_uncurry.

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

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

(** **** Exercise: 2 stars, advanced (nth_error_informal)

    Recall the definition of the [nth_error] function:

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

   Write an informal proof of the following theorem:

   forall X n l, length l = n -> @nth_error X l n = None
*)
(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_informal_proof : option (nat*string) := None.
(** [] *)

(** The following exercises 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. *)

Module Church.
Definition cnat := 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 : cnat :=
  fun (X : Type) (f : X -> X) (x : X) => f x.

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

Definition two : cnat :=
  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 : cnat :=
  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 : cnat := @doit3times.

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

(** **** Exercise: 1 star, advanced (church_succ)  *)

(** Successor of a natural number: given a Church numeral [n],
    the successor [succ n] is a function that iterates its
    argument once more than [n]. *)
Definition succ (n : cnat) : cnat := fun (X : Type) f x => n X f (f x).

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

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

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

(** [] *)

(** **** Exercise: 1 star, advanced (church_plus)  *)

(** Addition of two natural numbers: *)
Definition plus (n m : cnat) : cnat :=
  fun (X : Type) f x => m X f (n X f x).

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

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

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

(** [] *)

(** **** Exercise: 2 stars, advanced (church_mult)  *)

(** Multiplication: *)
Definition mult (n m : cnat) : cnat :=
  fun (X : Type) f x => m X (fun t => n X f t) x.

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

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

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

(** [] *)

(** **** Exercise: 2 stars, advanced (church_exp)  *)

(** 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.  Iterating over [cnat] itself is usually problematic.) *)

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

Example exp_1 : exp two two = plus two two.
Proof. reflexivity.  Qed.

Example exp_2 : exp three zero = one.
Proof. reflexivity.  Qed.

Example exp_3 : exp three two = plus (mult two (mult two two)) one.
Proof. reflexivity.  Qed.

(** [] *)

End Church.

End Exercises.

(* Wed Jan 9 12:02:44 EST 2019 *)


From mathcomp Require Import ssreflect ssrbool ssrfun.
From mathcomp Require Import eqtype ssrnat seq bigop order.
From ipcssr Require Import prelude.
Import Order.POrderTheory.
Import Order.TotalTheory.
Open Scope order_scope.

Inductive form A : Type :=
  | Falsum : form A
  | Atom : A -> form A
  | AndF : form A -> form A -> form A
  | OrF : form A -> form A -> form A
  | Imp : form A -> form A -> form A.

Arguments Falsum {A}.
Arguments Atom [A].
Arguments AndF [A].
Arguments OrF [A].
Arguments Imp [A].

Section Form.
Context {A : Type}.

Fixpoint vimp (qs : seq A) (f : form A) : form A :=
  if qs is q::qs' then vimp qs' (Imp (Atom q) f) else f.

End Form.

Section FormEq.
Context {A : eqType}.

Fixpoint eqform (f1 f2 : form A) :=
  match f1, f2 with
  | Falsum    , Falsum     => true
  | Atom i1   , Atom i2    => i1 == i2
  | AndF l1 r1, AndF l2 r2 => eqform l1 l2 && eqform r1 r2
  | OrF l1 r1 , OrF l2 r2  => eqform l1 l2 && eqform r1 r2
  | Imp l1 r1 , Imp l2 r2  => eqform l1 l2 && eqform r1 r2
  | _         , _          => false
  end.

Lemma eqformP: Equality.axiom eqform.
Proof.
elim=>[|i1|l1 IHl r1 IHr|l1 IHl r1 IHr|l1 IHl r1 IHr]; case=>[|i2|l2 r2|l2 r2|l2 r2] /=; try by constructor.
- case: (eqVneq i1 i2)=>[->|N]; constructor=>//.
  by apply: contra_neq_not N; case.
- by apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].
- by apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].
by apply: (equivP (andPP (IHl l2) (IHr r2))); split; [case=>->-> | case].
Qed.

Canonical form_eqMixin := EqMixin eqformP.
Canonical form_eqType := Eval hnf in EqType (form A) form_eqMixin.

Fixpoint subst_form (i : A) (a b : form A) : form A :=
  match b with
  | Falsum     => Falsum
  | Atom j     => if i == j then a else Atom j
  | AndF b0 b1 => AndF (subst_form i a b0) (subst_form i a b1)
  | OrF  b0 b1 => OrF  (subst_form i a b0) (subst_form i a b1)
  | Imp  b0 b1 => Imp  (subst_form i a b0) (subst_form i a b1)
  end.

Definition subst_list (i : A) (a : form A) (l : seq (form A)) :=
  map (subst_form i a) l.

Lemma subst_onth (i : A) (g : form A) (n : nat) (ctx : seq (form A)) :
  onth (subst_list i g ctx) n = omap (subst_form i g) (onth ctx n).
Proof. by elim: ctx n=>//= h ctx IH; case. Qed.

End FormEq.

Section FormOrd.
Context {disp : unit} {A : orderType disp}.

Fixpoint below_form (a : form A) (i : A) {struct a} : bool :=
  match a with
  | Falsum => true
  | Atom j => (j < i)%O
  | AndF x y => below_form x i && below_form y i
  | OrF  x y => below_form x i && below_form y i
  | Imp  x y => below_form x i && below_form y i
  end.

Definition below_list (l : seq (form A)) (i : A) :=
  all (below_form^~ i) l.

Lemma less_below_form_imply (a : form A) (i j : A) :
  (i < j)%O -> below_form a i ==> below_form a j.
Proof.
move=>H; elim: a=>//=.
- by move=>a; apply/implyP=>Ha; apply/lt_trans/H.
- by move=>f hf g Hg; apply: implyb_tensor.
- by move=>f hf g Hg; apply: implyb_tensor.
by move=>f hf g Hg; apply: implyb_tensor.
Qed.

Lemma less_below_list_imply (l : seq (form A)) (i j : A) :
  (i < j)%O -> below_list l i ==> below_list l j.
Proof.
move=>H; rewrite /below_list.
by apply/implyP/sub_all=>a; apply/implyP/less_below_form_imply.
Qed.

Lemma subst_form_below (i : A) (g a : form A) :
  below_form a i -> subst_form i g a = a.
Proof.
elim: a=>//=.
- by move=>a; rewrite lt_neqAle eq_sym=>/andP [/negbTE->].
- by move=>k IHk l IHl /andP [/IHk->/IHl->].
- by move=>k IHk l IHl /andP [/IHk->/IHl->].
by move=>k IHk l IHl /andP [/IHk->/IHl->].
Qed.

Lemma subst_list_below (i : A) (g : form A) (l : seq (form A)) :
  below_list l i -> subst_list i g l = l.
Proof.
rewrite /below_list /subst_list; elim: l=>//= h l IH.
case/andP=>H /IH->.
by rewrite (subst_form_below _ _ _ H).
Qed.

Lemma below_vimp (i : A) (l : seq A) (a b : form A) :
  (forall j : A, below_form a j ==> below_form b j) ->
  below_form (vimp l a) i ==> below_form (vimp l b) i.
Proof.
elim: l =>//= k l IH in a b *; move=>H.
by apply: IH=>/= j; apply/implyb_tensor.
Qed.

Lemma below_vimp_head (i : A) (l : seq A) (a : form A) :
  below_form (vimp l a) i ==> below_form a i.
Proof.
elim: l a=>//= h l IH a.
apply/implyb_trans/IH/below_vimp=>/= j.
by apply/implyP; case/andP.
Qed.

Lemma below_vimp_split (j : A) (l : seq A) (a : form A) :
  {in l, forall i, (i < j)%O} ->
  below_form a j ==> below_form (vimp l a) j.
Proof.
elim: l a=>//= h l IH a H.
apply/implyb_trans/IH=>/=; last first.
- by move=>z Hz; apply: (H z); rewrite inE Hz orbT.
apply/implyP=>->; rewrite andbT.
by apply: H; rewrite inE eqxx.
Qed.

Lemma below_vimp_tail (j : A) (l : seq A) (a : form A) :
  below_form (vimp l a) j -> {in l, forall i, (i < j)%O}.
Proof.
elim: l a=>//= h l IH a H z.
rewrite inE; case/orP=>[/eqP{z}->|]; last by apply: (IH _ H).
move: (below_vimp_head j l (Imp (Atom h) a))=>/=.
by move/implyP=>/(_ H); case/andP.
Qed.

Lemma subst_vimp_head (j : A) (l : seq A) (a b : form A) :
  {in l, forall i, (i < j)%O} ->
  subst_form j a (vimp l b) = vimp l (subst_form j a b).
Proof.
elim: l=>//= h l IH in a b *; move=>H.
rewrite IH /=; last first.
- by move=>z Hz; apply: (H z); rewrite inE Hz orbT.
case: eqP=>// E.
by move: (H j); rewrite E inE eqxx ltxx /= => /(_ erefl).
Qed.

End FormOrd.

(* could be abstracted as ssr num but probably not worth it *)
Section FormNat.

Fixpoint max_int_of_form (f : form nat) : nat :=
  match f with
  | Falsum => 0
  | Atom i => i.+1
  | AndF f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)
  | OrF  f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)
  | Imp  f0 f1 => maxn (max_int_of_form f0) (max_int_of_form f1)
  end.

Lemma max_int_of_form_below (a : form nat) : below_form a (max_int_of_form a).
Proof.
elim: a=>//=.
- by move=>a; rewrite ltEnat /= ltnS.
- move=>f IHf g IHg.
  case: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.
  - by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.
  - by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.
  by rewrite IHf /= H.
- move=>f IHf g IHg.
  case: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.
  - by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.
  - by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.
  by rewrite IHf /= H.
move=>f IHf g IHg.
case: (ltngtP (max_int_of_form f) (max_int_of_form g))=>H.
- by rewrite IHg andbT; move: IHf; apply/implyP/less_below_form_imply.
- by rewrite IHf; move: IHg; apply/implyP/less_below_form_imply.
by rewrite IHf /= H.
Qed.

Definition max_int_of_list (l : seq (form nat)) : nat :=
  foldr (maxn \o max_int_of_form) 0 l.

Lemma max_int_of_list_below (g : seq (form nat)) : below_list g (max_int_of_list g).
Proof.
elim: g=>//=h g IH.
have H := max_int_of_form_below h.
case: (ltngtP (max_int_of_form h) (max_int_of_list g))=>H2.
- by rewrite IH andbT; move: H; apply/implyP/less_below_form_imply.
- by rewrite H /=; move: IH; apply/implyP/less_below_list_imply.
by rewrite H /= H2.
Qed.

End FormNat.


(**
   GEB の TNT で証明された定理を Coq で証明する。
   2011_10_22
   *)

(** s と 「+」を定義する。*)
Inductive Nat : Set :=
| O : Nat
| s : Nat -> Nat.
Variable add : Nat -> Nat -> Nat.
Infix ".+" := add (at level 61, left associativity).

(** 公理 *)
Axiom a_2 : forall a, a .+ O = a.                (* 公理(2) *)
Axiom a_3 : forall a b, a .+ (s b) = s (a .+ b). (* 公理(3) *)

(**
   「S入れ」は、推論規則とされているが、補題として証明しておく。
   *)
Lemma s_in : forall r t, r = t -> (s r) = (s t).
Proof.
  intros.
  induction r.
  rewrite H.
  reflexivity.
  rewrite H.
  reflexivity.
Qed.

(**
   [GEB白1985] p.232で証明された定理を証明する。
   *)
Theorem t232 : forall a, (O .+ a) = a.
Proof.
  intro a.                              (* 特殊化 *)
  induction a as [|b IH].               (* 機能規則 *)
  Check (a_2 O).                        (* 「ピラミッドの最初の式」 *)
  apply (a_2 O).                        (* 帰納の二番目の前提 *)
  Check (a_3 O b).                      (* 式(7) *)
  rewrite (a_3 O b).                    (* 推移性 *)
  apply s_in.                           (* S入れ *)
  apply IH.                             (* 帰納の一番目の前提 *)
Qed.

(**
   補題、式(18)
   *)
Lemma l18 : forall c,
  (forall d, d .+ s c = s d .+ c) ->
  (forall d, d .+ s (s c) = s d .+ s c).
Proof.
  intros c H d.                             (* 特殊化 *)
  Check (a_3 d (s c)).                      (* 式(3) *)
  Check (a_3 (s d) c).                      (* 式(5) *)
  rewrite (a_3 (s d) c).                    (* 推移性、式(6) *)
  rewrite (a_3 d (s c)).                    (* 推移性、式(3) *)
  apply s_in.                               (* S入れ *)
  apply H.                                  (* 前提 *)
Qed.

(**
   補題、式(28)
   Sは加法において、前や後ろに移動できる。
   *)
Lemma l28 : forall c d, d .+ s c = s d .+ c.
Proof.
  induction c as [|c IH].                   (* 帰納規則 *)
  intros d.                                 (* 特殊化 *)
  Check (a_3 d O).                          (* 式(19) *)
  Check (a_2 (s d)).                        (* 式(26) *)
  rewrite (a_3 d O).                        (* 推移性、式(19) *)
  rewrite (a_2 (s d)).                      (* 推移性、式(26) *)
  apply s_in.                               (* S入れ *)
  apply a_2.                                (* 帰納の前提 *)
  Check (l18 c).                            (* *** *)
  apply (l18 c).                            (* *** *)
  apply IH.                                 (* 帰納の前提 *)
Qed.

(**
   補題、式(49)
   もしdが任意のcと交換可能なら、同じことがs dについてもいえる。
   *)
Lemma l49 : forall d,
  (forall c, c .+ d = d .+ c) ->
  (forall c, c .+ s d = s d .+ c).
Proof.
  intros d H.                             (* 特殊化 *)
  intros c.                               (* 特殊化 *)
  Check (a_3 c d).                        (* 式(30) *)
  Check (a_3 d c).                        (* 式(33) *)
  Check (l28 c d).                        (* 式(35) *)
  rewrite <- (l28 c d).                   (* 推移性、式(35) *)
  rewrite (a_3 d c).                      (* 推移性、式(33) *)
  rewrite (a_3 c d).                      (* 推移性、式(30) *)
  apply s_in.                             (* S入れ。 *)
  apply H.                                (* 前提 *)
Qed.

(**
   定理、[GEB白1985] p.234
   *)
Theorem geb_tnt_1 : forall d c, c .+ d = d .+ c.
Proof.
  intros d.                                 (* 特殊化 *)
  induction d as [|d H].                    (* 帰納規則 *)
  intros c.                                 (* 特殊化 *)
  Check (t232 c).                           (* 式(52) *)
  rewrite (t232 c).                         (* 推移性、式(52) *)
  apply a_2.                                (* 帰納の前提 *)
  apply l49.                                (* *** *)
  apply H.                                  (* 帰納の前提 *)
Qed.

(* END *)


Require Export GeoCoq.Elements.OriginalProofs.lemma_ray1.
Require Export GeoCoq.Elements.OriginalProofs.lemma_interior5.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma lemma_8_3 :
   forall A B C D,
   Per A B C -> Out B C D ->
   Per A B D.
Proof.
intros.
let Tf:=fresh in
assert (Tf:exists E, (BetS A B E /\ Cong A B E B /\ Cong A C E C /\ neq B C)) by (conclude_def Per );destruct Tf as [E];spliter.
assert (Cong B C B C) by (conclude cn_congruencereflexive).
assert (Cong C D C D) by (conclude cn_congruencereflexive).
assert (Cong B A B E) by (forward_using lemma_congruenceflip).
assert (Cong C A C E) by (forward_using lemma_congruenceflip).
assert ((BetS B D C \/ eq C D \/ BetS B C D)) by (conclude lemma_ray1).
assert (Per A B D).
by cases on (BetS B D C \/ eq C D \/ BetS B C D).
{
 assert (Cong B D B D) by (conclude cn_congruencereflexive).
 assert (Cong D C D C) by (conclude cn_congruencereflexive).
 assert (Cong D A D E) by (conclude lemma_interior5).
 assert (Cong A D E D) by (forward_using lemma_congruenceflip).
 assert (neq B D) by (forward_using lemma_betweennotequal).
 assert (Per A B D) by (conclude_def Per ).
 close.
 }
{
 assert (Per A B D) by (conclude cn_equalitysub).
 close.
 }
{
 assert (Cong A D E D) by (conclude axiom_5_line).
 assert (neq B D) by (forward_using lemma_betweennotequal).
 assert (Per A B D) by (conclude_def Per ).
 close.
 }
(** cases *)
close.
Qed.

End Euclid.


Require Import CT.Category.
Require Import CT.Functor.
Require Import CT.Instance.Functor.ComposeFunctor.
Require Import CT.Instance.Functor.Endofunctor.
Require Import CT.Instance.Functor.FaithfulFunctor.
Require Import CT.Instance.Functor.FullFunctor.

Program Definition IdentityFunctor {C : Category} : @Endofunctor C :=
  {| F_ob := fun x => x;
     F_mor := fun _ _ f => f;
  |}.

(** The identity functor is always faithful. *)
Theorem identity_is_faithful (C : Category) : FaithfulFunctor (@IdentityFunctor C).
Proof.
  intro.
  simpl.
  trivial.
Qed.

(** The identity functor is always full. *)
Theorem identity_is_full (C : Category) : FullFunctor (@IdentityFunctor C).
Proof.
  repeat intro.
  exists f.
  simpl.
  reflexivity.
Qed.

(** Composition of [IdentityFunctor]s is still the [IdentityFunctor]. *)
Theorem comp_identity_identity :
  forall {C : Category} (F G : @Endofunctor C),
    F = @IdentityFunctor C ->
    G = @IdentityFunctor C ->
    ComposeFunctor F G = @IdentityFunctor C.
Proof.
  intros.
  unfold ComposeFunctor.
  subst.
  simpl.
  unfold IdentityFunctor at 5.
  apply F_eq;
    reflexivity.
Qed.

(** Composition of anything with the [IdentityFunctor] the original thing. *)
Theorem comp_identity_right :
  forall {A B : Category} (F : Functor A B) (G : Functor B B),
    G = @IdentityFunctor B ->
    ComposeFunctor F G = F.
Proof.
  intros.
  unfold ComposeFunctor.
  subst.
  apply F_eq;
    reflexivity.
Qed.

Theorem comp_identity_left :
  forall {A B : Category} (F : Functor A B) (G : Functor A A),
    G = @IdentityFunctor A ->
    ComposeFunctor G F = F.
Proof.
  intros.
  unfold ComposeFunctor.
  subst.
  apply F_eq;
    reflexivity.
Qed.


(**************************************************************)
(*   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 Bool Lia Eqdep_dec.

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

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

From Undecidability.FOL.TRAKHTENBROT
  Require Import notations utils fol_ops fo_sig fo_terms fo_logic fo_sat.

Import fol_notations.

Set Implicit Arguments.

(* * Uniformize the arity of relations *)

Local Notation ø := vec_nil.

Section vec_fill_tail.

  Variable (X : Type) (n : nat) (k : nat) (v : vec X k) (e : X).

  Definition vec_fill_tail : vec X n.
  Proof using v e.
    apply vec_set_pos; intros p.
    destruct (le_lt_dec k (pos2nat p)) as [ | H ].
    + exact e.
    + exact (vec_pos v (nat2pos H)).
  Defined.

  Fact vec_fill_tail_lt p (Hp : pos2nat p < k) : vec_pos vec_fill_tail p = vec_pos v (nat2pos Hp).
  Proof.
    unfold vec_fill_tail; rew vec.
    destruct (le_lt_dec k (pos2nat p)).
    + exfalso; lia.
    + do 2 f_equal; apply lt_pirr.
  Qed.

  Fact vec_fill_tail_ge p : k <= pos2nat p -> vec_pos vec_fill_tail p = e.
  Proof.
    intros H; unfold vec_fill_tail; rew vec.
    destruct (le_lt_dec k (pos2nat p)); auto; exfalso; lia.
  Qed.

End vec_fill_tail.

Opaque vec_fill_tail.

Fact vec_map_fill_tail X Y (f : X -> Y) n k v e :
  vec_map f (@vec_fill_tail X n k v e) = vec_fill_tail n (vec_map f v) (f e).
Proof.
  apply vec_pos_ext; intros p; rew vec.
  destruct (le_lt_dec k (pos2nat p)) as [ | Hp ].
  + do 2 (rewrite vec_fill_tail_ge; auto).
  + do 2 rewrite vec_fill_tail_lt with (Hp := Hp); rew vec.
Qed.

Section vec_first_half.

  Variable (X : Type) (n : nat) (k : nat) (Hk : k <= n).

  Definition vec_first_half (v : vec X n) : vec X k.
  Proof using Hk.
    apply vec_set_pos; intros p.
    refine (vec_pos v (@nat2pos _ (pos2nat p) _)).
    apply Nat.lt_le_trans with (2 := Hk), pos2nat_prop.
  Defined.

  Fact vec_first_half_fill_tail v e : vec_first_half (vec_fill_tail _ v e) = v.
  Proof.
    apply vec_pos_ext; intros p.
    unfold vec_first_half; rew vec.
    match goal with
      | |- vec_pos _ ?p = _ => assert (H : pos2nat p < k)
    end.
    { rewrite pos2nat_nat2pos; apply pos2nat_prop. }
    rewrite vec_fill_tail_lt with (Hp := H).
    revert H.
    rewrite pos2nat_nat2pos.
    intros; f_equal; apply nat2pos_pos2nat.
  Qed.

End vec_first_half.

Section Sig_uniformize_rels.

  Variable (Σ : fo_signature) (n : nat) (Hn : forall r, ar_rels Σ r <= n).

  Definition Σunif : fo_signature.
  Proof using Σ n.
    exists (syms Σ) (rels Σ).
    + exact (ar_syms Σ).
    + exact (fun _ => n).
  Defined.

  Notation Σ' := Σunif.

  Fixpoint fol_uniformize (A : fol_form Σ) : fol_form Σ' :=
    match A with
      | ⊥                => ⊥
      | @fol_atom _ r v  => @fol_atom Σ' r (vec_fill_tail _ v (£0))
      | fol_bin c A B    => fol_bin c (fol_uniformize A) (fol_uniformize B)
      | fol_quant q A    => fol_quant q (fol_uniformize A)
    end.

  Variable (X : Type) (e : X).

  Section soundness.

    Variables (M : fo_model Σ X).

    Local Definition fom_uniformize : fo_model Σ' X.
    Proof using M Hn.
      split.
      + intros s; apply (fom_syms M s).
      + intros r v; exact (fom_rels M r (vec_first_half (Hn r) v)).
    Defined.

    Notation M' := fom_uniformize.

    Theorem fol_uniformize_sound A φ :
        fol_sem M φ A <-> fol_sem M' φ (fol_uniformize A).
    Proof.
      revert φ; induction A as [ | r v | A HA B HB | q A HA ]; simpl; try tauto; intros phi.
      + apply fol_equiv_ext; f_equal.
        rewrite vec_map_fill_tail, vec_first_half_fill_tail; auto.
      + apply fol_bin_sem_ext; auto.
      + apply fol_quant_sem_ext; auto.
    Qed.

  End soundness.

  Variable (lr : list (rels Σ)).

  Section completeness.

    Variable (M' : fo_model Σ' X).

    Local Definition fom_specialize : fo_model Σ X.
    Proof using M' e.
      split.
      + intros s; apply (fom_syms M' s).
      + intros r v; exact (fom_rels M' r (vec_fill_tail n v e)).
    Defined.

    Notation M := fom_specialize.

    Section uniform_after.

      Variable (r : rels Σ).

      Let k := ar_rels _ r.

      Let w1 : vec (fol_term Σ') _ :=
           vec_fill_tail n (vec_set_pos (fun p : pos k => £(2+pos2nat p))) (£ 1).
      Let w2 : vec (fol_term Σ') _ :=
           vec_fill_tail n (vec_set_pos (fun p : pos k => £(2+pos2nat p))) (£ 0).

      Local Definition fol_uniform_after : fol_form Σ' :=
           fol_mquant fol_fa k (∀∀ @fol_atom Σ' r w1 ↔ @fol_atom Σ' r w2).

      Local Fact fol_uniform_after_spec φ :
           fol_sem M' φ fol_uniform_after
       <-> forall v e1 e2,  fom_rels M' r (@vec_fill_tail _ n k v e1)
                        <-> fom_rels M' r (vec_fill_tail n v e2).
      Proof.
        unfold fol_uniform_after.
        rewrite fol_sem_mforall.
        apply forall_equiv; intros v.
        rewrite fol_sem_quant_fix.
        apply forall_equiv; intros e1.
        rewrite fol_sem_quant_fix.
        apply forall_equiv; intros e2.
        apply fol_equiv_sem_ext.
        + apply fol_equiv_ext; f_equal.
          unfold w1; rewrite vec_map_fill_tail; simpl; f_equal.
          apply vec_pos_ext; intros p; rew vec; simpl.
          rewrite env_vlift_fix0; auto.
        + apply fol_equiv_ext; f_equal.
          unfold w2; rewrite vec_map_fill_tail; simpl; f_equal.
          apply vec_pos_ext; intros p; rew vec; simpl.
          rewrite env_vlift_fix0; auto.
      Qed.

    End uniform_after.

    Local Definition fol_all_uniform_after : fol_form Σ' :=
             fol_lconj (map fol_uniform_after lr).

    Let uniform := forall r, In r lr -> forall (v : vec _ (ar_rels _ r)) e1 e2,
                            fom_rels M' r (vec_fill_tail n v e1)
                        <-> fom_rels M' r (vec_fill_tail n v e2).

    Local Fact fol_all_uniform_after_spec φ :
            fol_sem M' φ fol_all_uniform_after <-> uniform.
    Proof.
      unfold fol_all_uniform_after.
      rewrite fol_sem_lconj; unfold uniform.
      split.
      + intros H r Hr.
        apply (fol_uniform_after_spec _ φ), H, in_map_iff.
        exists r; auto.
      + intros H f; rewrite in_map_iff.
        intros (r & <- & Hr); apply fol_uniform_after_spec, H; auto.
    Qed.

    Hypothesis Hlr : uniform.

    Theorem fol_uniformize_complete A φ :
          incl (fol_rels A) lr
       -> fol_sem M φ A <-> fol_sem M' φ (fol_uniformize A).
    Proof using Hlr.
      revert φ; induction A as [ | r v | b A HA B HB | q A HA ]; simpl; try tauto; intros phi Hr.
      + rewrite vec_map_fill_tail; rew fot.
        apply Hlr, Hr; simpl; auto.
      + apply fol_bin_sem_ext; auto.
        * apply HA; intros ? ?; apply Hr, in_app_iff; auto.
        * apply HB; intros ? ?; apply Hr, in_app_iff; auto.
      + apply fol_quant_sem_ext; auto.
    Qed.

  End completeness.

  Variable (A : fol_form Σ) (HA : incl (fol_rels A) lr).

  Definition Σuniformize := fol_all_uniform_after ⟑ fol_uniformize A.

  Theorem Σuniformize_sound : fo_form_fin_dec_SAT_in A X
                           -> fo_form_fin_dec_SAT_in Σuniformize X.
  Proof using Hn.
    intros (M & H1 & H2 & phi & H).
    exists (fom_uniformize M), H1.
    exists.
    { intros ? ?; apply H2. }
    exists phi; split.
    + apply fol_all_uniform_after_spec.
      intros r _ v e1 e2; simpl.
      do 2 rewrite vec_first_half_fill_tail; tauto.
    + revert H; apply fol_uniformize_sound.
  Qed.

  Theorem Σuniformize_complete : fo_form_fin_dec_SAT_in Σuniformize X
                              -> fo_form_fin_dec_SAT_in A X.
  Proof using e HA.
    intros (M' & H1 & H2 & phi & H3 & H4).
    rewrite fol_all_uniform_after_spec in H3.
    exists (fom_specialize M'), H1.
    exists.
    { intros ? ?; apply H2. }
    exists phi.
    revert H4.
    apply fol_uniformize_complete; auto.
  Qed.

End Sig_uniformize_rels.


Require Import ZArith.
Require Import ASN1FP.Conversion.IEEE_ASN.

Open Scope Z.

(*
 * auxiliary functions for the most common formats
 * combining partial conversions into one full pass
 *)

Section B32.

  Let prec := 24.
  Let emax := 128.
  Let prec_gt_1 : prec > 1.
  Proof. reflexivity. Qed.
  Let prec_lt_emax : prec < emax.
  Proof. subst prec. subst emax. reflexivity. Qed.

  Definition normalize_b32_abstract (m e : Z) :=
    let '(mx, ex) := normalize_IEEE_finite prec emax (Z.to_pos m) e in
    (Zpos mx, ex).

  Definition BER_of_b32_abstract := BER_of_IEEE_exact prec emax.

  Definition b32_of_BER_abstract_exact := IEEE_of_BER_exact prec emax prec_gt_1.

  Definition b32_of_BER_abstract_rounded := IEEE_of_BER_rounded prec emax prec_gt_1 prec_lt_emax.

End B32.

Section B64.

  Let prec := 53%Z.
  Let emax := 1024%Z.
  Let prec_gt_1 : prec > 1.
  Proof. reflexivity. Qed.
  Let prec_lt_emax : prec < emax.
  Proof. subst prec. subst emax. reflexivity. Qed.

  Definition normalize_b64_abstract (m e : Z) :=
    let '(mx, ex) := normalize_IEEE_finite prec emax (Z.to_pos m) e in
    (Zpos mx, ex).

  Definition BER_of_b64_abstract := BER_of_IEEE_exact prec emax.

  Definition b64_of_BER_abstract_exact := IEEE_of_BER_exact prec emax prec_gt_1.

  Definition b64_of_BER_abstract_rounded := IEEE_of_BER_rounded prec emax prec_gt_1 prec_lt_emax.

End B64.


(* First, let us look at some example : *)

Lemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.
Proof.
 intros P Q H p; apply H.
 intro H0;apply H0;assumption.
Qed.

Lemma triple_neg : forall P:Prop, ~~~P -> ~P.
Proof.
 intros P ;unfold not; apply P3Q.
Qed.

Lemma all_perm :
 forall (A:Type) (P:A -> A -> Prop),
   (forall x y:A, P x y) ->
   forall x y:A, P y x.
Proof.
Admitted.

Lemma resolution :
 forall (A:Type) (P Q R S:A -> Prop),
   (forall a:A, Q a -> R a -> S a) ->
   (forall b:A, P b -> Q b) ->
   forall c:A, P c -> R c -> S c.
Proof.
Admitted.

Lemma not_ex_forall_not : forall (A: Type) (P: A -> Prop),
                      ~(exists x, P x) <-> forall x, ~ P x.
Proof.
Admitted.

Lemma ex_not_forall_not : forall (A: Type) (P: A -> Prop),
                       (exists x, P x) -> ~ (forall x, ~ P x).
Proof.
Admitted.

Lemma diff_sym : forall (A:Type) (a b : A), a <> b -> b <> a.
Proof.
Admitted.

Lemma fun_diff :  forall (A B:Type) (f : A -> B) (a b : A),
                       f a <> f b -> a <> b.
Proof.
Admitted.


(* Suzuki, Michio - Group Theory. I *)
From mathcomp
  Require Import ssreflect.
Require Import Coq.Logic.Description.
Require Import Coq.Logic.FinFun.
Require Import Coq.Logic.Classical_Prop.
Require Import Coq.Logic.FunctionalExtensionality.
Require Import Coq.Logic.JMeq.
Require Import Coq.Program.Basics.

(* Definition 1.1. *)
Structure group : Type := make_group
{
  group_carrier : Set;
  group_inhab : inhabited group_carrier;
  group_mul : group_carrier -> group_carrier -> group_carrier;
  group_mul_assoc : forall a b c : group_carrier, group_mul (group_mul a b) c = group_mul a (group_mul b c);
  group_r_trans : forall a b : group_carrier, exists x : group_carrier, group_mul a x = b;
  group_l_trans : forall a b : group_carrier, exists y : group_carrier, group_mul y a = b;
}.

Theorem group_eq (G0 G1 : group) :
  group_carrier G0 = group_carrier G1
  -> JMeq (group_mul G0) (group_mul G1)
  -> G0 = G1.
Proof.
  move=> Hcarrier Hmul.
  destruct G0 as [carrier0 inhab0 mul0 mul_assoc0 r_trans0 l_trans0].
  destruct G1 as [carrier1 inhab1 mul1 mul_assoc1 r_trans1 l_trans1].
  simpl in * |- *.
  destruct Hcarrier.
  apply JMeq_eq in Hmul.
  destruct Hmul.
  f_equal; apply proof_irrelevance.
Qed.

(* Definition 1.3. *)
Definition is_group_one (G : group) (e : group_carrier G) :=
  forall g : group_carrier G, group_mul G g e = g /\ group_mul G e g = g.

(* Theorem 1.2.(ii)' *)
Theorem group_one_ex_uni (G : group) :
  exists! group_one : group_carrier G, is_group_one G group_one.
Proof.
  destruct (group_inhab G) as [a].
  destruct (group_r_trans G a a) as [e Hae_eq_a].
  destruct (group_l_trans G a a) as [e' He'a_eq_a].
  exists e.

  assert (forall g : group_carrier G, group_mul G g e = g) as He_oner.
  + move=> g.
    destruct (group_r_trans G a g) as [u Hau_eq_g].
    destruct (group_l_trans G a g) as [v Hva_eq_g].
    rewrite -Hva_eq_g.
    rewrite group_mul_assoc.
    rewrite Hae_eq_a.
    by [].

  assert (forall g : group_carrier G, group_mul G e' g = g) as He'_onel.
  + move=> g.
    destruct (group_r_trans G a g) as [u Hau_eq_g].
    destruct (group_l_trans G a g) as [v Hva_eq_g].
    rewrite -Hau_eq_g.
    rewrite -group_mul_assoc.
    rewrite He'a_eq_a.
    by [].

  assert (e = e') as He_eq_e'.
  + rewrite -(He_oner e').
    rewrite (He'_onel e).
    by [].

  split.
  + move=> g.
    split.
    + apply (He_oner g).
    + rewrite He_eq_e'.
      rewrite (He'_onel g).
      by [].
  + move=> g Hg_one.
    destruct (Hg_one e) as [Heg_eq_e Hge_eq_e].
    rewrite -(He_oner g).
    rewrite Hge_eq_e.
    by [].
Qed.

Definition group_one (G : group) : group_carrier G
  := let 'exist one Hone := (constructive_definite_description (is_group_one G) (group_one_ex_uni G)) in one.

Theorem group_one_is_group_one (G : group) : is_group_one G (group_one G).
Proof.
  remember (group_one G) as e eqn: H.
  unfold group_one in H.
  destruct (constructive_definite_description (is_group_one G) (group_one_ex_uni G)) as [e' He'] in H.
  rewrite H.
  exact He'.
Qed.

Definition are_mut_inv (G : group) (a a' : group_carrier G) :=
  group_mul G a a' = group_one G /\ group_mul G a' a = group_one G.

(* Theorem 1.2.(ii)'' *)
Theorem group_inv_ex_uni (G : group) (a : group_carrier G) :
  exists! a' : group_carrier G, are_mut_inv G a a'.
Proof.
  destruct (group_r_trans G a (group_one G)) as [a' Haa'_eq_one].
  destruct (group_l_trans G a (group_one G)) as [a'' Ha''a_eq_one].

  assert (a' = a'') as Ha'_eq_a''.
  + rewrite -(proj1 ((group_one_is_group_one G) a'')).
    rewrite -Haa'_eq_one.
    rewrite -(group_mul_assoc G a'' a a').
    rewrite Ha''a_eq_one.
    rewrite (proj2 ((group_one_is_group_one G) a')).
    by [].

  rewrite -Ha'_eq_a'' in Ha''a_eq_one.
  exists a'.

  split.
  + split.
    + exact Haa'_eq_one.
    + exact Ha''a_eq_one.
  + move=> a''' [Hax_eq_one Hxa_eq_one].
    rewrite -(proj1 ((group_one_is_group_one G) a')).
    rewrite -Hax_eq_one.
    rewrite -(group_mul_assoc G a' a a''').
    rewrite Ha''a_eq_one.
    rewrite (proj2 ((group_one_is_group_one G) a''')).
    by [].
Qed.

Definition group_inv (G : group) : group_carrier G -> group_carrier G
  := fun a => let 'exist a' Ha' := (constructive_definite_description (are_mut_inv G a) (group_inv_ex_uni G a)) in a'.

Theorem group_inv_is_group_inv (G : group) (a : group_carrier G) : are_mut_inv G a (group_inv G a).
Proof.
  remember (group_inv G a) as a' eqn: H.
  unfold group_inv in H.
  destruct (constructive_definite_description (are_mut_inv G a) (group_inv_ex_uni G a)) as [a'' Ha''] in H.
  rewrite H.
  exact Ha''.
Qed.

Theorem group_one_mul (G : group) :
  forall a : group_carrier G,
  group_mul G (group_one G) a = a.
Proof.
  move=> a.
  exact (proj2 ((group_one_is_group_one G) a)).
Qed.

Theorem group_mul_one (G : group) :
  forall a : group_carrier G,
  group_mul G a (group_one G) = a.
Proof.
  move=> a.
  exact (proj1 ((group_one_is_group_one G) a)).
Qed.

Theorem group_inv_mul (G : group) :
  forall a : group_carrier G,
  group_mul G (group_inv G a) a = group_one G.
Proof.
  move=> a.
  exact (proj2 ((group_inv_is_group_inv G) a)).
Qed.

Theorem group_mul_inv (G : group) :
  forall a : group_carrier G,
  group_mul G a (group_inv G a) = group_one G.
Proof.
  move=> a.
  exact (proj1 ((group_inv_is_group_inv G) a)).
Qed.

Theorem group_one_inv (G : group) :
  group_inv G (group_one G) = group_one G.
Proof.
  pose proof (group_inv_ex_uni G (group_one G)) as Hex_uni.
  rewrite <- unique_existence in Hex_uni.
  destruct Hex_uni as [Hex Huni].
  apply (Huni (group_inv G (group_one G)) (group_one G)).
  + exact (group_inv_is_group_inv G (group_one G)).
  + split; rewrite group_one_mul; reflexivity.
Qed.

(* Theorem 1.2.(iii).1 *)
Theorem group_r_trans_ex_uni (G : group) :
  forall a b x : group_carrier G, group_mul G a x = b -> x = group_mul G (group_inv G a) b.
Proof.
  move=> a b x Hax_eq_b.
  rewrite -Hax_eq_b.
  rewrite -group_mul_assoc.
  rewrite (proj2 (group_inv_is_group_inv G a)).
  rewrite (proj2 (group_one_is_group_one G x)).
  reflexivity.
Qed.

(* Theorem 1.2.(iii).2 *)
Theorem group_l_trans_ex_uni (G : group) :
  forall a b y : group_carrier G, group_mul G y a = b -> y = group_mul G b (group_inv G a).
Proof.
  move=> a b y Hya_eq_b.
  rewrite -Hya_eq_b.
  rewrite group_mul_assoc.
  rewrite (proj1 (group_inv_is_group_inv G a)).
  rewrite (proj1 (group_one_is_group_one G y)).
  reflexivity.
Qed.

(* Corollary_p4_l7 *)
Structure group' : Type := make_group'
{
  group'_carrier : Set;
  group'_one : group'_carrier;
  group'_inv : group'_carrier -> group'_carrier;
  group'_mul : group'_carrier -> group'_carrier -> group'_carrier;
  group'_mul_assoc : forall a b c : group'_carrier, group'_mul (group'_mul a b) c = group'_mul a (group'_mul b c);
  group'_one_mul : forall a : group'_carrier, group'_mul group'_one a = a;
  group'_mul_one : forall a : group'_carrier, group'_mul a group'_one = a;
  group'_inv_mul : forall a : group'_carrier, group'_mul (group'_inv a) a = group'_one;
  group'_mul_inv : forall a : group'_carrier, group'_mul a (group'_inv a) = group'_one;
}.

Theorem group'_eq (G0 G1 : group') :
  group'_carrier G0 = group'_carrier G1
  -> JMeq (group'_mul G0) (group'_mul G1)
  -> G0 = G1.
Proof.
  move => Hcarrier Hmul.
  destruct G0 as [carrier0 one0 inv0 mul0 mul_assoc0 one_mul0 mul_one0 inv_mul0 mul_inv0].
  destruct G1 as [carrier1 one1 inv1 mul1 mul_assoc1 one_mul1 mul_one1 inv_mul1 mul_inv1].
  simpl in * |- *.
  destruct Hcarrier.
  apply JMeq_eq in Hmul.
  destruct Hmul.

  assert (one0 = one1) as Hone.
  + rewrite -(one_mul0 one1).
    rewrite (mul_one1 one0).
    reflexivity.
  destruct Hone.

  assert (inv0 = inv1) as Hinv.
  + apply functional_extensionality.
    move=> x.
    rewrite -(mul_one0 (inv0 x)).
    rewrite -(mul_inv1 x).
    rewrite -mul_assoc0.
    rewrite (inv_mul0 x).
    rewrite (one_mul0 (inv1 x)).
    reflexivity.
  destruct Hinv.

  f_equal; apply proof_irrelevance.
Qed.

Definition group_to_group' : group -> group'
  := fun G => (make_group'
    (group_carrier G)
    (group_one G)
    (group_inv G)
    (group_mul G)
    (group_mul_assoc G)
    (fun a => proj2 (group_one_is_group_one G a))
    (fun a => proj1 (group_one_is_group_one G a))
    (fun a => proj2 (group_inv_is_group_inv G a))
    (fun a => proj1 (group_inv_is_group_inv G a))
  ).

Theorem group'_to_group_sub_r (G' : group') :
  forall a b : group'_carrier G', exists x : group'_carrier G', group'_mul G' a x = b.
Proof.
  move=> a b.
  exists (group'_mul G' (group'_inv G' a) b).
  rewrite -group'_mul_assoc.
  rewrite group'_mul_inv.
  rewrite group'_one_mul.
  reflexivity.
Qed.

Theorem group'_to_group_sub_l (G' : group') :
  forall a b : group'_carrier G', exists y : group'_carrier G', group'_mul G' y a = b.
Proof.
  move=> a b.
  exists (group'_mul G' b (group'_inv G' a)).
  rewrite group'_mul_assoc.
  rewrite group'_inv_mul.
  rewrite group'_mul_one.
  reflexivity.
Qed.

Definition group'_to_group : group' -> group
  := fun G' => (make_group
    (group'_carrier G')
    (inhabits (group'_one G'))
    (group'_mul G')
    (group'_mul_assoc G')
    (group'_to_group_sub_r G')
    (group'_to_group_sub_l G')
  ).

Theorem group_to_group'_to_group_is_id :
  compose group'_to_group group_to_group' = id.
Proof.
  apply functional_extensionality.
  move=> G.
  destruct G.
  unfold id.
  unfold compose.
  unfold group_to_group'.
  unfold group'_to_group.
  simpl.
  f_equal; apply proof_irrelevance.
Qed.

Theorem group'_to_group_to_group'_is_id :
  compose group_to_group' group'_to_group = id.
Proof.
  apply functional_extensionality.
  move=> G'.
  destruct G'.
  unfold id.
  unfold compose.
  unfold group_to_group'.
  unfold group'_to_group.
  apply group'_eq.
  simpl.
  reflexivity.
  simpl.
  apply JMeq_refl.
Qed.

(* Theorem 1.4.1 *)
Theorem inv_inv (G : group) :
  forall a : group_carrier G, group_inv G (group_inv G a) = a.
Proof.
  move=> a.

  pose proof (group_inv_ex_uni G (group_inv G a)) as H.
  rewrite <- unique_existence in H.
  destruct H as [_ Huni].

  pose proof (group_inv_is_group_inv G (group_inv G a)) as Hinvinva.

  pose proof (group_inv_is_group_inv G a) as Ha.
  unfold are_mut_inv in Ha.
  rewrite <- and_comm in Ha.
  fold (are_mut_inv G (group_inv G a) a) in Ha.

  rewrite -(Huni a (group_inv G (group_inv G a)) Ha Hinvinva).
  reflexivity.
Qed.

(* Theorem 1.4.2 *)
Theorem group_mul_inv_rev (G : group) :
  forall a b : group_carrier G, group_inv G (group_mul G a b) = group_mul G (group_inv G b) (group_inv G a).
Proof.
  move=> a b.

  pose proof (group_inv_ex_uni G (group_mul G a b)) as H.
  rewrite <- unique_existence in H.
  destruct H as [_ Huni].

  pose proof (group_inv_is_group_inv G (group_mul G a b)) as H1.

  assert (are_mut_inv G (group_mul G a b) (group_mul G (group_inv G b) (group_inv G a))) as H2.
  + split.
    + rewrite (group_mul_assoc G a b (group_mul G (group_inv G b) (group_inv G a))).
      rewrite -(group_mul_assoc G b (group_inv G b) (group_inv G a)).
      rewrite (proj1 (group_inv_is_group_inv G b)).
      rewrite (proj2 (group_one_is_group_one G (group_inv G a))).
      rewrite (proj1 (group_inv_is_group_inv G a)).
      reflexivity.
    + rewrite (group_mul_assoc G (group_inv G b) (group_inv G a) (group_mul G a b)).
      rewrite -(group_mul_assoc G (group_inv G a) a b).
      rewrite (proj2 (group_inv_is_group_inv G a)).
      rewrite (proj2 (group_one_is_group_one G b)).
      rewrite (proj2 (group_inv_is_group_inv G b)).
      reflexivity.
  exact (Huni (group_inv G (group_mul G a b)) (group_mul G (group_inv G b) (group_inv G a)) H1 H2).
Qed.

(* Definition 2.1 *)
Definition subset (S : Set) := S -> Prop.

Structure subgroup (G : group) : Type := make_subgroup
{
  subgroup_carrier : subset (group_carrier G);
  subgroup_inhab : inhabited (sig subgroup_carrier);
  subgroup_mul_mem : forall a b : group_carrier  G, subgroup_carrier a -> subgroup_carrier b -> subgroup_carrier (group_mul G a b);
  subgroup_inv_mem : forall a : group_carrier G, subgroup_carrier a -> subgroup_carrier (group_inv G a);
}.

(* (2.2).(a) *)
Theorem subgroup_one_mem (G : group) (H : subgroup G) :
  subgroup_carrier G H (group_one G).
Proof.
  destruct (subgroup_inhab G H) as [Hinhab].
  destruct Hinhab as [a Ha_in_H].

  pose proof (subgroup_inv_mem G H a Ha_in_H) as Hainv_in_H.
  pose proof (subgroup_mul_mem G H a (group_inv G a) Ha_in_H Hainv_in_H) as Hmul_in_H.
  rewrite (proj1 (group_inv_is_group_inv G a)) in Hmul_in_H.
  exact Hmul_in_H.
Qed.

Definition subgroup_incl (G : group) (H : subgroup G) :
  (sig (subgroup_carrier G H)) -> group_carrier G
  := fun p => let 'exist x Hx := p in x.

Theorem subgroup_incl_is_injective (G : group) (H : subgroup G) :
  Injective (subgroup_incl G H).
Proof.
  move=> [x Hx] [y Hy] Heq.
  unfold subgroup_incl in Heq.
  move: Hx Hy.
  rewrite -Heq.
  move=> Hx Hy.
  apply f_equal.
  apply proof_irrelevance.
Qed.

Definition subgroup_mul (G : group) (H : subgroup G) :
  (sig (subgroup_carrier G H)) -> (sig (subgroup_carrier G H)) -> (sig (subgroup_carrier G H))
  := fun p q =>
    let 'exist a Ha := p in
    let 'exist b Hb := q in
      (exist (subgroup_carrier G H) (group_mul G a b) (subgroup_mul_mem G H a b Ha Hb)).

Theorem subgroup_mul_assoc (G : group) (H : subgroup G) :
  forall a b c : (sig (subgroup_carrier G H)),
    subgroup_mul G H (subgroup_mul G H a b) c =
      subgroup_mul G H a (subgroup_mul G H b c).
Proof.
  move=> [a Ha] [b Hb] [c Hc].
  apply (subgroup_incl_is_injective G H).
  unfold subgroup_mul.
  unfold subgroup_incl.
  exact (group_mul_assoc G a b c).
Qed.

Theorem subgroup_group_r_trans (G : group) (H : subgroup G) :
  forall a b : (sig (subgroup_carrier G H)),
  exists x : (sig (subgroup_carrier G H)),
  subgroup_mul G H a x = b.
Proof.
  move=> [a Ha] [b Hb].

  set (c := group_mul G (group_inv G a) b).
  set (Hc := subgroup_mul_mem G H (group_inv G a) b (subgroup_inv_mem G H a Ha) Hb).

  exists (exist (subgroup_carrier G H) c Hc).

  apply (subgroup_incl_is_injective G H).
  unfold subgroup_mul.
  unfold subgroup_incl.
  unfold c.
  rewrite -(group_mul_assoc G).
  rewrite (group_mul_inv G).
  rewrite (group_one_mul G).
  reflexivity.
Qed.

Theorem subgroup_group_l_trans (G : group) (H : subgroup G) :
  forall a b : (sig (subgroup_carrier G H)),
  exists y : (sig (subgroup_carrier G H)),
  subgroup_mul G H y a = b.
Proof.
  move=> [a Ha] [b Hb].

  set (c := group_mul G b (group_inv G a)).
  set (Hc := subgroup_mul_mem G H b (group_inv G a) Hb (subgroup_inv_mem G H a Ha)).

  exists (exist (subgroup_carrier G H) c Hc).

  apply (subgroup_incl_is_injective G H).
  unfold subgroup_mul.
  unfold subgroup_incl.
  unfold c.
  rewrite (group_mul_assoc G).
  rewrite (group_inv_mul G).
  rewrite (group_mul_one G).
  reflexivity.
Qed.

(* (2.2).(b) *)
Definition subgroup_to_group (G : group) :
  (subgroup G) -> group
  := fun H => (make_group
    (sig (subgroup_carrier G H))
    (subgroup_inhab G H)
    (subgroup_mul G H)
    (subgroup_mul_assoc G H)
    (subgroup_group_r_trans G H)
    (subgroup_group_l_trans G H)
  ).

(* (2.2).(c).1 *)
Theorem subgroup_one_is_group_one (G : group) (H : subgroup G) :
  subgroup_incl G H (group_one (subgroup_to_group G H)) = group_one G.
Proof.
  pose proof (group_one_ex_uni (subgroup_to_group G H)) as Hone_ex_uni.
  rewrite <- unique_existence in Hone_ex_uni.
  destruct Hone_ex_uni as [Hone_ex Hone_uni].

  set (one0 := group_one (subgroup_to_group G H)).
  set (one1 := (exist (subgroup_carrier G H) (group_one G) (subgroup_one_mem G H))).
  assert (one0 = one1) as Hyp0.
  + assert (is_group_one (subgroup_to_group G H) one1) as His_one.
    + move=> x.
      destruct x as [x Hx].
      split.
      + apply subgroup_incl_is_injective.
        simpl.
        rewrite (group_mul_one G).
        reflexivity.
      + apply subgroup_incl_is_injective.
        simpl.
        rewrite (group_one_mul G).
        reflexivity.
    + exact (Hone_uni one0 one1 (group_one_is_group_one (subgroup_to_group G H)) His_one).

  rewrite Hyp0.
  simpl.
  reflexivity.
Qed.

(* (2.2).(c).2 *)
Theorem subgroup_inv_is_group_inv (G : group) (H : subgroup G) :
  compose (subgroup_incl G H) (group_inv (subgroup_to_group G H))
  = compose (group_inv G) (subgroup_incl G H).
Proof.
  apply functional_extensionality.
  move=> [x Hx].
  unfold compose.
  simpl.

  pose proof (group_inv_ex_uni (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)) as Hinv_ex_uni.
  rewrite <- unique_existence in Hinv_ex_uni.
  destruct Hinv_ex_uni as [Hinv_ex Hinv_uni].

  set (inv0 := group_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)).
  set (inv1 := (exist (subgroup_carrier G H) (group_inv G (subgroup_incl G H (exist (subgroup_carrier G H) x Hx))) (subgroup_inv_mem G H x Hx))).
  assert (inv0 = inv1) as Hyp0.
  + assert (are_mut_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx) inv1) as His_inv.
    + split.
      + apply subgroup_incl_is_injective.
        simpl.
        rewrite (group_mul_inv G).
        rewrite (subgroup_one_is_group_one G H).
        reflexivity.
      + apply subgroup_incl_is_injective.
        simpl.
        rewrite (group_inv_mul G).
        rewrite (subgroup_one_is_group_one G H).
        reflexivity.
    + exact (Hinv_uni inv0 inv1 (group_inv_is_group_inv (subgroup_to_group G H) (exist (subgroup_carrier G H) x Hx)) His_inv).

  rewrite Hyp0.
  simpl.
  reflexivity.
Qed.

(* (2.3).1 *)
Definition maximum_subgroup_carrier (G : group) : subset (group_carrier G)
  := fun x => True.

Theorem maximum_subgroup_inhab (G : group) :
  inhabited (sig (maximum_subgroup_carrier G)).
Proof.
  destruct (group_inhab G) as [x].

  assert (maximum_subgroup_carrier G x) as Hyp.
  + unfold maximum_subgroup_carrier.
    exact.
  exact (inhabits (exist (maximum_subgroup_carrier G) x Hyp)).
Qed.

Theorem maximum_subgroup_mul_mem (G : group) :
  forall a b : group_carrier G,
  maximum_subgroup_carrier G a ->
  maximum_subgroup_carrier G b ->
  maximum_subgroup_carrier G (group_mul G a b).
Proof.
  move=> a b Ha Hb.
  unfold maximum_subgroup_carrier.
  exact I.
Qed.

Theorem maximum_subgroup_inv_mem (G : group) :
  forall a : group_carrier G,
  maximum_subgroup_carrier G a ->
  maximum_subgroup_carrier G (group_inv G a).
Proof.
  move=> a Ha.
  unfold maximum_subgroup_carrier.
  exact I.
Qed.

Definition maximum_subgroup (G : group) : subgroup G
  := (make_subgroup G
    (maximum_subgroup_carrier G)
    (maximum_subgroup_inhab G)
    (maximum_subgroup_mul_mem G)
    (maximum_subgroup_inv_mem G)
  ).

(* (2.3).2 *)
Definition minimum_subgroup_carrier (G : group) : subset (group_carrier G)
  := fun x => x = group_one G.

Theorem minimum_subgroup_carrier_sub0 (G : group) :
  forall x : group_carrier G,
  minimum_subgroup_carrier G x
  -> x = group_one G.
Proof.
  move=> x Hx.
  unfold minimum_subgroup_carrier in Hx.
  exact Hx.
Qed.

Theorem minimum_subgroup_inhab (G : group) :
  inhabited (sig (minimum_subgroup_carrier G)).
Proof.
  set (one := group_one G).
  assert (minimum_subgroup_carrier G one) as Hyp.
  + unfold minimum_subgroup_carrier.
    unfold one.
    reflexivity.
  exact (inhabits (exist (minimum_subgroup_carrier G) one Hyp)).
Qed.

Theorem minimum_subgroup_mul_mem (G : group) :
  forall a b : group_carrier G,
  minimum_subgroup_carrier G a ->
  minimum_subgroup_carrier G b ->
  minimum_subgroup_carrier G (group_mul G a b).
Proof.
  unfold minimum_subgroup_carrier.
  move=> a b Ha Hb.
  rewrite Ha Hb.
  rewrite group_mul_one.
  reflexivity.
Qed.

Theorem minimum_subgroup_inv_mem (G : group) :
  forall a : group_carrier G,
  minimum_subgroup_carrier G a ->
  minimum_subgroup_carrier G (group_inv G a).
Proof.
  unfold minimum_subgroup_carrier.
  move=> a Ha.
  rewrite Ha.
  exact (group_one_inv G).
Qed.

Definition minimum_subgroup (G : group) : subgroup G
  := (make_subgroup G
    (minimum_subgroup_carrier G)
    (minimum_subgroup_inhab G)
    (minimum_subgroup_mul_mem G)
    (minimum_subgroup_inv_mem G)
  ).

Definition is_proper_subset (S : Set) (T : subset S) :=
  exists s : S, ~(T s).

(* Definition 2.4 *)
Definition is_proper_subgroup (G : group) (H : subgroup G) :=
  is_proper_subset (group_carrier G) (subgroup_carrier G H).

github-repos/coq/ishioka0222-theorem-proving-in-coq/theorem-proving-in-coq-a67e7e5cfa837cefa776c0ec76f26152e80a6c39/src/Michio Suzuki (1982) Group Theory I/main.v


Require Import Coq.Logic.ClassicalFacts.

Require Import Notation.
Require Import GeneralTactics.
Require Import Axioms.Classical.

Require Export Coq.Logic.FunctionalExtensionality.
Require Export Coq.Logic.PropExtensionality.

(* Modified from `Coq.Logic.FunctionalExtensionality` to include propositional
   extensionality
 *)
Tactic Notation "extensionality" :=
  match goal with
    [ |- ?X = ?Y ] =>
    (apply (propositional_extensionality X Y) ||
     apply (@functional_extensionality _ _ X Y) ||
     apply (@functional_extensionality_dep _ _ X Y) ||
     apply forall_extensionalityP ||
     apply forall_extensionalityS ||
     apply forall_extensionality)
  end.

Tactic Notation "extensionality" ident(x) :=
  match goal with
    [ |- ?X = ?Y ] =>
    ((apply (propositional_extensionality X Y); split) ||
     apply (@functional_extensionality _ _ X Y) ||
     apply (@functional_extensionality_dep _ _ X Y) ||
     apply forall_extensionalityP ||
     apply forall_extensionalityS ||
     apply forall_extensionality) ; intro x
  end.

(* Note, LEM and prop extensionality would also follow from assuming
   degeneracy. Doing so would lessen our number of axioms. However,
   having both LEM and prop extensionality axiomitzed individually is
   a better separation of concerns.
 *)
Theorem prop_degeneracy : forall A: Prop,
  A = True \/ A = False.
Proof using.
  apply prop_ext_em_degen.
  - exact propositional_extensionality.
  - exact classic.
Qed.

Lemma true_neq_false : True <> False.
Proof using.
  intro H.
  now induction H.
Qed.

Lemma provable_is_true : forall A: Prop,
  A = (A = True).
Proof using.
  intros *.
  extensionality H.
  - now (destruct (prop_degeneracy A); subst).
  - symmetry in H.
    now induction H.
Qed.

Lemma provable_contradiction_is_false : forall A: Prop,
  (~A) = (A = False).
Proof using.
  intros *.
  extensionality H.
  - now (destruct (prop_degeneracy A); subst).
  - intros ?.
    now induction H.
Qed.

Lemma false_is_exfalso : False = forall P: Prop, P.
Proof using.
  extensionality; split; intros ?.
  - contradiction.
  - assumption!.
Qed.

(* convenient rewrite rules from LEM + prop extensionality *)

Theorem rew_NNPP: forall P: Prop,
  (~~P) = P.
Proof using.
  intros *.
  extensionality.
  split.
  - apply NNPP.
  - auto.
Qed.

Theorem rew_not_and : forall P Q: Prop,
  (~ (P /\ Q)) = ~P \/ ~Q.
Proof using.
  intros *.
  extensionality H.
  - now apply not_and_or.
  - now apply or_not_and.
Qed.

Theorem rew_not_or : forall P Q: Prop,
  (~ (P \/ Q)) = ~P /\ ~Q.
Proof using.
  intros *.
  extensionality H.
  - now apply not_or_and.
  - now apply and_not_or.
Qed.

Theorem rew_imply_or : forall P Q: Prop,
  (P -> Q) = ~P \/ Q.
Proof using.
  intros *.
  extensionality H.
  - now apply imply_to_or.
  - now apply or_to_imply.
Qed.

Theorem rew_not_all : forall U (P:U -> Prop),
  (~ forall n, P n) = exists n, ~ P n.
Proof using.
  intros *.
  extensionality H.
  - now apply not_all_ex_not.
  - now apply ex_not_not_all.
Qed.

Theorem rew_not_ex : forall U (P:U -> Prop),
  (~ exists n, P n) = forall n, ~ P n.
Proof using.
  intros *.
  extensionality H.
  - now apply not_ex_all_not.
  - now apply all_not_not_ex.
Qed.


From Coq Require Import ZArith.
From Coq Require Import ssreflect.
From stdpp Require Import base numbers.
From Perennial.Helpers Require Import Integers.

Open Scope Z_scope.
Set Default Goal Selector "!".
Set Default Proof Using "Type".

Local Ltac Zify.zify_post_hook ::= Z.div_mod_to_equations.

Lemma mod_add_modulus a k :
  k ≠ 0 ->
  a `mod` k = (a + k) `mod` k.
Proof.
  intros.
  rewrite -> Z.add_mod by auto.
  rewrite -> Z.mod_same by auto.
  rewrite Z.add_0_r.
  rewrite -> Z.mod_mod by auto.
  auto.
Qed.

Lemma mod_sub_modulus a k :
  k ≠ 0 ->
  a `mod` k = (a - k) `mod` k.
Proof.
  intros.
  rewrite -> Zminus_mod by auto.
  rewrite -> Z.mod_same by auto.
  rewrite Z.sub_0_r.
  rewrite -> Z.mod_mod by auto.
  auto.
Qed.

Theorem sum_overflow_check (x y: u64) :
  int.Z (word.add x y) < int.Z x <-> int.Z x + int.Z y >= 2^64.
Proof.
  split; intros.
  - revert H; word_cleanup; intros.
    rewrite /word.wrap in H1.
    destruct (decide (int.Z x + int.Z y >= 2^64)); [ auto | exfalso ].
    lia.
  - word_cleanup.
    rewrite /word.wrap.
    lia.
Qed.

Lemma sum_nooverflow_l (x y : u64) :
  int.Z x ≤ int.Z (word.add x y) →
  int.Z (word.add x y) = (int.Z x) + (int.Z y).
Proof.
  intros. word_cleanup. rewrite wrap_small //.
  split; first word.
  destruct (Z_lt_ge_dec (int.Z x + int.Z y) (2 ^ 64)) as [Hlt|Hge]; first done.
  apply sum_overflow_check in Hge.
  lia.
Qed.

Lemma word_add_comm (x y : u64) :
  word.add x y = word.add y x.
Proof.
  specialize (@word.ring_theory _ u64_instance.u64 _). intros W.
  rewrite W.(Radd_comm). done.
Qed.

Lemma sum_nooverflow_r (x y : u64) :
  int.Z y ≤ int.Z (word.add x y) →
  int.Z (word.add x y) = (int.Z x) + (int.Z y).
Proof.
  rewrite word_add_comm. intros ?%sum_nooverflow_l.
  rewrite Z.add_comm //.
Qed.

Theorem word_add1_neq (x: u64) :
  int.Z x ≠ int.Z (word.add x (U64 1)).
Proof.
  simpl.
  destruct (decide (int.Z x + 1 < 2^64)%Z); [ word | ].
  rewrite word.unsigned_add.
  change (int.Z (U64 1)) with 1%Z.
  rewrite /word.wrap.
  lia.
Qed.

(* avoid leaving it at div_mod_to_equations since it causes some backwards
incompatibility *)
Ltac Zify.zify_post_hook ::= idtac.