(** * Induction: Proof by Induction *)

(** First, we import all of our definitions from the previous
    chapter. *)

Require Export 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".

     - From the command line:

         Run [coqc Basics.v]

    *)

(* ################################################################# *)
(** * 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.  The fact that it is also a neutral element on the
    _right_... *)

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

(** ... cannot be proved 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.  We could use [destruct n'] to
   get one step further, but, since [n] can be arbitrarily large, if we
   try to keep on like this we'll never be done. *)

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.

(** 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 but the order is backwards: 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: first showing [P(O)] and then showing [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.  In the first branch, [n] is replaced by [0] and
    the goal becomes [0 + 0 = 0], which follows by simplification.  In
    the second, [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'] -- notice that this name is
    explicitly chosen in the [as...] clause of the call to [induction]
    rather than letting Coq choose one arbitrarily). The goal in this
    case becomes [(S n') + 0 = S n'], which simplifies to [S (n' + 0)
    = S n'], 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.
  (* FILL IN HERE *) Admitted.

Theorem plus_n_Sm : forall n m : nat,
  S (n + m) = n + (S m).
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, optional (evenb_S)  *)
(** One inconveninent aspect of our definition of [evenb n] is that it
    may need to perform a 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 a better characterization of [evenb (S n)]: *)

Theorem evenb_S : forall n : nat,
  evenb (S n) = negb (evenb n).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

(** The [assert] tactic is handy in many sorts of situations.  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 a little stupid 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)...
     it seems like plus_comm should do the trick! *)
  rewrite -> plus_comm.
  (* Doesn't work...Coq rewrote the wrong plus! *)
Abort.

(** To get [plus_comm] to apply at the point where we want it to, 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.

(* ################################################################# *)
(** * 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.
  (* FILL IN HERE *) Admitted.

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

Theorem mult_comm : forall m n : nat,
  m * n = n * m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** 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!) *)

Theorem leb_refl : forall n:nat,
  true = leb n n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem zero_nbeq_S : forall n:nat,
  beq_nat 0 (S n) = false.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem andb_false_r : forall b : bool,
  andb b false = false.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_ble_compat_l : forall n m p : nat,
  leb n m = true -> leb (p + n) (p + m) = true.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem S_nbeq_0 : forall n:nat,
  beq_nat (S n) 0 = false.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_1_l : forall n:nat, 1 * n = n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem all3_spec : forall b c : bool,
    orb
      (andb b c)
      (orb (negb b)
               (negb c))
  = true.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_plus_distr_r : forall n m p : nat,
  (n + m) * p = (n * p) + (m * p).
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_assoc : forall n m p : nat,
  n * (m * p) = (n * m) * p.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

    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, please copy the
    definitions from your solution to the [binary] exercise here so
    that this file can be graded on its own.  If you find yourself
    wanting to change your original definitions to make the property
    easier to prove, feel free to do so! *)

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

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

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

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

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

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

(** The question of what constitutes a proof of a mathematical
    claim 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.  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: (* FILL IN HERE *)
*)
(** [] *)

(** **** 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: (* FILL IN HERE *)
[] *)

(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)


(** 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) : natural := plus (Succ Zero) y.


(*Section Univ.
*)

Variable U : Type.

Definition set := U -> Prop.
Definition element (x : U) (S : set) := S x.
Definition subset (A B : set) := forall x : U, element x A -> element x B.

Definition transitive (T : Type) (R : T -> T -> Prop) := forall x y z : T, R x y -> R y z -> R x z.

Lemma subset_transitive : transitive set subset.


From HoTT Require Import HFiber Algebra.Groups Algebra.AbGroups.

(* Given a group [G], we define the centralizer of an element [g : G] as a subgroup and use this to show that the cyclic subgroup generated by [g] is abelian. *)

Open Scope mc_mult_scope.

(* First we show that the collection of elements that commute with a fixed element [g] is a subgroup. *)

Definition centralizer {G : Group} (g : G)
  := fun h => g * h = h * g.

Definition centralizer_unit {G : Group} (g : G) : centralizer g mon_unit.
Proof.
  exact (grp_unit_r _ @ (grp_unit_l _)^).
Defined.

Definition centralizer_sgop {G : Group} (g h k : G)
           (p : centralizer g h) (q : centralizer g k)
  : centralizer g (h * k).
Proof.
  refine (grp_assoc _ _ _ @ _).
  refine (ap (fun x => x * k) p @ _).
  refine ((grp_assoc _ _ _)^ @ _).
  refine (ap (fun x => h * x) q @ _).
  apply grp_assoc.
Defined.

Definition centralizer_inverse {G : Group} (g h : G)
           (p : centralizer g h)
  : centralizer g (-h).
Proof.
  unfold centralizer in *.
  symmetry.
  refine ((grp_unit_r _)^ @ _ @ grp_unit_l _).
  refine (ap (fun x => (-h * g * x)) (grp_inv_r h)^ @ _ @ ap (fun x => x * (g * -h)) (grp_inv_l h)).
  refine (grp_assoc _ _ _ @ _ @ (grp_assoc _ _ _)^).
  refine (ap (fun x => x * (-h)) _).
  refine ((grp_assoc _ _ _)^ @ _ @ grp_assoc _ _ _).
  exact (ap (fun x => (-h) * x) p).
Defined.

Global Instance issubgroup_centralizer {G : Group} (g : G)
  : IsSubgroup (centralizer g).
Proof.
  srapply Build_IsSubgroup.
  - apply centralizer_unit.
  - apply centralizer_sgop.
  - apply centralizer_inverse.
Defined.

Definition centralizer_subgroup {G : Group} (g : G)
  := Build_Subgroup G (centralizer g) _.

(* Now we define cyclic subgroups.  We allow any map [Unit -> G] in this definition, because in applications (such as [Z_commutative]) we have no control over the map. *)
Definition cyclic_subgroup_from_unit {G : Group} (gen : Unit -> G) := subgroup_generated (hfiber gen).

(* When we have a particular element [g] of [G], we could choose the predicate to be [fun h => h = g], but to fit into the above definition, we use [unit_name g], which gives the predicate [fun h => hfiber (unit_name g) h]. *)
Definition cyclic_subgroup {G : Group} (g : G) := cyclic_subgroup_from_unit (unit_name g).

(* Any cyclic subgroup is commutative. *)
Global Instance commutative_cyclic_subgroup {G : Group} (gen : Unit -> G)
  : Commutative (@group_sgop (cyclic_subgroup_from_unit gen)).
Proof.
  intros h k.
  destruct h as [h H]; cbn in H.
  destruct k as [k K]; cbn in K.
  strip_truncations.
  (* It's enough to check equality after including into G: *)
  apply (equiv_ap_isembedding (subgroup_incl _) _ _)^-1.  cbn.
  induction H as [h [[] p]| |h1 h2 H1 H2 IHH1 IHH2].
  - (* The case when h = g: *)
    induction p.
    induction K as [k [[] q]| |k1 k2 K1 K2 IHK1 IHK2].
    + (* The case when k = g: *)
      induction q.
      reflexivity.
    + (* The case when k = mon_unit: *)
      apply centralizer_unit.
    + (* The case when k = k1 (-k2): *)
      srapply (issubgroup_in_op_inv (H:=centralizer (gen tt))); assumption.
  - (* The case when h = mon_unit: *)
    symmetry; apply centralizer_unit.
  - (* The case when h = h1 (-h2): *)
    symmetry.
    srapply (issubgroup_in_op_inv (H:=centralizer k)); unfold centralizer; symmetry; assumption.
Defined.

Definition abgroup_cyclic_subgroup {G : Group} (g : G) : AbGroup
  := Build_AbGroup (cyclic_subgroup g) _.


Require Import Nat Arith Bool.

Inductive Nat : Type := succ : Nat -> Nat |  zero : Nat.

Scheme Equality for Nat.

Inductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.

Inductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.

Inductive Pair : Type := mkpair : Nat -> Nat -> Pair
with ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.

Fixpoint mem (mem_arg0 : Nat) (mem_arg1 : Lst) : bool
           := match mem_arg0, mem_arg1 with
              | x, nil => false
              | x, cons y z => orb (Nat_beq x y) (mem x z)
              end.

Definition lst_mem := mem.

Fixpoint lst_union (lst_union_arg0 : Lst) (lst_union_arg1 : Lst) : Lst
           := match lst_union_arg0, lst_union_arg1 with
              | nil, x => x
              | cons n x, y => if lst_mem n y then lst_union x y else cons n (lst_union x y)
              end.

Theorem theorem0 : forall (x : Nat) (y : Lst) (z : Lst), eq (lst_mem x y) true -> eq (lst_mem x (lst_union z y)) true.
Proof.
  intros.
  induction z.
  - assumption.
  - simpl. destruct (lst_mem n y).
    + assumption.
    + simpl. rewrite IHz. apply orb_true_r.
Qed.


From Tealeaves.Classes Require Import
  Monoid Monad Applicative.
From Tealeaves Require Export
  Data.Sets.

Import Product.Notations.
Import Applicative.Notations.
Import Data.Sets.Notations.

#[local] Generalizable Variables A B.

(** * The <<set>> monad *)
(******************************************************************************)

(** ** Functor instance *)
(******************************************************************************)

(** [fmap f s] is the image of a set [s] under a morphism [f] *)
#[export] Instance Fmap_set : Fmap set :=
  fun A B (f : A -> B) (x : A -> Prop) (b : B) => exists a : A, x a /\ f a = b.

(** *** Rewriting lemmas for [fmap] *)
(******************************************************************************)
Definition fmap_set_nil `{f : A -> B} :
  fmap set f ∅ = ∅ := ltac:(solve_basic_set).

Definition fmap_set_add `{f : A -> B} {x y} :
  fmap set f (x ∪ y) = fmap set f x ∪ fmap set f y
  := ltac:(solve_basic_set).

#[export] Hint Rewrite @fmap_set_nil @fmap_set_add : tea_set.

(** *** Functor laws *)
(******************************************************************************)
Definition fun_fmap_id_set {A} : fmap set id = @id (set A) :=
  ltac:(solve_basic_set).

Definition fun_fmap_fmap_set {A B C} : forall (f : A -> B) (g : B -> C),
    fmap set g ∘ fmap set f = fmap set (g ∘ f)
    := ltac:(solve_basic_set).

#[export] Instance Functor_set : Functor set :=
  ltac:(constructor; solve_basic_set).

(** ** [fmap] is a monoid homomorphism *)
(******************************************************************************)
#[export, program] Instance Monmor_set_fmap `(f : A -> B) :
  Monoid_Morphism (fmap set f) :=
  {| monmor_unit := @fmap_set_nil A B f;
    monmor_op := @fmap_set_add A B f;
  |}.

(** ** Monad operations *)
(******************************************************************************)
#[export] Instance Return_set : Return set := fun A a b => a = b.

#[export] Instance Join_set : Join set :=
  fun A (x : (A -> Prop) -> Prop) => fun a => exists (y : A -> Prop) , x y /\ y a.

#[local] Notation "{{ x }}" := (ret set x).

Theorem set_ret_injective : forall A (a b : A),
    {{ a }} = {{ b }} -> a = b.
Proof.
  intros. assert (lemma : forall x, {{ a }} x = {{ b }} x).
  intros. now rewrite H. specialize (lemma a).
  cbv in lemma. symmetry. now rewrite <- lemma.
Qed.

(** ** Rewriting laws for [join] and [ret] *)
(******************************************************************************)
Definition set_in_ret : forall A (a b : A),
    (ret set a) b = (a = b)
  := ltac:(solve_basic_set).

Lemma join_set_nil : forall A,
    join (A:=A) set ∅ = ∅.
Proof.
  solve_basic_set.
Qed.

Lemma join_set_one : forall A (x : set A),
    join set {{ x }} = x.
Proof.
  solve_basic_set.
Qed.

Lemma join_set_add : forall A (x y : set (set A)),
    join set (x ∪ y) = join set x ∪ join set y.
Proof.
  solve_basic_set.
Qed.

Lemma fmap_set_one `{f : A -> B} {a : A} :
  fmap set f {{ a }} = {{ f a }}.
Proof.
  solve_basic_set.
Qed.

#[export] Hint Rewrite @set_in_ret @join_set_nil @join_set_one @join_set_add
     @fmap_set_add @fmap_set_one : tea_set.

(** ** Monad laws *)
(******************************************************************************)
Theorem join_ret {A} :
  join set ∘ ret set = @id (A -> Prop).
Proof.
  solve_basic_set.
Qed.

Theorem join_fmap_ret {A} :
  join set ∘ fmap set (ret set) = @id (A -> Prop).
Proof.
  unfold transparent tcs; unfold_set. unfold compose. setext.
  - firstorder (do 2 subst; auto).
  - firstorder eauto.
Qed.

Theorem join_join {A} :
  join set ∘ join set =
  join set ∘ fmap set (join set (A:=A)).
Proof.
  unfold transparent tcs; unfold_set. unfold compose. setext.
  - intros. preprocess. repeat eexists; eauto.
  - intros. preprocess. repeat eexists; eauto.
Qed.

#[export] Instance Natural_ret : Natural (@ret set _) :=
  ltac:(constructor; try typeclasses eauto;
       unfold compose; solve_basic_set).

#[export] Instance Natural_join : Natural (@join set _).
Proof.
  ltac:(constructor; try typeclasses eauto).
  intros. unfold compose. ext SS. ext b.
  propext.
  - unfold transparent tcs.
    intros [a [a_in_join a_to_b]].
    destruct a_in_join as [S [S1 S2]].
    exists (fmap set f S). split.
    + now (exists S).
    + unfold transparent tcs. now (exists a).
  - unfold transparent tcs.
    intros [Sb [H1 H2]].
    destruct H1 as [S [SS1 SS2]].
    rewrite <- SS2 in H2. destruct H2 as [a [a1 a2]].
    subst. exists a. split; auto. now (exists S).
Qed.

#[export] Instance Monad_set : Monad set :=
  {| mon_join_ret := @join_ret;
     mon_join_fmap_ret := @join_fmap_ret;
     mon_join_join := @join_join;
  |}.

(** * Set as an applicative functor *)
(******************************************************************************)
(*
TODO: This isn't really necessary because it is inferred from the monad instance.
 *)
Section set_applicative.

  Instance Pure_set : Pure set := @eq.

  #[export] Instance Mult_set : Mult set :=
    fun (A B : Type) (p : set A * set B) (v : A * B) =>
      (fst p) (fst v) /\ (snd p) (snd v).

  Theorem app_mult_pure_set : forall (A B : Type) (a : A) (b : B),
      mult set (pure set a, pure set b) = pure set (a, b).
  Proof.
    intros. unfold transparent tcs.
    ext [a1 b1]. cbn. propext; now rewrite pair_equal_spec.
  Qed.

  Theorem app_pure_natural_set : forall (A B : Type) (f : A -> B) (x : A),
      fmap set f (pure set x) = pure set (f x).
  Proof.
    intros. unfold transparent tcs. ext b.
    propext; firstorder (now subst).
  Qed.

  Theorem app_mult_natural_set : forall (A B C D: Type) (f : A -> C) (g : B -> D) (x : set A) (y : set B),
      mult set  (fmap set f x, fmap set g y) = fmap set (map_tensor f g) (mult set (x, y)).
  Proof.
    intros. unfold transparent tcs. ext [c d].
    cbn. propext.
    - intros [[a ?] [b ?]].
      exists (a, b). firstorder (now subst).
    - intros [[a b] rest]. cbn in *.
      rewrite pair_equal_spec in rest.
      split. exists a; tauto. exists b; tauto.
  Qed.

  Theorem app_assoc_set : forall (A B C : Type) (x : set A) (y : set B) (z : set C),
      fmap set α (x ⊗ y ⊗ z) = x ⊗ (y ⊗ z).
  Proof.
    intros. ext [a [b c]]. unfold transparent tcs.
    cbn. propext.
    - intros [[[a1 b1] c1]]. cbn in *.
      now preprocess.
    - intros. now exists (a, b, c).
  Qed.

  Theorem app_unital_l_set : forall (A : Type) (x : set A),
      fmap set left_unitor (pure set tt ⊗ x) = x.
  Proof.
    intros. ext a. unfold transparent tcs. cbn. propext.
    + intros [[? a1] rest]. cbn in rest. now preprocess.
    + exists (tt, a). easy.
  Qed.

  Theorem app_unital_r_set : forall (A : Type) (x : set A),
      fmap set right_unitor (x ⊗ pure set tt) = x.
  Proof.
    intros. ext a. unfold transparent tcs. cbn. propext.
    + intros [[? a1] rest]. cbn in rest. now preprocess.
    + intros. exists (a, tt). easy.
  Qed.

  Instance Applicative_set : Applicative set :=
    {| app_mult_pure := app_mult_pure_set;
      app_pure_natural := app_pure_natural_set;
      app_mult_natural := app_mult_natural_set;
      app_assoc := app_assoc_set;
      app_unital_l := app_unital_l_set;
      app_unital_r := app_unital_r_set;
    |}.

End set_applicative.

Import Tealeaves.Classes.Kleisli.Monad.
Import Tealeaves.Classes.Monad.ToKleisli.

(** ** [set]/[set] right module *)
(******************************************************************************)
#[export] Instance Bind_set: Bind set set := Monad.ToKleisli.Bind_join set.
#[export] Instance KleisliMonad_list : Kleisli.Monad.Monad set := Kleisli_Monad set.

(** ** Rewriting lemmas for <<bind>> *)
(******************************************************************************)
Lemma bind_set_nil `{f : A -> set B} :
  bind set f ∅ = ∅.
Proof.
  solve_basic_set.
Qed.

Lemma bind_set_one `{f : A -> set B} (a : A) :
  bind set f {{ a }} = f a.
Proof.
  unfold_ops @Bind_set.
  unfold_ops @Bind_join.
  unfold compose; cbn.
  rewrite fmap_set_one.
  rewrite join_set_one.
  reflexivity.
Qed.

Lemma bind_set_add `{f : A -> set B} {x y} :
  bind set f (x ∪ y) = bind set f x ∪ bind set f y.
Proof.
  solve_basic_set.
Qed.

(** Since [bind] is defined tediously by composing <<join>> and
    <<fmap>>, we give a characterization of <<set>>'s <<bind>> that is
    easier to use. N.B. be mindful that this rewriting would have to
    be done ~before~ calling <<unfold transparent tcs>>, otherwise <<bind set>>
    will be unfolded to its definition first. *)
Lemma bind_set_spec : forall `(f : A -> set B) (s : set A) (b : B),
    bind set f s b = exists (a : A), s a /\ f a b.
Proof.
  unfold_ops @Bind_set.
  unfold_ops @Bind_join.
  solve_basic_set.
Qed.

#[export] Hint Rewrite @bind_set_nil @bind_set_one @bind_set_add : tea_set.

(** ** <<bind>> is a monoid homomorphism *)
(******************************************************************************)
#[export] Instance Monmor_bind {A B f} : Monoid_Morphism (bind set f) :=
  {| monmor_unit := @bind_set_nil A B f;
     monmor_op := @bind_set_add A B f;
  |}.


Load LFindLoad.
From lfind Require Import LFind.
Unset Printing Notations.
Set Printing Implicit.

From QuickChick Require Import QuickChick.
Inductive natural : Type := Succ : natural -> natural |  Zero : natural.
Derive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.
Inductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst.

Inductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.

Inductive Pair : Type := mkpair : natural -> natural -> Pair
with Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.

Fixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst
           := match append_arg0, append_arg1 with
              | Nil, x => x
              | Cons x y, z => Cons x (append y z)
              end.

Fixpoint len (len_arg0 : lst) : natural
           := match len_arg0 with
              | Nil => Zero
              | Cons x y => Succ (len y)
              end.

Fixpoint rotate (rotate_arg0 : natural) (rotate_arg1 : lst) : lst
           := match rotate_arg0, rotate_arg1 with
              | Zero, x => x
              | Succ n, Nil => Nil
              | Succ n, Cons y x => rotate n (append x (Cons y Nil))
              end.

Lemma append_nil : forall (x : lst), append x Nil = x.
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. reflexivity.
Qed.

Lemma append_assoc : forall (x y z : lst), append (append x y) z = append x (append y z).
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite IHx. reflexivity.
Qed.

Lemma rotate_len_append : forall (x y : lst), rotate (len x) (append x y) = append y x.
Proof.
   intro.
   induction x.
   - intros. simpl. rewrite append_nil. reflexivity.
   - intros.  simpl. lfind.  rewrite IHx. lfind.  reflexivity.
Admitted.

Theorem rotate_len : forall (x : lst), eq (rotate (len x) x) x.
Proof.
   intros.
   induction x.
   - reflexivity.
   - simpl. rewrite rotate_len_append. reflexivity.
Qed.


From Hammer Require Import Hammer.

Require Export Relations_1.

Definition Complement (U:Type) (R:Relation U) : Relation U :=
fun x y:U => ~ R x y.

Theorem Rsym_imp_notRsym :
forall (U:Type) (R:Relation U),
Symmetric U R -> Symmetric U (Complement U R).
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.Rsym_imp_notRsym".
unfold Symmetric, Complement.
intros U R H' x y H'0; red; intro H'1; apply H'0; auto with sets.
Qed.

Theorem Equiv_from_preorder :
forall (U:Type) (R:Relation U),
Preorder U R -> Equivalence U (fun x y:U => R x y /\ R y x).
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.Equiv_from_preorder".
intros U R H'; elim H'; intros H'0 H'1.
apply Definition_of_equivalence.
red in H'0; auto 10 with sets.
2: red; intros x y h; elim h; intros H'3 H'4; auto 10 with sets.
red in H'1; red; auto 10 with sets.
intros x y z h; elim h; intros H'3 H'4; clear h.
intro h; elim h; intros H'5 H'6; clear h.
split; apply H'1 with y; auto 10 with sets.
Qed.
Hint Resolve Equiv_from_preorder.

Theorem Equiv_from_order :
forall (U:Type) (R:Relation U),
Order U R -> Equivalence U (fun x y:U => R x y /\ R y x).
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.Equiv_from_order".
intros U R H'; elim H'; auto 10 with sets.
Qed.
Hint Resolve Equiv_from_order.

Theorem contains_is_preorder :
forall U:Type, Preorder (Relation U) (contains U).
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.contains_is_preorder".
auto 10 with sets.
Qed.
Hint Resolve contains_is_preorder.

Theorem same_relation_is_equivalence :
forall U:Type, Equivalence (Relation U) (same_relation U).
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.same_relation_is_equivalence".
unfold same_relation at 1; auto 10 with sets.
Qed.
Hint Resolve same_relation_is_equivalence.

Theorem cong_reflexive_same_relation :
forall (U:Type) (R R':Relation U),
same_relation U R R' -> Reflexive U R -> Reflexive U R'.
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.cong_reflexive_same_relation".
unfold same_relation; intuition.
Qed.

Theorem cong_symmetric_same_relation :
forall (U:Type) (R R':Relation U),
same_relation U R R' -> Symmetric U R -> Symmetric U R'.
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.cong_symmetric_same_relation".
compute; intros; elim H; intros; clear H;
apply (H3 y x (H0 x y (H2 x y H1))).

Qed.

Theorem cong_antisymmetric_same_relation :
forall (U:Type) (R R':Relation U),
same_relation U R R' -> Antisymmetric U R -> Antisymmetric U R'.
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.cong_antisymmetric_same_relation".
compute; intros; elim H; intros; clear H;
apply (H0 x y (H3 x y H1) (H3 y x H2)).

Qed.

Theorem cong_transitive_same_relation :
forall (U:Type) (R R':Relation U),
same_relation U R R' -> Transitive U R -> Transitive U R'.
Proof. hammer_hook "Relations_1_facts" "Relations_1_facts.cong_transitive_same_relation".
intros U R R' H' H'0; red.
elim H'.
intros H'1 H'2 x y z H'3 H'4; apply H'2.
apply H'0 with y; auto with sets.
Qed.


(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)
Require Import ssreflect.
Require Import ssrbool.
Require Import funs.
Require Import dataset.
Require Import ssrnat.
Require Import seq.

Set Implicit Arguments.
Unset Strict Implicit.
Import Prenex Implicits.

(* The basic theory of paths over a dataSet; this is essentially a   *)
(* complement to seq.v.                                              *)
(* Paths are non-empty sequences that obey a progression relation.   *)
(* They are passed around in three parts : the head and tail of the  *)
(* sequence, and a (boolean) predicate asserting the progression.    *)
(* This is rarely embarrassing, as the first two are usually         *)
(* implicit parameters inferred from the predicate, and it saves the *)
(* hassle of constantly constructing and destructing a dependent     *)
(* record. We allow duplicates; uniqueness, if desired (as is the    *)
(* case for several geometric constructions), must be asserted       *)
(* separately. We do provide shorthand, but for cycles only, because *)
(* the equational properties of "path" and "uniq" are unfortunately  *)
(* incompatible (esp. wrt "cat").                                    *)
(*    We define similarly cycles, but in this case we allow the      *)
(* empty sequence (which is a non-rooted empty cycle; by contrast,   *)
(* the empty path from x is the one-item sequence containing only x) *)
(*    We define notations for the common cases of function paths,    *)
(* where the progress relation is actually a function. We also       *)
(* define additional traversal/surgery operations, many of which     *)
(* could have been in seq.v, but are here because they only really   *)
(* are useful for sequences considered as paths :                    *)
(*  - directed surgery : splitPl, splitP, splitPr are dependent      *)
(*    predicates whose elimination splits a path x0:p at one of its  *)
(*    elements (say x). The three variants differ as follows:        *)
(*      - splitPl applies when x in in x0:p, generates two paths p1  *)
(*        and p2, along with the equation x = (last x0 p), and       *)
(*        replaces p with (cat p1 p2) in the goal (the patterned     *)
(*        Elim can be used to select occurrences and generate an     *)
(*        equation p = (cat p1 p2).                                  *)
(*      - splitP applies when x is in p, and replaces p with         *)
(*        (cat (add_last p1 x) p2), where x appears explicitly at    *)
(*        the end of the left part.                                  *)
(*      - splitPr similarly replaces p with (cat p1 (Adds x p2)),    *)
(*        where appears explicitly at the right of the split, when x *)
(*        is actually in p.                                          *)
(*    The parts p1 and p2 are computed using index/take/drop. The    *)
(*    splitP variant (but not the others) attempts to replace the    *)
(*    explicit expressions for p1 and p2 by p1 and p2, respectively. *)
(*    This is moderately useful, allows for defining other splitting *)
(*    lemmas with conclusions of the form (split x p p1 p2), with    *)
(*    other expressions for p1 and p2 that might be known to occur.  *)
(*  - function trajectories: traject, and a looping predicate.       *)
(*  - cycle surgery : arc extracts the sub-arc between two points    *)
(*    (including the first, excluding the second). (arc p x y) is    *)
(*    thus only meaningful if x and y are different points in p.     *)
(*  - cycle traversal : next, prev                                   *)
(*  - path order: mem2 checks whether two points belong to a         *)
(*    and appear in order (i.e., (mem2 p x y) checks that y appears  *)
(*    after an occurrence of x in p). This predicate a crucial part  *)
(*    of the definition of the abstract Jordan property.             *)
(*  - loop removal : shorten returns a shorter, duplicate-free path  *)
(*    with the same endpoints as its argument. The related shortenP  *)
(*    dependent predicate simultaneously substitutes a new path p',  *)
(*    for (shorten e x p), (last x p') for (last x p), and generates *)
(*    predicates asserting that p' is a duplicate-free subpath of p. *)
(* Although these functions operate on the underlying sequences, we  *)
(* provide a series of lemmas that define their interaction with the *)
(* path and cycle predicates, e.g., the path_cat equation can be     *)
(* used to split the path predicate after splitting the underlying   *)
(* sequence.                                                         *)

Section Paths.

Variables (n0 : nat) (d : dataSet) (x0 : d).

Notation dsub := (sub x0).

Section Path.

Variable e : rel d.

Fixpoint path (x : d) (p : seq d) {struct p} : bool :=
  if p is Adds y p' then e x y && path y p' else true.

Lemma path_cat : forall x p1 p2,
  path x (cat p1 p2) = path x p1 && path (last x p1) p2.
Proof.
by move=> x p1 p2; elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA.
Qed.

Inductive split (x : d) : seq d -> seq d -> seq d -> Set :=
  Split : forall p1 p2 : seq d, split x (cat (add_last p1 x) p2) p1 p2.

Lemma splitP : forall (p : seq d) x, p x ->
   let i := index x p in split x p (take i p) (drop (S i) p).
Proof.
move=> p x Hx i; have := esym (cat_take_drop i p).
have Hi := Hx; rewrite -index_mem -/i in Hi; rewrite (drop_sub x Hi) -cat_add_last.
by rewrite {2}/i (sub_index x Hx) => Dp; rewrite {1}Dp.
Qed.

Inductive splitl (x1 x : d) : seq d -> Set :=
  Splitl : forall p1 p2 : seq d, last x1 p1 = x -> splitl x1 x (cat p1 p2).

Lemma splitPl : forall x1 p x, Adds x1 p x -> splitl x1 x p.
Proof.
move=> x1 p x; rewrite /= /setU1.
case: (x1 =P x) => [<-|_]; first by rewrite -(cat0s p).
case/splitP; split; exact: last_add_last.
Qed.

Inductive splitr (x : d) : seq d -> Set :=
  Splitr : forall p1 p2 : seq d, splitr x (cat p1 (Adds x p2)).

Lemma splitPr : forall (p : seq d) x, p x -> splitr x p.
Proof. by move=> p x H; case (splitP H); move=> p1 p2; rewrite cat_add_last. Qed.

Lemma pathPx : forall x p,
 reflect (forall i, i < size p -> e (dsub (Adds x p) i) (dsub p i)) (path x p).
Proof.
move=> x p; elim: p x => [|y p Hrec] x /=; first by left.
apply: (iffP andP) => [[Hxy Hp]|Hp].
  move=> [|i] Hi //; exact: Hrec _ Hp i Hi.
split; first exact: Hp 0 (leq0n (size p)).
apply/(Hrec y) => i; exact: Hp (S i).
Qed.

Fixpoint next_at (x y0 y : d) (p : seq d) {struct p} : d :=
  match p with
  | Seq0 => if x =d y then y0 else x
  | Adds y' p' => if x =d y then y' else next_at x y0 y' p'
  end.

Definition next p x := if p is Adds y p' then next_at x y y p' else x.

Fixpoint prev_at (x y0 y : d) (p : seq d) {struct p} : d :=
  match p with
  | Seq0 => if x =d y0 then y else x
  | Adds y' p' => if x =d y' then y else prev_at x y0 y' p'
  end.

Definition prev p x := if p is Adds y p' then prev_at x y y p' else x.

Lemma next_sub : forall p x,
  next p x = if p x then if p is Adds y p' then sub y p' (index x p) else x else x.
Proof.
move=> [|y0 p] x //=; elim: p {2 3 5}y0 => [|y' p Hrec] y /=;
  by rewrite /setU1 -(eqd_sym x); case (x =d y); try exact: Hrec.
Qed.

Lemma prev_sub : forall p x,
  prev p x = if p x then if p is Adds y p' then sub y p (index x p') else x else x.
Proof.
move=> [|y0 p] x //=; rewrite /setU1 eqd_sym orbC.
elim: p {2 5}y0 => [|y' p Hrec] y; rewrite /= /setU1 eqd_sym //.
case (y' =d x); simpl; auto.
Qed.

Lemma mem_next : forall (p : seq d) x, p (next p x) = p x.
Proof.
move=> p x; rewrite next_sub; case Hpx: (p x) => [|] //.
case: p (index x p) Hpx => [|y0 p'] //= i _; rewrite /setU1.
case: (ltnP i (size p')) => Hi; first by rewrite (mem_sub y0 Hi) orbT.
by rewrite (sub_default y0 Hi) set11.
Qed.

Lemma mem_prev : forall (p : seq d) x, p (prev p x) = p x.
Proof.
move=> p x; rewrite prev_sub; case Hpx: (p x) => [|] //.
case: p Hpx => [|y0 p'] Hpx //.
by apply mem_sub; rewrite /= ltnS index_size.
Qed.

Definition cycle p := if p is Adds x p' then path x (add_last p' x) else true.

(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)
(* so that it can be used as a coercion target. *)
Definition ucycleb p := cycle p && uniq p.
Definition ucycle p : Prop := cycle p && uniq p.

(* Projections, used for creating local lemmas. *)
Lemma ucycle_cycle : forall p, ucycle p -> cycle p.
Proof. by move=> p; case/andP. Qed.

Lemma ucycle_uniq : forall p, ucycle p -> uniq p.
Proof. by move=> p; case/andP. Qed.

Lemma cycle_path : forall p, cycle p = path (last x0 p) p.
Proof. by move=> [|x p] //=; rewrite -cats1 path_cat /= andbT andbC. Qed.

Lemma next_cycle : forall p x, cycle p -> p x -> e x (next p x).
Proof.
move=> [|y0 p] //= x.
elim: p {1 3 5}y0 => [|y' p Hrec] y /=; rewrite eqd_sym /setU1.
  by rewrite andbT orbF=> Hy Dy; rewrite Dy -(eqP Dy).
move/andP=> [Hy Hp]; case: (y =P x) => [<-|_] //; exact: Hrec.
Qed.

Lemma prev_cycle : forall p x, cycle p -> p x -> e (prev p x) x.
Proof.
move=> [|y0 p] //= x; rewrite /setU1 orbC.
elim: p {1 5}y0 => [|y' p Hrec] y /=; rewrite /= ?(eqd_sym x) /setU1.
  by rewrite andbT=> Hy Dy; rewrite Dy -(eqP Dy).
move/andP=> [Hy Hp]; case: (y' =P x) => [<-|_] //; exact: Hrec.
Qed.

Lemma cycle_rot : forall p, cycle (rot n0 p) = cycle p.
Proof.
case: (n0) => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.
rewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA path_cat.
case: (drop n p) => [|z0 q]; rewrite /= -cats1 !path_cat /= !andbT andbC //.
by rewrite last_cat; repeat BoolCongr.
Qed.

Lemma ucycle_rot : forall p, ucycle (rot n0 p) = ucycle p.
Proof. by move=> *; rewrite /ucycle uniq_rot cycle_rot. Qed.

Lemma cycle_rotr : forall p, cycle (rotr n0 p) = cycle p.
Proof. by move=> p; rewrite -cycle_rot rot_rotr. Qed.

Lemma ucycle_rotr : forall p, ucycle (rotr n0 p) = ucycle p.
Proof. by move=> *; rewrite /ucycle uniq_rotr cycle_rotr. Qed.

(* The "appears no later" partial preorder defined by a path. *)

Definition mem2 (p : seq d) x y : bool := drop (index x p) p y.

Lemma mem2l : forall p x y, mem2 p x y -> p x.
Proof.
move=> p x y; rewrite /mem2 -!index_mem size_drop; move=> Hxy.
by rewrite ltn_lt0sub -(ltnSpred Hxy) ltnS leq0n.
Qed.

Lemma mem2lf : forall (p : seq d) x, p x = false -> forall y, mem2 p x y = false.
Proof. move=> p x Hx y; apply/idP => [Hp]; case/idP: Hx; apply: mem2l Hp. Qed.

Lemma mem2r : forall p x y, mem2 p x y -> p y.
Proof.
rewrite /mem2; move=> p x y Hxy.
by rewrite -(cat_take_drop (index x p) p) mem_cat /setU Hxy orbT.
Qed.

Lemma mem2rf : forall (p : seq d) y, p y = false -> forall x, mem2 p x y = false.
Proof. move=> p y Hy x; apply/idP => [Hp]; case/idP: Hy; apply: mem2r Hp. Qed.

Lemma mem2_cat : forall p1 p2 x y,
 mem2 (cat p1 p2) x y = mem2 p1 x y || mem2 p2 x y || p1 x && p2 y.
Proof.
move=> p1 p2 x y; rewrite {1}/mem2 index_cat drop_cat; case Hp1x: (p1 x).
  rewrite index_mem Hp1x mem_cat /setU /= -orbA.
  by case Hp2: (p2 y); [ rewrite !orbT // | rewrite (mem2rf Hp2) ].
by rewrite ltnNge leq_addr /= orbF subn_addr (mem2lf Hp1x).
Qed.

Lemma mem2_splice : forall p1 p3 x y p2,
  mem2 (cat p1 p3) x y -> mem2 (cat p1 (cat p2 p3)) x y.
Proof.
move=> p1 p3 x y p2 Hxy; move: Hxy; rewrite !mem2_cat mem_cat /setU.
case: (mem2 p1 x y) (mem2 p3 x y) => [|] // [|] /=; first by rewrite orbT.
by case: (p1 x) => [|] //= Hy; rewrite Hy !orbT.
Qed.

Lemma mem2_splice1 : forall p1 p3 x y z,
  mem2 (cat p1 p3) x y -> mem2 (cat p1 (Adds z p3)) x y.
Proof. move=> p1 p3 x y z; apply: (mem2_splice (seq1 z)). Qed.

Lemma mem2_adds : forall x p y,
  mem2 (Adds x p) y =1 (if x =d y then setU1 x p else mem2 p y).
Proof. by move=> x p y z; rewrite {1}/mem2 /= eqd_sym; case (x =d y). Qed.

Lemma mem2_last : forall y0 p x, mem2 (Adds y0 p) x (last y0 p) = Adds y0 p x.
Proof.
move=> y0 p x; apply/idP/idP; first by apply mem2l.
rewrite -index_mem /mem2; move: (index x (Adds y0 p)) => i Hi.
by rewrite lastI drop_add_last ?size_belast // mem_add_last /= setU11.
Qed.

Lemma mem2l_cat : forall (p1 : seq d) x, p1 x = false ->
  forall p2, mem2 (cat p1 p2) x =1 mem2 p2 x.
Proof. by move=> p1 x Hx p2 y; rewrite mem2_cat (Hx) (mem2lf Hx) /= orbF. Qed.

Lemma mem2r_cat : forall (p2 : seq d) y, p2 y = false ->
   forall p1 x, mem2 (cat p1 p2) x y = mem2 p1 x y.
Proof. by move=> p2 y Hy p1 x; rewrite mem2_cat (Hy) (mem2rf Hy) andbF !orbF. Qed.

Lemma mem2lr_splice : forall (p2 : seq d) x y, p2 x = false -> p2 y = false ->
  forall p1 p3, mem2 (cat (cat p1 p2) p3) x y = mem2 (cat p1 p3) x y.
Proof.
move=> p2 x y Hx Hy p1 p3.
by rewrite !mem2_cat !mem_cat /setU (Hx) Hy (mem2lf Hx) !andbF !orbF.
Qed.

Inductive split2r (x y : d) : seq d -> Set :=
  Split2l : forall p1 p2, Adds x p2 y -> split2r x y (cat p1 (Adds x p2)).

Lemma splitP2r : forall p x y, mem2 p x y -> split2r x y p.
Proof.
move=> p x y Hxy; have Hx := mem2l Hxy.
have Hi := Hx; rewrite -index_mem in Hi.
move: Hxy; rewrite /mem2 (drop_sub x Hi) (sub_index x Hx).
by case (splitP Hx); move=> p1 p2; rewrite cat_add_last; split.
Qed.

Fixpoint shorten (x : d) (p : seq d) {struct p} : seq d :=
  if p is Adds y p' then
    if p x then shorten x p' else Adds y (shorten y p')
  else seq0.

Inductive shorten_spec (x : d) (p : seq d) : d -> seq d -> Set :=
   ShortenSpec : forall p', path x p' -> uniq (Adds x p') -> sub_set p' p ->
                 shorten_spec x p (last x p') p'.

Lemma shortenP : forall x p, path x p -> shorten_spec x p (last x p) (shorten x p).
Proof.
move=> x p Hp; elim: p x {1 2 5}x Hp (setU11 x p) => [|y2 p Hrec] y0 y1.
  by rewrite /setU1 orbF; move=> _ Dy1; rewrite (eqP Dy1); repeat split; move.
rewrite /setU1 /= orbC; case/andP=> [Hy12 Hp].
case Hpy0: (setU1 y2 p y0).
case: (Hrec _ _ Hp Hpy0) => [p' Hp' Up' Hp'p] _; split; auto; simpl.
  move=> z; move/Hp'p; apply: setU1r.
case: (Hrec _ _ Hp (setU11 y2 p)) => [p' Hp' Up' Hp'p] Dy1.
have Hp'p2: sub_set (setU1 y2 p') (setU1 y2 p).
  move=> z; rewrite /= /setU1; case: (y2 =d z) => [|] //; apply: Hp'p.
rewrite -[last y2 p']/(last y0 (Adds y2 p')); split; auto.
  by rewrite -(eqP Dy1) /= Hy12.
by simpl; case Hy0: (setU1 y2 p' y0); first by rewrite (Hp'p2 _ Hy0) in Hpy0.
Qed.

End Path.

Lemma eq_path : forall e e', e =2 e' -> path e =2 path e'.
Proof.
by move=> e e' Ee x p; elim: p x => [|y p Hrec] x //=; rewrite Ee Hrec.
Qed.

Lemma sub_path : forall e e', sub_rel e e' ->
  forall x p, path e x p -> path e' x p.
Proof.
move=> e e' He x p; elim: p x => [|y p Hrec] x //=.
by case/andP=> [Hx Hp]; rewrite (He _ _ Hx) (Hrec _ Hp).
Qed.

End Paths.

Notation "'pathP' x0" := (pathPx x0 _ _ _) (at level 10, x0 at level 8).

Notation "'fpath' f" := (path (eqdf f)) (at level 10, f at level 8).

Notation "'fcycle' f" := (cycle (eqdf f)) (at level 10, f at level 8).

Notation "'ufcycle' f" := (ucycle (eqdf f)) (at level 10, f at level 8).

Prenex Implicits path next prev cycle ucycle mem2.

Section Trajectory.

Variables (d : dataSet) (f : d -> d).

Fixpoint traject (x : d) (n : nat) {struct n} : seq d :=
  if n is S n' then Adds x (traject (f x) n') else seq0.

Lemma size_traject : forall x n, size (traject x n) = n.
Proof. by move=> x n; elim: n x => [|n Hrec] x //=; NatCongr. Qed.

Lemma last_traject : forall x n, last x (traject (f x) n) = iter n f x.
Proof. by move=> x n; elim: n x => [|n Hrec] x //; rewrite -iter_f -Hrec. Qed.

Lemma fpathPx : forall x p, reflect (exists n, traject (f x) n = p) (fpath f x p).
Proof.
move=> x p; elim: p x => [|y p Hrec] x; first by left; exists 0.
rewrite /= andbC; case: {Hrec}(Hrec y) => Hrec.
  apply: (iffP eqP); first by case: Hrec => [n <-] <-; exists (S n).
  by case=> [] [|n] // [Dp].
by right; move=> [[|n] Dp] //; case: Hrec; exists n; case: Dp => <- <-.
Qed.

Lemma fpath_traject : forall x n, fpath f x (traject (f x) n).
Proof. by move=> x n; apply/(fpathPx x _); exists n. Qed.

Definition looping x n := traject x n (iter n f x).

Lemma loopingPx : forall x n,
  reflect (forall m, traject x n (iter m f x)) (looping x n).
Proof.
move=> x n; apply introP; last by move=> Hn Hn'; rewrite /looping Hn' in Hn.
case: n => [|n] Hn //; elim=> [|m Hrec]; first by apply: setU11.
move: (fpath_traject x n) Hn; rewrite /looping -!f_iter -last_traject /=.
rewrite /= in Hrec; case/splitPl: Hrec; move: (iter m f x) => y p1 p2 Ep1.
rewrite path_cat last_cat Ep1; case: p2 => [|z p2] //; case/and3P=> [_ Dy _] _.
by rewrite /setU1 mem_cat /setU /= (eqP Dy) /= setU11 !orbT.
Qed.

Lemma sub_traject : forall i n, i < n ->
  forall x, sub x (traject x n) i = iter i f x.
Proof.
move=> i n Hi x; elim: n {2 3}x i Hi => [|n Hrec] y [|i] Hi //=.
by rewrite Hrec ?iter_f.
Qed.

Lemma trajectPx : forall x n y,
  reflect (exists2 i, i < n & iter i f x = y) (traject x n y).
Proof.
move=> x n y; elim: n x => [|n Hrec] x; first by right; case.
  rewrite /= /setU1 orbC; case: {Hrec}(Hrec (f x)) => Hrec.
  by left; case: Hrec => [i Hi <-]; exists (S i); last by rewrite iter_f.
apply: (iffP eqP); first by exists 0; first by rewrite ltnNge.
by move=> [[|i] Hi Dy] //; case Hrec; exists i; last by rewrite iter_f.
Qed.

Lemma looping_uniq : forall x n, uniq (traject x (S n)) = negb (looping x n).
Proof.
move=> x n; rewrite /looping; elim: n x => [|n Hrec] x //.
rewrite -iter_f {2}[S]lock /= -lock {}Hrec -negb_orb /setU1; BoolCongr.
set y := iter n f (f x); case (trajectPx (f x) n y); first by rewrite !orbT.
rewrite !orbF; move=> Hy; apply/idP/eqP => [Hx|Dy].
  case/trajectPx: Hx => [m Hm Dx].
  have Hx': looping x (S m) by rewrite /looping -iter_f Dx /= setU11.
  case/trajectPx: (loopingPx _ _ Hx' (S n)); rewrite -iter_f -/y.
  move=> [|i] Hi //; rewrite -iter_f; move=> Dy.
  by case: Hy; exists i; first by exact (leq_trans Hi Hm).
by rewrite {2}Dy /(y) -last_traject /= mem_lastU.
Qed.

End Trajectory.

Notation fpathP := (fpathPx _ _ _).
Notation loopingP := (loopingPx _ _ _).
Notation trajectP := (trajectPx _ _ _ _).

Prenex Implicits traject.

Section UniqCycle.

Variables (n0 : nat) (d : dataSet) (e : rel d) (p : seq d).

Hypothesis Up : uniq p.

Lemma prev_next : forall x, prev p (next p x) = x.
Proof.
move=> x; rewrite prev_sub mem_next next_sub.
case Hpx: (p x) => [|] //; case Dp: p Up Hpx => [|y p'] //.
rewrite -(Dp) {1}Dp /=; move/andP=> [Hpy Hp'] Hx.
set i := index x p; rewrite -(sub_index y Hx) -/i; congr (sub y).
rewrite -index_mem -/i Dp /= ltnS leq_eqVlt in Hx.
case/setU1P: Hx => [Di|Hi]; last by apply: index_uniq.
rewrite Di (sub_default y (leqnn _)).
rewrite -index_mem -leqNgt in Hpy.
by apply: eqP; rewrite eqn_leq Hpy /index find_size.
Qed.

Lemma next_prev : forall x, next p (prev p x) = x.
Proof.
move=> x; rewrite next_sub mem_prev prev_sub.
case Hpx: (p x) => [|] //; case Dp: p Up Hpx => [|y p'] //.
rewrite -(Dp); move=> Hp Hpx; set i := index x p'.
have Hi: i < size p by rewrite Dp /= ltnS /i /index find_size.
rewrite (index_uniq y Hi Hp); case Hx: (p' x); first by apply: sub_index.
rewrite Dp /= /setU1 (Hx) orbF in Hpx; rewrite (eqP Hpx).
rewrite -index_mem ltnNge -/i in Hx; exact (sub_default _ (negbEf Hx)).
Qed.

Lemma cycle_next : fcycle (next p) p.
Proof.
case: p Up => [|x p'] Up' //; apply/(pathP x) => [i Hi].
rewrite size_add_last in Hi.
rewrite -cats1 -cat_adds sub_cat /= (Hi) /eqdf next_sub mem_sub //.
rewrite index_uniq // sub_cat /=; rewrite ltnS leq_eqVlt in Hi.
case/setU1P: Hi => [Di|Hi]; last by rewrite Hi set11.
by rewrite Di ltnn subnn sub_default ?leqnn /= ?set11.
Qed.

Lemma cycle_prev : cycle (fun x y => x =d (prev p y)) p.
Proof.
apply: etrans cycle_next; symmetry; case Dp: p => [|x p'] //.
apply: eq_path; rewrite -Dp; exact (monic2_eqd prev_next next_prev).
Qed.

Lemma cycle_from_next : (forall x, p x -> e x (next p x)) -> cycle e p.
Proof.
move=> He; case Dp: p cycle_next => [|x p'] //; rewrite -(Dp) !(cycle_path x).
have Hx: p (last x p) by rewrite Dp /= mem_lastU.
move: (next p) He {Hx}(He _ Hx) => np.
elim: (p) {x p' Dp}(last x p) => [|y p' Hrec] x He Hx //=.
case/andP=> [Dy Hp']; rewrite -{1}(eqP Dy) Hx /=.
apply: Hrec Hp' => [z Hz|]; apply: He; [exact: setU1r | exact: setU11].
Qed.

Lemma cycle_from_prev : (forall x, p x -> e (prev p x) x) -> cycle e p.
Proof.
move=> He; apply: cycle_from_next => [x Hx].
by rewrite -{1}[x]prev_next He ?mem_next.
Qed.

Lemma next_rot : next (rot n0 p) =1 next p.
Proof.
move=> x; have Hp := cycle_next; rewrite -(cycle_rot n0) in Hp.
case Hx: (p x); last by rewrite !next_sub mem_rot Hx.
rewrite -(mem_rot n0) in Hx; exact (esym (eqP (next_cycle Hp Hx))).
Qed.

Lemma prev_rot : prev (rot n0 p) =1 prev p.
Proof.
move=> x; have Hp := cycle_prev; rewrite -(cycle_rot n0) in Hp.
case Hx: (p x); last by rewrite !prev_sub mem_rot Hx.
rewrite -(mem_rot n0) in Hx; exact (eqP (prev_cycle Hp Hx)).
Qed.

End UniqCycle.

Section UniqRotrCycle.

Variables (n0 : nat) (d : dataSet) (p : seq d).

Hypothesis Up : uniq p.

Lemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.

Lemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.

End UniqRotrCycle.

Section UniqCycleRev.

Variable d : dataSet.

Lemma prev_rev : forall p : seq d, uniq p -> prev (rev p) =1 next p.
Proof.
move=> p Up x; case Hx: (p x); last by rewrite next_sub prev_sub mem_rev Hx.
case/rot_to: Hx (Up) => [i p' Dp] Urp; rewrite -uniq_rev in Urp.
rewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?uniq_rotr //.
rewrite -rev_rot -(next_rot i Up) {i p Up Urp}Dp.
case: p' => [|y p'] //; rewrite !rev_adds rotr1_add_last /= set11.
by rewrite -add_last_adds rotr1_add_last /= set11.
Qed.

Lemma next_rev : forall p : seq d, uniq p -> next (rev p) =1 prev p.
Proof. by move=> p Up x; rewrite -{2}[p]rev_rev prev_rev // uniq_rev. Qed.

End UniqCycleRev.

Section MapPath.

Variables (d d' : dataSet) (h : d' -> d) (e : rel d) (e' : rel d').

Definition rel_base (b : set d) :=
  forall x' y', negb (b (h x')) -> e (h x') (h y') = e' x' y'.

Lemma path_maps : forall b x' p',
   rel_base b -> negb (has (comp b h) (belast x' p')) ->
 path e (h x') (maps h p') = path e' x' p'.
Proof.
move=> b x' p' Hb; elim: p' x' => [|y' p' Hrec] x' //=; move/norP=> [Hbx Hbp].
congr andb; auto.
Qed.

Hypothesis Hh : injective h.

Lemma mem2_maps : forall x' y' p', mem2 (maps h p') (h x') (h y') = mem2 p' x' y'.
Proof. by move=> *; rewrite {1}/mem2 (index_maps Hh) -maps_drop mem_maps. Qed.

Lemma next_maps : forall p, uniq p ->
  forall x, next (maps h p) (h x) = h (next p x).
Proof.
move=> p Up x; case Hx: (p x); last by rewrite !next_sub (mem_maps Hh) Hx.
case/rot_to: Hx => [i p' Dp].
rewrite -(next_rot i Up); rewrite -(uniq_maps Hh) in Up.
rewrite -(next_rot i Up) -maps_rot {i p Up}Dp /=.
by case: p' => [|y p] //=; rewrite !set11.
Qed.

Lemma prev_maps : forall p, uniq p ->
  forall x, prev (maps h p) (h x) = h (prev p x).
Proof.
move=> p Up x; rewrite -{1}[x](next_prev Up) -(next_maps Up).
by rewrite prev_next ?uniq_maps.
Qed.

End MapPath.

Definition fun_base d d' h f f' := @rel_base d d' h (eqdf f) (eqdf f').

Section CycleArc.

Variable d : dataSet.

Definition arc (p : seq d) x y :=
  let px := rot (index x p) p in take (index y px) px.

Lemma arc_rot : forall p x, uniq p -> p x -> forall i, arc (rot i p) x =1 arc p x.
Proof.
move=> p x Up Hx i y; congr (fun q => take (index y q) q); move: Up Hx {y}.
rewrite -{1 2 5 6}(cat_take_drop i p) /rot uniq_cat; case/and3P=> [_ Hp _].
rewrite !drop_cat !take_cat !index_cat mem_cat /setU orbC.
case Hx: (drop i p x) => [|] /=.
  move=> _; rewrite (negbE (hasPn Hp _ Hx)).
  by rewrite index_mem Hx ltnNge leq_addr /= subn_addr catA.
by move=> Hx'; rewrite Hx' index_mem Hx' ltnNge leq_addr /= subn_addr catA.
Qed.

Lemma left_arc : forall x y p1 p2, let p := Adds x (cat p1 (Adds y p2)) in
  uniq p -> arc p x y = Adds x p1.
Proof.
move=> x y p1 p2 p Up; rewrite /arc {1}/p /= set11 rot0.
move: Up; rewrite /p -cat_adds uniq_cat index_cat; move: (Adds x p1) => xp1.
rewrite /= negb_orb -!andbA; case/and3P=> [_ Hy _].
by rewrite (negbE Hy) set11 addn0 take_size_cat.
Qed.

Lemma right_arc : forall x y p1 p2, let p := Adds x (cat p1 (Adds y p2)) in
   uniq p -> arc p y x = Adds y p2.
Proof.
move=> x y p1 p2 p Up; set n := size (Adds x p1); rewrite -(arc_rot Up _ n).
  move: Up; rewrite -(uniq_rot n) /p -cat_adds /n rot_size_cat.
  by move=> *; rewrite /= left_arc.
by rewrite /p -cat_adds mem_cat /setU /= setU11 orbT.
Qed.

Inductive rot_to_arc_spec (p : seq d) (x y : d) : Set :=
    RotToArcSpec : forall i p1 p2,
      Adds x p1 = arc p x y ->
      Adds y p2 = arc p y x ->
      rot i p = Adds x (cat p1 (Adds y p2)) ->
    rot_to_arc_spec p x y.

Lemma rot_to_arc : forall p x y,
 uniq p -> p x -> p y -> negb (x =d y) -> rot_to_arc_spec p x y.
Proof.
move=> p x y Up Hx Hy Hxy; case: (rot_to Hx) (Hy) (Up) => [i p' Dp] Hy'.
rewrite -(mem_rot i) (Dp) /= /setU1 (negbE Hxy) in Hy'; rewrite -(uniq_rot i) Dp.
case/splitPr: p' / Hy' Dp => [p1 p2] Dp Up'; exists i p1 p2; auto.
  by rewrite -(arc_rot Up Hx i) Dp (left_arc Up').
by rewrite -(arc_rot Up Hy i) Dp (right_arc Up').
Qed.

End CycleArc.

Prenex Implicits arc.

Unset Implicit Arguments.


Require Import Classical.
Require Import ClassicalChoice.
Require Import FunctionalExtensionality.
Require Import PropExtensionality.
Require Import Description.
Require Import ClassicalDescription.

Lemma set_ext {E} :
  forall (A B : E -> Prop), (forall x, A x <-> B x) -> A = B.
Proof.
  intros A B. intro H.
  extensionality x. apply propositional_extensionality.
  destruct (H x). split ; assumption.
Qed.

Definition compl {E} (A : E -> Prop) := (fun x => ~ (A x)).

Definition subset {E} (A B : E -> Prop) := forall x, (B x) -> (A x).
Check subset.

Lemma compl_decreasing {E} : forall X Y : E -> Prop, subset X Y -> subset (compl Y) (compl X).
Proof.
  firstorder.
Qed.
(*intros X Y. intro H. unfold subset in *. unfold compl. intro x. specialize (H x). tauto. *)

Definition union {E} (A B : E -> Prop) := (fun x => (A x) \/ (B x)).
Definition union_gen {E} (X : (E -> Prop) -> Prop) := (fun x => exists A, X A /\ A x).
Check union_gen.

Definition set_of_subsets {E} (A : E -> Prop) := (fun x => (subset A x)).
Definition image_set {E F} (f : E -> F) (A : E -> Prop) := (fun y => (exists x, (A x) /\ (f x) = y)).
Definition pre_image {E F} (f : E -> F) (B : F -> Prop) := (fun x => B (f x)).

Lemma image_increasing {E F} : forall X Y : E -> Prop, forall f : E -> F, subset X Y -> subset (image_set f X) (image_set f Y).
Proof.
  firstorder.
Qed.

Definition inj {E F} (f : E -> F) := forall x y, f x = f y -> x = y.
Definition surj {E F} (f : E -> F) := forall y, exists x, f x = y.
Definition bij {E F} (f : E -> F)  := (inj f) /\ (surj f).

Definition is_recip {E F} (f : E -> F) (g : F -> E) :=
  (forall x, (g (f x)) = x) /\ (forall y, (f (g y)) = y).

Lemma bij_exists_recip {E F} (f : E -> F) :
  (bij f) -> exists (g : F -> E), (is_recip f g).
Proof.
  intro H. unfold bij in H. destruct H as [H1 H2].
  unfold surj in H2.
  assert (exists g, forall x, x = f (g x)).
  - apply unique_choice with (R := fun x gx => x = f gx).
    intro y. destruct (H2 y). exists x. unfold unique. split.
    + symmetry ; assumption.
    + intro x'. intro H0. symmetry in H.
      unfold inj in H1. destruct (H1 x x').
      * rewrite <- H. rewrite H0. reflexivity.
      * reflexivity.
  - destruct H as [g0]. exists g0.
    unfold is_recip. split.
    + intro x. unfold inj in H1. destruct (H1 x (g0 (f x))).
      * rewrite <- H. reflexivity.
      * reflexivity.
    + intro y. symmetry. rewrite <- H. reflexivity.
Qed.

Lemma is_in_image {E F} (f : E -> F) (A : E -> Prop) (x : E) : (A x) -> (image_set f A) (f x).
Proof.
  intro H. unfold image_set. exists x. split ; [assumption |reflexivity].
Qed.

Lemma is_in_image_all {E F} (f : E -> F) (x : E) : image_set f (fun _ => True) (f x).
Proof.
  apply is_in_image. constructor.
Qed.

Definition is_fixpoint {E} (f : (E -> Prop) -> (E -> Prop)) (A : E -> Prop) := f A = A.
Definition is_increasing {E} (f : (E -> Prop) -> (E -> Prop)) := forall X Y, subset X Y -> subset (f X) (f Y).
Check is_increasing.

Lemma union_increasing {E} (f : (E -> Prop) -> (E -> Prop)) :
  is_increasing f -> forall A, subset (f (union_gen A)) (union_gen (image_set f A)).
Proof.
  intro H_inc. intro A. intro x. intro Hx.
  unfold union_gen in *.
  destruct Hx as [A0 [H1 H2]]. unfold image_set in H1. destruct H1 as [A1 [ H3 H4]].
  apply (H_inc _  A1).
  - intro x'. intro H0.
    exists A1. split ; assumption.
  - rewrite H4 ; assumption.
Qed.

Lemma proj1_inj : forall (E : Type) (P : E -> Prop) (x y : sig P), proj1_sig x = proj1_sig y -> x = y.
Proof.
  intros E P x y. intro H_eq.
  destruct x as [x Px]. destruct y as [y Py]. simpl in H_eq.
  subst. f_equal. apply proof_irrelevance.
Qed.

Lemma bij_on_image {E F : Type} (h : E -> F)  :
  (inj h) -> bij (fun x => exist (image_set h (fun _ => True)) (h x) (is_in_image_all h x)).
Proof.
  intro H_inj. unfold bij. split.
  - unfold inj.
    intros x y H_eq.
    injection H_eq. apply H_inj.
  - unfold surj. intro y. destruct y as [y Py]. destruct Py as [x Hx].
    exists x. apply proj1_inj. simpl. apply Hx.
Qed.

Definition potential_fixpoint {E} (f : (E -> Prop) -> (E -> Prop)) := union_gen (fun A => (subset (f A) A)).

Lemma first_inclusion {E} (f : (E -> Prop) -> ( E -> Prop)) :
  (is_increasing f) -> subset (f (potential_fixpoint f)) (potential_fixpoint f).
Proof.
  intros H_inc x H.
  unfold potential_fixpoint in *. apply union_increasing.
  - exact H_inc.
  - unfold union_gen in H. destruct H as [A [H0]].
    unfold union_gen. exists (f A). unfold image_set. split.
    + exists A. split.
      * assumption.
      * reflexivity.
    + apply H0 ; assumption.
Qed.

Lemma second_inclusion {E} (f : (E -> Prop) -> (E -> Prop)) :
  (is_increasing f) -> subset (potential_fixpoint f) (f (potential_fixpoint f)).
Proof.
  intros H_inc x H.
  assert (subset (f (f (potential_fixpoint f))) (f (potential_fixpoint f))).
  - apply H_inc. apply first_inclusion. assumption.
  - unfold potential_fixpoint. unfold union_gen. exists (f (potential_fixpoint f)).
    split ; assumption.
Qed.

Lemma exists_fixpoint {E} (f : ((E -> Prop) -> (E -> Prop))) :
  (is_increasing f) -> exists U, (is_fixpoint f U).
Proof.
  intro H_inc. exists (potential_fixpoint f). unfold is_fixpoint.
  apply set_ext. intro x. split.
  - apply second_inclusion ; assumption.
  - apply first_inclusion ; assumption.
Qed.

Definition interesting_function {E F} (f : E -> F) (g : F -> E) (X : E -> Prop) :=
  compl (image_set g (compl (image_set f X))).

Theorem Cantor_Schröder_Bernstein {E F} (f : E -> F) (g : F -> E) :
  (inj f) -> (inj g) -> exists h : E -> F, bij h.
Proof.
  intros Hf Hg. assert (exists U, is_fixpoint (interesting_function f g) U).
  {
    apply exists_fixpoint. intros X Y. intro H. apply compl_decreasing.
    apply image_increasing. apply compl_decreasing. apply image_increasing. assumption.
  }
  destruct H as [U Hu].
  assert (Hg2 := bij_on_image g Hg).
  apply bij_exists_recip in Hg2. destruct Hg2 as [g' [Hg'1 Hg'2]].
  assert (H_excl_mid : forall x, ~ (U x) -> image_set g (fun _ => True) x).
  - intros x H. unfold is_fixpoint in Hu. rewrite <- Hu in H.
    unfold interesting_function in H.
    apply NNPP in H.
    destruct H as [y Py]. exists y ; tauto.
  - exists (fun x => match (excluded_middle_informative (U x)) with | left _ => (f x) | right H => g' (exist _ x (H_excl_mid x H)) end).
    split.
    + intros x y.
      destruct (excluded_middle_informative (U x)) as [Hx | Hx] ; destruct (excluded_middle_informative (U y)) as [Hy | Hy].
      * apply Hf.
      * intro H_eq. exfalso.
        assert (H_eq2 := f_equal g H_eq).
        specialize (Hg'2 (exist (image_set g (fun _ => True)) y (H_excl_mid y Hy))).
        injection Hg'2. intro H_eq3. rewrite H_eq3 in H_eq2.
        clear Hg'2 H_eq H_eq3.
        rewrite <- H_eq2 in Hy.
        unfold is_fixpoint in Hu. rewrite <- Hu in Hy. unfold interesting_function in Hy.
        apply NNPP in Hy. destruct Hy as [z [Hz1 Hz2]].
        apply Hg in Hz2. apply Hz1. exists x. split.
        -- assumption.
        -- symmetry ; assumption.
      *  intro H_eq. exfalso.
        assert (H_eq2 := f_equal g H_eq).
        specialize (Hg'2 (exist (image_set g (fun _ => True)) x (H_excl_mid x Hx))).
        injection Hg'2. intro H_eq3. rewrite H_eq3 in H_eq2.
        clear Hg'2 H_eq H_eq3.
        rewrite H_eq2 in Hx.
        unfold is_fixpoint in Hu. rewrite <- Hu in Hx. unfold interesting_function in Hx.
        apply NNPP in Hx. destruct Hx as [z [Hz1 Hz2]].
        apply Hg in Hz2. apply Hz1. exists y. split.
        -- assumption.
        -- symmetry ; assumption.
      * intro H_eq.
        assert (H_eq2 := f_equal (fun z => exist (image_set g (fun _ => True)) (g z) (is_in_image_all g z)) H_eq). simpl in H_eq2. rewrite !Hg'2 in H_eq2. injection H_eq2. tauto.
    + intro y.
      destruct (excluded_middle_informative (image_set f U y)) as [Hy | Hy].
      * destruct Hy as [x [Hx1 Hx2]].
        exists x. destruct (excluded_middle_informative (U x)).
        -- assumption.
        -- exfalso. tauto.
      * exists (g y). destruct (excluded_middle_informative (U (g y))) as [Hgy | Hgy].
        -- exfalso.
           unfold is_fixpoint in Hu. rewrite <- Hu in Hgy.
           unfold interesting_function in Hgy.
           apply Hgy. exists y. split.
           ++ exact Hy.
           ++ reflexivity.
        -- rewrite <- Hg'1. f_equal. apply proj1_inj. simpl. reflexivity.
Qed.


From mathcomp Require Import all_ssreflect.

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

(**

----------------------------------------------------------
#
#
** Lesson 4: summary

- Curry Howard: the big picture
  + dependent function space
- Predicates and connectives
  + introduction
  + elimination
- Induction
- Consistency
- Dependent elimination

#
#

----------------------------------------------------------
#
#
** Curry Howard

We link typed programs to statements with a proof.

Let's play a game in which we use inductive types
as our satements.

#
#
*)

Check nat : Type.

Definition zero : nat := 0.

Lemma zero_bis : nat.
Proof.
apply: 0.
Qed.

Print zero.
Print zero_bis.

(**
#
#

We learn that 0 is a term of type nat, but Coq
also accepts it as a proof of nat.

#
#
In type theory: [p] is a proof of [T]
means that [p] inhabits the type [T].
#
#

Now let's look at the function space.

#
#
*)

Check nat -> nat  :  Type.

Definition silly : nat -> nat := fun x => x.

Lemma sillier : nat -> nat.
Proof. move=> x. apply: x. Qed.

Print silly.
Print sillier.

(**
#
#

The function space [->] can represent implication.
An inhabitant of [A -> B] is a function turning
a proof of [A] into a proof of [B] (a program
taking in input a term of type [A] and returning
a term of type [B]).

The function space of type theory is *dependent*.

#
#
*)

Section DependentFunction.

Variable P : nat -> Type.
Variable p1 : P 1.

Check forall x, P x.
Check forall x : nat, P 1.

Check fun x : nat => p1.

(**
#
#

We managed to build (introduce) an arrow and a forall using [fun].
Let's see how we can use (eliminate) an arrow or a forall.

#
#
*)

Check factorial.
Check factorial 2.

Variable px1 : forall x, P x.+1.

Check px1.
Check px1 3.

End DependentFunction.

(**
#
#

Following the Curry Howard correspondence *application*
lets one call a function [f : A -> B] on [a : A] to
obtain a term of type [B]. If the type of [f] is
a dependent arrow (forall) [f : forall x : A, B x]
then the argument [a] appears in the type of
term we obtain, that is [f a] has type [B a].

In other words application instantiates universally
quantified lemmas and implements modus ponens.

Lemmas can be seen as views to transform assumptions.

#
#
*)

Section Views.

Variable P : nat -> Type.
Variable Q : nat -> Type.
Variable p2q : forall x, P x -> Q x.

Goal P 3 -> True.
Proof.
move=> (*/p2q*) p3.
Abort.

End Views.

(**
#
#

So far we used [nat] (and [P]) as a predicate and [->] for implication.

Can we use inductive types to model other predicates or connectives?

#

#

#
(notes)
#

This slide corresponds to
section 4.x of
#the Mathematical Components book#
#

#

#
#

----------------------------------------------------------
#
#
** Predicates and connectives

Let's start with #$$ \top $$#

Note: here the label [Prop] could be a synonym of [Type].

#
#
*)

Print True.

Definition trivial1 : True := I.

Definition trivial2 : True -> nat :=
  fun t =>
    match t with I => 3 end.

Lemma trivial3 : True -> nat.
Proof.
move=> t. case: t. apply: 3.
Qed.

(**
#
#

Now let's look at #$$ \bot $$#

#
#
*)

Print False.

Fail Definition hard1 : False := what.

Definition ex_falso A : False -> A :=
  fun abs => match abs with end.

Lemma ex_falso2 A : False -> A.
Proof.
move=> abs. case: abs.
Qed.

(**
#
#

Connectives: #$$ \land $$# and #$$\lor $$#

#
#
*)

Section Connectives.

Print and.

Variable A : Prop.
Variable B : Prop.
Variable C : Prop.

Variable a : A.
Variable b : B.

Check conj a b.

Definition and_elim_left : and A B -> A :=
  fun ab => match ab with conj a b => a end.

Lemma and_elim_left2 : and A B -> A.
Proof. case=> l r. apply: l. Qed.

Print or.

Check or_introl a : or A B.
Check or_intror b : or A B.

Definition or_elim :
  A \/ B -> (A -> C) -> (B -> C) -> C :=
 fun aob a2c b2c =>
   match aob with
   | or_introl a => a2c a
   | or_intror b => b2c b
   end.

Lemma or_elim_example : A \/ B -> C.
Proof.
move=> aob.
case: aob.
Abort.

(**
#
#

Quantifier #$$ \exists $$#

#
#
*)

Print ex.

Lemma ex_elim P : (exists x : A, P x) -> True.
Proof.
case => x px.
Abort.

End Connectives.

(**
#
#

#

#

#
(notes)
#

This slide corresponds to
section 4.x of
#the Mathematical Components book#
#

#

#
#
----------------------------------------------------------
#
#
** Induction

We want to prove theorems by induction, right?
Hence there must be a term that corresponds to the induction principle.
This term is a recursive function.

Note: [Fixpoint] is just sugar for [Definition] followed by [fix].

#
#
*)

About nat_ind.

Definition ind :
  forall P : nat -> Prop,
    P 0 -> (forall n : nat, P n -> P n.+1) -> forall n : nat, P n :=
  fun P p0 pS =>
    fix IH n : P n :=
      match n with
      | O => p0
      | S p => pS p (IH p)
      end.

(**
#
#

#

#

#
(notes)
#

This slide corresponds to
section 4.x of
#the Mathematical Components book#
#

#

----------------------------------------------------------
#
#
** Consistency

We give here the intuition why some terms that are in principle
well typed are rejected by Coq and why Coq is consistent.

#
#
*)
Print False.
Print True.
(**
#
#

What does it mean that [t : T] and [T] is not [False]?

#
#
*)
Check (match 3 with O => I | S _ => I end) : True.
(**
#
#

Constructors are not the only terms that can inhabit a type.
Hence we cannot simply look at terms, but we could look at
their normal form.

Subject reduction: [t : T] and [t ~> t1] then [t1 : T].
We claim there is not such [t1] (normal form) that
inhabits [False].

We have to reject [t] that don't have a normal form.

Exaustiveness of pattern matching:

#
#
*)

Lemma helper x : S x = 0 -> False. Proof. by []. Qed.

Fail Definition partial n : n = 0 -> False :=
  match n with
  | S x => fun p : S x = 0 => helper x p
(*  | 0 => fun _ => I*)
  end.

Fail Check partial 0 (erefl 0). (* : False *)

Fail Compute partial 0 (erefl 0). (* = ??? : False *)

(**
#
#

According to Curry Howard this means that in a case
split we did not forget to consider a branch!

Termination of recursion:

#
#
*)

Fail Fixpoint oops (n : nat) : False := oops n.+1.

Fail Check oops 3. (* : False *)

Fail Compute oops 3. (* = ??? : False *)

(**
#
#

According to Curry Howard this means that we did not
do any circular argument.

Non termination is subtle since a recursive call could
be hidden in a box.

#
#
*)

Fail Inductive hidden := Hide (f : hidden -> False).

Fail Definition oops (hf : hidden) : False :=
  match hf with Hide f => f hf end.

Fail Check oops (Hide oops). (* : False *)

Fail Compute oops (Hide oops). (* = ??? : False *)

(**
#
#

This condition of inductive types is called positivity:
The type of [Hide] would be [(hidden -> False) -> hidden],
where the first occurrence of [hidden] is on the left (negative)
of the arrow.

#

#

#
(notes)
#

This slide corresponds to
section 3.2.3 of
#the Mathematical Components book#
#

#

#
#

----------------------------------------------------------
#
#
** Inductive types with indexes (casse-tête)

... and their elimination.

The intuition, operationally.

Inductive types can express tricky invariants:

#
#
*)

(* Translucent box, we know if it is empty or not without opening it *)
Inductive tbox : bool -> Type :=
  | Empty          : tbox false
  | Full (n : nat) : tbox true.

Check Empty.
Check Full 3.

Definition default (d : nat) (f : bool) (b : tbox f) : nat :=
  match b with
  | Empty => d
  | Full x => x
  end.

(* Why this complication? (believe me, not worth it) *)
Definition get (b : tbox true) : nat :=
  match b with Full x => x end.

(* the meat: why is the elimination tricky? *)
Lemma default_usage f (b : tbox f) : 0 <= default 3 b .
Proof.
case: b.
Fail Check @default 3 f Empty.
  by [].
by [].
Qed.

(**
#
#

Take home:
- the elimination of an inductive data type with indexes
  expresses equations between the value of the indexes
  in the type of the eliminated term and the value of the
  indexes prescribed in the declatation of the inductive data
- the implicit equations are substituted automatically at
  elimination time
- working with indexed data is hard, too hard :-/
- we can still make good use of indexes when we define "spec" lemmas,
  argument of the next lecture

#

#

#
(notes)
#

This slide corresponds to
section 4.x of
#the Mathematical Components book#
#

#

#
#

----------------------------------------------------------
#
#
** Lesson 4: sum up

- In Coq terms/types play a double role:
  + programs and their types
  + statements and their proofs
- Inductives can be used to model predicates and
  connectives
- Pattern machind and recursion can model induction
- The empty type is, well, empty, hence Coq is consistent
- Inductives with indexes

#
#

*)


Fixpoint Tree(A: Type)(d: nat): Type :=
  match d with
  | O => A
  | S n => Tree A n * Tree A n
  end.

Definition ChildType(A: Type)(d: nat): Type :=
  match d with
  | O => unit
  | S n => Tree A n
  end.

Definition leftChild{A: Type}{d: nat}(t: Tree A d): ChildType A d :=
  match d as n return (Tree A n -> ChildType A n) with
  | O => fun _ => tt
  | S n => fun t => fst t
  end t.


Definition e:=Set.
Set Implicit Arguments.
Definition Ensemble :=(e -> Prop)->Prop.
Definition In (A:Ensemble) (x:e->Prop) : Prop := A x.
Definition Included (B C:Ensemble) : Prop := forall x:e->Prop, In B x -> In C x.

Definition Strict_Included (B C:Ensemble) : Prop := Included B C /\ B <> C.

Inductive Empty_set : Ensemble :=.

Inductive Full_set : Ensemble :=
 Full_intro : forall x:e->Prop, In Full_set x.

Inductive Singleton (x:e->Prop) : Ensemble :=
    In_singleton : In (Singleton x) x.

Inductive Union (B C:Ensemble) : Ensemble :=
    | Union_introl : forall x:e->Prop, In B x -> In (Union B C) x
    | Union_intror : forall x:e->Prop, In C x -> In (Union B C) x.

Definition Add (B:Ensemble) (x:e->Prop) : Ensemble := Union B (Singleton x).

Inductive Intersection (B C:Ensemble) : Ensemble :=
    Intersection_intro :
    forall x:e->Prop, In B x -> In C x -> In (Intersection B C) x.

Inductive Couple (x y:e->Prop) : Ensemble :=
    | Couple_l : In (Couple x y) x
    | Couple_r : In (Couple x y) y.

Inductive Triple (x y z:e->Prop) : Ensemble :=
    | Triple_l : In (Triple x y z) x
    | Triple_m : In (Triple x y z) y
    | Triple_r : In (Triple x y z) z.

Definition Complement (A:Ensemble) : Ensemble := fun x:e->Prop => ~ In A x.

  Definition Setminus (B C:Ensemble) : Ensemble :=
    fun x:e->Prop => In B x /\ ~ In C x.

  Definition Subtract (B:Ensemble) (x:e->Prop) : Ensemble := Setminus B (Singleton x).

  Inductive Disjoint (B C:Ensemble) : Prop :=
    Disjoint_intro : (forall x:e->Prop, ~ In (Intersection B C) x) -> Disjoint B C.

  Definition Same_set (B C:Ensemble) : Prop := Included B C /\ Included C B.
    Axiom Extensionality_Ensembles : forall A B:Ensemble, Same_set A B -> A = B.

Definition ensemble :=e->Prop.
Definition In_s (A:ensemble) (x:e) : Prop := A x.
Definition included (B C:ensemble) : Prop := forall x:e, In_s B x -> In_s C x.

Definition strict_Included (B C:ensemble) : Prop := included B C /\ B <> C.

Inductive empty_set : ensemble :=.

Inductive full_set : ensemble :=
full_intro : forall x:e, In_s full_set x.

  Inductive singleton (x:e) : ensemble :=
    in_singleton : In_s (singleton x) x.

  Inductive union (B C:ensemble) : ensemble :=
    | union_introl : forall x:e, In_s B x -> In_s (union B C) x
    | union_intror : forall x:e, In_s C x -> In_s (union B C) x.

Definition add (B:ensemble) (x:e) : ensemble := union B (singleton x).

Inductive intersection (B C:ensemble) : ensemble :=
    intersection_intro :
    forall x:e, In_s B x -> In_s C x -> In_s (intersection B C) x.

Inductive couple (x y:e) : ensemble :=
    | couple_l : In_s (couple x y) x
    | couple_r : In_s (couple x y) y.

Inductive triple (x y z:e) : ensemble :=
    | triple_l : In_s (triple x y z) x
    | triple_m : In_s (triple x y z) y
    | triple_r : In_s (triple x y z) z.

Definition complement (A:ensemble) : ensemble := fun x:e => ~ In_s A x.

Definition setminus (B C:ensemble) : ensemble :=
    fun x:e => In_s B x /\ ~ In_s C x.

Definition subtract (B:ensemble) (x:e) : ensemble := setminus B (singleton x).

Inductive disjoint (B C:ensemble) : Prop :=
    disjoint_intro : (forall x:e, ~ In_s (intersection B C) x) -> disjoint B C.

Inductive inhabited (B:ensemble) : Prop :=
    inhabited_intro : forall x:e, In_s B x -> inhabited B.

Definition strict_included (B C:ensemble) : Prop := included B C /\ B <> C.

Definition same_set (B C:ensemble) : Prop := included B C /\ included C B.
    Axiom extensionality_ensembles : forall A B:ensemble, same_set A B -> A = B.