(* I have not worked with any partners. *)
(** * Induction: Proof by Induction *)

(** Before getting started, we need to import all of our
    definitions from the previous chapter: *)

Require Export LF.Basics.

(** For the [Require Export] to work, you first need to use
    [coqc] to compile [Basics.v] into [Basics.vo].  This is like
    making a .class file from a .java file, or a .o file from a .c
    file.  There are two ways to do it:

     - In CoqIDE:

         Open [Basics.v].  In the "Compile" menu, click on "Compile
         Buffer".

         (N.b.: These instructions need to be updated to take the "-R
         LF ." into account.  Can a CoqIDE expert tell me how this is
         done, please?)

     - From the command line:

         [make Basics.vo]

   If you have trouble (e.g., if you get complaints about missing
   identifiers later in the file), it may be because the "load path"
   for Coq is not set up correctly.  The [Print LoadPath.] command may
   be helpful in sorting out such issues. *)

(* ################################################################# *)
(** * Proof by Induction *)

(** We proved in the last chapter that [0] is a neutral element
    for [+] on the left, using an easy argument based on
    simplification.  We also observed that proving the fact that it is
    also a neutral element on the _right_... *)

Theorem plus_n_O_firsttry : forall n:nat,
  n = n + 0.

(** ... can't be done in the same simple way.  Just applying
  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary
  unknown number, so the [match] in the definition of [+] can't be
  simplified.  *)

Proof.
  intros n.
  simpl. (* Does nothing! *)
Abort.

(** And reasoning by cases using [destruct n] doesn't get us much
    further: the branch of the case analysis where we assume [n = 0]
    goes through fine, but in the branch where [n = S n'] for some [n'] we
    get stuck in exactly the same way. *)

Theorem plus_n_O_secondtry : forall n:nat,
  n = n + 0.
Proof.
  intros n. destruct n as [| n'].
  - (* n = 0 *)
    reflexivity. (* so far so good... *)
  - (* n = S n' *)
    simpl.       (* ...but here we are stuck again *)
Abort.

(** We could use [destruct n'] to get one step further, but,
    since [n] can be arbitrarily large, if we just go on like this
    we'll never finish. *)

(** To prove interesting facts about numbers, lists, and other
    inductively defined sets, we usually need a more powerful
    reasoning principle: _induction_.

    Recall (from high school, a discrete math course, etc.) the
    _principle of induction over natural numbers_: If [P(n)] is some
    proposition involving a natural number [n] and we want to show
    that [P] holds for all numbers [n], we can reason like this:
         - show that [P(O)] holds;
         - show that, for any [n'], if [P(n')] holds, then so does
           [P(S n')];
         - conclude that [P(n)] holds for all [n].

    In Coq, the steps are the same: we begin with the goal of proving
    [P(n)] for all [n] and break it down (by applying the [induction]
    tactic) into two separate subgoals: one where we must show [P(O)]
    and another where we must show [P(n') -> P(S n')].  Here's how
    this works for the theorem at hand: *)

Theorem plus_n_O : forall n:nat, n = n + 0.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)    reflexivity.
  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.  Qed.

(** Like [destruct], the [induction] tactic takes an [as...]
    clause that specifies the names of the variables to be introduced
    in the subgoals.  Since there are two subgoals, the [as...] clause
    has two parts, separated by [|].  (Strictly speaking, we can omit
    the [as...] clause and Coq will choose names for us.  In practice,
    this is a bad idea, as Coq's automatic choices tend to be
    confusing.)

    In the first subgoal, [n] is replaced by [0].  No new variables
    are introduced (so the first part of the [as...] is empty), and
    the goal becomes [0 = 0 + 0], which follows by simplification.

    In the second subgoal, [n] is replaced by [S n'], and the
    assumption [n' + 0 = n'] is added to the context with the name
    [IHn'] (i.e., the Induction Hypothesis for [n']).  These two names
    are specified in the second part of the [as...] clause.  The goal
    in this case becomes [S n' = (S n') + 0], which simplifies to
    [S n' = S (n' + 0)], which in turn follows from [IHn']. *)

Theorem minus_diag : forall n,
  minus n n = 0.
Proof.
  (* WORKED IN CLASS *)
  intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    simpl. reflexivity.
  - (* n = S n' *)
    simpl. rewrite -> IHn'. reflexivity.  Qed.

(** (The use of the [intros] tactic in these proofs is actually
    redundant.  When applied to a goal that contains quantified
    variables, the [induction] tactic will automatically move them
    into the context as needed.) *)

(** **** Exercise: 2 stars, recommended (basic_induction)  *)
(** Prove the following using induction. You might need previously
    proven results. *)

Theorem mult_0_r : forall n:nat,
  n * 0 = 0.
Proof.
  induction n as [| n' IHn'].
  - reflexivity.
  - simpl. rewrite -> IHn'. reflexivity. Qed.

Theorem plus_n_Sm : forall n m : nat,
  S (n + m) = n + (S m).
Proof.
  induction n as [| n' IHn'].
  - reflexivity.
  - simpl. intros [| m'].
    + rewrite<-IHn'. reflexivity.
    + rewrite->IHn'. reflexivity.
Qed.

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros n m. induction n as [| n' IHn'].
  - rewrite<-plus_n_O. reflexivity.
  - simpl. rewrite->IHn'. rewrite->plus_n_Sm. reflexivity.
Qed.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros n m p. induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite->IHn'. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars (double_plus)  *)
(** Consider the following function, which doubles its argument: *)

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

(** Use induction to prove this simple fact about [double]: *)

Lemma double_plus : forall n, double n = n + n .
Proof.
  induction n as [| n' IHn'].
  - reflexivity.
  - simpl. rewrite->IHn'. rewrite->plus_n_Sm. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, optional (evenb_S)  *)
(** One inconvenient aspect of our definition of [evenb n] is the
    recursive call on [n - 2]. This makes proofs about [evenb n]
    harder when done by induction on [n], since we may need an
    induction hypothesis about [n - 2]. The following lemma gives an
    alternative characterization of [evenb (S n)] that works better
    with induction: *)

Theorem evenb_S : forall n : nat,
  evenb (S n) = negb (evenb n).
Proof.
  induction n as [| n' IHn'].
  - reflexivity.
  - rewrite->IHn'. simpl. rewrite->negb_involutive. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 1 star (destruct_induction)  *)
(** Briefly explain the difference between the tactics [destruct]
    and [induction].

- destruct and induction are both used to do case analysis in a proof.
Besides, induction provides a inductive hypothesis. We prove that
if a former hypothesis holds, the successor also holds. Since the basic
case holds, all these cases will hold, like a chain.
*)
(** [] *)

(* ################################################################# *)
(** * Proofs Within Proofs *)

(** In Coq, as in informal mathematics, large proofs are often
    broken into a sequence of theorems, with later proofs referring to
    earlier theorems.  But sometimes a proof will require some
    miscellaneous fact that is too trivial and of too little general
    interest to bother giving it its own top-level name.  In such
    cases, it is convenient to be able to simply state and prove the
    needed "sub-theorem" right at the point where it is used.  The
    [assert] tactic allows us to do this.  For example, our earlier
    proof of the [mult_0_plus] theorem referred to a previous theorem
    named [plus_O_n].  We could instead use [assert] to state and
    prove [plus_O_n] in-line: *)

Theorem mult_0_plus' : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  assert (H: 0 + n = n). { reflexivity. }
  rewrite -> H.
  reflexivity.  Qed.

(** The [assert] tactic introduces two sub-goals.  The first is
    the assertion itself; by prefixing it with [H:] we name the
    assertion [H].  (We can also name the assertion with [as] just as
    we did above with [destruct] and [induction], i.e., [assert (0 + n
    = n) as H].)  Note that we surround the proof of this assertion
    with curly braces [{ ... }], both for readability and so that,
    when using Coq interactively, we can see more easily when we have
    finished this sub-proof.  The second goal is the same as the one
    at the point where we invoke [assert] except that, in the context,
    we now have the assumption [H] that [0 + n = n].  That is,
    [assert] generates one subgoal where we must prove the asserted
    fact and a second subgoal where we can use the asserted fact to
    make progress on whatever we were trying to prove in the first
    place. *)

(** Another example of [assert]... *)

(** For example, suppose we want to prove that [(n + m) + (p + q)
    = (m + n) + (p + q)]. The only difference between the two sides of
    the [=] is that the arguments [m] and [n] to the first inner [+]
    are swapped, so it seems we should be able to use the
    commutativity of addition ([plus_comm]) to rewrite one into the
    other.  However, the [rewrite] tactic is not very smart about
    _where_ it applies the rewrite.  There are three uses of [+] here,
    and it turns out that doing [rewrite -> plus_comm] will affect
    only the _outer_ one... *)

Theorem plus_rearrange_firsttry : forall n m p q : nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  (* We just need to swap (n + m) for (m + n)... seems
     like plus_comm should do the trick! *)
  rewrite -> plus_comm.
  (* Doesn't work...Coq rewrote the wrong plus! *)
Abort.

(** To use [plus_comm] at the point where we need it, we can introduce
    a local lemma stating that [n + m = m + n] (for the particular [m]
    and [n] that we are talking about here), prove this lemma using
    [plus_comm], and then use it to do the desired rewrite. *)

Theorem plus_rearrange : forall n m p q : nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  assert (H: n + m = m + n).
  { rewrite -> plus_comm. reflexivity. }
  rewrite -> H. reflexivity.  Qed.

(* ################################################################# *)
(** * Formal vs. Informal Proof *)

(** "_Informal proofs are algorithms; formal proofs are code_." *)

(** What constitutes a successful proof of a mathematical claim?
    The question has challenged philosophers for millennia, but a
    rough and ready definition could be this: A proof of a
    mathematical proposition [P] is a written (or spoken) text that
    instills in the reader or hearer the certainty that [P] is true --
    an unassailable argument for the truth of [P].  That is, a proof
    is an act of communication.

    Acts of communication may involve different sorts of readers.  On
    one hand, the "reader" can be a program like Coq, in which case
    the "belief" that is instilled is that [P] can be mechanically
    derived from a certain set of formal logical rules, and the proof
    is a recipe that guides the program in checking this fact.  Such
    recipes are _formal_ proofs.

    Alternatively, the reader can be a human being, in which case the
    proof will be written in English or some other natural language,
    and will thus necessarily be _informal_.  Here, the criteria for
    success are less clearly specified.  A "valid" proof is one that
    makes the reader believe [P].  But the same proof may be read by
    many different readers, some of whom may be convinced by a
    particular way of phrasing the argument, while others may not be.
    Some readers may be particularly pedantic, inexperienced, or just
    plain thick-headed; the only way to convince them will be to make
    the argument in painstaking detail.  But other readers, more
    familiar in the area, may find all this detail so overwhelming
    that they lose the overall thread; all they want is to be told the
    main ideas, since it is easier for them to fill in the details for
    themselves than to wade through a written presentation of them.
    Ultimately, there is no universal standard, because there is no
    single way of writing an informal proof that is guaranteed to
    convince every conceivable reader.

    In practice, however, mathematicians have developed a rich set of
    conventions and idioms for writing about complex mathematical
    objects that -- at least within a certain community -- make
    communication fairly reliable.  The conventions of this stylized
    form of communication give a fairly clear standard for judging
    proofs good or bad.

    Because we are using Coq in this course, we will be working
    heavily with formal proofs.  But this doesn't mean we can
    completely forget about informal ones!  Formal proofs are useful
    in many ways, but they are _not_ very efficient ways of
    communicating ideas between human beings. *)

(** For example, here is a proof that addition is associative: *)

Theorem plus_assoc' : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof. intros n m p. induction n as [| n' IHn']. reflexivity.
  simpl. rewrite -> IHn'. reflexivity.  Qed.

(** Coq is perfectly happy with this.  For a human, however, it
    is difficult to make much sense of it.  We can use comments and
    bullets to show the structure a little more clearly... *)

Theorem plus_assoc'' : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros n m p. induction n as [| n' IHn'].
  - (* n = 0 *)
    reflexivity.
  - (* n = S n' *)
    simpl. rewrite -> IHn'. reflexivity.   Qed.

(** ... and if you're used to Coq you may be able to step
    through the tactics one after the other in your mind and imagine
    the state of the context and goal stack at each point, but if the
    proof were even a little bit more complicated this would be next
    to impossible.

    A (pedantic) mathematician might write the proof something like
    this: *)

(** - _Theorem_: For any [n], [m] and [p],

      n + (m + p) = (n + m) + p.

    _Proof_: By induction on [n].

    - First, suppose [n = 0].  We must show

        0 + (m + p) = (0 + m) + p.

      This follows directly from the definition of [+].

    - Next, suppose [n = S n'], where

        n' + (m + p) = (n' + m) + p.

      We must show

        (S n') + (m + p) = ((S n') + m) + p.

      By the definition of [+], this follows from

        S (n' + (m + p)) = S ((n' + m) + p),

      which is immediate from the induction hypothesis.  _Qed_. *)

(** The overall form of the proof is basically similar, and of
    course this is no accident: Coq has been designed so that its
    [induction] tactic generates the same sub-goals, in the same
    order, as the bullet points that a mathematician would write.  But
    there are significant differences of detail: the formal proof is
    much more explicit in some ways (e.g., the use of [reflexivity])
    but much less explicit in others (in particular, the "proof state"
    at any given point in the Coq proof is completely implicit,
    whereas the informal proof reminds the reader several times where
    things stand). *)

(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  *)
(** Translate your solution for [plus_comm] into an informal proof:

    Theorem: Addition is commutative.

    Proof: By induction on [n].
    - First, suppose [n = 0]. We must know
        0 + m = m + 0.
      The left side can be simplified to [m] by the definition of [+].
      The right side can be simplified to [m] too by Theorem [plus_n_O].
      Thus this holds.
    - Next, suppose [n = S n'], where
        n' + m = m + n'.
      We must know
        S n' + m = m + S n'.
      By the definition of [+], this follows from
        S (n' + m) = m + S n'.
      By Theorem plus_n_Sm, this can be further simplified as
        S (n' + m) = S (m + n').
      which is immediate from the induction hypothesis.
    Qed.
*)
(** [] *)

(** **** Exercise: 2 stars, optional (beq_nat_refl_informal)  *)
(** Write an informal proof of the following theorem, using the
    informal proof of [plus_assoc] as a model.  Don't just
    paraphrase the Coq tactics into English!

    Theorem: [true = beq_nat n n] for any [n].

    Proof: By induction on [n].
    - First, suppose [n = 0]. We must know
        true = beq_nat 0 0.
      which is immediate from the definition of [beq_nat].
    - Next, suppose [n = S n'], where
        true = beq_nat n' n'.
      We must know
        true = beq_nat (S n') (S n').
      By the definition of [beq_nat], this follows from
        true = beq_nat n' n'.
      which is immediate from the induction hypothesis.
    Qed.
[] *)

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

(** **** Exercise: 3 stars, recommended (mult_comm)  *)
(** Use [assert] to help prove this theorem.  You shouldn't need to
    use induction on [plus_swap]. *)

Theorem plus_swap : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite->plus_assoc. rewrite->plus_assoc.
  assert (H: n + m = m + n). { rewrite->plus_comm. reflexivity. }
  rewrite->H. reflexivity.
Qed.

(** Now prove commutativity of multiplication.  (You will probably
    need to define and prove a separate subsidiary theorem to be used
    in the proof of this one.  You may find that [plus_swap] comes in
    handy.) *)

Lemma mult_n_O: forall n : nat, n * 0 = 0.
Proof.
  induction n as [| n' IHn'].
  - reflexivity.
  - simpl. rewrite->IHn'. reflexivity.
Qed.

Lemma mult_plus_r: forall m n : nat, m * S n = m + m * n.
Proof.
  intros m n. induction m as [|m' IHm'].
  - reflexivity.
  - simpl. rewrite->IHm'. rewrite->plus_swap. reflexivity.
Qed.

Theorem mult_comm : forall m n : nat,
  m * n = n * m.
Proof.
  intros m n. induction m as [|m' IHm'].
  - rewrite->mult_n_O. reflexivity.
  - simpl. rewrite->mult_plus_r. rewrite->IHm'. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (more_exercises)  *)
(** Take a piece of paper.  For each of the following theorems, first
    _think_ about whether (a) it can be proved using only
    simplification and rewriting, (b) it also requires case
    analysis ([destruct]), or (c) it also requires induction.  Write
    down your prediction.  Then fill in the proof.  (There is no need
    to turn in your piece of paper; this is just to encourage you to
    reflect before you hack!) *)

Check leb.

Theorem leb_refl : forall n:nat,
  true = leb n n.
Proof.
  induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite<-IHn'. reflexivity.
Qed.

Theorem zero_nbeq_S : forall n:nat,
  beq_nat 0 (S n) = false.
Proof.
  reflexivity.
Qed.

Theorem andb_false_r : forall b : bool,
  andb b false = false.
Proof.
  intros [|].
  - reflexivity.
  - reflexivity.
Qed.

Theorem plus_ble_compat_l : forall n m p : nat,
  leb n m = true -> leb (p + n) (p + m) = true.
Proof.
  intros n m p H. induction p as [|p' IHp'].
  - simpl. rewrite->H. reflexivity.
  - simpl. rewrite->IHp'. reflexivity.
Qed.

Theorem S_nbeq_0 : forall n:nat,
  beq_nat (S n) 0 = false.
Proof.
  reflexivity.
Qed.

Theorem mult_1_l : forall n:nat, 1 * n = n.
Proof.
  intros n. simpl. rewrite<-plus_n_O. reflexivity.
Qed.

Theorem all3_spec : forall b c : bool,
  orb
    (andb b c)
    (orb (negb b)
            (negb c))
  = true.
Proof.
  intros [|] [|].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.

Theorem mult_plus_distr_r : forall n m p : nat,
  (n + m) * p = (n * p) + (m * p).
Proof.
  intros n m p. induction p as [|p' IHp'].
  - rewrite mult_n_O. rewrite mult_n_O. rewrite mult_n_O. reflexivity.
  - rewrite->mult_plus_r. rewrite->mult_plus_r. rewrite->mult_plus_r.
    rewrite IHp'. rewrite->plus_assoc. rewrite->plus_assoc.
    assert (H: n + m + n * p' = n + n * p' + m). {
      rewrite<-plus_assoc. rewrite<-plus_assoc.
      assert (H': m + n * p' =  n * p' + m). {
        rewrite->plus_comm. reflexivity.
      }
      rewrite->H'. reflexivity.
    }
    rewrite->H. reflexivity.
Qed.

Theorem mult_assoc : forall n m p : nat,
  n * (m * p) = (n * m) * p.
Proof.
  intros n m p. induction m as [|m' IHm'].
  - simpl. rewrite mult_n_O. reflexivity.
  - simpl. assert (H: n * S m' = S m' * n). { rewrite->mult_comm. reflexivity. }
    rewrite->H. simpl. rewrite->mult_comm. rewrite->mult_plus_distr_r.
    rewrite->mult_plus_distr_r.
    assert (H': m' * p * n = m' * n * p). {
      rewrite->mult_comm. rewrite->IHm'.
      assert (H0: n * m' = m' * n). { rewrite->mult_comm. reflexivity. }
      rewrite->H0. reflexivity.
    }
    rewrite->H'.
    assert (H1: p * n = n * p). { rewrite->mult_comm. reflexivity. }
    rewrite->H1. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, optional (beq_nat_refl)  *)
(** Prove the following theorem.  (Putting the [true] on the left-hand
    side of the equality may look odd, but this is how the theorem is
    stated in the Coq standard library, so we follow suit.  Rewriting
    works equally well in either direction, so we will have no problem
    using the theorem no matter which way we state it.) *)

Theorem beq_nat_refl : forall n : nat,
  true = beq_nat n n.
Proof.
  induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite<-IHn'. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, optional (plus_swap')  *)
(** The [replace] tactic allows you to specify a particular subterm to
   rewrite and what you want it rewritten to: [replace (t) with (u)]
   replaces (all copies of) expression [t] in the goal by expression
   [u], and generates [t = u] as an additional subgoal. This is often
   useful when a plain [rewrite] acts on the wrong part of the goal.

   Use the [replace] tactic to do a proof of [plus_swap'], just like
   [plus_swap] but without needing [assert (n + m = m + n)]. *)

Theorem plus_swap' : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite->plus_assoc. rewrite->plus_assoc.
  replace (n + m) with (m + n). reflexivity.
  rewrite->plus_comm. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, recommended (binary_commute)  *)
(** Recall the [incr] and [bin_to_nat] functions that you
    wrote for the [binary] exercise in the [Basics] chapter.  Prove
    that the following diagram commutes:

                            incr
              bin ----------------------> bin
               |                           |
    bin_to_nat |                           |  bin_to_nat
               |                           |
               v                           v
              nat ----------------------> nat
                             S

    That is, incrementing a binary number and then converting it to
    a (unary) natural number yields the same result as first converting
    it to a natural number and then incrementing.
    Name your theorem [bin_to_nat_pres_incr] ("pres" for "preserves").

    Before you start working on this exercise, copy the definitions
    from your solution to the [binary] exercise here so that this file
    can be graded on its own.  If you want to change your original
    definitions to make the property easier to prove, feel free to
    do so! *)

Theorem bin_to_nat_pres_incr:
  forall b : bin, S (bin_to_nat b) = bin_to_nat (incr b).
Proof.
  intros b. induction b as [|t' IHt'|p' IHp'].
  - reflexivity.
  - simpl. reflexivity.
  - simpl. rewrite<-IHp'. simpl. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 5 stars, advanced (binary_inverse)  *)
(** This exercise is a continuation of the previous exercise about
    binary numbers.  You will need your definitions and theorems from
    there to complete this one; please copy them to this file to make
    it self contained for grading.

    (a) First, write a function to convert natural numbers to binary
        numbers.  Then prove that starting with any natural number,
        converting to binary, then converting back yields the same
        natural number you started with.

    (b) You might naturally think that we should also prove the
        opposite direction: that starting with a binary number,
        converting to a natural, and then back to binary yields the
        same number we started with.  However, this is not true!
        Explain what the problem is.

    (c) Define a "direct" normalization function -- i.e., a function
        [normalize] from binary numbers to binary numbers such that,
        for any binary number b, converting to a natural and then back
        to binary yields [(normalize b)].  Prove it.  (Warning: This
        part is tricky!)

    Again, feel free to change your earlier definitions if this helps
    here. *)

Fixpoint nat_to_bin (n : nat) : bin :=
  match n with
    | O => B
    | S n' => incr (nat_to_bin n')
  end.

Theorem incr_bin_plus:
  forall b : bin, bin_to_nat (incr b) = S (bin_to_nat b).
Proof.
  intros b. induction b as [|t IHt|p IHp].
  - reflexivity.
  - simpl. reflexivity.
  - simpl. rewrite IHp. simpl. reflexivity.
Qed.

Theorem nat_to_bin_to_nat:
  forall n : nat, bin_to_nat (nat_to_bin n) = n.
Proof.
  intros n. induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite<-IHn'. rewrite<-incr_bin_plus. rewrite->IHn'. reflexivity.
Qed.

(* b
If a binary is [T B], or [T (T B)] ... etc. Converting it to natural number
will give 0, and due to the definition of [nat_to_bin], 0 will give [B], with
leading [T] removed. Also, any other binary number that contains this subsequence
faces the same problem like [P (T (T B))]. Shown as below:

// THIS DO NOT HOLD!
Example test_bin_nat_convert_twice:  nat_to_bin (bin_to_nat (P (T B))) = P (T B).
Proof. simpl. reflexivity.  Qed.
*)

Fixpoint normalize (b : bin): bin :=
match b with
  | B => B
  | T b' => match (normalize b') with
    | B => B
    | b' => T b'
    end
  | P b' => P (normalize b')
end.

Example test_bin_nat_convert_twice:  nat_to_bin (bin_to_nat (incr (P (incr (P B))))) = normalize (incr (P (incr (P B)))).
Proof. simpl. reflexivity.  Qed.

Example test_bin_nat_convert_twice2:  nat_to_bin (bin_to_nat (T (T (T (T B))))) = normalize (T (T (T (T B)))).
Proof. simpl. reflexivity.  Qed.

Lemma norm_incr_comm : forall b : bin,
normalize (incr b) = incr (normalize b).
Proof.
  induction b as [|b' IHb' |b' IHb'].
  - reflexivity.
  - simpl. destruct (normalize b').
    + simpl. reflexivity.
    + simpl. reflexivity.
    + simpl. reflexivity.
  - simpl. destruct (normalize b').
    + rewrite->IHb'. simpl. reflexivity.
    + rewrite->IHb'. simpl. reflexivity.
    + rewrite->IHb'. simpl. reflexivity.
Qed.

Lemma doub_n_norm_T : forall n : nat,
  nat_to_bin (mult n 2) = normalize(T (nat_to_bin n)).
Proof.
  induction n as [|n' IHn'].
  - reflexivity.
  - simpl. rewrite->norm_incr_comm. rewrite->IHn'. simpl.
    destruct (normalize (nat_to_bin n')).
    + reflexivity.
    + simpl. reflexivity.
    + simpl. reflexivity.
Qed.

Lemma normalize_twice_eq : forall b : bin,
normalize (normalize b) = normalize b.
Proof.
  induction b as [|b' IHb' |b' IHb'].
  - simpl. reflexivity.
  - simpl. destruct (normalize b').
    + simpl. reflexivity.
    + simpl. rewrite<-IHb'. simpl.
      replace (match normalize b with
        | B => B
        | T b0 => T (T b0)
        | P b0 => T (P b0)
      end) with (T b). reflexivity.
    + simpl. rewrite<-IHb'. simpl. reflexivity.
  - simpl. rewrite->IHb'. reflexivity.
Qed.

Theorem bin_to_nat_to_bin : forall b : bin,
  nat_to_bin (bin_to_nat b) = normalize b.
Proof.
  induction b as [|b' IHb'|b' IHb'].
  - reflexivity.
  - simpl. rewrite->doub_n_norm_T. simpl. rewrite->IHb'.
    rewrite->normalize_twice_eq. reflexivity.
  - simpl. rewrite->doub_n_norm_T. simpl. rewrite->IHb'.
    rewrite->normalize_twice_eq. destruct (normalize b').
    + reflexivity.
    + reflexivity.
    + reflexivity.
Qed.
(** [] *)

(** $Date: 2017-08-22 17:13:32 -0400 (Tue, 22 Aug 2017) $ *)


From Coq Require Import Logic.FunctionalExtensionality.
From CM Require Import Category.

Module Inverse.
  Definition inverse {A B: Object} (f: Morphism A B) (g: Morphism B A) :=
    compose f g = identity A /\ compose g f = identity B.

  (** A morphism cannot have more than one inverse.
    The Idea is to prove (g . f . k = g . f . g),
    then use the associtivity law to prove ((g . f) . k = (g . f) . g),
    finally use the identity law to prove (k = g).
  *)
  Theorem inverse_unique: forall (A B: Object) (f: Morphism A B) (g k: Morphism B A),
    inverse f g ->
    inverse f k ->
    g = k.
  Proof.
    intros. unfold inverse in *. destruct H, H0.
    assert (H3: compose g (compose f k) = compose g (compose f g)).
    { rewrite H. rewrite H0. reflexivity. }
    repeat rewrite <- composition_assoc in H3.
    rewrite H1 in H3. repeat rewrite composition_id_left in H3.
    symmetry. apply H3.
  Qed.
End Inverse.

Module Isomorphism.
  Import Inverse.
  Definition isomorphism {A B: Object} (f: Morphism A B) :=
    exists g: Morphism B A, inverse f g.

  Theorem isomorphism_cancellation_left:
    forall (A B C: Object) (f: Morphism A B) (h k: Morphism B C),
      isomorphism f ->
      compose f h = compose f k ->
      h = k.
  Proof.
    intros. destruct H as [g H].
    assert (compose (compose g f) h = compose (compose g f) k).
    {
      repeat rewrite composition_assoc. rewrite H0. reflexivity.
    }
    unfold inverse in H. destruct H. rewrite H2 in H1.
    repeat rewrite composition_id_left in H1. apply H1.
  Qed.

  Theorem isomorphism_cancellation_right:
    forall (A B C: Object) (f: Morphism A B) (h k: Morphism C A),
      isomorphism f ->
      compose h f = compose k f ->
      h = k.
  Proof.
    intros. destruct H as [g H].
    assert (compose h (compose f g) = compose k (compose f g)).
    {
      repeat rewrite <- composition_assoc. rewrite H0. reflexivity.
    }
    unfold inverse in H. destruct H. rewrite H in H1.
    repeat rewrite composition_id_right in H1. apply H1.
  Qed.
End Isomorphism.

Module Isomorphic.
  Import Isomorphism.

  Definition isomorphic (A B: Object) :=
    exists f: Morphism A B, isomorphism f.

  (* A is isomorphic to A. *)
  Theorem isomorphic_refl: forall A: Object,
    isomorphic A A.
  Proof.
    intros. unfold isomorphic. exists (identity A).
    unfold isomorphism. exists (identity A).
    split; apply composition_id.
  Qed.

  (* If A is isomorphic to B, then B is isomorphic to A. *)
  Theorem isomorphic_symm: forall (A B: Object),
    isomorphic A B -> isomorphic B A.
  Proof.
    intros. destruct H. destruct H. destruct H.
    exists x0. exists x. split; assumption.
  Qed.

  (* If A is isomorphic to B, and B is isomorphic to C, then A is isomorphic to C. *)
  Theorem isomorphic_tran: forall (A B C: Object),
    isomorphic A B ->
    isomorphic B C ->
    isomorphic A C.
  Proof.
    intros. destruct H. destruct H0. exists (compose x x0).
    destruct H. destruct H0. exists (compose x2 x1).
    destruct H. destruct H0. split; rewrite composition_assoc.
    - assert (compose x0 (compose x2 x1) = compose (compose x0 x2) x1).
      { rewrite <- composition_assoc. reflexivity. }
      rewrite H3. rewrite H0. destruct (composition_id B A x1). rewrite H4. assumption.
    - assert (compose x1 (compose x x0) = compose (compose x1 x) x0).
      { rewrite <- composition_assoc. reflexivity. }
      rewrite H3. rewrite H1. destruct (composition_id B C x0). rewrite H4. assumption.
  Qed.
End Isomorphic.


Require Export Relation_Definitions.
Require Import Relation_Definitions_Implicit.
Require Import Classical_Wf.
Require Import Description.
Require Import FunctionalExtensionality.
Require Import Classical.
Require Import ZornsLemma.
Require Import ProofIrrelevance.
Require Import EnsemblesSpec.

Section WellOrder.

(* this definition is for the strict order, e.g. the
   element relation for ordinals of ZFC *)
Variable T:Type.

Definition total_strict_order (R:relation T) : Prop :=
  forall x y:T, R x y \/ x = y \/ R y x.

Record well_order (R:relation T) : Prop := {
  wo_well_founded: well_founded R;
  wo_total_strict_order: total_strict_order R
}.

Lemma wo_irrefl: forall R:relation T, well_order R ->
  (forall x:T, ~ R x x).
Proof.
intuition.
assert (forall y:T, Acc R y -> y <> x).
intros.
induction H1.
intuition.
rewrite H3 in H2.
apply H2 with x.
trivial.
trivial.

pose proof (wo_well_founded R H).
unfold well_founded in H2.
pose proof (H1 x (H2 x)).
auto.
Qed.

Lemma wo_antisym: forall R:relation T, well_order R ->
  (forall x y:T, R x y -> ~ R y x).
Proof.
intuition.
assert (forall z:T, Acc R z -> z <> x /\ z <> y).
intros.
induction H2.
intuition.
rewrite H4 in H3.
pose proof (H3 y H1).
tauto.
rewrite H4 in H3.
pose proof (H3 x H0).
tauto.

pose proof (wo_well_founded R H).
unfold well_founded in H3.
pose proof (H2 x (H3 x)).
tauto.
Qed.

Lemma wo_transitive: forall R:relation T, well_order R -> transitive R.
Proof.
intros.
unfold transitive.
intros.
case (wo_total_strict_order R H x z).
trivial.
intro.
case H2.
intro.
rewrite H3 in H0.
pose proof (wo_antisym R H y z).
contradict H0.
auto.

intro.

assert (forall a:T, Acc R a -> a <> x /\ a <> y /\ a <> z).
intros.
induction H4.
intuition.
rewrite H2 in H5.
pose proof (H5 z H3).
tauto.
rewrite H2 in H5.
pose proof (H5 x H0).
tauto.
rewrite H2 in H5.
pose proof (H5 y H1).
tauto.
rewrite H2 in H5.
pose proof (H5 z H3).
tauto.
rewrite H2 in H5.
pose proof (H5 x H0).
tauto.
rewrite H2 in H5.
pose proof (H5 y H1).
tauto.

pose proof (wo_well_founded R H).
unfold well_founded in H5.
pose proof (H4 x (H5 x)).
tauto.
Qed.

End WellOrder.

Arguments total_strict_order {T}.
Arguments well_order {T}.
Arguments wo_well_founded {T} {R}.
Arguments wo_transitive {T} {R}.
Arguments wo_total_strict_order {T} {R}.
Arguments wo_irrefl {T} {R}.
Arguments wo_antisym {T} {R}.

Section WellOrderMinimum.

Variable T:Type.
Variable R:relation T.
Hypothesis well_ord: well_order R.

Definition WO_minimum:
  forall S:Ensemble T, Inhabited S ->
    { x:T | In S x /\ forall y:T, In S y -> y = x \/ R x y }.
refine (fun S H => constructive_definite_description _ _).
pose proof (WF_implies_MEP T R (wo_well_founded well_ord)).
unfold minimal_element_property in H0.
pose proof (H0 S H).

destruct H1.
destruct H1.
exists x.
red.
split.
split.
assumption.
intros.
case (wo_total_strict_order well_ord x y).
tauto.
intro.
case H4.
auto.
intro.
contradict H5.
auto.

intros.
destruct H3.
case (wo_total_strict_order well_ord x x').
intro.
pose proof (H4 x H1).
case H6.
trivial.
intro.
contradict H7.
auto.

intro.
case H5.
trivial.
intro.
contradict H6.
auto.
Defined.

End WellOrderMinimum.

Arguments WO_minimum {T}.

Section WellOrderConstruction.

Variable T:Type.

Definition restriction_relation (R:relation T) (S:Ensemble T) :
  relation ({z:T | In S z}) :=
  fun (x y:{z:T | In S z}) => R (proj1_sig x) (proj1_sig y).

Record partial_WO : Type := {
  pwo_S: Ensemble T;
  pwo_R: relation T;
  pwo_R_lives_on_S: forall (x y:T), pwo_R x y -> In pwo_S x /\ In pwo_S y;
  pwo_wo: well_order (restriction_relation pwo_R pwo_S)
}.

(* the last condition below says that S WO1 is a downward closed
   subset of S WO2 *)
Record partial_WO_ord (WO1 WO2:partial_WO) : Prop := {
  pwo_S_incl: Included (pwo_S WO1) (pwo_S WO2);
  pwo_restriction: forall x y:T, In (pwo_S WO1) x -> In (pwo_S WO1) y ->
    (pwo_R WO1 x y <-> pwo_R WO2 x y);
  pwo_downward_closed: forall x y:T, In (pwo_S WO1) y -> In (pwo_S WO2) x ->
    pwo_R WO2 x y -> In (pwo_S WO1) x
}.

Lemma partial_WO_preord : preorder partial_WO_ord.
Proof.
constructor.
unfold reflexive.
intro.
destruct x.
constructor; simpl.
auto with sets.
split.
trivial.
trivial.
auto.

unfold transitive.
destruct x.
destruct y.
destruct z.
intros.
destruct H.
destruct H0.

simpl in pwo_S_incl0; simpl in pwo_restriction0;
  simpl in pwo_downward_closed0; simpl in pwo_S_incl1;
  simpl in pwo_restriction1; simpl in pwo_downward_closed1.
constructor; simpl.
auto with sets.
intros.
apply iff_trans with (pwo_R1 x y).
apply pwo_restriction0; auto with sets.
apply pwo_restriction1; auto with sets.

intros.
apply pwo_downward_closed0 with y; trivial.
apply pwo_downward_closed1 with y; trivial.
auto with sets.
apply <- (pwo_restriction1 x y); trivial.
auto with sets.
apply pwo_downward_closed1 with y; trivial.
auto with sets.
Qed.

Definition partial_WO_chain_ub: forall C:Ensemble partial_WO,
  chain partial_WO_ord C -> partial_WO.
refine (fun C H => let US := [ x:T | exists WO:partial_WO,
                                     In C WO /\ In (pwo_S WO) x ] in
           let UR := fun x y:T => exists WO:partial_WO, In C WO /\
                                     pwo_R WO x y in
        Build_partial_WO US UR _ _).
intros.
unfold UR in H0.
destruct H0.
destruct H0.
split.
constructor.
exists x0.
split.
assumption.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.
constructor.
exists x0.
split.
assumption.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.

constructor.
assert (forall (WO:partial_WO) (x:{z:T | In (pwo_S WO) z}),
   In C WO -> In US (proj1_sig x)).
intros.
constructor.
exists WO.
split.
assumption.
exact (proj2_sig x).

assert (forall (WO:partial_WO) (iC:In C WO) (x:{z:T | In (pwo_S WO) z}),
  Acc (restriction_relation (pwo_R WO) (pwo_S WO)) x ->
  Acc (restriction_relation UR US)
        (exist _ (proj1_sig x) (H0 WO x iC))).
intros.
induction H1.
constructor.
intros.
destruct x as [x ix].
destruct y as [y iy].
unfold restriction_relation in H3.
simpl in H3.
assert (In (pwo_S WO) y).
destruct H3.
destruct H3.
pose proof (H WO x0 iC H3).
case H5.
intro.
destruct H6.
apply pwo_downward_closed0 with x.
assumption.
pose proof (pwo_R_lives_on_S x0 y x).
tauto.
assumption.
intro.
destruct H6.
apply pwo_S_incl0.
pose proof (pwo_R_lives_on_S x0 y x).
tauto.

pose proof (H2 (exist (In (pwo_S WO)) y H4)).
simpl in H5.
assert (iy = H0 WO (exist (In (pwo_S WO)) y H4) iC).
apply proof_irrelevance.
rewrite <- H6 in H5.
apply H5.
unfold restriction_relation.
simpl.
destruct H3.
destruct H3.
pose proof (H WO x0 iC H3).
case H8.
intros.
destruct H9.
apply <- pwo_restriction0.
assumption.
assumption.
assumption.
intro.
destruct H9.
apply -> pwo_restriction0.
assumption.
pose proof (pwo_R_lives_on_S x0 y x).
tauto.
pose proof (pwo_R_lives_on_S x0 y x).
tauto.

red.
intro.
destruct a.
inversion i.
destruct H2.
destruct H2.
pose proof (H1 x0 H2 (exist _ x H3)).
simpl in H4.
assert (i = H0 x0 (exist _ x H3) H2).
apply proof_irrelevance.
rewrite <- H5 in H4.
apply H4.
apply (wo_well_founded (pwo_wo x0)).

unfold total_strict_order.
intros.
destruct x.
destruct y.
unfold restriction_relation.
simpl.
destruct i.
destruct e.
destruct a.
destruct i0.
destruct e.
destruct a.

case (H x1 x2 i i0).
intro.
assert (In (pwo_S x2) x).
apply H0.
assumption.
case (wo_total_strict_order (pwo_wo x2) (exist _ x H1) (exist _ x0 i2)).
unfold restriction_relation.
simpl.
left.
exists x2.
tauto.
intro.
case H2.
right; left.
apply subset_eq_compat.
injection H3.
trivial.
unfold restriction_relation.
simpl.
right; right.
exists x2.
tauto.

intro.
assert (In (pwo_S x1) x0).
apply H0.
assumption.
case (wo_total_strict_order (pwo_wo x1) (exist _ x i1) (exist _ x0 H1)).
unfold restriction_relation.
simpl.
left.
exists x1.
tauto.
intro.
case H2.
right; left.
apply subset_eq_compat.
injection H3.
trivial.
unfold restriction_relation; simpl.
right; right.
exists x1.
tauto.
Defined.

Lemma partial_WO_chain_ub_correct: forall (C:Ensemble partial_WO)
  (c:chain partial_WO_ord C), forall WO:partial_WO, In C WO ->
  partial_WO_ord WO (partial_WO_chain_ub C c).
Proof.
intros.
constructor.
unfold Included.
intros.
constructor.
exists WO.
tauto.

intros.
split.
intro.
exists WO.
tauto.
intro.
destruct H2.
destruct H2.
case (c WO x0 H H2).
intro.
destruct H4.
apply <- pwo_restriction0.
assumption.
assumption.
assumption.
intro.
destruct H4.
apply -> pwo_restriction0.
assumption.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.

intros.
destruct H2.
destruct H2.
case (c WO x0 H H2).
intro.
destruct H4.
apply pwo_downward_closed0 with y.
assumption.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.
assumption.
intro.
apply H4.
pose proof (pwo_R_lives_on_S x0 x y).
tauto.
Qed.

Definition extend_strictly_partial_WO: forall (WO:partial_WO)
  (a:T), ~ In (pwo_S WO) a -> partial_WO.
refine (fun WO a H => let S' := Add (pwo_S WO) a in
  let R' := fun x y:T => pwo_R WO x y \/ (In (pwo_S WO) x /\ y = a) in
  Build_partial_WO S' R' _ _).
intros.
case H0.
intros.
split.
left.
pose proof (pwo_R_lives_on_S WO x y).
tauto.
left.
pose proof (pwo_R_lives_on_S WO x y).
tauto.
intros.
destruct H1.
split.
left.
assumption.
right.
rewrite H2.
auto with sets.

constructor.
red.
intros.
assert (forall x:{y:T | In (pwo_S WO) y}, In S' (proj1_sig x)).
intro.
destruct x.
left.
simpl.
assumption.

assert (forall x:{y:T | In (pwo_S WO) y},
  Acc (restriction_relation R' S') (exist _ (proj1_sig x) (H0 x))).
intro.
pose proof (wo_well_founded (pwo_wo WO) x).
induction H1.
constructor.
intros.
destruct x.
destruct y.
unfold restriction_relation in H3.
simpl in H3.
assert (In (pwo_S WO) x0).
case H3.
intro.
pose proof (pwo_R_lives_on_S WO x0 x).
tauto.
tauto.
assert (pwo_R WO x0 x).
case H3.
trivial.
intro.
destruct H5.
contradict H.
rewrite <- H6.
assumption.

pose proof (H2 (exist _ x0 H4)).
simpl in H6.
assert (i0 = (H0 (exist (In (pwo_S WO)) x0 H4))).
apply proof_irrelevance.
rewrite <- H7 in H6.
apply H6.
red.
simpl.
assumption.

destruct a0.
case i.
intros.
pose proof (H1 (exist _ x0 i0)).
simpl in H2.
assert (H0 (exist (In (pwo_S WO)) x0 i0) =
  Union_introl T (pwo_S WO) (Singleton a) x0 i0).
apply proof_irrelevance.
rewrite <- H3.
assumption.
intros.
generalize i0.
destruct i0.
intro.
constructor.
intros.
unfold restriction_relation in H2.
destruct y.
simpl in H2.
case H2.
intro.
contradict H.
pose proof (pwo_R_lives_on_S WO x0 a).
tauto.
intros.
destruct H3.
pose proof (H1 (exist _ x0 H3)).
simpl in H5.
assert (H0 (exist (In (pwo_S WO)) x0 H3) = i1).
apply proof_irrelevance.
rewrite H6 in H5.
assumption.

red.
intros.
destruct x.
destruct y.
unfold restriction_relation.
simpl.
case i.
case i0.
intros.
case (wo_total_strict_order (pwo_wo WO)
  (exist _ x2 i2) (exist _ x1 i1)).
intro.
red in H0.
simpl in H0.
left.
constructor 1.
assumption.
intro.
case H0.
right; left.
apply subset_eq_compat.
injection H1.
trivial.

right; right.
red in H1.
simpl in H1.
constructor 1.
assumption.

intros.
left.
destruct i1.
constructor 2.
tauto.

case i0.
intros.
right; right.
destruct i2.
constructor 2.
tauto.

right; left.
apply subset_eq_compat.
destruct i1.
destruct i2.
trivial.
Defined.

Lemma extend_strictly_partial_WO_correct: forall (WO:partial_WO)
  (x:T) (ni:~ In (pwo_S WO) x),
  partial_WO_ord WO (extend_strictly_partial_WO WO x ni).
Proof.
intros.
constructor.
unfold extend_strictly_partial_WO; simpl.
constructor 1.
assumption.
intros.
unfold extend_strictly_partial_WO; simpl.
split.
tauto.
intro.
case H1.
trivial.
intro.
destruct H2.
contradict ni.
rewrite <- H3.
assumption.

unfold extend_strictly_partial_WO; simpl.
intros.
case H1.
intro.
pose proof (pwo_R_lives_on_S WO x0 y).
tauto.
intro.
tauto.
Qed.

Lemma premaximal_partial_WO_is_full: forall WO:partial_WO,
  premaximal partial_WO_ord WO -> pwo_S WO = Full_set.
Proof.
intros.
apply Extensionality_Ensembles.
split.
unfold Included.
intros.
constructor.
unfold Included.
intros.
apply NNPP.
unfold not; intro.
pose (WO' := extend_strictly_partial_WO WO x H1).
assert (partial_WO_ord WO' WO).
apply H.
apply extend_strictly_partial_WO_correct.
assert (In (pwo_S WO') x).
simpl.
constructor 2.
auto with sets.
apply H1.
apply H2.
assumption.
Qed.

Theorem well_orderable: exists R:relation T, well_order R.
Proof.
assert (exists WO:partial_WO, premaximal partial_WO_ord WO).
apply ZornsLemmaForPreorders.
exact partial_WO_preord.
intros.
exists (partial_WO_chain_ub S H).
exact (partial_WO_chain_ub_correct S H).

destruct H as [WO].
exists (pwo_R WO).
constructor.
assert (forall x:T, In (pwo_S WO) x).
rewrite premaximal_partial_WO_is_full.
intro.
constructor.
assumption.

assert (forall a:{x:T | In (pwo_S WO) x}, Acc (pwo_R WO) (proj1_sig a)).
intro.
pose proof (wo_well_founded (pwo_wo WO)).
induction (H1 a).
destruct x.
simpl.
unfold restriction_relation in H3; simpl in H3.
constructor.
intros.
apply H3 with (y := exist _ y (H0 y)).
assumption.
red; intro.
apply H1 with (a := exist _ a (H0 a)).

red; intros.
assert (forall x:T, In (pwo_S WO) x).
rewrite premaximal_partial_WO_is_full; intro.
constructor.
apply H.
case (wo_total_strict_order (pwo_wo WO)
  (exist _ x (H0 x)) (exist _ y (H0 y))).
unfold restriction_relation; tauto.
intro.
case H1.
intro.
right; left.
injection H2.
trivial.
unfold restriction_relation; tauto.
Qed.

End WellOrderConstruction.

Section WO_implies_AC.

Lemma WO_implies_AC: forall (A B:Type) (R: A -> B -> Prop)
  (WO:relation B), well_order WO ->
  (forall x:A, exists y:B, R x y) ->
  exists f:A->B, forall x:A, R x (f x).
Proof.
intros.
assert (forall a:A, Inhabited [ b:B | R a b ]).
intro.
pose proof (H0 a).
destruct H1.
exists x.
constructor; assumption.

exists (fun a:A => proj1_sig
  (WO_minimum WO H [ b:B | R a b ] (H1 a))).
intro.
destruct @WO_minimum.
simpl.
destruct a.
destruct H2.
assumption.
Qed.

End WO_implies_AC.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (y : natural) (z : natural) : natural := plus z (mult z y).


Require Import Coq.Sets.Ensembles.
Require Import Coq.Sets.Powerset_facts.

Section Lemma_1_18.

Variable U : Type.

Variable (A B C : Ensemble U).

Theorem Union_increases_l: forall (U : Type) (a b : Ensemble U),
  Included U a (Union U a b).
Proof.
  unfold Included. intros. unfold In.
  apply Union_introl. apply H.
Qed.

Theorem Union_minimal: forall (U : Type) (a b X : Ensemble U),
  Included U a X -> Included U b X -> Included U (Union U a b) X.
Proof.
  unfold Included. intros. destruct H1.
  - apply H. apply H1.
  - apply H0. apply H1.
Qed.

(* This is the same as Union_commutative *)
Lemma i_a: Union U A B = Union U B A.
Proof.
  simple apply Extensionality_Ensembles.
  unfold Same_set. split.
  - simple apply Union_minimal.
    + simple apply Union_increases_r.
    + simple apply Union_increases_l.
  - simple apply Union_minimal.
    + simple apply Union_increases_r.
    + simple apply Union_increases_l.
Qed.

(* This is the same as Intersection_commutative *)
Lemma i_b : Intersection U A B = Intersection U B A.
Proof.
  simple apply Extensionality_Ensembles.
  unfold Same_set. split.
  - unfold Included. intros. destruct H.
    apply Intersection_intro. apply H0. apply H.
  - unfold Included. intros. destruct H.
    apply Intersection_intro. apply H0. apply H.
Qed.

(* This is the same as Union_associative *)
Lemma ii_a: Union U A (Union U B C) = Union U (Union U A B) C.
Proof.
  simple apply Extensionality_Ensembles.
  unfold Same_set. split.
  - unfold Included. intros.
    destruct H.
    + apply Union_introl. apply Union_introl. apply H.
    + destruct H.
      * apply Union_introl. apply Union_intror. apply H.
      * apply Union_intror. apply H.
  - unfold Included. intros. destruct H.
    + destruct H.
      * apply Union_introl. apply H.
      * apply Union_intror. apply Union_introl. apply H.
    + apply Union_intror. apply Union_intror. apply H.
Qed.

(* This is the same as Intersection_associative *)
Lemma ii_b : Intersection U A (Intersection U B C) = Intersection U (Intersection U A B) C.
Proof.
  simple apply Extensionality_Ensembles.
  unfold Same_set.
  split.
  - unfold Included. intros.
    unfold In. unfold In in H. destruct H.
    * repeat apply Intersection_intro. destruct H0.
      apply H. destruct H0. apply H0.
      destruct H0. apply H1.
  - unfold Included. intros.
    repeat apply Intersection_intro. destruct H.
    destruct H. apply H. destruct H. destruct H. apply H1.
    destruct H. apply H0.
Qed.

(* This is the same as Distributivity *)
Lemma iii_a :
    Intersection U A (Union U B C) =
    Union U (Intersection U A B) (Intersection U A C).
Proof.
  admit.
Qed.

(* This is the same as Distributivity' *)
Lemma iii_b :
    Union U A (Intersection U B C) =
    Intersection U (Union U A B) (Union U A C).
Proof.
  admit.
Qed.

(* Using intuitionistic logic, it is possible to prove that
   (A intersection B) is a subset of (A \ (A \ B)), but proving the converse
   requires classical logic. *)
Lemma iv_constructive :
    Included U (Intersection U A B) (Setminus U A (Setminus U A B)).
Proof.
  admit.
Qed.

(* Either add this one classical axiom only to this section *)
Hypothesis NNPP : forall p:Prop, ~ ~ p -> p.
(* or uncomment the following line to import all of Classical_Prop for this
   whole module *)
(* Require Import Coq.Logic.Classical_Prop. *)
Lemma iv : Setminus U A (Setminus U A B) = Intersection U A B.
Proof.
  admit.
Qed.

End Lemma_1_18.

Section Lemma_1_19.

Variable X : Type.

Variable (A B : Ensemble X).

(* This half is provable using intuitionistic logic *)
Lemma a_constructive :
    Included X (Union X (Complement X A) (Complement X B))
    (Complement X (Intersection X A B)).
Proof.
  admit.
Qed.

Hypothesis NNPP : forall p:Prop, ~ ~ p -> p.

Lemma a :
    Complement X (Intersection X A B) =
    Union X (Complement X A) (Complement X B).
Proof.
  admit.
Qed.

(* This half is provable using intuitionistic logic *)
Lemma b_constructive :
    Included X (Intersection X (Complement X A) (Complement X B))
    (Complement X (Union X A B)).
Proof.
  admit.
Qed.

Lemma b :
    Complement X (Union X A B) =
    Intersection X (Complement X A) (Complement X B).
Proof.
  admit.
Qed.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (y : natural) (x : natural) : natural := plus (mult y x) y.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (lf1 : natural) (x : natural) (y : natural) : natural :=
  mult x y.


(* The Cantor-Schröder-Bernstein theorem. *)

From set_theory Require Import lib fn set.

(* I use full types instead of Ensembles to make the proof more elegant. *)
Section Aquivalenzsatz.

Variable X : Type.
Variable Y : Type.
Variable f : X -> Y.
Variable g : Y -> X.
Hypothesis f_inj : Injective f.
Hypothesis g_inj : Injective g.

(* Infinite (ω) reflection of the set Y ⧵ Rng f. *)
Inductive CSB_Y : nat -> Y -> Prop :=
  | CSB_Y_0 : ∀y, ¬Rng f y -> CSB_Y 0 y
  | CSB_Y_S : ∀n x, CSB_X n x -> CSB_Y (S n) (f x)
with CSB_X : nat -> X -> Prop :=
  | CSB_X_n : ∀n y, CSB_Y n y -> CSB_X n (g y).

(* Bijective mapping as a functional relation. *)
Definition CSB_h x y : Prop :=
  (g y = x /\ ∃n, CSB_Y n y) \/ (f x = y /\ ¬∃n, CSB_X n x).

Lemma CSB_h_unique x :
  ∃!y, CSB_h x y.
Proof.
destruct (classic (∃n, CSB_X n x)) as [[n Hn]|H].
- inversion Hn; subst; exists y; split. left; split. easy. now exists n.
  intros y' [[Hy' _]|[_ Hy']]. now apply g_inj.
  exfalso; apply Hy'; now exists n.
- exists (f x); split. now right. intros y' [[Hy' [n Hn]]|[Hy' _]].
  exfalso; apply H; exists n. rewrite <-Hy'; now apply CSB_X_n. easy.
Qed.

Lemma CSB_h_inj x x' y :
  CSB_h x y -> CSB_h x' y -> x = x'.
Proof.
intros [[H1 [n Hn]]|[H1a H1b]] [[H2 [m Hm]]|[H2a H2b]].
- now rewrite <-H1, <-H2.
- exfalso; destruct n; inversion Hn; subst. apply H; now exists x'.
  apply f_inj in H2; subst. apply H2b; now exists n.
- exfalso; destruct m; inversion Hm; subst. apply H; now exists x.
  apply f_inj in H1; subst. apply H1b; now exists m.
- apply f_inj; now rewrite H1a, H2a.
Qed.

Lemma CSB_h_surj y :
  ∃x, CSB_h x y.
Proof.
destruct (classic (∃n, CSB_Y n y)) as [[n Hn]|H].
- exists (g y); left; split. easy. now exists n.
- destruct (classic (Rng f y)) as [[x Hx]|Hy].
  + exists x; right; split. easy. intros [n Hn].
    apply H; exists (S n). rewrite <-Hx; now apply CSB_Y_S.
  + exfalso; apply H; exists 0; now apply CSB_Y_0.
Qed.

Theorem CSB :
  ∃f : X -> Y, Bijective f.
Proof.
destruct (unique_choice _ _ _ CSB_h_unique) as [h Hh];
exists h; apply fn_inj_surj_bi.
- intros x x' H; apply CSB_h_inj with (y:=h x).
  apply Hh. rewrite H; apply Hh.
- intros y; destruct (CSB_h_surj y) as [x Hx]; exists x.
  destruct (CSB_h_unique x) as [y' [_ Hy']].
  now rewrite <-(Hy' y), <-(Hy' (h x)).
Qed.

End Aquivalenzsatz.


Require Import Coq.NArith.NArith
  Znumtheory Lia
  Zdiv Zpow_facts.

Section Fn.

  Fixpoint repeat_op_ntimes_rec (e : N) (n : positive) (w : N) : N :=
    match n with
    | xH => N.modulo e w
    | xO p => let ret := repeat_op_ntimes_rec e p w in N.modulo (ret * ret) w
    | xI p => let ret := repeat_op_ntimes_rec e p w in N.modulo (e * (ret * ret)) w
    end.

  Definition Npow_mod (e : N) (n w : N) :=
    match n with
    | N0 => Npos xH
    | Npos p => repeat_op_ntimes_rec e p w
    end.

  (* slow function, will be used to prove that this slow function is
    equivalent to Npow_mod, faster one. *)
  Fixpoint Npow_mod_unary (e : N) (n : nat) (w : N) : N :=
    match n with
    | 0%nat => Npos xH
    | S n' => N.modulo (e * Npow_mod_unary e n' w) w
    end.

  (* acc is accumulator, for efficient reduction of terms *)
  Fixpoint repeat_op_ntimes_acc (e : N) (n : positive) (w acc : N) : N :=
    match n with
    | xH => N.modulo (e * acc) w
    | xO p => let ee := (N.modulo (e * e) w) in repeat_op_ntimes_acc ee p w acc
    | xI p => let ee := (N.modulo (e * e) w) in
              let ea := (N.modulo (e * acc) w) in
              repeat_op_ntimes_acc ee p w ea
    end.

  Lemma op_pushes_out : forall n e w, prime (Z.of_N w) ->
    repeat_op_ntimes_rec ((e * e) mod w) n w =
    N.modulo ((repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)) w.
  Proof.
    induction n.
    - simpl; intros ? ? Hw.
      rewrite IHn.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.
      rewrite <- N.mul_mod_idemp_r.
      repeat rewrite N.mul_mod_idemp_l.
      repeat rewrite N.mul_mod_idemp_r.
      assert (Ht : (e * enw * (e * enw) =
        e * e * (enw * enw))%N). lia.
      rewrite Ht; clear Ht.
      repeat rewrite N.mul_assoc.
      rewrite N.mul_mod_idemp_r.
      reflexivity.
      all:(try lia; try assumption).
    - simpl; intros ? ? Hw.
      rewrite IHn.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      reflexivity. exact Hw.
    - simpl; intros ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      rewrite N.mod_mod.
      rewrite N.mul_mod_idemp_l.
      rewrite N.mul_mod_idemp_r.
      reflexivity.
      all:lia.
  Qed.

  Lemma positive_mul_group_acc_rec_connection : forall n e w acc, prime (Z.of_N w) ->
    repeat_op_ntimes_acc e n w acc = N.modulo (acc * repeat_op_ntimes_rec e n w) w.
  Proof.
    induction n.
    - simpl; intros ? ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      specialize (IHn (N.modulo (e * e) w) w (N.modulo (e * acc) w)).
      rewrite IHn.
      rewrite op_pushes_out.
      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.
      rewrite N.mul_mod_idemp_l.
      repeat rewrite N.mul_mod_idemp_r.
      assert (Ht : ((acc * (e * enw) = e * acc * enw)%N)).
      lia.
      rewrite Ht; clear Ht.
      reflexivity.
      all:(try lia; try assumption).
    - simpl; intros ? ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      rewrite IHn. rewrite op_pushes_out.
      reflexivity.
      all:assumption.
    - simpl; intros ? ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      rewrite N.mul_mod_idemp_r.
      assert (Ht : (acc * e = e * acc)%N). lia.
      rewrite Ht; clear Ht.
      reflexivity.
      lia.
  Qed.

  Definition Npow_mod_constant_space (e : N) (n w : N) :=
    match n with
    | N0 => Npos xH
    | Npos p => repeat_op_ntimes_acc e p w 1
    end.

  Lemma npow_mod_npow_constant_eqv : forall n e w, prime (Z.of_N w) ->
    Npow_mod e n w = Npow_mod_constant_space e n w.
  Proof.
    destruct n; simpl; intros ? ? Hw.
    - reflexivity.
    - pose proof positive_mul_group_acc_rec_connection p e w 1 Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      rewrite H. rewrite N.mul_1_l.
      destruct p.
      all:simpl; rewrite N.mod_mod; lia.
  Qed.

  Lemma Npow_mod_unary_bound : forall (n : nat) (e w : N), prime (Z.of_N w) ->
    (Npow_mod_unary e n w < w)%N.
  Proof.
    induction n.
    - simpl; intros ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      lia.
    - simpl; intros ? ? Hw.
      apply N.mod_lt.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      lia.
  Qed.

  Lemma binnat_zero : forall (n : nat), 0%N = N.of_nat n -> n = 0%nat.
  Proof.
    induction n; try lia.
  Qed.

  Theorem Npow_mod_add_mul : forall n m e w, prime (Z.of_N w) ->
    Npow_mod_unary e (n + m) w = N.modulo (Npow_mod_unary e n w *
    Npow_mod_unary e m w) w.
  Proof.
    induction n.
    - intros ? ? ? Hw.
      rewrite Nat.add_0_l.
      assert (Ht : Npow_mod_unary e 0 w = Npos xH).
      simpl. reflexivity.
      rewrite Ht.
      rewrite N.mul_1_l.
      induction m.
      + simpl. rewrite N.mod_1_l.
        reflexivity.
        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
        lia.
      + simpl. rewrite N.mod_mod.
        reflexivity.
        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
        lia.
    - simpl; intros ? ? ? Hw.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
      rewrite IHn.
      rewrite N.mul_mod_idemp_r.
      rewrite N.mul_mod_idemp_l.
      rewrite N.mul_assoc. reflexivity.
      lia. lia. assumption.
  Qed.

  Lemma binnat_odd : forall (p : positive) (n : nat),
    N.pos (xI p) = N.of_nat n ->
    exists k,  n = (2 * k + 1)%nat /\  (N.pos p) = (N.of_nat k).
  Proof.
    intros p n Hp.
    destruct (Nat.Even_or_Odd n) as [H | H].
    destruct H as [k Hk].
    (* Even (impossible) Case *)
    rewrite Hk in Hp; lia.
    (* Odd (possible) case *)
    destruct H as [k Hk].
    rewrite Hk in Hp.
    exists k.
    split. exact Hk. lia.
  Qed.

  Lemma binnat_even : forall (p : positive) (n : nat),
    N.pos (xO p) = N.of_nat n :> N ->
    exists k, n = (Nat.mul 2 k) /\  (N.pos p) = (N.of_nat k).
  Proof.
    intros p n Hp.
    destruct (Nat.Even_or_Odd n) as [H | H].
    destruct H as [k Hk].
    (* Even (possible) case*)
    rewrite Hk in Hp. exists k.
    split. exact Hk. lia.
    (* Odd (impossible) case *)
    destruct H as [k Hk].
    rewrite Hk in Hp. lia.
  Qed.

  (* slow is equivalent to fast *)
  Lemma npow_mod_exp_unary_binary_eqv : forall (n : N) e w, prime (Z.of_N w) ->
    Npow_mod_unary e (N.to_nat n) w = Npow_mod e n w.
  Proof.
    destruct n.
    - simpl; intros ? ? Hw.
      reflexivity.
    - simpl; revert p.
      induction p.
      + simpl; intros ? ? Hw.
        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.
        rewrite <-IHp.
        rewrite ZL6.
        rewrite Npow_mod_add_mul.
        rewrite N.mul_mod_idemp_r.
        reflexivity.
        lia. exact Hw.
        exact Hw.
      + simpl; intros ? ? Hw.
        rewrite <-IHp.
        rewrite Pos2Nat.inj_xO.
        assert (Ht : (2 * Pos.to_nat p =
          Pos.to_nat p + Pos.to_nat p)%nat).
        lia. rewrite Ht.
        rewrite Npow_mod_add_mul.
        reflexivity.
        exact Hw.
        exact Hw.
      + simpl; intros ? ? Hw.
        rewrite N.mul_1_r.
        reflexivity.
  Qed.

  Lemma mod_reduce_pow : forall n e w, prime (Z.of_N w) -> repeat_op_ntimes_rec e n w =
    repeat_op_ntimes_rec (N.modulo e w) n w.
  Proof.
    induction n.
    - simpl; intros ? ? Hp.
      rewrite IHn.
      remember (repeat_op_ntimes_rec (e mod w) n w *
      repeat_op_ntimes_rec (e mod w) n w)%N as t.
      rewrite N.mul_mod_idemp_l.
      reflexivity.
      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.
      lia. exact Hp.
    - simpl; intros ? ? Hp.
      rewrite IHn.
      reflexivity.
      exact Hp.
    - simpl; intros ? ? Hp.
      rewrite N.mod_mod.
      reflexivity.
      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.
      lia.
  Qed.

  Lemma Nmod_reduce_pow : forall n e w, prime (Z.of_N w) ->
    Npow_mod e n w = Npow_mod (N.modulo e w) n w.
  Proof.
    destruct n.
    - simpl; intros ? ? Hp.
      reflexivity.
    - simpl; intros ? ? Hp.
      apply mod_reduce_pow.
      exact Hp.
  Qed.

  Lemma wp_mod_zero : forall (w k p : N), prime (Z.of_N p) -> (2 <= k)%N -> (2 <= p)%N ->
    (w mod p = 0)%N ->  (Npow_mod (w mod p) k p = 0)%N.
  Proof.
    intros ? ? ? Hp Hk Hpt Hwp.
    rewrite Hwp.
    unfold Npow_mod.
    destruct k. lia.
    clear Hk.
    induction p0.
    simpl. rewrite N.mod_0_l.
    reflexivity. lia.
    simpl. rewrite IHp0.
    rewrite N.mod_0_l.
    reflexivity. lia.
    simpl. rewrite N.mod_0_l.
    reflexivity. lia.
  Qed.

  Lemma wp_mod_one : forall (w k p : N), prime (Z.of_N p) -> (2 <= k)%N -> (2 <= p)%N ->
    (w mod p = 1)%N ->  (Npow_mod (w mod p) k p = 1)%N.
  Proof.
    intros ? ? ? Hp Hk Hpt Hwp.
    rewrite Hwp.
    unfold Npow_mod.
    destruct k. lia.
    clear Hk.
    induction p0.
    simpl. rewrite IHp0.
    simpl. rewrite N.mod_1_l.
    reflexivity. lia.
    simpl. rewrite IHp0.
    rewrite N.mod_1_l.
    reflexivity. lia.
    simpl. rewrite N.mod_1_l.
    reflexivity. lia.
  Qed.

  Lemma zmod_nmod : forall (b a w : N), prime (Z.of_N w) ->
    Z.of_N (Npow_mod a b w) = Zpow_mod (Z.of_N a) (Z.of_N b) (Z.of_N w).
  Proof.
    intros ? ? ? Hw.
    rewrite Zpow_mod_correct.
    destruct b; simpl.
    - symmetry.
      rewrite Z.mod_1_l.
      reflexivity.
      pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.
      lia.
    - revert p.
      induction p.
      + simpl.
        assert (Ht : (p~1 = p + p + 1)%positive).
        lia. rewrite Ht.
        rewrite Zpower_pos_is_exp.
        rewrite Zpower_pos_is_exp.
        rewrite Zpower_pos_1_r.
        rewrite N2Z.inj_mod.
        rewrite N2Z.inj_mul.
        rewrite N2Z.inj_mul.
        rewrite IHp.
        remember (Z.pow_pos (Z.of_N a) p) as zps.
        remember (Z.of_N a) as za.
        remember (Z.of_N w) as zw.
        assert (Hzp: zps * zps * za = za * (zps * zps)).
        lia. rewrite Hzp; clear Hzp; clear Ht.
        rewrite <-Zmult_mod_idemp_l.
        assert (Ht : (za * (zps * zps)) mod zw = (za mod zw * (zps * zps)) mod zw).
        rewrite <-Zmult_mod_idemp_l.
        reflexivity. rewrite Ht; clear Ht.
        assert (Ht : (za mod zw * (zps * zps)) mod zw =
        (za mod zw * ((zps * zps) mod zw)) mod zw).
        rewrite <-Zmult_mod_idemp_r. reflexivity.
        rewrite Ht; clear Ht.
        assert (Ht : (zps * zps) mod zw =
          (zps mod zw * (zps mod zw)) mod zw).
        rewrite <-Zmult_mod_idemp_l.
        rewrite <-Zmult_mod_idemp_r.
        reflexivity.
        rewrite Ht.
        rewrite Zmult_mod_idemp_r.
        reflexivity.
      + simpl.
        assert (Ht : (p~0 = p + p)%positive).
        lia. rewrite Ht.
        rewrite Zpower_pos_is_exp.
        rewrite N2Z.inj_mod.
        rewrite N2Z.inj_mul.
        rewrite IHp.
        remember (Z.pow_pos (Z.of_N a) p) as zps.
        remember (Z.of_N a) as za.
        remember (Z.of_N w) as zw.
        rewrite Zmult_mod_idemp_l.
        rewrite Zmult_mod_idemp_r.
        reflexivity.
      + simpl. rewrite Zpower_pos_1_r.
        rewrite N2Z.inj_mod.
        reflexivity.
    - pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.
      lia.
  Qed.

  Lemma npow_mod_nat : forall (n a p : nat),
    prime (Z.of_nat p) ->
    Npow_mod_unary (N.of_nat a) n (N.of_nat p) =
    N.of_nat (Nat.modulo (Nat.pow a n) p).
  Proof.
    induction n.
    + intros * Hp.
      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.
      simpl. rewrite Nat.mod_1_l.
      lia. lia.
    + intros * Hp.
      simpl.
      pose proof (IHn a p Hp).
      rewrite H.
      rewrite <-Nat2N.inj_mul,
      <-Nat2N.inj_mod.
      f_equal.
      rewrite Nat.mul_mod_idemp_r.
      reflexivity.
      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.
      lia.
  Qed.

  Lemma N_to_nat_exp : forall (n a p : N),
    prime (Z.of_N p) ->
    N.modulo (N.pow a n) p =
    N.of_nat (Nat.modulo (Nat.pow (N.to_nat a)
      (N.to_nat n)) (N.to_nat p)).
  Proof.
    intros * Hp.
    rewrite <-N2Nat.inj_pow.
    rewrite <-N2Nat.inj_mod.
    lia.
  Qed.

End Fn.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (y : natural) (x : natural) (lf1 : natural) : natural :=
  mult y (plus x Zero).


Require Import Nat.
Require Import definitions.

Record ThetaLambdaInner := mkTLInner {
  tl_eest      : nat;
  tl_energy    : nat;
  tl_energyΛ   : nat * option Activity;
  tl_envelope  : nat;
  tl_envelopeΛ : nat * option Activity;
}.

Inductive ThetaLambdaLeaf :=
| tl_theta : Activity -> ThetaLambdaLeaf
| tl_lambda : Activity -> ThetaLambdaLeaf.

Definition thetaLambdaInnerFromLeaf (C: nat) (l: ThetaLambdaLeaf) :=
  match l with
  | tl_theta  a => mkTLInner (est a) (energy a) ((envelope_unit C a), None) 0 (0, None)
  | tl_lambda a => mkTLInner (est a) 0 (0, None) (energy a) (envelope_unit C a, None)
  end.

Definition rmax {R} (a b: nat*R) :=
  match (a, b) with ((a, ra), (b, rb)) =>
  let m := max a b in
  (m, if m =? a then ra else rb)
  end.

Definition radd1 {R} (a: nat*R) (b: nat) := ((fst a)+b, snd a).
Definition radd2 {R} (a: nat) (b: nat*R) := (a+(fst b), snd b).

Definition thetaLambdaPropagate (a b: ThetaLambdaInner) : ThetaLambdaInner :=
  mkTLInner
    (min (tl_eest a)   (tl_eest b))
    (add (tl_energy a) (tl_energy b))
    (rmax (radd1 (tl_energyΛ a) (tl_energy  b))
          (radd2 (tl_energy  a) (tl_energyΛ b)))
    (max (add (tl_envelope a) (tl_energy  b))
         (tl_envelope b))
    (rmax (tl_envelopeΛ b) (rmax
          (radd1 (tl_envelopeΛ a) (tl_energy  b))
          (radd2 (tl_envelope  a) (tl_energyΛ b))))
.

Inductive AbstractTree {A B: Type} (f: A->B) (g: B->B->B) : B -> Type :=
| at_inner {a b} : AbstractTree f g a -> AbstractTree f g b -> AbstractTree f g (g a b)
| at_leaf  (a: A) : AbstractTree f g (f a).

Inductive Path {A B} {f: A->B} {g: B->B->B} : forall {b}, AbstractTree f g b -> Type :=
| p_left  {bl} (l: AbstractTree f g bl)
          {br} (r: AbstractTree f g br) :
          Path l ->
          Path (at_inner f g l r)
| p_right {bl} (l: AbstractTree f g bl)
          {br} (r: AbstractTree f g br) :
          Path r ->
          Path (at_inner f g l r)
| p_here  {a} :
          Path (at_leaf f g a).

Require Import Coq.Program.Equality.

Fixpoint lookupLeaf {A B: Type} (f: A->B) (g: B->B->B)
    {b: B} {node: AbstractTree f g b} (path: Path node) : A :=
  match path with
  | p_left  l r pl => lookupLeaf f g pl
  | p_right l r pr => lookupLeaf f g pr
  | @p_here _ _ _ _ a => a
  end.

Definition updateLeaf {A B: Type} (f: A->B) (g: B->B->B) (update: A->A)
    {b: B} {node: AbstractTree f g b} (path: Path node) : { b': B & AbstractTree f g b' }.
induction path.
+ exists bl. apply l.
+ exists br. apply r.
+ exists (f (update a)). apply at_leaf.
Defined.

Definition updateLeafRel
  {A B: Type} (f: A->B) (g: B->B->B) (update: A->A)
  (y x: { b: B & AbstractTree f g b }) :=
    exists (path: Path (projT2 x)), updateLeaf f g update path = y.

Require Import Coq.Init.Wf.

Definition wfFunc
  {A}
  (f: A -> A)
:= {P: A->Prop | @well_founded A (fun a b => P b /\ f b = a)}.

Ltac apply_clear X := apply X; clear X.

(* just make sure wfFunc is sane *)
Theorem wfDec : wfFunc (fun (a: nat) => a-1).
  exists (fun x => x > 0).
  intro.
  induction a; constructor; intros y [precondition rel].
  inversion precondition.
  simpl in rel.
  rewrite PeanoNat.Nat.sub_0_r in rel; subst.
  apply IHa.
Qed.

Theorem updateLeafWellFounded
  {A B: Type} (f: A->B) (g: B->B->B) (update: A->A) (WF: wfFunc update) :
  well_founded (updateLeafRel f g update).
Proof.
  intro.
  destruct a as [xb x].
  constructor.
  intros.
  destruct y as [yb y].
  (* it's tempting to destroy the 'Acc' in the goal here, but not so fast!
     for the final element there -is- no even smaller element.
     in that situation there should be a contradiction in the assumptions. *)
  destruct H as [path HUpdate].
  set (yby := existT (fun b : B => AbstractTree f g b) yb y) in *.

  induction path eqn:Z.
  (*
       x    y
      / \
     l   r
  *)
  (* in the first two cases, the path taking the left or right side
     implies that both x and y -have- to be at_inner, not at_leaf.
     demonstrate this by destroying x and y and showing that their
     at_inner cases are infeasible. *)
  (*
  + enough (xb = g bl br). subst xb.
    enough (x = at_inner f g l r). subst x.
    destruct y.
    rewrite <- H. clear H.
    simpl.*)
  + admit.
  + admit.
  +

Definition ThetaLambdaNode (C: nat) :=
  @AbstractTree
    ThetaLambdaLeaf
    ThetaLambdaInner
    (thetaLambdaInnerFromLeaf C)
    thetaLambdaPropagate.

Definition maxEnvelopeΛPath {C} {b} (node: ThetaLambdaNode C b) : Path node.
  induction node.
  pose (fst (tl_envelopeΛ b) <? fst (tl_envelopeΛ a)).
  destruct b0 eqn:Z.
  apply p_left.
  apply IHnode1.
  apply p_right.
  apply IHnode2.
  apply p_here.
Qed.


From mathcomp.ssreflect Require Import ssreflect ssrnat ssrbool.
Set Implicit Arguments.
Unset Strict Implicit.
Import Prenex Implicits.

Require Import Coq.Init.Wf.

Definition Fin (n : nat) := Acc lt n.

Definition all_fin : forall n, Fin n := Wf_nat.lt_wf.

Lemma inv_succ : forall n m, Fin n -> n = m.+1 -> Fin m.
Proof. by move=> n m H E; move: E H=>-> H; apply/(Acc_inv H). Defined.

Lemma inv_maxl: forall n l r, Fin n -> n = (maxn l r).+1 -> Fin l.
Proof.
  move=> n l r H E; move: E H=>-> H; apply/(Acc_inv H)=>{H}.
  by apply/(rwP leP); rewrite ltnS leq_maxl.
Defined.

Lemma inv_maxr: forall n l r, Fin n -> n = (maxn l r).+1 -> Fin r.
Proof.
  move=> n l r H E; move: E H=>-> H; apply/(Acc_inv H)=>{H}.
  by apply/(rwP leP); rewrite ltnS leq_maxr.
Defined.


From mathcomp Require Import all_ssreflect.
From GraphTheory Require Import preliminaries digraph sgraph.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Set Bullet Behavior "Strict Subproofs".

(** * Domination Theory *)

(** ** Hereditary and superhereditary properties *)
Section Hereditary.
Variable (T : finType).

Implicit Types (p : pred {set T}) (F D : {set T}).

Definition hereditary p : bool := [forall (D : {set T} | p D), forall (F : {set T} | F \subset D), p F].

Definition superhereditary p : bool := hereditary [pred D | p (~: D)].

Proposition hereditaryP p :
  reflect (forall D F : {set T}, (F \subset D) -> p D -> p F) (hereditary p).
Proof.
  apply: (iffP forall_inP) => [H1 D F FsubD pD|H2 D pD].
  - exact: (forall_inP (H1 _ pD)).
  - apply/forall_inP => F FsubD; exact: H2 pD.
Qed.

Proposition superhereditaryP (p : pred {set T}) :
  reflect (forall D F : {set T}, (D \subset F) -> p D -> p F) (superhereditary p).
Proof.
  apply: (iffP (hereditaryP _)) => /= sh_p D F.
  all: by rewrite -setCS => /sh_p; rewrite ?setCK; auto.
Qed.

Proposition maximal_indsysP p D : hereditary p ->
  reflect (p D /\ forall v : T, v \notin D -> ~~ p (v |: D)) (maxset p D).
Proof.
  move/hereditaryP => p_hereditary; apply: (iffP maxset_properP).
  - case => pD maxD; split => // v vD. apply: maxD.
    by rewrite setUC properUl // sub1set.
  - case => pD max1D; split => // A /properP [subA [v vA /max1D vD]].
    apply: contraNN vD; apply: p_hereditary; by rewrite subUset sub1set vA.
Qed.

Proposition minimal_indsysP p D : superhereditary p ->
  reflect (p D /\ forall v : T, v \in D -> ~~ p (D :\ v)) (minset p D).
Proof.
  rewrite minmaxset => sh_p; apply: (iffP (maximal_indsysP _ _)) => //=.
  all: rewrite ?setCK => -[pD H]; split => // v; move: (H v).
  all: by rewrite !inE ?setCU ?setCK ?negbK setDE setIC.
Qed.

End Hereditary.

(** ** Weighted Sets *)

Section Weighted_Sets.
Variables (T : finType) (weight : T -> nat).
Implicit Types (A B S : {set T}) (p : pred {set T}).

Definition weight_set (S : {set T}) := \sum_(v in S) weight v.
Let W := weight_set.

Lemma leqwset A B : A \subset B -> W A <= W B.
Proof. move=> AsubB ; by rewrite [X in _ <= X](big_setID A) /= (setIidPr AsubB) leq_addr. Qed.

Hypothesis positive_weights : forall v : T, weight v > 0.

Lemma wset0 A : (A == set0) = (W A == 0).
Proof.
  apply/eqP/eqP.
  - move=> Dempty ; rewrite /weight_set.
    move: Dempty ->. exact: big_set0.
  - move=> /eqP weightzero.
    apply/eqP ; move: weightzero.
    apply: contraLR => /set0Pn. elim=> x xinD.
    apply: lt0n_neq0 ; rewrite /W /weight_set (bigD1 x) //=.
    exact/ltn_addr/positive_weights.
Qed.

Lemma ltnwset A B :  A \proper B -> W A < W B.
Proof.
  move => /properP [AsubB].
  elim=> x xinB xnotinA.
  rewrite {2}/W /weight_set (big_setID A) /= (setIidPr AsubB).
  rewrite -[X in X <= _]addn0 addSn -addnS leq_add2l lt0n.
  rewrite -/(weight_set _) -wset0.
  by apply/set0Pn; exists x; apply/setDP.
Qed.

(* Sets of minimum/maximum weight *)

Lemma maxweight_maxset p A : p A -> (forall B, p B -> W B <= W A) -> maxset p A.
Proof.
  move => pA maxA. apply/maxset_properP; split => // B /ltnwset; rewrite ltnNge.
  exact/contraNN/maxA.
Qed.

Lemma minweight_minset p A : p A -> (forall B, p B -> W A <= W B) -> minset p A.
Proof.
  move => pA minA; apply/minset_properP; split => // B /ltnwset; rewrite ltnNge.
  exact/contraNN/minA.
Qed.

Lemma arg_maxset p A : p A -> maxset p (arg_max A p W).
Proof. by move => pA; apply/maxweight_maxset; case: arg_maxnP. Qed.

Lemma arg_minset p A : p A -> minset p (arg_min A p W).
Proof. by move => pA ; apply/minweight_minset; case: arg_minnP. Qed.

End Weighted_Sets.

Section Domination_Theory.

Variable G : sgraph.

(** ** Stable, Dominating and Irredundant Sets *)
Section Stable_Set.

Variable S : {set G}.

Definition stable : bool := [disjoint NS(S) & S].

Local Lemma stableP_alt :
  reflect {in S&, forall u v, ~~ u -- v} [forall u in S, forall v in S, ~~ (u -- v)].
Proof. apply: equivP (in11_in2 S S). do 2 (apply: forall_inPP => ?). exact: idP. Qed.

Lemma stableEedge : stable = [forall u in S, forall v in S, ~~ (u -- v)].
Proof.
  symmetry ; rewrite /stable ; apply/stableP_alt/disjointP => stS.
  - move => x /bigcupP [y yS adjyx] xS.
    move: adjyx. rewrite in_opn. apply/negP. by apply: stS.
  - move => x y xS yS. apply/negP => adjxy.
    exact: (stS y (mem_opns xS adjxy) yS).
Qed.

Proposition stableP : reflect {in S&, forall u v, ~~ u -- v} stable.
Proof. rewrite stableEedge ; exact: stableP_alt. Qed.

Proposition stablePn : reflect (exists x y, [/\ x \in S, y \in S & x -- y]) (~~ stable).
Proof.
  rewrite stableEedge.
  set E := exists _, _.
  have EE : (exists2 x, x \in S & exists2 y, y \in S & x -- y) <-> E by firstorder.
  rewrite !negb_forall_in; apply: equivP EE; apply: exists_inPP => x.
  rewrite negb_forall_in; apply: exists_inPP => y. exact: negPn.
Qed.

End Stable_Set.

(* the empty set is stable *)
Lemma stable0 : stable set0.
Proof. by apply/stableP=> ? ? ; rewrite in_set0. Qed.

Lemma stable1 x : stable [set x].
Proof. by apply/stableP => ? ? /set1P -> /set1P ->; rewrite sgP. Qed.

(* if D is stable, any subset of D is also stable *)
Lemma st_hereditary : hereditary stable.
Proof.
  apply/hereditaryP.
  move=> D F FsubD /stableP Dstable.
  apply/stableP => u v uinF vinF.
  move: (subsetP FsubD u uinF) => uinD.
  move: (subsetP FsubD v vinF) => vinD.
  exact: Dstable.
Qed.

(* TOTHINK: do we need that [hereditary] is a boolean predicate? *)
Lemma sub_stable (B A : {set G}) :
  A \subset B -> stable B -> stable A.
Proof.
move => subAB stB. exact: (hereditaryP _ st_hereditary _ _ subAB).
Qed.

(**********************************************************************************)
Section Dominating_Set.

Variable D : {set G}.

Definition dominating : bool := [forall v, v \in NS[D]].

Local Lemma dominatingP_alt : reflect
  (forall v : G, v \notin D -> exists2 u : G, u \in D & u -- v)
  [forall (v | v \notin D), exists u in D, u -- v].
Proof. apply: forall_inPP => v; exact: exists_inP. Qed.

Lemma dominatingEedge : dominating = [forall (v | v \notin D), exists u in D, u -- v].
Proof.
  apply/forallP/forall_inP => [H v vND |H v].
  - have [u udomv] := bigcupP (H v).
    rewrite in_cln; case/predU1P => [?|uv]; first by subst;contrab.
    by apply/exists_inP; exists u.
  - case: (boolP (v \in D)) => [|/H/exists_inP[u uD uv]]; last exact: mem_clns uv.
    exact/subsetP/set_sub_clns.
Qed.

Proposition dominatingP : reflect
  (forall v : G, v \notin D -> exists2 u : G, u \in D & u -- v) dominating.
Proof. rewrite dominatingEedge; apply/dominatingP_alt. Qed.

Lemma dominatingPn :
  reflect (exists2 v : G, v \notin D & {in D, forall u, ~~ u -- v}) (~~ dominating).
Proof.
  rewrite dominatingEedge negb_forall_in.
  apply: exists_inPP => x; exact: exists_inPn.
Qed.

End Dominating_Set.

(* V(G) is dominating *)
Lemma domT : dominating [set: G].
Proof. apply/forallP => x. exact: (subsetP (set_sub_clns _)). Qed.

(* if D is dominating, any supraset of D is also dominating *)
Lemma dom_superhereditary : superhereditary dominating.
Proof.
  apply/superhereditaryP => D F /subsetP DsubF /dominatingP Ddom.
  apply/dominatingP => v vnotinF.
  have/Ddom [w winD wv]: v \notin D by apply: contraNN vnotinF; exact: DsubF.
  exists w => //; exact: DsubF.
Qed.

(**********************************************************************************)
Section Irredundant_Set.

Variable D : {set G}.
Implicit Types x y v w : G.

Definition private_set (v : G) := N[v] :\: NS[D :\ v].

Lemma privateP v w :
  reflect (v -*- w /\ {in D, forall u, u -*- w -> u = v}) (w \in private_set v).
Proof.
  apply: (iffP setDP); rewrite !in_cln => -[v_dom_w H]; split => //.
  - move => u inD u_dom_w; apply: contraNeq H => uDv.
    apply/bigcupP; exists u; by [exact/setD1P|rewrite in_cln].
  - apply/negP => /bigcupP [u /setD1P [uDv /H]]. rewrite in_cln => X {}/X.
    exact/eqP.
Qed.

Definition irredundant : bool := [forall v : G, (v \in D) ==> (private_set v != set0)].

Proposition irredundantP: reflect {in D, forall v, (private_set v != set0)} irredundant.
Proof.
  rewrite /irredundant ; apply: (iffP forallP).
  - move=> H1 v vinD. by move/implyP: (H1 v) => /(_ vinD).
  - move=> H2 v. apply/implyP=> vinD. by move: (H2 v vinD).
Qed.

Proposition irredundantPn : reflect (exists2 v, v \in D & private_set v == set0) (~~ irredundant).
Proof.
  rewrite /irredundant ; apply: (iffP forall_inPn) ; last first.
  - case => x xinD H1. by exists x ; rewrite ?xinD ?H1.
  - case => x xinD H2; rewrite negbK in H2. by exists x.
Qed.

End Irredundant_Set.

(* the empty set is irredundant *)
Lemma irr0 : irredundant set0.
Proof. apply/irredundantP => v ; by rewrite in_set0. Qed.

(* if D is irredundant, any subset of D is also irredundant *)
Lemma irr_hereditary : hereditary irredundant.
Proof.
  apply/hereditaryP.
  move=> D F FsubD /irredundantP Dirr.
  apply/irredundantP => v vinF.
  move: (subsetP FsubD v vinF) => vinD.
  move: (Dirr v vinD).
  case/set0Pn => x /privateP [vdomx H1]. apply/set0Pn; exists x.
  apply/privateP ; split=> //.
  move=> u uinF udomx. move: (subsetP FsubD u uinF) => uinD.
  exact: (H1 u uinD udomx).
Qed.

(** ** Fundamental facts about Domination Theory *)
Section Relations_between_stable_dominating_irredundant_sets.

Variable D : {set G}.

(* A stable set D is maximal iff D is stable and dominating
 * See Prop. 3.5 of Fundamentals of Domination *)
Theorem maximal_st_iff_st_dom : maxset stable D <-> (stable D /\ dominating D).
Proof.
  rewrite -(rwP (maximal_indsysP _ st_hereditary)).
  rewrite /iff ; split ; last first.
  - move=> [ stableD /dominatingP dominatingD].
    split => // v vnotinD.
    have [w winD adjwv] := dominatingD _ vnotinD.
    apply/stablePn; exists v; exists w.
    by rewrite !inE eqxx winD sgP adjwv orbT.
  - move => [stableD H1]; split=> //.
    apply/dominatingP => x xnotinD.
    have/stablePn [w [z [winDcupx zinDcupx adjwz]]] := H1 x xnotinD.
    case: (eqVneq z x) => [zisx|zisnotx].
    + by subst z; exists w => //; rewrite !inE (sg_edgeNeq adjwz) in winDcupx.
    + have zinD : z \in D by rewrite !inE (negbTE zisnotx) /= in zinDcupx.
      exists z => //.
      move: winDcupx; rewrite in_setU in_set1.
      case/predU1P => [|winD]; first by move<- ; rewrite sg_sym adjwz.
      have := stableP D stableD w z winD zinD.
      apply: contraR. by rewrite adjwz.
Qed.

(* A maximal stable set is minimal dominating
 * See Prop. 3.6 of Fundamentals of Domination *)
Theorem maximal_st_is_minimal_dom : maxset stable D -> minset dominating D.
Proof.
  rewrite maximal_st_iff_st_dom => -[/stableP stableD dominatingD].
  apply/(minimal_indsysP _ dom_superhereditary); split=> // x xinD.
  apply/dominatingPn ; exists x ; first by rewrite in_setD1 eqxx andFb.
  move=> y /setD1P [_ yinD]. exact: stableD.
Qed.

(* A dominating set D is minimal iff D is dominating and irredundant
 * See Prop. 3.8 of Fundamentals of Domination *)
Theorem minimal_dom_iff_dom_irr : minset dominating D <-> (dominating D /\ irredundant D).
Proof.
  rewrite -(rwP (minimal_indsysP _ dom_superhereditary)); split ; last first.
  - move=> [dominatingD /irredundantP irredundantD]; split => // v vinD.
    have/set0Pn [w /privateP [vdomw H1]] := irredundantD v vinD.
    apply/dominatingPn; exists w.
    + rewrite in_setD1 negb_and negbK orbC.
      case: (boolP (w \in D)) => //= /H1 -> //. exact: dominates_refl.
    + move=> u /setD1P [uneqv uinD].
      apply: contra_neqN uneqv => uv.
      by apply: H1 => //; rewrite /dominates uv orbT.
  - move => [dominatingD H2] ; split=> //.
    apply/irredundantP => v vinD.
    have/dominatingPn[w wnotinDminusv H3] := H2 v vinD.
    apply/set0Pn; exists w; apply/privateP ; split ; last first.
    + move=> u uinD udomw.
      apply: contraTeq udomw => uneqv.
      have uinDminusv : u \in D :\ v by rewrite in_setD1 uneqv uinD.
      rewrite /dominates negb_or (H3 u uinDminusv) andbT.
      by apply: contraNneq wnotinDminusv => <-.
    + rewrite /dominates ; case: (boolP (v == w)) => //= vneqw.
      move: wnotinDminusv ; rewrite in_setD1 eq_sym vneqw andTb => wnotinD.
      have [u uinD] := dominatingP _ dominatingD w wnotinD.
      case: (boolP (u == v)) => [|uneqv] ; first by move/eqP->.
      have uinDminusv : u \in D :\ v by rewrite in_setD1 uneqv uinD.
      by rewrite (negbTE (H3 u uinDminusv)).
Qed.

(* A minimal dominating set is maximal irredundant
 * See Prop. 3.9 of Fundamentals of Domination *)
Theorem minimal_dom_is_maximal_irr : minset dominating D -> maxset irredundant D.
Proof.
  rewrite minimal_dom_iff_dom_irr -(rwP (maximal_indsysP _ irr_hereditary)).
  move=> [dominatingD irredundantD]; split=> // v vnotinD.
  apply/irredundantPn; exists v; first by rewrite in_setU1 eqxx.
  apply: contraNT vnotinD => /set0Pn [x /privateP [vdomx xpriv]].
  have/bigcupP [u uinD udomx] := forallP dominatingD x.
  by rewrite -[v](xpriv u) -?in_cln // inE uinD orbT.
Qed.

End Relations_between_stable_dominating_irredundant_sets.

(**********************************************************************************)
Section Existence_of_stable_dominating_irredundant_sets.

(* Definitions of "maximal stable", "minimal dominating" and "maximal irredundant" sets *)

Definition max_st := maxset stable.

Definition min_dom := minset dominating.

Definition max_irr := maxset irredundant.

(* Inhabitants that are "maximal stable", "minimal dominating" and "maximal irredundant"
 * Recall that ex_minimal and ex_maximal requires a proof of an inhabitant of "stable",
 * "dominating" and "irredudant" to be able to generate the maximal/minimal set. *)

Definition inhb_max_st := s2val (maxset_exists stable0).

Definition inhb_min_dom := s2val (minset_exists domT).

Definition inhb_max_irr := s2val (maxset_exists irr0).

Lemma inhb_max_st_is_maximal_stable : max_st inhb_max_st.
Proof. exact: (s2valP (maxset_exists stable0)). Qed.

Lemma inhb_min_dom_is_minimal_dominating : min_dom inhb_min_dom.
Proof. exact: (s2valP (minset_exists domT)). Qed.

Lemma inhb_max_irr_is_maximal_irredundant : max_irr inhb_max_irr.
Proof. exact: (s2valP (maxset_exists irr0)). Qed.

End Existence_of_stable_dominating_irredundant_sets.

(**********************************************************************************)
Section Weighted_domination_parameters.

Variable weight : G -> nat.
Hypothesis positive_weights : forall v : G, weight v > 0.

Let W := weight_set weight.

(* Definition of weighted parameters. *)

Definition ir_w : nat := W (arg_min inhb_max_irr max_irr W).

Fact ir_min D : max_irr D -> ir_w <= W D.
Proof.
  rewrite /ir_w.
  by case: (arg_minnP W inhb_max_irr_is_maximal_irredundant) => A _ ; apply.
Qed.

Fact ir_witness : exists2 D, max_irr D & W D = ir_w.
Proof.
  rewrite /ir_w.
  case: (arg_minnP W inhb_max_irr_is_maximal_irredundant) => D.
  by exists D.
Qed.

Fact ir_minset D : max_irr D -> W D = ir_w -> minset max_irr D.
Proof.
  move => max_irrD irD; apply: minweight_minset => // A.
  rewrite -/W irD; exact: ir_min.
Qed.

Definition gamma_w : nat := W (arg_min setT dominating W).

Fact gamma_min D : dominating D -> gamma_w <= W D.
Proof. rewrite /gamma_w. case: (arg_minnP W domT) => A _ ; apply. Qed.

Fact gamma_witness : exists2 D, dominating D & W D = gamma_w.
Proof.
  rewrite /gamma_w.
  case: (arg_minnP W domT) => D.
  by exists D.
Qed.

Fact gamma_minset D : dominating D -> W D = gamma_w -> minset dominating D.
Proof.
  move => domD gammaD; apply: minweight_minset => // A.
  rewrite -/W gammaD; exact: gamma_min.
Qed.

Definition ii_w : nat := W (arg_min inhb_max_st max_st W).

Fact ii_min S : max_st S -> ii_w <= W S.
Proof.
  rewrite /ii_w.
  by case: (arg_minnP W inhb_max_st_is_maximal_stable) => A _ ; apply.
Qed.

Fact ii_witness : exists2 S, max_st S & W S = ii_w.
Proof.
  rewrite /ii_w.
  case: (arg_minnP W inhb_max_st_is_maximal_stable) => S.
  by exists S.
Qed.

Fact ii_minset D : max_st D -> W D = ii_w -> minset max_st D.
Proof.
  move => max_stD iiD; apply: minweight_minset => // A.
  rewrite -/W iiD; exact: ii_min.
Qed.

Definition alpha_w : nat := W (arg_max set0 stable W).

Fact alpha_max S : stable S -> W S <= alpha_w.
Proof. by move: S; rewrite /alpha_w; case: (arg_maxnP W stable0). Qed.

Fact alpha_witness : exists2 S, stable S & W S = alpha_w.
Proof. by rewrite /alpha_w; case: (arg_maxnP W stable0) => A; exists A. Qed.

Fact alpha_maxset S : stable S -> W S = alpha_w -> maxset stable S.
Proof.
  move => stS alphaS; apply: maxweight_maxset => // A.
  rewrite -/W alphaS; exact: alpha_max.
Qed.

Definition Gamma_w : nat := W (arg_max inhb_min_dom min_dom W).

Fact Gamma_max D : min_dom D -> W D <= Gamma_w.
Proof.
  move: D ; rewrite /Gamma_w.
  by case: (arg_maxnP W inhb_min_dom_is_minimal_dominating).
Qed.

Fact Gamma_witness : exists2 D, min_dom D & W D = Gamma_w.
Proof.
  rewrite /Gamma_w.
  case: (arg_maxnP W inhb_min_dom_is_minimal_dominating) => D.
  by exists D.
Qed.

Fact Gamma_maxset D : min_dom D -> W D = Gamma_w -> maxset min_dom D.
Proof.
  move => min_domD GammaD; apply: maxweight_maxset => // A.
  rewrite -/W GammaD; exact: Gamma_max.
Qed.

Definition IR_w : nat := W (arg_max set0 irredundant W).

Fact IR_max D : irredundant D -> W D <= IR_w.
Proof. by move: D; rewrite /IR_w; case: (arg_maxnP W irr0). Qed.

Fact IR_witness : exists2 D, irredundant D & W D = IR_w.
Proof. by rewrite /IR_w; case: (arg_maxnP W irr0) => D; exists D. Qed.

Fact IR_maxset D : irredundant D -> W D = IR_w -> maxset irredundant D.
Proof.
  move => irrD IRD; apply: maxweight_maxset => // A.
  rewrite -/W IRD; exact: IR_max.
Qed.

(** ** Weighted version of the Cockayne-Hedetniemi domination chain. *)

Proposition ir_w_leq_gamma_w : ir_w <= gamma_w.
Proof.
  rewrite /gamma_w.
  have [D domD minWD] := arg_minnP W domT.
  have min_domD := minweight_minset positive_weights domD minWD.
  have max_irrD := minimal_dom_is_maximal_irr min_domD.
  exact: ir_min.
Qed.

Proposition gamma_w_leq_ii_w : gamma_w <= ii_w.
Proof.
  rewrite /ii_w.
  have [S max_stS _] := arg_minnP W inhb_max_st_is_maximal_stable.
  have domS := minsetp (maximal_st_is_minimal_dom max_stS).
  exact: gamma_min.
Qed.

Proposition ii_w_leq_alpha_w : ii_w <= alpha_w.
Proof.
  rewrite /alpha_w.
  have [S stS maxWS] := arg_maxnP W stable0.
  have max_stS := maxweight_maxset positive_weights stS maxWS.
  exact: ii_min.
Qed.

Proposition alpha_w_leq_Gamma_w : alpha_w <= Gamma_w.
Proof.
  rewrite /alpha_w.
  have [S stS maxWS] := arg_maxnP W stable0.
  have max_stS := maxweight_maxset positive_weights stS maxWS.
  have min_domS := maximal_st_is_minimal_dom max_stS.
  exact: Gamma_max.
Qed.

Proposition Gamma_w_leq_IR_w : Gamma_w <= IR_w.
Proof.
  rewrite /Gamma_w.
  have [D min_domD _] := arg_maxnP W inhb_min_dom_is_minimal_dominating.
  have irrD := maxsetp (minimal_dom_is_maximal_irr min_domD).
  exact: IR_max.
Qed.

Theorem Cockayne_Hedetniemi_chain_w:
  sorted leq [:: ir_w; gamma_w; ii_w; alpha_w; Gamma_w; IR_w].
Proof.
rewrite /sorted /= ir_w_leq_gamma_w gamma_w_leq_ii_w ii_w_leq_alpha_w.
by rewrite alpha_w_leq_Gamma_w Gamma_w_leq_IR_w.
Qed.

(* Usage: [apply: (Cockayne_Hedetniemi_w i j)] with i,j concrete
indices into the above list [i < j] *)

Definition Cockayne_Hedetniemi_w_leq :=
  @sorted_leq_nth nat leq leq_trans leqnn 0 _ Cockayne_Hedetniemi_chain_w.

Notation Cockayne_Hedetniemi_w i j :=
  (@Cockayne_Hedetniemi_w_leq i j erefl erefl erefl).

(** Example *)
Let gamma_w_leq_Gamma_w: gamma_w <= Gamma_w.
Proof. exact: (Cockayne_Hedetniemi_w 1 4). Qed.

End Weighted_domination_parameters.

(* "argument" policy:
   every weighted parameter requires a graph, the weight vector and a proof that their
   components are positive *)
Arguments ir_w : clear implicits.
Arguments gamma_w : clear implicits.
Arguments ii_w : clear implicits.
Arguments alpha_w : clear implicits.
Arguments Gamma_w : clear implicits.
Arguments IR_w : clear implicits.

(** ** Classic (unweighted) parameters (use cardinality instead of weight)        *)

Section Classic_domination_parameters.

Definition ones : (G -> nat) := (fun _ => 1).

Let W1 : ({set G} -> nat) := (fun A => #|A|).

Lemma cardwset1 (A : {set G}) : #|A| = weight_set ones A.
Proof. by rewrite /weight_set sum1dep_card cardsE. Qed.

Local Notation eq_arg_min := (eq_arg_min _ (frefl _) cardwset1).
Local Notation eq_arg_max := (eq_arg_max _ (frefl _) cardwset1).

(** Definition of unweighted parameters and its conversion to weighted ones. *)

Definition ir : nat := #|arg_min inhb_max_irr max_irr W1|.

Fact eq_ir_ir1 : ir = ir_w ones.
Proof. by rewrite /ir /ir_w -cardwset1 eq_arg_min. Qed.

Definition gamma : nat := #|arg_min setT dominating W1|.

Fact eq_gamma_gamma1 : gamma = gamma_w ones.
Proof. by rewrite /gamma /gamma_w -cardwset1 eq_arg_min. Qed.

Definition ii : nat := #|arg_min inhb_max_st max_st W1|.

Fact eq_ii_ii1 : ii = ii_w ones.
Proof. by rewrite /ii /ii_w -cardwset1 eq_arg_min. Qed.

Definition alpha : nat := #|arg_max set0 stable W1|.

Fact eq_alpha_alpha1 : alpha = alpha_w ones.
Proof. by rewrite /alpha /alpha_w -cardwset1 eq_arg_max. Qed.

Definition Gamma : nat := #|arg_max inhb_min_dom min_dom W1|.

Fact eq_Gamma_Gamma1 : Gamma = Gamma_w ones.
Proof. by rewrite /Gamma /Gamma_w -cardwset1 eq_arg_max. Qed.

Definition IR : nat := #|arg_max set0 irredundant W1|.

Fact eq_IR_IR1 : IR = IR_w ones.
Proof. by rewrite /IR /IR_w -cardwset1 eq_arg_max. Qed.

(** ** Classic Cockayne-Hedetniemi domination chain. *)

Corollary ir_leq_gamma : ir <= gamma.
Proof. by rewrite eq_ir_ir1 eq_gamma_gamma1 ir_w_leq_gamma_w. Qed.

Corollary gamma_leq_ii : gamma <= ii.
Proof. by rewrite eq_gamma_gamma1 eq_ii_ii1 gamma_w_leq_ii_w. Qed.

Corollary ii_leq_alpha : ii <= alpha.
Proof. by rewrite eq_ii_ii1 eq_alpha_alpha1 ii_w_leq_alpha_w. Qed.

Corollary alpha_leq_Gamma : alpha <= Gamma.
Proof. by rewrite eq_alpha_alpha1 eq_Gamma_Gamma1 alpha_w_leq_Gamma_w. Qed.

Corollary Gamma_leq_IR : Gamma <= IR.
Proof. by rewrite eq_Gamma_Gamma1 eq_IR_IR1 Gamma_w_leq_IR_w. Qed.

Corollary Cockayne_Hedetniemi_chain:
  sorted leq [:: ir; gamma; ii; alpha; Gamma; IR].
Proof.
rewrite /sorted /= ir_leq_gamma gamma_leq_ii ii_leq_alpha.
by rewrite alpha_leq_Gamma Gamma_leq_IR.
Qed.

Definition Cockayne_Hedetniemi_leq :=
  @sorted_leq_nth nat leq leq_trans leqnn 0 _ Cockayne_Hedetniemi_chain.

Notation Cockayne_Hedetniemi i j :=
  (@Cockayne_Hedetniemi_leq i j erefl erefl erefl).

(** Example *)
Let gamma_leq_Gamma: gamma <= Gamma.
Proof. exact: (Cockayne_Hedetniemi 1 4). Qed.

End Classic_domination_parameters.

End Domination_Theory.

Arguments ir_w : clear implicits.
Arguments gamma_w : clear implicits.
Arguments ii_w : clear implicits.
Arguments alpha_w : clear implicits.
Arguments Gamma_w : clear implicits.
Arguments IR_w : clear implicits.
Arguments ir : clear implicits.
Arguments gamma : clear implicits.
Arguments ii : clear implicits.
Arguments alpha : clear implicits.
Arguments Gamma : clear implicits.
Arguments IR : clear implicits.


Require Import Coq.ZArith.ZArith Coq.micromega.Lia.
Require Import Crypto.Util.ZUtil.Hints.Core.
Require Import Crypto.Util.ZUtil.Hints.ZArith.
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
Local Open Scope Z_scope.

Module Z.
  Lemma mod_mod_small a n m
        (Hnm : (m mod n = 0)%Z)
        (Hnm_le : (0 < n <= m)%Z)
        (H : (a mod m < n)%Z)
    : ((a mod n) mod m = a mod m)%Z.
  Proof.
    assert ((a mod n) < m)%Z
      by (eapply Z.lt_le_trans; [ apply Z.mod_pos_bound | ]; omega).
    rewrite (Z.mod_small _ m) by auto with zarith.
    apply Z.mod_divide in Hnm; [ | omega ].
    destruct Hnm as [x ?]; subst.
    repeat match goal with
           | [ H : context[(_ mod _)%Z] |- _ ]
             => revert H
           end.
    Z.div_mod_to_quot_rem.
    lazymatch goal with
    | [ H : a = (?x * ?n * ?q) + _, H' : a = (?n * ?q') + _ |- _ ]
      => assert (q' = x * q) by nia; subst q'; nia
    end.
  Qed.

  (** [rewrite_mod_small] is a better version of [rewrite Z.mod_small
      by rewrite_mod_small_solver]; it backtracks across occurences
      that the solver fails to solve the side-conditions on. *)
  Ltac rewrite_mod_small_solver :=
    zutil_arith_more_inequalities.
  Ltac rewrite_mod_small :=
    repeat match goal with
           | [ |- context[?x mod ?y] ]
             => rewrite (Z.mod_small x y) by rewrite_mod_small_solver
           end.
  Ltac rewrite_mod_mod_small :=
    repeat match goal with
           | [ |- context[(?a mod ?n) mod ?m] ]
             => rewrite (mod_mod_small a n m) by rewrite_mod_small_solver
           end.
  Ltac rewrite_mod_small_more :=
    repeat (rewrite_mod_small || rewrite_mod_mod_small).
End Z.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (y : natural) (z : natural) (lf2 : natural) : natural :=
  plus (mult z (Succ y)) lf2.